Exemplo n.º 1
0
class bootstrapInformation(univ.Sequence):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType('id', univ.Integer()),
        namedtype.NamedType('os-name', univ.OctetString()),
        namedtype.NamedType('os-version', univ.OctetString()),
        namedtype.NamedType('download-uri', univ.OctetString()),
        namedtype.NamedType('hash-algorithm', univ.OctetString()),
        namedtype.NamedType('hash-value', univ.OctetString()),
        namedtype.NamedType('configuration-handling', univ.OctetString()),
        namedtype.NamedType('pre-configuration-script', univ.OctetString()),
        namedtype.NamedType('configuration', univ.OctetString()),
        namedtype.NamedType('post-configuration-script', univ.OctetString()))


nsmap_add("sys", "urn:ietf:params:xml:ns:yang:ietf-system")


def verifyString(cert, sign, stringToVerify, algo):
    try:
        result = OpenSSL.crypto.verify(cert, sign, stringToVerify, algo)
        print("signature verified")
        return True
    except Exception as e:
        print(e)
        print("verify failed")
        return False


def getCertStringfromFile(filepath):
    with open(filepath, 'r') as myfile:
Exemplo n.º 2
0
#
from __future__ import absolute_import, division, unicode_literals, print_function, nested_scopes
import getpass
import logging
from netconf import NSMAP, qmap, nsmap_add
import netconf.util as ncutil
import netconf.error as ncerror
import netconf.server as ncserver

logger = logging.getLogger(__name__)
nc_server = None
NC_PORT = None
NC_DEBUG = True

mock_module = "urn:test:mock"
nsmap_add('t', 'urn:test:mock')


class MockMethods(object):
    NCFILTER = qmap("nc") + "filter"
    """This is an abstract class that is used to document the server methods functionality

    The server return not-implemented if the method is not found in the methods object,
    so feel free to use duck-typing here (i.e., no need to inherit)
    """
    def nc_append_capabilities(self, capabilities):  # pylint: disable=W0613
        """The server should append any capabilities it supports to capabilities"""
        ncutil.subelm(capabilities, "capability").text = mock_module
        ncutil.subelm(
            capabilities,
            "capability").text = "urn:ietf:params:netconf:capability:xpath:1.0"
Exemplo n.º 3
0
#client for netconf
from netconf.client import NetconfSSHSession
from lxml import etree
import netconf.util as util
from netconf import nsmap_add, nsmap_update
from netconf import NSMAP

import re

nsmap_add("sys", "urn:ietf:params:xml:ns:yang:ietf-system")
MODEL_NS = "urn:my-urn:my-model"
nsmap_add('pfx', MODEL_NS)
#nsmap_update({'pfx': MODEL_NS})
data = util.elm("bootstrap")
redirect = util.subelm(data, "redirect-information")
boots_server = util.subelm(redirect, "bootstrap-server")
boots_server.append(util.leaf_elm("address", "172.17.0.1"))
boots_server.append(util.leaf_elm("port", "8300"))
boots_server.append(util.leaf_elm("trust_anchor", "undefined"))

onboard = util.subelm(data, "onboarding-information")
boot_img = util.subelm(onboard, "boot-image")
boot_img.append(util.leaf_elm("os-name", "IOS"))
boot_img.append(util.leaf_elm("os-version", "16.8"))
boot_img.append(util.leaf_elm("download-uri", "tftp://10.0.0.1/files"))
img_verification = util.subelm(boot_img, "image-verification")
img_verification.append(util.leaf_elm("hash-algorithm", "md5"))
img_verification.append(util.leaf_elm("hash-value", "12345678"))

onboard.append(util.leaf_elm("configuration-handling", "append"))
onboard.append(util.leaf_elm("pre-configuration-script", "pre.py"))
Exemplo n.º 4
0
def main(args):

    if not args:
        return
    #print(type(args))
    #return

    #TODO: check if args is a valid IP

    nsmap_add("sys", "urn:ietf:params:xml:ns:yang:ietf-system")
    MODEL_NS = "urn:my-urn:my-model"
    nsmap_add('pfx', MODEL_NS)

    keyFileToSend = "python/cwCA/intermediate/certs/www.ap.controlware.com.cert.pem"
    privateKeyFile = "/usr/src/app/python/vendorCA/intermediate/private/www.ownership.vendor1.com.key.pem"

    fileString = getCertStringfromFile(keyFileToSend)

    sign = signString(privateKeyFile, b"password", fileString.encode('ascii'),
                      "sha256")

    #Encode signature so it can be send as a string
    sign_base64 = base64.b64encode(sign)
    utf8Signature = sign_base64.decode('utf-8')
    ownershipRPC = util.elm("ownership")
    cert = OpenSSL.crypto.load_certificate(
        OpenSSL.crypto.FILETYPE_PEM,
        getCertStringfromFile(
            '/usr/src/app/python/vendorCA/intermediate/certs/www.ownership.vendor1.com.cert.pem'
        ))
    #if verifyString(cert, sign, fileString.encode('ascii'),"sha256"):
    if verifyString(
            '/usr/src/app/python/vendorCA/intermediate/certs/www.ownership.vendor1.com.cert.pem',
            sign, fileString.encode('ascii'), "sha256"):
        ownerCertificate = util.subelm(ownershipRPC, "ownerCertificate")
        ownerCertificate.append(util.leaf_elm("certificate", fileString))
        #ownerCertificate.append(util.leaf_elm("certificateSignature", sign_base64))
        ownerCertificate.append(
            util.leaf_elm("certificateSignature", utf8Signature))

    bootstrapRPC = util.elm("bootstrap")
    bootInfo = util.subelm(bootstrapRPC, "bootInfo")

    #bootInfo_base64 = base64.b64encode(asnString)
    bytebootstrapArtifact = buildbootstrapArtifact()
    bootInfo_base64 = base64.b64encode(bytebootstrapArtifact)
    utf8BootInfo = bootInfo_base64.decode('utf-8')

    privateKeyFile = "/usr/src/app/python/cwCA/intermediate/private/www.ap.controlware.com.key.pem"
    sign = signString(privateKeyFile, b"password",
                      utf8BootInfo.encode('ascii'), "sha256")
    sign_base64 = base64.b64encode(sign)
    utf8Signature = sign_base64.decode('utf-8')

    bootInfo.append(util.leaf_elm("bootInfoASN", utf8BootInfo))

    if verifyString(
            '/usr/src/app/python/cwCA/intermediate/certs/www.ap.controlware.com.cert.pem',
            sign, utf8BootInfo.encode('ascii'), "sha256"):
        bootInfo.append(util.leaf_elm("bootInfoSignature", utf8Signature))

    #TODO: not hardcode
    session = NetconfSSHSession(args, "8300", "admin", "admin", debug=True)
    root, reply, replystring = session.send_rpc(ownershipRPC)
    root, reply, replystring = session.send_rpc(bootstrapRPC)
    session.close()

    dataElem = reply.find("nc:data", namespaces=NSMAP)
    x = dataElem.find("nc:result", namespaces=NSMAP)
    if x is not None:
        print(x.text)
    else:
        print("not found")
Exemplo n.º 5
0
import numpy as np
from lxml import etree
from netconf import server, util, nsmap_add, NSMAP
from pyangbind.lib.serialise import pybindIETFXMLEncoder, pybindIETFXMLDecoder
from pyangbind.lib import pybindJSON
from six.moves import configparser

sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))

from agent_core import AgentCore
from bindings import bindingConfiguration

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

nsmap_add("blueSPACE-DRoF-configuration", "urn:blueSPACE-DRoF-configuration")
nsmap_add("blueSPACE-DRoF-TP-capability", "urn:blueSPACE-DRoF-TP-capability")


class NETCONFServer(object):
    """
    This is a class for NETCONF server module.
    """
    def __init__(self, username, password, port, agent):
        """
        The constructor for the NETCONF Server class.

        :param username: username to allow the NETCONF server
        :type username: str
        :param password: password to allow the NETCONF server
        :type password: str
Exemplo n.º 6
0
from netconf import nsmap_add, NSMAP
from prompt_toolkit import prompt
from prompt_toolkit.history import FileHistory
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.completion import WordCompleter

nc_completer = WordCompleter(['exit', 'raise_alarm'], ignore_case=True)

data_path = os.path.join(os.path.dirname(__file__), 'data')

ns_file_map = {}
ns_file_map['acc-devm'] = os.path.join(data_path, 'acc-devm-data.xml')

# nsmap_add("sys", "urn:ietf:params:xml:ns:yang:ietf-system")
for ns in ns_file_map:
    nsmap_add(ns, ':'.join(("urn:ccsa:yang", ns)))

# nsmap_add('ncEvent', 'urn:ietf:params:xml:ns:netconf:notification:1.0')

logger = logging.getLogger(__name__)


def date_time_string(dt):
    tz = dt.strftime("%z")
    s = dt.strftime("%Y-%m-%dT%H:%M:%S.%f")
    if tz:
        s += " {}:{}".format(tz[:-2], tz[-2:])
    return s


class SystemServer(object):
Exemplo n.º 7
0
from lxml import etree
from netconf import nsmap_add, NSMAP
from netconf import server, util
from pyangbind.lib.serialise import pybindIETFXMLEncoder, pybindIETFXMLDecoder

# from callback import *
import bindingConnection
import bindingTopology
from bindingConnection import node_connectivity

__author__ = "Laura Rodriguez Navas <*****@*****.**>"
__copyright__ = "Copyright 2018, CTTC"

logging.basicConfig(level=logging.DEBUG)

nsmap_add("node-topology", "urn:node-topology")
nsmap_add("node-connectivity", "urn:node-connectivity")


class NetconfServer(object):
    def __init__(self, username, password, port):
        auth = server.SSHUserPassController(username=username,
                                            password=password)
        self.server = server.NetconfSSHServer(server_ctl=auth,
                                              server_methods=self,
                                              port=port,
                                              debug=False)
        self.node_topology = None
        self.node_connectivity = node_connectivity()

    def close(self):
Exemplo n.º 8
0
#
from __future__ import absolute_import, division, unicode_literals, print_function, nested_scopes
import getpass
import logging
from netconf import NSMAP, qmap, nsmap_add
import netconf.util as ncutil
import netconf.error as ncerror
import netconf.server as ncserver

logger = logging.getLogger(__name__)
nc_server = None
NC_PORT = None
NC_DEBUG = True

mock_module = "urn:mock:module"
nsmap_add('xmlns', 'http://tail-f.com/ns/ncs')


class MockMethods(object):
    NCFILTER = qmap("nc") + "filter"
    """This is an abstract class that is used to document the server methods functionality

    The server return not-implemented if the method is not found in the methods object,
    so feel free to use duck-typing here (i.e., no need to inherit)
    """

    def nc_append_capabilities(self, capabilities):  # pylint: disable=W0613
        """The server should append any capabilities it supports to capabilities"""
        ncutil.subelm(capabilities, "capability").text = mock_module
        ncutil.subelm(capabilities,
                      "capability").text = "urn:ietf:params:netconf:capability:xpath:1.0"