본문 바로가기

카테고리 없음

OnePK

OnePK

 

onePK-sdk-python-rel-1.3.0.181.tar.gz


1. PC에 SDK File 다운로드
https://developer.cisco.com/site/devnet/home/index.gsp#comboFilters%5Bcontenttype%5D=.sdks
 onePK-sdk-python-rel-1.3.0.181.tar.gz

2. onePK Master(?)로 파일 전송
$ scp onePK-sdk-python-rel-1.3.0.181.tar.gz username@Server_IP

OnePK 정의 https://ciscomarketing.jiveon.com/docs/DOC-53411
OnePK 파이션 기초 http://ipengineer.net/2014/05/using-ciscos-onepk-python/
OnePK 연결 http://artynetworks.com/cisco-onepk-first-connection/
OnePK 커스텀 라우팅 http://www.routereflector.com/2013/09/custom-routing-with-cisco-onepk/

from onep.element.NetworkApplication import NetworkApplication
from onep.element import SessionConfig
IP
USERNAME
PASSWORD
PIN_F ILE = 확인
PORT

network_application = NetworkApplication.get_instance()
net_element = network_application.get_network_element(IP)
session_config = SessionConfig(sessionConfig.SessionTransportMode.TLS)

session_config.ca_certs= None
session_config.keyfile= None
session_config.certfile = None
session_config.port = PORT  (15002?)

session_config.set_tls_pinning(PIN_FILE,None)
session_handle = net_element.connect(USERNAME, PASSWORD, session_config)

net_element.disconnect()


-------------------------------------------------------------------------------------------------------
net_element.properties.processor
net_element.properties.product_id
net_element.properties.SerialNo
net_element.properties.sys_descr
net_element.properties.sys_name
net_element.properties.sys_uptime




http://www.bytebucket.org/rohorner/onepk-python-demo/src/3a4ce755b5389a29d1997d84c3747fa238230758/test-examples/test-session.py?at=master
 


http://packetpushers.net/kicking-tires-ciscos-onepk/                                   
-------------------------------------------------

 

http://packetpushers.net/kicking-tires-ciscos-onepk/

 

* Java
 http://artynetworks.com/cisco-onepk-first-connection/

https://communities.cisco.com/thread/44820

show onep status



import onep.element.NetworkElement


IPaddr = '10.1.1.82'

User = 'zigi'

Pass = 'zigi'

Port = '15002'


elem = onep.element.NetworkElement(IPaddr,'ZIGI-OnePK')


print "App Name:", elem.appname

print "Connected:", elem.is_connected()


#

# Connect to the NetworkElement

#

con = elem.connect(User, Pass)

print "\nConnecting..."

print "\nConnected:", elem.is_connected()

print 'Connected to: ',con


print "Host Content String:\n", elem.properties.content_string


print "System Name:        ", elem.properties.sys_name

print "System Uptime:      ", elem.properties.sys_uptime

print "Total System Memory:", elem.total_system_memory

print "Free System Memory: ", elem.free_system_memory

print ""


elem.disconnect()




==============

root@ubuntu:~/onepk# python onepk_ex1.py

App Name: ZIGI-OnePK

Connected: False

ERROR:onep.element.NetworkElement:Thrift exception: No CA certificates were given so the network element could not be verified.

ERROR:onep.element.NetworkElement:Could not connect to NetworkElement: Error occurred in the operation.  Failed to connect to the network element or the session is closed. 

Traceback (most recent call last):

  File "onepk_ex1.py", line 16, in <module>

    con = elem.connect(User, Pass)

  File "/eem-5/shr_scratch/build/nightly/sdk_1.3-nightly/latest/infra/onep/presentation/python/pkg_rel/onep/element/NetworkElement.py", line 1583, in connect

  File "/eem-5/shr_scratch/build/nightly/sdk_1.3-nightly/latest/infra/onep/presentation/python/pkg_rel/onep/element/NetworkElement.py", line 1889, in connect_

onep.core.exception.OnepConnectionException.OnepConnectionException: Error occurred in the operation.  Failed to connect to the network element or the session is closed. 

root@ubuntu:~/onepk# sudo nano onepk_ex1.py


 


테스트 완료 버전

zigi@zigi-VirtualBox:~/onepk$ cat ex2.py


import onep.element.NetworkElement
from onep.element.SessionConfig import SessionConfig
from onep.core.util import tlspinning

 

 

class PinningHandler(tlspinning.TLSUnverifiedElementHandler):                                # Python Class 상속 시, ( ) Parent class기입
      def __init__(self, pinning_file):
            self.pinning_file = pinning_file
      def handle_verify(self, host, hashtype, finger_print, changed):
            return tlspinning.DecisionType.ACCEPT_ONCE


elem = onep.element.NetworkElement('192.168.56.201','ZIGI-OnePK')

print 'App Name : ',elem.appname

 

config = SessionConfig(None)
config.set_tls_pinning(' ',PinningHandler(''))
config.transportMode = SessionConfig.SessionTransportMode.TLS
config.ca_certs = None
config.keyfile = None
config.certfile = None

 

con=elem.connect('zigi','zigi',config)

 

print 'connected: ',elem.is_connected()

print 'System Name      : ',elem.properties.sys_name
print 'System Uptime    : ',elem.properties.sys_uptime
print 'system Desc      : ',elem.properties.sys_descr
print 'System Processor : ',elem.properties.processor
print 'System Product ID: ',elem.properties.product_id
print 'System Serial No : ',elem.properties.SerialNo

elem.disconnect()

print 'connected: ',elem.is_connected()

 

------------------------------------------------------

from onep.element.NetworkApplication import NetworkApplication

 

na = NetworkApplication.get_instance()

elem = na.get_network_element('192.168.56.201')

session_config = SessionConfig(SessionConfig.SessionTransportMode.TLS)
session_config.ca_certs = None
session_config.keyfile = None
session_config.certfile = None

session_config.set_tls_pinning(' ', PinningHandler(''))
-----------------------------------------------------


결과값.

zigi@zigi-VirtualBox:~/onepk$ python ex2.py
App Name :  ZIGI-OnePK
connected:  True
System Name      :  vIOS-01
System Uptime    :  67664
system Desc      :  Cisco IOS Software, IOSv Software (VIOS-ADVENTERPRISEK9-M), Version 15.4(2)T1, RELEASE SOFTWARE (fc3)
Technical Support: http://www.cisco.com/techsupport
Copyright (c) 1986-2014 by Cisco Systems, Inc.
Compiled Thu 26-Jun-14 15:58 by prod_rel_team
System Processor :  IOSv Chassis
System Product ID:  IOSv
System Serial No :  9STZVU5NPGC1X3Y88T3V9
connected:  False

 

vIOS 설정

username zigi privilege 15 secret 5 $1$32Sx$WklOjFnRiB7W.
onep
    transport type tls disable-remotecert-validation
               * Self-Signed Certificate를 하기 위한 설정.      ↔ Authority   (transport type tls remotecert onep-tp)

vIOS 로그


vIOS-01#
*Dec 12 22:14:04.048: %ONEP_BASE-6-CONNECT: [Element]: ONEP session Application:ZIGI-OnePK Host:192.168.56.201 ID:8793 User:zigi has connected.
*Dec 12 22:14:04.073: %ONEP_BASE-6-DISCONNECT: [Element]: ONEP session Application:ZIGI-OnePK Host:192.168.56.201 ID:8793 User:zigi has disconnected.

 


OnePK를 접속하기

 - NetworkElement라고하는 접속하고자 하는 Network Device에 대한 정보를 설정한다.

    ※ onep.element.NetworkElement
 - 초기 OnePK에서는 Vanilla TCP(일반적인 TCP 통신)를 사용하였으나,

   최신 OnePK(1.3), IOS (15.4)에서는 암호화되지 않은 통신은 Disable되고,  TLS를 사용하도록 하여 보안을 강화하였다.

 

TLS Pinning

 - TLS를 사용하여 암호화 통신은 유지하면서, 인증에 대한 부분을 Bypass하여 쉽게 OnePK를 사용할 수 있도록 하는 방법.

    ※ LINK : https://communities.cisco.com/thread/44820

 

 

OnePK Application은 안전하게 디지털 인증서과 Key를 관리해야 하는데, 기존의 전통적인 PKI 대신에 OnePK SDK에서는 TLS Certificate pinning이라는 구현 방법을 제공한다.

Pinning은 Peer와 연결을 위해서 수동으로 Peer의 공개키를 저장하고, 권한을 부여한다

 

 

Pinning : 특정 Host가 Whitelist 기반의 TLS 인증을 하는 절차.  Key 관리하는 SSH Model이라고도 함.

 

Pinning File Format

# Device ID(IP or FQDN), Hash type, Fingerprint

192.168.56.201,SHA-1,F2:1E:50:C1:0D:8A:79:B8:8B:B2:20:F8:87:DD:FD:D6:3F:9E:3A:03
....

 

OnePK Site

https://developer.cisco.com/site/onepk/

 

OnePK Python API

https://developer.cisco.com/site/onepk/documents/api-reference/python/

 

 

 

 

 


 

onep.element.NetworkElement 모듈

   - 클래스 : NetworkElement

                   ◇ Network OS (Device/Host)

 

                      ▶ Method

                           - __init__(self,host_address='127.0.0.1', appname='noname')

                           - connect(self, username, password, session_config=None) 

                                 : return type : onep.element.Session_Handle

 

 


onep.core.util.tlspinning 모듈

   - 클래스 : TLSUnverifiedElementHandler

                   ◇ Network element가 확인되지 않은 TLS 연결을 위한 Handler

 

                      ▶ Method : handle_verify(self, host, hash_type, fingerprint, changed)   : 추상메서드

                            ◇ Network element가 확인되지 않은 경우에 호출되는 Callback Method.

                                 * host(문자열) : Network Device의 Hostname

                                 * hash_type(문자열) : fingerprint에서 사용되는 hashing 알고리즘

                                 * fingerprint(문자열) : 인증서의 fingerprint

                                 * chaged(bool) : 호스트와의 인증 내용이 일치하지 않은 경우 True.

                      ▶ Return type : DecisionType                             

 

                      

 

   - 속성 : DecisionType.ACCEPT_ONCE            : 별도의 Peer 인증서 없이 TLS 접속을 허용

                                         .ACCEPT_AND_PIN     : Peer의 인증서에 대한 정보가 있는지 확인 후, 접속 허용.

                                         .REJECT                           : TLS 접속을 차단 


onep.element.SessionConfig 모듈

  - 클래스 : SessionConfig

 

                      ▶ Method : set_tls_pinning(self, pinning_file, handler)

 

                               * pinning_file(문자열) : pinning File의 경로 / Default 값은 None이며 이 경우에는 Pinning File을 사용하지 않는다.

                               * handler(TLSUnverifiedElementHandler) :Default 값은 None이며, 이 경우 확인되지 않았기 때문에 접속을 끊는다.

 

  - 상수: SessionTransPortMode.TLS / SOCKET / TIPC

 

 

 


 

vIOS에서 Session 강제로 끊기


vIOS-01#onep stop session ?
  ZIGI-OnePK-4712  Application name: ZIGI-OnePK, Session ID: 4712
  all              All sessions

vIOS-01#onep stop session ZIGI-OnePK-4712
vIOS-01#sh
*Dec 13 06:25:00.788: %ONEP_BASE-6-DISCONNECT: [Element]: ONEP session Application:ZIGI-OnePK Host:192.168.56.201 ID:4712 User:zigi has disconnected.

 

 


import onep.element.NetworkElement
from onep.element.SessionConfig import SessionConfig
from onep.core.util import tlspinning
from onep.interfaces import InterfaceFilter
from onep.interfaces import NetworkInterface

class PinningHandler(tlspinning.TLSUnverifiedElementHandler):
      def __init__(self, pinning_file):
            self.pinning_file = pinning_file
      def handle_verify(self, host, hashtype, finger_print, changed):
            return tlspinning.DecisionType.ACCEPT_ONCE

elem = onep.element.NetworkElement('192.168.56.201','ZIGI-OnePK')

config = SessionConfig(None)
config.set_tls_pinning(' ',PinningHandler(''))
config.transportMode = SessionConfig.SessionTransportMode.TLS
config.ca_certs = None
config.keyfile = None
config.certfile = None

try:
      elem.connect('zigi','zigi',config)

      InterfaceTypes = NetworkInterface.InterfaceTypes
      filter = InterfaceFilter(None, InterfaceTypes.ONEP_IF_TYPE_ETHERNET)

      vIOS_int = elem.get_interface_list(filter)
 #     vIOS_int = elem.get_status(filter)
      print type(vIOS_int)

      for interface in vIOS_int:
            print interface.get_status()
finally:
      elem.disconnect()

 

 


장비 설정 변경

vIOS

  VTY Service : OnePK를 통해서 Cli 커맨드를 입력하는 방법

onep
    vIOS-01(config-onep)#service set ?
            mediatrace  mediatrace service set
            vty                 vty service set

    vIOS-01(config-onep)#service set vty

 

Server

from onep.vty import VtyService

vty_service = VtyService(elem)

vty_service.open()

cli = vty_service.write("sh ip int br")

cli = vty_service.write("conf t")

cli = vty_service.write("int lo 0")

cli = vty_service.write("ip add 1.1.1.1 255.255.255.255")

 

import onep.element.NetworkElement
from onep.element.SessionConfig import SessionConfig
from onep.core.util import tlspinning
from onep.interfaces import InterfaceFilter
from onep.interfaces import NetworkInterface
from onep.vty import VtyService

class PinningHandler(tlspinning.TLSUnverifiedElementHandler):
      def __init__(self, pinning_file):
            self.pinning_file = pinning_file
      def handle_verify(self, host, hashtype, finger_print, changed):
            return tlspinning.DecisionType.ACCEPT_ONCE

elem = onep.element.NetworkElement('192.168.56.201','ZIGI-OnePK')

config = SessionConfig(None)
config.set_tls_pinning(' ',PinningHandler(''))
config.transportMode = SessionConfig.SessionTransportMode.TLS
config.ca_certs = None
config.keyfile = None
config.certfile = None

try:
      elem.connect('zigi','zigi',config)
      vty_service = VtyService(elem)
      vty_service.open()
      cli = vty_service.write('show run')
      print cli

#      cli = vty_service.write('conf t')
#     cli = vty_service.write('int loopback 0')
#      cli = vty_service.write('ip address 1.1.1.1 255.255.255.255')

 

finally:
      elem.disconnect()

 

 

 

 

장비에서 vty 미 설정 시에

zigi@zigi-VirtualBox:~/onepk$ python ex4.py
Traceback (most recent call last):
  File "ex4.py", line 25, in <module>
    vty_service = VtyService(elem)
  File "/eem-5/shr_scratch/build/nightly/sdk_1.3-nightly/latest/infra/onep/presentation/python/pkg_rel/onep/vty/VtyService.py", line 90, in __init__
onep.core.exception.OnepRemoteProcedureException.OnepRemoteProcedureException: VTY service set not enabled, ONEP_FAIL



 



vIOS-01#sh onep status
Status: enabled by: Config
Version: 1.2.1
Transport: tls; Status: running; Port: 15002; localcert: TP-self-signed-4294967295; client cert validation disabled
Certificate Fingerprint SHA1: F21E50C1 0D8A79B8 8BB220F8 87DDFDD6 3F9E3A03
Transport: tipc; Status: disabled
Session Max Limit: 10
CPU Interval: 0 seconds
CPU Falling Threshold: 0%
CPU Rising Threshold: 0%
History Buffer: Enabled
History Buffer Purge: Oldest
History Buffer Size: 32768 bytes
History Syslog: Disabled
History Archived Session: 7
History Max Archive: 16
Trace buffer debugging level is info

 

vIOS-01(config)#crypto pki export TP-self-signed-4294967295 pem terminal
% Self-signed CA certificate:
-----BEGIN CERTIFICATE-----
MIICKzCCAZSgAwIBAgIBATANBgkqhkiG9w0BAQUFADAxMS8wLQYDVQQDEyZJT1Mt
U2VsZi1TaWduZWQtQ2VydGlmaWNhdGUtNDI5NDk2NzI5NTAeFw0xNDEyMTIwMzAz
NDdaFw0yMDAxMDEwMDAwMDBaMDExLzAtBgNVBAMTJklPUy1TZWxmLVNpZ25lZC1D
ZXJ0aWZpY2F0ZS00Mjk0OTY3Mjk1MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB
gQCviyb4o65lMD7yOp/NFvTGYOexCygJ61QBTas16lFFtGC0+lwkJESmu6Md5wtA
dAmoFxYggrkMdT9cQTA5Z07cE5tGUc1HLdYCmbzq0IT4w+2Aoo3lbBp9JSCfJokH
NC3LQTZCg3pWB2dwNs31N3IRtcKbCbdslar6rVx41BOgywIDAQABo1MwUTAPBgNV
HRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFHAPXc6CEo7+HbeoyagSlzsoH833MB0G
A1UdDgQWBBRwD13OghKO/h23qMmoEpc7KB/N9zANBgkqhkiG9w0BAQUFAAOBgQBQ
MXMymrt9CilHuKju8N3i2ML+t7+SvzukhMr6vEh47BS2jz0unKXvflSVqBL/0dZj
koTKrfw04MYuAiI4FkrcGCHDjwuU61a8yBIeElgoEj6icz1usAkAyt4Cxw56CNuL
Kny54HKx+BSY8AyBJZoyHcjNa21zQJMbsm43siApzw==
-----END CERTIFICATE-----

% General Purpose Certificate:
-----BEGIN CERTIFICATE-----
MIICKzCCAZSgAwIBAgIBATANBgkqhkiG9w0BAQUFADAxMS8wLQYDVQQDEyZJT1Mt
U2VsZi1TaWduZWQtQ2VydGlmaWNhdGUtNDI5NDk2NzI5NTAeFw0xNDEyMTIwMzAz
NDdaFw0yMDAxMDEwMDAwMDBaMDExLzAtBgNVBAMTJklPUy1TZWxmLVNpZ25lZC1D
ZXJ0aWZpY2F0ZS00Mjk0OTY3Mjk1MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB
gQCviyb4o65lMD7yOp/NFvTGYOexCygJ61QBTas16lFFtGC0+lwkJESmu6Md5wtA
dAmoFxYggrkMdT9cQTA5Z07cE5tGUc1HLdYCmbzq0IT4w+2Aoo3lbBp9JSCfJokH
NC3LQTZCg3pWB2dwNs31N3IRtcKbCbdslar6rVx41BOgywIDAQABo1MwUTAPBgNV
HRMBAf8EBTADAQH/MB8GA1UdIwQYMBaAFHAPXc6CEo7+HbeoyagSlzsoH833MB0G
A1UdDgQWBBRwD13OghKO/h23qMmoEpc7KB/N9zANBgkqhkiG9w0BAQUFAAOBgQBQ
MXMymrt9CilHuKju8N3i2ML+t7+SvzukhMr6vEh47BS2jz0unKXvflSVqBL/0dZj
koTKrfw04MYuAiI4FkrcGCHDjwuU61a8yBIeElgoEj6icz1usAkAyt4Cxw56CNuL
Kny54HKx+BSY8AyBJZoyHcjNa21zQJMbsm43siApzw==
-----END CERTIFICATE-----