def __init__(self, absPath, maxAttributes):
        self.keyChain = KeyChain("pib-memory:", "tpm-memory:")
        self.keyChain.createIdentityV2("/test/identity")
        self.validator = Validator(
            ValidationPolicyFromPib(self.keyChain.getPib()))
        # , filename, groupSize, nAttributes, absPath, keepData = False):

        # sys.stderr.write ("Using NDN-ABS authority, signer, and verifier database from %s\n" % absPath)
        self.db = ndnabs.PickleDb(absPath)

        self.signer = ndnabs.Signer(self.db)
        self.verifier = ndnabs.Verifier(self.db)

        try:
            info = self.signer.get_public_params_info()
            if info.getName().getPrefix(
                    -2).toUri() != "/icn2019/test/authority":
                raise RuntimeError(
                    'NDN-ABS authority exists, but not setup for experiment. Use `ndnabs setup -f /icn2019/test/authority` to force-setup the authority'
                )
        except:
            raise RuntimeError(
                "Public parameters are not properly installed for the signer/verifier"
            )

        maxAttributes = [
            b'attribute%d' % i for i in range(1, maxAttributes + 1)
        ]

        for attr in maxAttributes:
            if not attr in self.signer.get_attributes():
                raise RuntimeError(
                    "%s attribute missing. Generate attributes for the experiment using `ndnabs gen-secret %s | ndnabs install-secret`"
                    % (str(attr, 'utf-8'), ' '.join(
                        [str(i, 'utf-8') for i in maxAttributes])))
Exemple #2
0
def main():
    face = Face("localhost")

    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(
      IdentityManager(identityStorage, privateKeyStorage), None)
    keyChain.setFace(face)

    # Initialize the storage.
    keyName = Name("/testname/DSK-reposerver")
    certificateName = keyName.getSubName(0, keyName.size() - 1).append(
      "KEY").append(keyName[-1]).append("ID-CERT").append("0")
    identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_PUBLIC_KEY_DER))
    privateKeyStorage.setKeyPairForKeyName(
      keyName, DEFAULT_PUBLIC_KEY_DER, DEFAULT_PRIVATE_KEY_DER)

    echo = RepoServer(keyChain, certificateName)
    prefix = Name("/ndn/ucla.edu/bms")
    dump("Register prefix", prefix.toUri())
    face.registerPrefix(prefix, echo.onInterest, echo.onRegisterFailed)

    while True: 
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)

    face.shutdown()
Exemple #3
0
def main():
    if len(sys.argv) < 2:
        print("Usage:", sys.argv[0], "command-prefix", file=sys.stderr)
        return -1
    else:
        command_prefix = sys.argv[1]

    logging.basicConfig(format='[%(asctime)s]%(levelname)s:%(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S',
                        level=logging.INFO)

    event_loop = asyncio.get_event_loop()
    face = Face()
    keychain = KeyChain()
    face.setCommandSigningInfo(keychain, keychain.getDefaultCertificateName())
    server = Server(face, command_prefix)

    async def face_loop():
        nonlocal face, server
        while server.running:
            face.processEvents()
            await asyncio.sleep(0.01)

    try:
        event_loop.run_until_complete(face_loop())
    finally:
        event_loop.close()
def benchmarkDecodeDataSeconds(nIterations, useCrypto, encoding):
    """
    Loop to decode a data packet nIterations times.

    :param int nIterations: The number of iterations.
    :param bool useCrypto: If true, verify the signature.  If false, don't
      verify.
    :param Blob encoding: The wire encoding to decode.
    """
    # Initialize the private key storage in case useCrypto is true.
    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
                        SelfVerifyPolicyManager(identityStorage))
    keyName = Name("/testname/DSK-123")
    certificateName = keyName.getSubName(
        0,
        keyName.size() - 1).append("KEY").append(
            keyName[-1]).append("ID-CERT").append("0")
    identityStorage.addKey(keyName, KeyType.RSA,
                           Blob(DEFAULT_RSA_PUBLIC_KEY_DER))

    start = getNowSeconds()
    for i in range(nIterations):
        data = Data()
        data.wireDecode(encoding)

        if useCrypto:
            keyChain.verifyData(data, onVerified, onVerifyFailed)

    finish = getNowSeconds()

    return finish - start
Exemple #5
0
    def __init__(self, face, encryptResult, link = None):
        # Set up face
        self.face = face
        self._encryptResult = encryptResult
        self._link = link

        self.databaseFilePath = "policy_config/test_consumer_dpu.db"
        try:
            os.remove(self.databaseFilePath)
        except OSError:
            # no such file
            pass

        self.groupName = Name("/org/openmhealth/haitao")

        # Set up the keyChain.
        identityStorage = BasicIdentityStorage()
        privateKeyStorage = FilePrivateKeyStorage()
        self.keyChain = KeyChain(
          IdentityManager(identityStorage, privateKeyStorage),
          NoVerifyPolicyManager())
        # Authorized identity
        identityName = Name("/ndn/edu/basel/dpu")
        # Function name: the function that this DPU provides
        self._functionName = "bounding_box"
        self._identityName = identityName
        
        self.certificateName = self.keyChain.createIdentityAndCertificate(identityName)
        # TODO: if using BasicIdentityStorage and FilePrivateKeyStorage
        #   For some reason this newly generated cert is not installed by default, calling keyChain sign later would result in error
        #self.keyChain.installIdentityCertificate()
        
        self.face.setCommandSigningInfo(self.keyChain, self.certificateName)

        consumerKeyName = IdentityCertificate.certificateNameToPublicKeyName(self.certificateName)
        consumerCertificate = identityStorage.getCertificate(self.certificateName)
        self.consumer = Consumer(
          face, self.keyChain, self.groupName, identityName,
          Sqlite3ConsumerDb(self.databaseFilePath))

        # TODO: Read the private key to decrypt d-key...this may or may not be ideal
        base64Content = None
        with open(privateKeyStorage.nameTransform(consumerKeyName.toUri(), ".pri")) as keyFile:
            print privateKeyStorage.nameTransform(consumerKeyName.toUri(), ".pri")
            base64Content = keyFile.read()
            #print base64Content
        der = Blob(base64.b64decode(base64Content), False)
        self.consumer.addDecryptionKey(consumerKeyName, der)

        self.memoryContentCache = MemoryContentCache(self.face)
        self.memoryContentCache.registerPrefix(identityName, self.onRegisterFailed, self.onDataNotFound)
        self.memoryContentCache.add(consumerCertificate)

        accessRequestInterest = Interest(Name(self.groupName).append("read_access_request").append(self.certificateName).appendVersion(int(time.time())))
        self.face.expressInterest(accessRequestInterest, self.onAccessRequestData, self.onAccessRequestTimeout)
        print "Access request interest name: " + accessRequestInterest.getName().toUri()

        self._tasks = dict()

        return
    def setUp(self):
        testCertDirectory = 'policy_config/certs'
        self.testCertFile = os.path.join(testCertDirectory, 'test.cert')

        self.identityStorage = MemoryIdentityStorage()
        self.privateKeyStorage = MemoryPrivateKeyStorage()
        self.identityManager = IdentityManager(self.identityStorage,
                self.privateKeyStorage)
        self.policyManager = ConfigPolicyManager('policy_config/simple_rules.conf')

        self.identityName = Name('/TestConfigPolicyManager/temp')
        # to match the anchor cert
        keyName = Name(self.identityName).append('ksk-1416010123')
        self.privateKeyStorage.setKeyPairForKeyName(
          keyName, KeyType.RSA, TEST_RSA_PUBLIC_KEY_DER, TEST_RSA_PRIVATE_KEY_DER)
        self.identityStorage.addKey(
          keyName, KeyType.RSA, Blob(TEST_RSA_PUBLIC_KEY_DER))

        cert = self.identityManager.selfSign(keyName)
        self.identityStorage.setDefaultKeyNameForIdentity(keyName)
        self.identityManager.addCertificateAsDefault(cert)

        self.keyChain = KeyChain(self.identityManager, self.policyManager)
        self.keyName = keyName

        self.face = Face()
def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

    if sys.version_info[0] <= 2:
        userPrefixUri = raw_input("Enter your user prefix (e.g. /a): ")
    else:
        userPrefixUri = input("Enter your user prefix (e.g. /a): ")
    if userPrefixUri == "":
        dump("You must enter a user prefix")
        return

    syncPrefixUri = "/sync"
    nUserPrefixes = 2
    maxPublishedSequenceNo = 3

    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    # Set up the KeyChain.
    keyChain = KeyChain("pib-memory:", "tpm-memory:")
    keyChain.importSafeBag(
        SafeBag(Name("/testname/KEY/123"),
                Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False),
                Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False)))
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    producer = Producer(face, keyChain, Name(syncPrefixUri), userPrefixUri,
                        nUserPrefixes, maxPublishedSequenceNo)

    # The main event loop.
    while True:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
Exemple #8
0
def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    memberName = Name("/first/user")
    memberKeyName = Name(memberName).append(Name("/KEY/%0C%87%EB%E6U%27B%D6"))

    memberKeyChain = KeyChain("pib-memory:", "tpm-memory:")
    memberKeyChain.importSafeBag(SafeBag
      (memberKeyName, Blob(MEMBER_PRIVATE_KEY, False),
       Blob(MEMBER_PUBLIC_KEY, False)))
    # TODO: Use a real Validator.
    decryptor = DecryptorV2(
      memberKeyChain.getPib().getIdentity(memberName).getDefaultKey(),
      ValidatorNull(), memberKeyChain, face)

    contentPrefix = Name("/testname/content")
    contentNamespace = Namespace(contentPrefix)
    contentNamespace.setFace(face)
    contentNamespace.setDecryptor(decryptor)

    enabled = [True]
    def onSegmentedObject(objectNamespace):
        dump("Got segmented content", objectNamespace.obj.toRawStr())
        enabled[0] = False
    SegmentedObjectHandler(contentNamespace, onSegmentedObject).objectNeeded()

    while enabled[0]:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
def benchmarkDecodeDataSeconds(nIterations, useCrypto, keyType, encoding):
    """
    Loop to decode a data packet nIterations times.

    :param int nIterations: The number of iterations.
    :param bool useCrypto: If true, verify the signature.  If false, don't
      verify.
    :param KeyType keyType: KeyType.RSA or EC, used if useCrypto is True.
    :param Blob encoding: The wire encoding to decode.
    :return: The number of seconds for all iterations.
    :rtype: float
    """
    # Initialize the KeyChain in case useCrypto is true.
    keyChain = KeyChain("pib-memory:", "tpm-memory:")
    # This puts the public key in the pibImpl used by the SelfVerifyPolicyManager.
    keyChain.importSafeBag(SafeBag
      (Name("/testname/KEY/123"),
       Blob(DEFAULT_EC_PRIVATE_KEY_DER if keyType == KeyType.EC
            else DEFAULT_RSA_PRIVATE_KEY_DER, False),
       Blob(DEFAULT_EC_PUBLIC_KEY_DER if keyType == KeyType.EC
            else DEFAULT_RSA_PUBLIC_KEY_DER, False)))
    validator = Validator(ValidationPolicyFromPib(keyChain.getPib()))

    start = getNowSeconds()
    for i in range(nIterations):
        data = Data()
        data.wireDecode(encoding)

        if useCrypto:
            validator.validate(data,onVerifySuccess, onVerifyFailed)

    finish = getNowSeconds()

    return finish - start
Exemple #10
0
    def __init__(self, data_size, verbose=False):
        # create a KeyChain for signing data packets
        self._key_chain = KeyChain()
        self._is_done = False
        self._num_interests = 0
        #  self._keyChain.createIdentityV2(Name("/ndn/identity"))

        # host data at the local forwarder
        self._face = Face()

        # immutable byte array to use as data
        self._byte_array = bytes(data_size)

        # the number of bytes contained in each data packet
        self._data_size = data_size

        # the verbosity of diagnostic information
        self._verbose = verbose

        # keep track of if the first interest has been recieved (for timing)
        self._is_first_interst = True

        # keep track of various performance metrics:
        self._interests_satisfied = 0
        self._interests_recieved = 0
        self._data_sent = 0
        self._elapsed_time = {}
        self._initial_time = {}
        self._final_time = {}

        print("Producer instance created.")
Exemple #11
0
    def __init__(self, networkName, nodeName):
        super(IotConsole, self).__init__()

        self.deviceSuffix = Name(nodeName)
        self.networkPrefix = Name(networkName)
        self.prefix = Name(self.networkPrefix).append(self.deviceSuffix)

        self._identityStorage = IotIdentityStorage()
        self._policyManager = IotPolicyManager(self._identityStorage)
        self._identityManager = IotIdentityManager(self._identityStorage)
        self._keyChain = KeyChain(self._identityManager, self._policyManager)

        self._policyManager.setEnvironmentPrefix(self.networkPrefix)
        self._policyManager.setTrustRootIdentity(self.prefix)
        self._policyManager.setDeviceIdentity(self.prefix)
        self._policyManager.updateTrustRules()

        self.foundCommands = {}
        self.unconfiguredDevices = []

        # TODO: use xDialog in XWindows
        self.ui = Dialog(backtitle='NDN IoT User Console', height=18, width=78)

        trolliusLogger = logging.getLogger('trollius')
        trolliusLogger.addHandler(logging.StreamHandler())
    def setUp(self):
        testCertDirectory = 'policy_config/certs'
        self.testCertFile = os.path.join(testCertDirectory, 'test.cert')

        self.pibImpl = PibMemory()
        self.tpmBackEnd = TpmBackEndMemory()
        self.policyManager = ConfigPolicyManager(
            'policy_config/simple_rules.conf', CertificateCacheV2())

        self.identityName = Name('/TestConfigPolicyManager/temp')
        # to match the anchor cert
        self.keyName = Name(
            self.identityName).append("KEY").append("ksk-1416010123")
        self.pibImpl.addKey(self.identityName, self.keyName,
                            TEST_RSA_PUBLIC_KEY_DER)
        # Set the password to None since we have an unencrypted PKCS #8 private key.
        self.tpmBackEnd.importKey(self.keyName, TEST_RSA_PRIVATE_KEY_PKCS8,
                                  None)

        self.keyChain = KeyChain(self.pibImpl, self.tpmBackEnd,
                                 self.policyManager)

        pibKey = self.keyChain.getPib().getIdentity(self.identityName).getKey(
            self.keyName)
        # selfSign adds to the PIB.
        self.keyChain.selfSign(pibKey)
Exemple #13
0
    def wrap_content(self, name, content, key=None, key_locator=None):
        """
        @param name - name of the data
        @param content - data to be wrapped
        @param key - key used to sign the data
        @return the content object created
        wraps the given name and content into a content object
        """
        co = Data(Name(name))
        co.setContent(content)
        co.getMetaInfo().setFreshnessPeriod(5000)
        co.getMetaInfo().setFinalBlockID(Name("/%00%09")[0])

        identityStorage = MemoryIdentityStorage()
        privateKeyStorage = MemoryPrivateKeyStorage()
        identityManager = IdentityManager(identityStorage, privateKeyStorage)
        keyChain = KeyChain(identityManager, None)

        # Initialize the storage.
        keyName = Name("/ndn/bms/DSK-default")
        certificateName = keyName.getSubName(0, keyName.size() - 1).append(
                "KEY").append(keyName[-1]).append("ID-CERT").append("0")
        identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_PUBLIC_KEY_DER))
        privateKeyStorage.setKeyPairForKeyName(keyName, DEFAULT_PUBLIC_KEY_DER, 
                DEFAULT_PRIVATE_KEY_DER)

        keyChain.sign(co, certificateName)

        _data = co.wireEncode()

        return _data.toRawStr()
Exemple #14
0
def benchmarkDecodeDataSeconds(nIterations, useCrypto, keyType, encoding):
    """
    Loop to decode a data packet nIterations times.

    :param int nIterations: The number of iterations.
    :param bool useCrypto: If true, verify the signature.  If false, don't
      verify.
    :param KeyType keyType: KeyType.RSA or EC, used if useCrypto is True.
    :param Blob encoding: The wire encoding to decode.
    :return: The number of seconds for all iterations.
    :rtype: float
    """
    # Initialize the private key storage in case useCrypto is true.
    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
                        SelfVerifyPolicyManager(identityStorage))
    keyName = Name("/testname/DSK-123")
    identityStorage.addKey(
      keyName, keyType, Blob(
      DEFAULT_EC_PUBLIC_KEY_DER if keyType == KeyType.ECDSA else DEFAULT_RSA_PUBLIC_KEY_DER))

    start = getNowSeconds()
    for i in range(nIterations):
        data = Data()
        data.wireDecode(encoding)

        if useCrypto:
            keyChain.verifyData(data, onVerified, onValidationFailed)

    finish = getNowSeconds()

    return finish - start
def main():
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(
      IdentityManager(identityStorage, privateKeyStorage), None)
    keyChain.setFace(face)

    # Initialize the storage.
    keyName = Name("/testname/DSK-123")
    certificateName = keyName.getSubName(0, keyName.size() - 1).append(
      "KEY").append(keyName[-1]).append("ID-CERT").append("0")
    identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER))
    privateKeyStorage.setKeyPairForKeyName(
      keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER)

    echo = Echo(keyChain, certificateName)
    prefix = Name("/testecho")
    dump("Register prefix", prefix.toUri())
    face.registerPrefix(prefix, echo.onInterest, echo.onRegisterFailed)

    while echo._responseCount < 1:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)    

    face.shutdown()
def main():
    face = Face()
    keychain = KeyChain()
    face.setCommandSigningInfo(keychain, keychain.getDefaultCertificateName())

    async def face_loop():
        nonlocal face
        while True:
            face.processEvents()
            await asyncio.sleep(0.001)

    parser = argparse.ArgumentParser(description='segmented insert client')
    parser.add_argument('-r', '--repo_name',
                        required=True, help='Name of repo')
    parser.add_argument('-p', '--process_id',
                        required=True, help="Process ID")
    args = parser.parse_args()

    logging.basicConfig(format='[%(asctime)s]%(levelname)s:%(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S',
                        level=logging.INFO)

    client = CommandChecker(face, keychain)
    event_loop = asyncio.get_event_loop()
    event_loop.create_task(face_loop())
    event_loop.run_until_complete(client.check_delete(args.repo_name, int(args.process_id)))
    def setUp(self):
        # set up the keychain so we can sign data
        self.identityStorage = MemoryIdentityStorage()
        self.privateKeyStorage = MemoryPrivateKeyStorage()
        self.keyChain = KeyChain(
            IdentityManager(self.identityStorage, self.privateKeyStorage))
        self.privateKeyStorage = MemoryPrivateKeyStorage()

        # not using keychain for verification so we don't need to set the
        # policy manager
        self.keyChain = KeyChain(
            IdentityManager(self.identityStorage, self.privateKeyStorage))
        self.identityName = Name('/SecurityTestSecRule/Basic/Longer')
        keyName = Name(self.identityName).append('ksk-2439872')
        self.defaultCertName = self._certNameFromKeyName(keyName)
        self.identityStorage.addKey(keyName, KeyType.RSA,
                                    Blob(DEFAULT_RSA_PUBLIC_KEY_DER))
        self.privateKeyStorage.setKeyPairForKeyName(
            keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER,
            DEFAULT_RSA_PRIVATE_KEY_DER)

        keyName = Name('/SecurityTestSecRule/Basic/ksk-0923489')
        self.identityStorage.addKey(keyName, KeyType.RSA,
                                    Blob(DEFAULT_RSA_PUBLIC_KEY_DER))
        self.privateKeyStorage.setKeyPairForKeyName(
            keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER,
            DEFAULT_RSA_PRIVATE_KEY_DER)
        self.shortCertName = self._certNameFromKeyName(keyName, -2)
Exemple #18
0
    def __init__(self, producerName, namePrefix):
        self.configPrefix = Name(namePrefix)
        prefix_pullService = "/picasso/pull_Service/"
        self.prefix_pullService = Name(prefix_pullService)
        self.Datamessage_size = 2000000  #20MB --> Max Size from modified NDN
        self.window = 1
        self.producerName = producerName
        self.outstanding = dict()
        self.isDone = False
        self.keyChain = KeyChain()
        self.face = Face("127.0.0.1")
        self.script_path = os.path.abspath(
            __file__)  # i.e. /path/to/dir/foobar.py
        self.script_dir = os.path.split(
            self.script_path)[0]  #i.e. /path/to/dir/
        self.interestLifetime = 12000000
        self.num_deployedContainer = 0
        self.lastChunk_window = 0
        self.lastChunk_sent = 0

        folder_name = "SEG_repository/"
        self.repo_path = os.path.join(self.script_dir, folder_name)
        if not os.path.exists(self.repo_path):
            os.makedirs(self.repo_path)

        folder_name = "Migration_cost/"
        self.timestamp_path = os.path.join(self.script_dir, folder_name)
        if not os.path.exists(self.timestamp_path):
            os.makedirs(self.timestamp_path)
def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

    interest = Interest()
    interest.wireDecode(TlvInterest)

    # Use a hard-wired secret for testing. In a real application the signer
    # ensures that the verifier knows the shared key and its keyName.
    key = Blob(bytearray([
       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15,
      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31
    ]))

    if KeyChain.verifyInterestWithHmacWithSha256(interest, key):
      dump("Hard-coded interest signature verification: VERIFIED")
    else:
      dump("Hard-coded interest signature verification: FAILED")

    freshInterest = Interest(Name("/ndn/abc"))
    freshInterest.setMustBeFresh(False)
    keyName = Name("key1")
    dump("Signing fresh interest", freshInterest.getName().toUri())
    KeyChain.signWithHmacWithSha256(freshInterest, key, keyName)

    if KeyChain.verifyInterestWithHmacWithSha256(freshInterest, key):
      dump("Freshly-signed interest signature verification: VERIFIED")
    else:
      dump("Freshly-signed interest signature verification: FAILED")
Exemple #20
0
class Producer(object):
    def __init__(self):
        self.keyChain = KeyChain()
        self.isDone = False

    def run(self, namespace):
        # Create a connection to the local forwarder over a Unix socket
        face = Face()

        prefix = Name(namespace)

        # Use the system default key chain and certificate name to sign commands.
        face.setCommandSigningInfo(self.keyChain, \
                                   self.keyChain.getDefaultCertificateName())

        # Also use the default certificate name to sign Data packets.
        face.registerPrefix(prefix, self.onInterest, self.onRegisterFailed)

        print "Registering prefix", prefix.toUri()

        # Run the event loop forever. Use a short sleep to
        # prevent the Producer from using 100% of the CPU.
        while not self.isDone:
            face.processEvents()
            time.sleep(0.01)

    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        filepath = 'cpu.txt'
        counter = 0.0
        avg = 0
        fp = open(filepath)
        line = fp.readline()
        cnt = 0
        while line:
            conv_int = float(line)
            line = fp.readline()
            #print("Line {}: {}".format(cnt, line.strip()))
            counter = counter + conv_int
            cnt += 1
        total = (cnt)
        #print (total)
        avg = (counter) / total
        #print (avg)
        interestName = interest.getName()

        data = Data(interestName)
        data.setContent("CPU avg:" + str(avg))

        hourMilliseconds = 3600 * 1000
        data.getMetaInfo().setFreshnessPeriod(hourMilliseconds)

        self.keyChain.sign(data, self.keyChain.getDefaultCertificateName())

        transport.send(data.wireEncode().toBuffer())

        print "Replied to: %s" % interestName.toUri()

    def onRegisterFailed(self, prefix):
        print "Register failed for prefix", prefix.toUri()
        self.isDone = True
def main():
    interest = Interest()
    interest.wireDecode(TlvInterest)

    # Use a hard-wired secret for testing. In a real application the signer
    # ensures that the verifier knows the shared key and its keyName.
    key = Blob(bytearray([
       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15,
      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31
    ]))

    if KeyChain.verifyInterestWithHmacWithSha256(interest, key):
      dump("Hard-coded interest signature verification: VERIFIED")
    else:
      dump("Hard-coded interest signature verification: FAILED")

    freshInterest = Interest(Name("/ndn/abc"))
    freshInterest.setMustBeFresh(False)
    keyName = Name("key1")
    dump("Signing fresh interest", freshInterest.getName().toUri())
    KeyChain.signWithHmacWithSha256(freshInterest, key, keyName)

    if KeyChain.verifyInterestWithHmacWithSha256(freshInterest, key):
      dump("Freshly-signed interest signature verification: VERIFIED")
    else:
      dump("Freshly-signed interest signature verification: FAILED")
Exemple #22
0
def main():
    async def face_loop():
        nonlocal face, repo
        while repo.running:
            face.processEvents()
            await asyncio.sleep(0.001)

    config = get_yaml()
    logging.info(config)

    face = Face()
    keychain = KeyChain()
    face.setCommandSigningInfo(keychain, keychain.getDefaultCertificateName())
    # storage = LevelDBStorage(config['db_config']['leveldb']['dir'])
    storage = MongoDBStorage(config['db_config']['mongodb']['db'],
                             config['db_config']['mongodb']['collection'])
    read_handle = ReadHandle(face, keychain, storage)
    write_handle = WriteCommandHandle(face, keychain, storage, read_handle)
    delete_handle = DeleteCommandHandle(face, keychain, storage)
    tcp_bulk_insert_handle = TcpBulkInsertHandle(
        storage, read_handle, config['tcp_bulk_insert']['addr'],
        config['tcp_bulk_insert']['port'])

    repo = Repo(Name(config['repo_config']['repo_name']), face, storage,
                read_handle, write_handle, delete_handle,
                tcp_bulk_insert_handle)

    repo.listen()  # my nfd is broken...

    event_loop = asyncio.get_event_loop()
    try:
        event_loop.run_until_complete(face_loop())
    finally:
        event_loop.close()
    def __init__(self, prefix, transferfile):
        self.keyChain = KeyChain()
        self.prefix = Name(prefix)
        self.isDone = False
        self.transferfile = transferfile

        # Initialize list for Data packet storage.
        # We'll treat the indices as equivalent to the sequence
        # number requested by Interests.
        self.data = []

        f = open(transferfile, 'rb')
        imgdata = f.read()
        chunks = list(chunkstring(imgdata, 8192))
        print len(chunks)

        finalBlock = Name.Component.fromNumberWithMarker(len(chunks) - 1, 0x00)
        hourMilliseconds = 3600 * 1000

        # Pre-generate and sign all of Data we can serve.
        # We can also set the FinalBlockID in each packet
        # ahead of time because we know the entire sequence.

        for i in range(0, len(chunks)):
            dataName = Name(prefix).appendSegment(i)
            print dataName

            data = Data(dataName)
            data.setContent(chunks[i])
            data.getMetaInfo().setFinalBlockID(finalBlock)
            data.getMetaInfo().setFreshnessPeriod(hourMilliseconds)

            self.keyChain.sign(data, self.keyChain.getDefaultCertificateName())

            self.data.append(data)
Exemple #24
0
    def __init__(self, namePrefix):
        self.outstanding = dict()
        self.isDone = False
        self.keyChain = KeyChain()
        self.face = Face("127.0.0.1")
        self.configPrefix = Name(namePrefix)
        self.script_path = os.path.abspath(
            __file__)  # i.e. /path/to/dir/foobar.py
        self.script_dir = os.path.split(
            self.script_path)[0]  #i.e. /path/to/dir/
        self.interestLifetime = 800000
        #self.Datamessage_size = 1999000
        self.Datamessage_size = 19990000
        folder_name = "SC_repository/"
        rel_path = os.path.join(self.script_dir, folder_name)
        prefix_startDE = "/picasso/start_de/"
        self.prefix_startDE = Name(prefix_startDE)
        self.prefix_deployService = '/picasso/service_deployment_push/'
        self.json_server_Spec_default = {  # This is only an skeleton
            'par': {  #  service parameters
                'serviceName': 'nameOfService',
                'imageName': 'NameOfImageToIstantiateService',
                'imageSize': 'sizeOfImage',
                'maxConReq': 'maxNumConcurrentRequestsThatAnIntanceCanHandle',
                'startUpTime': 'timeToInstatiateService'
            },
            'QoS': {  #QoS parameters expected from the service
                'responseTime': 'resposeTimeExpectedFromService',
                'availability': 'availabilityExpectedFromService',
                'numConReq': 'numConcurrentRequestsToBeHandledByService'
            }
        }

        if not os.path.exists(rel_path):
            os.makedirs(rel_path)
Exemple #25
0
    def __init__(self, prefix="/ndn/edu/ucla/remap/music/list"):

        logging.basicConfig()
        '''#这些log是干嘛的myIP="192.168.1.1",lightIP="192.168.1.50",
        self.log = logging.getLogger("RegisterSongList")
        self.log.setLevel(logging.DEBUG)
        sh = logging.StreamHandler()
        sh.setLevel(logging.DEBUG)
        self.log.addHandler(sh)
        fh = logging.FileHandler("RegisterSongList.log")
        fh.setLevel(logging.INFO)
        self.log.addHandler(fh)'''
        self.device = "PC3"
        self.deviceComponent = Name.Component(self.device)
        self.excludeDevice = None
        #self.songList = originalList

        #security?
        self.prefix = Name(prefix)
        self.changePrefix = Name("/ndn/edu/ucla/remap/music/storage")
        self.keychain = KeyChain()
        self.certificateName = self.keychain.getDefaultCertificateName()

        self.address = ""
        self._isStopped = True
Exemple #26
0
 def init_network(self, prefix):
     self.prefix = prefix
     self.face = Face()
     self.keychain = KeyChain()
     self.face.setCommandSigningInfo(
         self.keychain, self.keychain.getDefaultCertificateName())
     self.face.registerPrefix(self.prefix, None, self.on_register_failed)
Exemple #27
0
    def __init__(self, face, groupManagerName, dataType, dKeyDatabaseFilePath):
        # Set up face
        self.face = face
        #self.loop = eventLoop

        # Set up the keyChain.
        identityStorage = MemoryIdentityStorage()
        privateKeyStorage = MemoryPrivateKeyStorage()
        self.keyChain = KeyChain(
            IdentityManager(identityStorage, privateKeyStorage),
            NoVerifyPolicyManager())

        self.certificateName = self.keyChain.createIdentityAndCertificate(
            groupManagerName)

        self.dKeyDatabaseFilePath = dKeyDatabaseFilePath

        self.manager = GroupManager(
            groupManagerName, dataType,
            Sqlite3GroupManagerDb(self.dKeyDatabaseFilePath), 2048, 1,
            self.keyChain)

        self.memoryContentCache = MemoryContentCache(self.face)

        self.memoryContentCache.registerPrefix(groupManagerName,
                                               self.onRegisterFailed,
                                               self.onDataNotFound)

        self.needToPublishGroupKeys = False
        return
Exemple #28
0
def main():
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
                        None)
    keyChain.setFace(face)

    # Initialize the storage.
    keyName = Name("/testname/DSK-123")
    certificateName = keyName.getSubName(
        0,
        keyName.size() - 1).append("KEY").append(
            keyName[-1]).append("ID-CERT").append("0")
    identityStorage.addKey(keyName, KeyType.RSA,
                           Blob(DEFAULT_RSA_PUBLIC_KEY_DER))
    privateKeyStorage.setKeyPairForKeyName(keyName, KeyType.RSA,
                                           DEFAULT_RSA_PUBLIC_KEY_DER,
                                           DEFAULT_RSA_PRIVATE_KEY_DER)

    echo = Echo(keyChain, certificateName)
    prefix = Name("/testecho")
    dump("Register prefix", prefix.toUri())
    face.registerPrefix(prefix, echo.onInterest, echo.onRegisterFailed)

    while echo._responseCount < 1:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)

    face.shutdown()
def main():
    data = Data()
    data.wireDecode(TlvData)

    # Use a hard-wired secret for testing. In a real application the signer
    # ensures that the verifier knows the shared key and its keyName.
    key = Blob(bytearray([
       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15,
      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31
    ]))

    if KeyChain.verifyDataWithHmacWithSha256(data, key):
      dump("Hard-coded data signature verification: VERIFIED")
    else:
      dump("Hard-coded data signature verification: FAILED")

    freshData = Data(Name("/ndn/abc"))
    signature = HmacWithSha256Signature()
    signature.getKeyLocator().setType(KeyLocatorType.KEYNAME)
    signature.getKeyLocator().setKeyName(Name("key1"))
    freshData.setSignature(signature)
    freshData.setContent("SUCCESS!")
    dump("Signing fresh data packet", freshData.getName().toUri())
    KeyChain.signWithHmacWithSha256(freshData, key)

    if KeyChain.verifyDataWithHmacWithSha256(freshData, key):
      dump("Freshly-signed data signature verification: VERIFIED")
    else:
      dump("Freshly-signed data signature verification: FAILED")
Exemple #30
0
def main():
    if len(argv) < 3:
        dump("Usage:", argv[0], "<repo-command-prefix> <fetch-prefix>")
        return

    repoCommandPrefix = Name(argv[1])
    repoDataPrefix = Name(argv[2])

    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()
    # Use the system default key chain and certificate name to sign commands.
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    enabled = [True]

    def onInsertStarted():
        # nonlocal enabled
        dump("Insert started for", repoDataPrefix.toUri())
        enabled[0] = False

    def onFailed():
        # nonlocal enabled
        enabled[0] = False

    requestInsert(face, repoCommandPrefix, repoDataPrefix, onInsertStarted,
                  onFailed)

    # Run until all the data is sent.
    while enabled[0]:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)

    face.shutdown()
Exemple #31
0
    def test_self_verification(self):
        policyManager = SelfVerifyPolicyManager(self.identityStorage)
        keyChain = KeyChain(self.identityManager, policyManager)

        identityName  = Name('TestValidator/RsaSignatureVerification')
        keyChain.createIdentityAndCertificate(identityName)

        data = Data(Name('/TestData/1'))
        keyChain.signByIdentity(data, identityName)

        vr = doVerify(policyManager, data)

        self.assertFalse(vr.hasFurtherSteps,
                "SelfVerifyPolicyManager returned a ValidationRequest")
        self.assertEqual(vr.failureCount, 0,
            "Verification of identity-signed data failed")
        self.assertEqual(vr.successCount, 1,
            "Verification success called {} times instead of 1".format(
            vr.successCount))

        data2 = Data(Name('/TestData/2'))

        vr = doVerify(policyManager,
                data2)

        self.assertFalse(vr.hasFurtherSteps,
                "SelfVerifyPolicyManager returned a ValidationRequest")
        self.assertEqual(vr.successCount, 0,
            "Verification of unsigned data succeeded")
        self.assertEqual(vr.failureCount, 1,
            "Verification failure callback called {} times instead of 1".format(
            vr.failureCount))
def main():
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()

    # Use the system default key chain and certificate name to sign.
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    objectPrefix = Namespace("/ndn/eb/run/28/description", keyChain)

    dump("Register prefix", objectPrefix.name)
    # Set the face and register to receive Interests.
    objectPrefix.setFace(
        face,
        lambda prefixName: dump("Register failed for prefix", prefixName))

    dump("Preparing data for", objectPrefix.name)
    GeneralizedObjectHandler().setObject(objectPrefix,
                                         Blob("EB run #28. Ham and oats"),
                                         "text/html")

    while True:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
Exemple #33
0
    def __init__(self):
        self.identityStorage = MemoryIdentityStorage()
        self.privateKeyStorage = MemoryPrivateKeyStorage()
        self.keyChain = KeyChain(
            IdentityManager(self.identityStorage, self.privateKeyStorage),
            SelfVerifyPolicyManager(self.identityStorage))
        keyName = Name("/testname/DSK-123")
        self.defaultCertName = keyName[:-1].append("KEY").append(
            keyName[-1]).append("ID-CERT").append("0")

        ecdsaKeyName = Name("/testEcdsa/DSK-123")
        self.ecdsaCertName = ecdsaKeyName[:-1].append("KEY").append(
            ecdsaKeyName[-1]).append("ID-CERT").append("0")

        self.identityStorage.addKey(keyName, KeyType.RSA,
                                    Blob(DEFAULT_RSA_PUBLIC_KEY_DER))
        self.privateKeyStorage.setKeyPairForKeyName(
            keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER,
            DEFAULT_RSA_PRIVATE_KEY_DER)

        self.identityStorage.addKey(ecdsaKeyName, KeyType.ECDSA,
                                    Blob(DEFAULT_EC_PUBLIC_KEY_DER))
        self.privateKeyStorage.setKeyPairForKeyName(
            ecdsaKeyName, KeyType.ECDSA, DEFAULT_EC_PUBLIC_KEY_DER,
            DEFAULT_EC_PRIVATE_KEY_DER)
def main():
    data = Data()
    data.wireDecode(TlvData)

    # Use a hard-wired secret for testing. In a real application the signer
    # ensures that the verifier knows the shared key and its keyName.
    key = Blob(
        bytearray([
            0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
            19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31
        ]))

    if KeyChain.verifyDataWithHmacWithSha256(data, key):
        dump("Hard-coded data signature verification: VERIFIED")
    else:
        dump("Hard-coded data signature verification: FAILED")

    freshData = Data(Name("/ndn/abc"))
    signature = HmacWithSha256Signature()
    signature.getKeyLocator().setType(KeyLocatorType.KEYNAME)
    signature.getKeyLocator().setKeyName(Name("key1"))
    freshData.setSignature(signature)
    freshData.setContent("SUCCESS!")
    dump("Signing fresh data packet", freshData.getName().toUri())
    KeyChain.signWithHmacWithSha256(freshData, key)

    if KeyChain.verifyDataWithHmacWithSha256(freshData, key):
        dump("Freshly-signed data signature verification: VERIFIED")
    else:
        dump("Freshly-signed data signature verification: FAILED")
def benchmarkDecodeDataSeconds(nIterations, useCrypto, encoding):
    """
    Loop to decode a data packet nIterations times.

    :param int nIterations: The number of iterations.
    :param bool useCrypto: If true, verify the signature.  If false, don't
      verify.
    :param Blob encoding: The wire encoding to decode.
    """
    # Initialize the private key storage in case useCrypto is true.
    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
                        SelfVerifyPolicyManager(identityStorage))
    keyName = Name("/testname/DSK-123")
    certificateName = keyName.getSubName(0, keyName.size() - 1).append(
      "KEY").append(keyName[-1]).append("ID-CERT").append("0")
    identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER))

    start = getNowSeconds()
    for i in range(nIterations):
        data = Data()
        data.wireDecode(encoding)

        if useCrypto:
            keyChain.verifyData(data, onVerified, onVerifyFailed)

    finish = getNowSeconds()

    return finish - start
Exemple #36
0
def main():
    face = Face()
    keychain = KeyChain()
    face.setCommandSigningInfo(keychain, keychain.getDefaultCertificateName())
    running = True
    img = None

    interest = Interest(Name("/icear-server/result/example-data/2/deeplab"))
    interest.mustBeFresh = True

    def on_data(_, data):
        # type: (Interest, Data) -> None
        nonlocal running, img
        print(data.name.toUri())
        print(data.content.toBytes())
        running = False
        if data.metaInfo.type == ContentType.NACK:
            print("NACK")
        else:
            img = data.content.toBytes()

    face.expressInterest(interest, on_data)

    while running:
        face.processEvents()
        time.sleep(0.01)

    face.shutdown()

    if img:
        image = Image.open(io.BytesIO(img))
        image.show()
def main():
    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    dataPrefix = "/home/test1/data"
    repoDataPrefix = "/home/test1/data"
    # Set up repo-ng, register prefix for repo-ng's fetch prefix
    # Per configuration file in /usr/local/etc/ndn/repo-ng.conf
    # memCache is not used for now; repo is hoping that the piece of data in question is still being held at nfd
    #memCache = MemoryContentCache(face, 100000)
    #memCache.registerPrefix(Name(repoDataPrefix), onRegisterFailed, onDataNotFound)

    counter = Counter(face, repoDataPrefix)

    interest = Interest(Name(dataPrefix))
    interest.setChildSelector(1)
    interest.setInterestLifetimeMilliseconds(defaultInterestLifetime)
    face.expressInterest(interest, counter.onData, counter.onTimeout)
    
    while True:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(1)
    face.shutdown()
Exemple #38
0
class Producer(object):
    def __init__(self):
        self.keyChain = KeyChain()
        self.isDone = False
        self.maxNdnPacketSize = 0

    def run(self, namespace):
        # Create a connection to the local forwarder over a Unix socket
        #        face = Face()
        face = Face("127.0.0.1")
        prefix = Name(namespace)

        # Use the system default key chain and certificate name to sign commands.
        cert_name = self.keyChain.getDefaultCertificateName()
        face.setCommandSigningInfo(self.keyChain, cert_name)

        # Also use the default certificate name to sign Data packets.
        face.registerPrefix(prefix, self.onInterest, self.onRegisterFailed)

        print "Registering prefix", prefix.toUri()

        self.maxNdnPacketSize = face.getMaxNdnPacketSize()

        # Run the event loop forever. Use a short sleep to
        # prevent the Producer from using 100% of the CPU.
        while not self.isDone:
            face.processEvents()
            time.sleep(0.01)

    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        interestName = interest.getName()

        data = Data(interestName)

        print "Downloading : %s" % interestName.toUri()

        min_char = self.maxNdnPacketSize - 400
        max_char = self.maxNdnPacketSize - 400
        allchar = string.ascii_letters + string.punctuation + string.digits
        rint = randint(min_char, max_char)
        cont = "".join(choice(allchar) for x in range(rint))
        data.setContent(cont)
        time.sleep(2)

        hourMilliseconds = 3600 * 1000
        data.getMetaInfo().setFreshnessPeriod(hourMilliseconds)

        self.keyChain.sign(data, self.keyChain.getDefaultCertificateName())

        transport.send(data.wireEncode().toBuffer())

        print "Replied to: %s" % interestName.toUri()

    def onRegisterFailed(self, prefix):
        print "Register failed for prefix", prefix.toUri()
        self.isDone = True

    def getKeyID(self, key):
        pub_der = key.publickey().exportKey(format="DER")
        return bytearray(hashlib.sha256(pub_der).digest())
Exemple #39
0
class CredentialStorage:
    def __init__(self):
        self.identityStorage = MemoryIdentityStorage()
        self.privateKeyStorage = MemoryPrivateKeyStorage()
        self.keyChain = KeyChain(
            IdentityManager(self.identityStorage, self.privateKeyStorage),
            SelfVerifyPolicyManager(self.identityStorage))
        keyName = Name("/testname/DSK-123")
        self.defaultCertName = keyName.getSubName(
            0,
            keyName.size() - 1).append("KEY").append(
                keyName[-1]).append("ID-CERT").append("0")

        self.identityStorage.addKey(keyName, KeyType.RSA,
                                    Blob(DEFAULT_RSA_PUBLIC_KEY_DER))
        self.privateKeyStorage.setKeyPairForKeyName(
            keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER,
            DEFAULT_RSA_PRIVATE_KEY_DER)

    def signData(self, data, certificateName=None):
        if certificateName is None:
            certificateName = self.defaultCertName
        self.keyChain.sign(data, certificateName)

    def verifyData(self, data, verifiedCallback, failedCallback):
        self.keyChain.verifyData(data, verifiedCallback, failedCallback)
Exemple #40
0
class Producer(object):
    def __init__(self, delay=None):
        self.delay = delay
        self.nDataServed = 0
        self.isDone = False


    def run(self, prefix):
        self.keyChain = KeyChain()

        self.consoleThread = ConsoleThread()
        self.consoleThread.start()

        # The default Face will connect using a Unix socket
        face = Face()
        prefix = Name(prefix)

        # Use the system default key chain and certificate name to sign commands.
        face.setCommandSigningInfo(self.keyChain, self.keyChain.getDefaultCertificateName())

        # Also use the default certificate name to sign data packets.
        face.registerPrefix(prefix, self.onInterest, self.onRegisterFailed)

        print "Registering prefix", prefix.toUri()

        while not self.isDone:
            face.processEvents()
            time.sleep(0.01)



    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        global stopServing

        if stopServing:
            print "refusing to serve " + interest.getName().toUri()
            self.consoleThread.join()
            print "join'd thread"
            return

        if self.delay is not None:
            time.sleep(self.delay)

        interestName = interest.getName()

        data = Data(interestName)
        data.setContent("Hello " + interestName.toUri())
        data.getMetaInfo().setFreshnessPeriod(3600 * 1000)

        self.keyChain.sign(data, self.keyChain.getDefaultCertificateName())

        transport.send(data.wireEncode().toBuffer())

        self.nDataServed += 1
        print "Replied to: %s (#%d)" % (interestName.toUri(), self.nDataServed)


    def onRegisterFailed(self, prefix):
        print "Register failed for prefix", prefix.toUri()
def main():
    interest = Interest()
    interest.wireDecode(TlvInterest)
    dump("Interest:")
    dumpInterest(interest)

    # Set the name again to clear the cached encoding so we encode again.
    interest.setName(interest.getName())
    encoding = interest.wireEncode()
    dump("")
    dump("Re-encoded interest", encoding.toHex())

    reDecodedInterest = Interest()
    reDecodedInterest.wireDecode(encoding)
    dump("Re-decoded Interest:")
    dumpInterest(reDecodedInterest)

    freshInterest = Interest(Name("/ndn/abc"))
    freshInterest.setMustBeFresh(False)
    dump(freshInterest.toUri())
    freshInterest.setMinSuffixComponents(4)
    freshInterest.setMaxSuffixComponents(6)
    freshInterest.getKeyLocator().setType(KeyLocatorType.KEY_LOCATOR_DIGEST)
    freshInterest.getKeyLocator().setKeyData(bytearray(
      [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
       0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F]))
    freshInterest.getExclude().appendComponent(Name("abc")[0]).appendAny()
    freshInterest.setInterestLifetimeMilliseconds(30000)
    freshInterest.setChildSelector(1)
    freshInterest.setMustBeFresh(True);
    freshInterest.setScope(2)

    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
                        SelfVerifyPolicyManager(identityStorage))

    # Initialize the storage.
    keyName = Name("/testname/DSK-123")
    certificateName = keyName.getSubName(0, keyName.size() - 1).append(
      "KEY").append(keyName[-1]).append("ID-CERT").append("0")
    identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER))
    privateKeyStorage.setKeyPairForKeyName(
      keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER)

    # Make a Face just so that we can sign the interest.
    face = Face("localhost")
    face.setCommandSigningInfo(keyChain, certificateName)
    face.makeCommandInterest(freshInterest)

    reDecodedFreshInterest = Interest()
    reDecodedFreshInterest.wireDecode(freshInterest.wireEncode())
    dump("")
    dump("Re-decoded fresh Interest:")
    dumpInterest(reDecodedFreshInterest)

    keyChain.verifyInterest(
      reDecodedFreshInterest, makeOnVerified("Freshly-signed Interest"),
      makeOnVerifyFailed("Freshly-signed Interest"))
def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

    interest = Interest()
    interest.wireDecode(TlvInterest)
    dump("Interest:")
    dumpInterest(interest)

    # Set the name again to clear the cached encoding so we encode again.
    interest.setName(interest.getName())
    encoding = interest.wireEncode()
    dump("")
    dump("Re-encoded interest", encoding.toHex())

    reDecodedInterest = Interest()
    reDecodedInterest.wireDecode(encoding)
    dump("Re-decoded Interest:")
    dumpInterest(reDecodedInterest)

    freshInterest = (Interest(Name("/ndn/abc"))
      .setMustBeFresh(False)
      .setMinSuffixComponents(4)
      .setMaxSuffixComponents(6)
      .setInterestLifetimeMilliseconds(30000)
      .setChildSelector(1)
      .setMustBeFresh(True))
    freshInterest.getKeyLocator().setType(KeyLocatorType.KEY_LOCATOR_DIGEST)
    freshInterest.getKeyLocator().setKeyData(bytearray(
      [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
       0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F]))
    freshInterest.getExclude().appendComponent(Name("abc")[0]).appendAny()
    freshInterest.getForwardingHint().add(1, Name("/A"))
    dump(freshInterest.toUri())

    # Set up the KeyChain.
    keyChain = KeyChain("pib-memory:", "tpm-memory:")
    keyChain.importSafeBag(SafeBag
      (Name("/testname/KEY/123"),
       Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False),
       Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False)))
    validator = Validator(ValidationPolicyFromPib(keyChain.getPib()))

    # Make a Face just so that we can sign the interest.
    face = Face("localhost")
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())
    face.makeCommandInterest(freshInterest)

    reDecodedFreshInterest = Interest()
    reDecodedFreshInterest.wireDecode(freshInterest.wireEncode())
    dump("")
    dump("Re-decoded fresh Interest:")
    dumpInterest(reDecodedFreshInterest)

    validator.validate(
      reDecodedFreshInterest, makeSuccessCallback("Freshly-signed Interest"),
      makeFailureCallback("Freshly-signed Interest"))
Exemple #43
0
 def onSetupFailed(msg):
     print(msg)
     print("In this test, try start publishing with default keychain certificate anyway")
     keyChain = KeyChain()
     try:
         defaultCertificateName = keyChain.getDefaultCertificateName()
         startProducers(defaultCertificateName, keyChain)
     except SecurityException as e:
         print str(e)
Exemple #44
0
 def start(self):
     self.isStopped = False
     self.loop = asyncio.new_event_loop()
     asyncio.set_event_loop(self.loop)
     self.face = ThreadsafeFace(self.loop, '')
     k = KeyChain()
     self.face.setCommandSigningInfo(k, k.getDefaultCertificateName())
     self.face.stopWhen(lambda:self.isStopped)
     try:
         self.loop.run_until_complete(self.sendNextInsertRequest())
     finally:
         self.face.shutdown()
Exemple #45
0
def main():
    """
    Call requestInsert and register a prefix so that ProduceSegments will answer
    interests from the repo to send the data packets. This assumes that repo-ng
    is already running (e.g. `sudo ndn-repo-ng`).
    """
    repoCommandPrefix = Name("/example/repo/1")
    repoDataPrefix = Name("/example/data/1")

    nowMilliseconds = int(time.time() * 1000.0)
    fetchPrefix = Name(repoDataPrefix).append("testinsert").appendVersion(nowMilliseconds)

    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()
    # Use the system default key chain and certificate name to sign commands.
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    # Register the prefix and send the repo insert command at the same time.
    startBlockId = 0
    endBlockId = 1
    enabled = [True]
    def onFinished():
        dump("All data was inserted.")
        enabled[0] = False
    produceSegments = ProduceSegments(
      keyChain, keyChain.getDefaultCertificateName(), startBlockId, endBlockId,
      onFinished)
    dump("Register prefix", fetchPrefix.toUri())
    def onRegisterFailed(prefix):
        dump("Register failed for prefix", prefix.toUri())
        enabled[0] = False
    face.registerPrefix(
      fetchPrefix, produceSegments.onInterest, onRegisterFailed)

    def onInsertStarted():
        dump("Insert started for", fetchPrefix.toUri())
    def onFailed():
        enabled[0] = False
    requestInsert(
      face, repoCommandPrefix, fetchPrefix, onInsertStarted, onFailed,
      startBlockId, endBlockId)

    # Run until all the data is sent.
    while enabled[0]:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)

    face.shutdown()
Exemple #46
0
def status_put(name, data):

    # Use the system default key chain and certificate name to sign commands.
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())
    
    # Also use the default certificate name to sign data packets.
    echo = Echo(keyChain, keyChain.getDefaultCertificateName(), data)
    prefix = Name(name)
    dump("Register prefix", prefix.toUri())
    logging.debug('Register prefix ' + prefix.toUri())

    face.registerPrefix(prefix, echo.onInterest, echo.onRegisterFailed)
    face.processEvents()
Exemple #47
0
def main():
    loop = asyncio.get_event_loop()
    face = ThreadsafeFace(loop, "localhost")
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    # TODO: NFD hack: uncomment once NFD forwarding fixed
    # discoveree = Discoveree(loop, face, keyChain)
    # TODO: NFD hack: remove once NFD forwarding fixed
    discoveree = LocalDiscoveree(loop, face, keyChain)

    cecTv = CecTv(loop, face, keyChain, discoveree)

    loop.run_forever()
    face.shutdown()
class Producer(object):
    def __init__(self):
        self.keyChain = KeyChain()
        self.isDone = False


    def run(self, namespace):
        # Create a connection to the local forwarder over a Unix socket
        face = Face()

        prefix = Name(namespace)

        # Use the system default key chain and certificate name to sign commands.
        face.setCommandSigningInfo(self.keyChain, \
                                   self.keyChain.getDefaultCertificateName())

        # Also use the default certificate name to sign Data packets.
        face.registerPrefix(prefix, self.onInterest, self.onRegisterFailed)

        print "Registering prefix", prefix.toUri()

        # Run the event loop forever. Use a short sleep to
        # prevent the Producer from using 100% of the CPU.
        while not self.isDone:
            face.processEvents()
            time.sleep(0.01)



    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        interestName = interest.getName()

        data = Data(interestName)
        data.setContent("Hello, " + interestName.toUri())

        hourMilliseconds = 3600 * 1000
        data.getMetaInfo().setFreshnessPeriod(hourMilliseconds)

        self.keyChain.sign(data, self.keyChain.getDefaultCertificateName())

        transport.send(data.wireEncode().toBuffer())

        print "Replied to: %s" % interestName.toUri()


    def onRegisterFailed(self, prefix):
        print "Register failed for prefix", prefix.toUri()
        self.isDone = True
def main():
    """
    Call startRepoWatch and register a prefix so that SendSegments will answer
    interests from the repo to send data packets for the watched prefix.  When
    all the data is sent (or an error), call stopRepoWatch. This assumes that
    repo-ng is already running (e.g. `sudo ndn-repo-ng`).
    """
    repoCommandPrefix = Name("/example/repo/1")
    repoDataPrefix = Name("/example/data/1")

    nowMilliseconds = int(time.time() * 1000.0)
    watchPrefix = Name(repoDataPrefix).append("testwatch").appendVersion(
      nowMilliseconds)

    # The default Face will connect using a Unix socket, or to "localhost".
    face = Face()
    # Use the system default key chain and certificate name to sign commands.
    keyChain = KeyChain()
    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    # Register the prefix and start the repo watch at the same time.
    enabled = [True]
    def onFinishedSending():
        stopRepoWatchAndQuit(face, repoCommandPrefix, watchPrefix, enabled)
    sendSegments = SendSegments(
      keyChain, keyChain.getDefaultCertificateName(), onFinishedSending)
    def onRegisterFailed(prefix):
        dump("Register failed for prefix", prefix.toUri())
        enabled[0] = False
    dump("Register prefix", watchPrefix.toUri())
    face.registerPrefix(watchPrefix, sendSegments.onInterest, onRegisterFailed)

    def onRepoWatchStarted():
        dump("Watch started for", watchPrefix.toUri())
    def onStartFailed():
        dump("startRepoWatch failed.")
        stopRepoWatchAndQuit(face, repoCommandPrefix, watchPrefix, enabled)
    startRepoWatch(
      face, repoCommandPrefix, watchPrefix, onRepoWatchStarted, onStartFailed)

    # Run until someone sets enabled[0] = False.
    enabled[0] = True
    while enabled[0]:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)

    face.shutdown()
Exemple #50
0
    def __init__(self, prefix="/ndn/edu/ucla/remap/music/list"):

	logging.basicConfig()        
	'''#这些log是干嘛的myIP="192.168.1.1",lightIP="192.168.1.50",
        self.log = logging.getLogger("RegisterSongList")
        self.log.setLevel(logging.DEBUG)
        sh = logging.StreamHandler()
        sh.setLevel(logging.DEBUG)
        self.log.addHandler(sh)
        fh = logging.FileHandler("RegisterSongList.log")
        fh.setLevel(logging.INFO)
        self.log.addHandler(fh)'''
    	self.device = "PC3"
    	self.deviceComponent = Name.Component(self.device)
	self.excludeDevice = None
    	#self.songList = originalList

        #security?
        self.prefix = Name(prefix)
	self.changePrefix = Name("/ndn/edu/ucla/remap/music/storage")
        self.keychain = KeyChain()
        self.certificateName = self.keychain.getDefaultCertificateName()

        self.address = ""
        self._isStopped = True
    def addSubCertificate(self, subIdentityName, issuer, params = None):
        """
        Issue a certificate for subIdentityName signed by issuer. If the
        identity does not exist, it is created. A new key is generated as the
        default key for the identity. A default certificate for the key is
        signed by the issuer using its default certificate.
        """
        if params == None:
            params = KeyChain.getDefaultKeyParams()

        subIdentity = self.addIdentity(subIdentityName, params)

        request = subIdentity.getDefaultKey().getDefaultCertificate()

        request.setName(request.getKeyName().append("parent").appendVersion(1))

        certificateParams = SigningInfo(issuer)
        # Validity period of 20 years.
        now = Common.getNowMilliseconds()
        certificateParams.setValidityPeriod(
          ValidityPeriod(now, now + 20 * 365 * 24 * 3600 * 1000.0))

        # Skip the AdditionalDescription.

        self._keyChain.sign(request, certificateParams)
        self._keyChain.setDefaultCertificate(subIdentity.getDefaultKey(), request)

        return subIdentity
Exemple #52
0
class ThreadsafeFaceWrapper(object):
    def __init__(self):
        self._loop = asyncio.get_event_loop()
        self._face = ThreadsafeFace(self._loop, "")
        self._keyChain = KeyChain()
        self._certificateName = self._keyChain.getDefaultCertificateName()
        self._face.setCommandSigningInfo(self._keyChain, self._certificateName)
	
        
    def startProcessing(self):
        try:
            self._loop.run_forever()        
        finally:
            self.stop()
        
    def stopProcessing(self):
        self._loop.close()
        self._face.shutdown()
        self._face = None
        sys.exit(1)
    
    def getFace(self):
        return self._face
        
    def getLoop(self):
        return self._loop
Exemple #53
0
    def setUp(self):
        testCertDirectory = 'policy_config/certs'
        self.testCertFile = os.path.join(testCertDirectory, 'test.cert')

        # Reuse the policy_config subdirectory for the temporary SQLite file.
        self.databaseFilePath = "policy_config/test-public-info.db"
        try:
            os.remove(self.databaseFilePath)
        except OSError:
            # no such file
            pass

        self.identityStorage = BasicIdentityStorage(self.databaseFilePath)
        self.privateKeyStorage = MemoryPrivateKeyStorage()
        self.identityManager = IdentityManager(self.identityStorage,
                self.privateKeyStorage)
        self.policyManager = ConfigPolicyManager('policy_config/simple_rules.conf')

        self.identityName = Name('/TestConfigPolicyManager/temp')
        # to match the anchor cert
        keyName = Name(self.identityName).append('ksk-1416010123')
        self.privateKeyStorage.setKeyPairForKeyName(
          keyName, KeyType.RSA, TEST_RSA_PUBLIC_KEY_DER, TEST_RSA_PRIVATE_KEY_DER)
        self.identityStorage.addKey(
          keyName, KeyType.RSA, Blob(TEST_RSA_PUBLIC_KEY_DER))

        cert = self.identityManager.selfSign(keyName)
        self.identityStorage.setDefaultKeyNameForIdentity(keyName)
        self.identityManager.addCertificateAsDefault(cert)

        self.keyChain = KeyChain(self.identityManager, self.policyManager)
        self.keyName = keyName

        self.face = Face()
Exemple #54
0
    def __init__(self, nStrands=1, myIP="192.168.1.1", lightIP="192.168.1.50", prefix="/testlight"):
        self.log = logging.getLogger("LightController")
        self.log.setLevel(logging.DEBUG)
        sh = logging.StreamHandler()
        sh.setLevel(logging.DEBUG)
        self.log.addHandler(sh)
        fh = logging.FileHandler("LightController.log")
        fh.setLevel(logging.INFO)
        self.log.addHandler(fh)

        self.payloadBuffer = [[0]*self.STRAND_SIZE*self.COLORS_PER_LIGHT for n in range(nStrands)]

        self.kinetsender = KinetSender(myIP, lightIP, nStrands, self.STRAND_SIZE*self.COLORS_PER_LIGHT)
        self.prefix = Name(prefix)
        self.keychain = KeyChain()

        self.address = ""
        self._isStopped = True

        self.lightState = False
        #mengchen: let's make the lighting lits only a half every time
        #self.uphalf =  True
        self.HALF_STRAND_SIZE = 25       
        self.certificateName = self.keychain.getDefaultCertificateName()
        self.receiveFile = open('interestReceiveFile', 'w')
Exemple #55
0
    def __init__(self, networkName, nodeName):
        super(IotConsole, self).__init__()

        self.deviceSuffix = Name(nodeName)
        self.networkPrefix = Name(networkName)
        self.prefix = Name(self.networkPrefix).append(self.deviceSuffix)

        self._identityStorage = IotIdentityStorage()
        self._policyManager = IotPolicyManager(self._identityStorage)
        self._identityManager = IotIdentityManager(self._identityStorage)
        self._keyChain = KeyChain(self._identityManager, self._policyManager)

        self._policyManager.setEnvironmentPrefix(self.networkPrefix)
        self._policyManager.setTrustRootIdentity(self.prefix)
        self._policyManager.setDeviceIdentity(self.prefix)
        self._policyManager.updateTrustRules()

        self.foundCommands = {}
        self.unconfiguredDevices = []

        # TODO: use xDialog in XWindows
        self.ui = Dialog(backtitle="NDN IoT User Console", height=18, width=78)

        trolliusLogger = logging.getLogger("trollius")
        trolliusLogger.addHandler(logging.StreamHandler())
Exemple #56
0
    def __init__(self, face):
        self._defaultIdentity = None
        self._defaultCertificateName = None
        
        self._controllerName = None
        self._controllerCertificate = None

        self._applicationName = ""

        self._identityManager = IdentityManager(BasicIdentityStorage(), FilePrivateKeyStorage())

        self._policyManager = ConfigPolicyManager()
        self._policyManager.config.read("validator \n \
            {                                      \n \
              rule                                 \n \
              {                                    \n \
                id \"initial rule\"                \n \
                for data                           \n \
                checker                            \n \
                {                                  \n \
                  type hierarchical                \n \
                }                                  \n \
              }                                    \n \
            }", "initial-schema")
        # keyChain is what we return to the application after successful setup
        # TODO: should we separate keyChain from internal KeyChain used to verify trust schemas?
        self._keyChain = KeyChain(self._identityManager, self._policyManager)

        self._face = face
        # setFace for keyChain or else it won't be able to express interests for certs
        self._keyChain.setFace(self._face)
        self._certificateContentCache = MemoryContentCache(face)
        
        self._trustSchemas = dict()
Exemple #57
0
    def __init__(self):

        self._device = "PC1"
        self._playPrefix = Name("/ndn/edu/ucla/remap/music/play")
	self.prefix = self._playPrefix.append(self._device)
        self._face = None
        self._loop = None

	self.thread = None
        
        self._keyChain = KeyChain()
        self._certificateName = self._keyChain.getDefaultCertificateName()

        self._repoCommandPrefix = "/example/repo/1"

	self.song = ""
	self.ftxt = ""
	self.ffreq = ""

	self.songList = ""
	self.mp = MusicPlayer()
	self.config = RawConfigParser()
	self.config.read('config.cfg')
	self.s = LightMessenger(self.config)

	self.q = Queue.Queue()
Exemple #58
0
def main():
    face = Face()

    # Use the system default key chain and certificate name to sign commands.
    keyChain = KeyChain()
    certificateName = keyChain.getDefaultCertificateName()
    face.setCommandSigningInfo(keyChain, certificateName)
    test = DiscoveryTest(face, keyChain, certificateName)
    test.start()

    while True:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)

    face.shutdown()