Beispiel #1
0
    def test_prepare_unsigned_certificate(self):
        identityStorage = MemoryIdentityStorage()
        privateKeyStorage = MemoryPrivateKeyStorage()
        identityManager = IdentityManager(identityStorage, privateKeyStorage)
        keyName = Name("/test/ksk-1457560485494")
        identityStorage.addKey(keyName, KeyType.RSA, Blob(PUBLIC_KEY))

        subjectDescriptions = []
        subjectDescriptions.append(CertificateSubjectDescription(
          TEST_OID, "TEST NAME"))
        newCertificate = identityManager.prepareUnsignedIdentityCertificate(
            keyName,
            keyName.getPrefix(1), self.toyCertNotBefore,
            self.toyCertNotAfter, subjectDescriptions)

        # Update the generated certificate version to equal the one in toyCert.
        newCertificate.setName(
          Name(newCertificate.getName().getPrefix(-1).append
           (self.toyCert.getName().get(-1))))

        # Make a copy to test encoding.
        certificateCopy = IdentityCertificate(newCertificate)
        self.assertEqual(
          str(self.toyCert), str(certificateCopy),
          "Prepared unsigned certificate dump does not have the expected format")
Beispiel #2
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()
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
Beispiel #4
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[:-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 signData(self, data, certificateName = None):
        if certificateName is None:
            certificateName = self.defaultCertName
        self.keyChain.sign(data, certificateName)

    def signDataWithSha256(self, data):
        self.keyChain.signWithSha256(data)

    def verifyData(self, data, verifiedCallback, failedCallback):
        self.keyChain.verifyData(data, verifiedCallback, failedCallback)
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()
Beispiel #6
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
Beispiel #7
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()
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"))
Beispiel #9
0
    def setUp(self):
        self.decryptionKeys = {}  # key: Name, value: Blob
        self.encryptionKeys = {}  # key: Name, value: Data

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

        self.groupName = Name("/Prefix/READ")
        self.contentName = Name("/Prefix/SAMPLE/Content")
        self.cKeyName = Name("/Prefix/SAMPLE/Content/C-KEY/1")
        self.eKeyName = Name("/Prefix/READ/E-KEY/1/2")
        self.dKeyName = Name("/Prefix/READ/D-KEY/1/2")
        self.uKeyName = Name("/U/Key")
        self.uName = Name("/U")

        # Generate the E-KEY and D-KEY.
        params = RsaKeyParams()
        self.fixtureDKeyBlob = RsaAlgorithm.generateKey(params).getKeyBits()
        self.fixtureEKeyBlob = RsaAlgorithm.deriveEncryptKey(
            self.fixtureDKeyBlob).getKeyBits()

        # Generate the user key.
        self.fixtureUDKeyBlob = RsaAlgorithm.generateKey(params).getKeyBits()
        self.fixtureUEKeyBlob = RsaAlgorithm.deriveEncryptKey(
            self.fixtureUDKeyBlob).getKeyBits()

        # Load the C-KEY.
        self.fixtureCKeyBlob = Blob(AES_KEY, False)

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

        # Initialize the storage.
        keyName = Name("/testname/DSK-123")
        self.certificateName = keyName.getSubName(
            0,
            keyName.size() - 1).append("KEY").append(
                keyName.get(-1)).append("ID-CERT").append("0")
        identityStorage.addKey(keyName, KeyType.RSA,
                               Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False))
        privateKeyStorage.setKeyPairForKeyName(keyName, KeyType.RSA,
                                               DEFAULT_RSA_PUBLIC_KEY_DER,
                                               DEFAULT_RSA_PRIVATE_KEY_DER)
Beispiel #10
0
    def setUp(self):
        self.decryptionKeys = {} # key: Name, value: Blob
        self.encryptionKeys = {} # key: Name, value: Data

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

        self.groupName = Name("/Prefix/READ")
        self.contentName = Name("/Prefix/SAMPLE/Content")
        self.cKeyName = Name("/Prefix/SAMPLE/Content/C-KEY/1")
        self.eKeyName = Name("/Prefix/READ/E-KEY/1/2")
        self.dKeyName = Name("/Prefix/READ/D-KEY/1/2")
        self.uKeyName = Name("/U/Key")
        self.uName = Name("/U")

        # Generate the E-KEY and D-KEY.
        params = RsaKeyParams()
        self.fixtureDKeyBlob = RsaAlgorithm.generateKey(params).getKeyBits()
        self.fixtureEKeyBlob = RsaAlgorithm.deriveEncryptKey(
          self.fixtureDKeyBlob).getKeyBits()

        # Generate the user key.
        self.fixtureUDKeyBlob = RsaAlgorithm.generateKey(params).getKeyBits()
        self.fixtureUEKeyBlob = RsaAlgorithm.deriveEncryptKey(
          self.fixtureUDKeyBlob).getKeyBits()

        # Load the C-KEY.
        self.fixtureCKeyBlob = Blob(AES_KEY, False)

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

        # Initialize the storage.
        keyName = Name("/testname/DSK-123")
        self.certificateName = keyName.getSubName(0, keyName.size() - 1).append(
          "KEY").append(keyName.get(-1)).append("ID-CERT").append("0")
        identityStorage.addKey(
          keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False))
        privateKeyStorage.setKeyPairForKeyName(
          keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER,
          DEFAULT_RSA_PRIVATE_KEY_DER)
Beispiel #11
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
Beispiel #12
0
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 commands.
    #print("key1")
    #keyChain = KeyChain()
    #print("key2")
    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
                        NoVerifyPolicyManager())
    identityName = Name("TestProducer")
    certificateName = keyChain.createIdentityAndCertificate(identityName)
    keyChain.getIdentityManager().setDefaultIdentity(identityName)

    face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())

    # Also use the default certificate name to sign data packets.
    ubicdn = UbiCDN(keyChain, certificateName)
    prefix = Name("/ubicdn/video")
    dump("Register prefix", prefix.toUri())
    face.registerPrefix(prefix, ubicdn.onInterest, ubicdn.onRegisterFailed)

    while 1:
        #while ubicdn._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()
Beispiel #13
0
    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()
Beispiel #14
0
def main():
    data = Data()
    data.wireDecode(TlvData)
    dump("Decoded Data:")
    dumpData(data)

    # Set the content again to clear the cached encoding so we encode again.
    data.setContent(data.getContent())
    encoding = data.wireEncode()

    reDecodedData = Data()
    reDecodedData.wireDecode(encoding)
    dump("")
    dump("Re-decoded Data:")
    dumpData(reDecodedData)

    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)

    keyChain.verifyData(reDecodedData, makeOnVerified("Re-decoded Data"),
                        makeOnVerifyFailed("Re-decoded Data"))

    freshData = Data(Name("/ndn/abc"))
    freshData.setContent("SUCCESS!")
    freshData.getMetaInfo().setFreshnessPeriod(5000)
    freshData.getMetaInfo().setFinalBlockId(Name("/%00%09")[0])
    keyChain.sign(freshData, certificateName)
    dump("")
    dump("Freshly-signed Data:")
    dumpData(freshData)

    keyChain.verifyData(freshData, makeOnVerified("Freshly-signed Data"),
                        makeOnVerifyFailed("Freshly-signed Data"))
Beispiel #15
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.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)
Beispiel #16
0
def createVerifyKeyChain():
    """
    Create an in-memory KeyChain with a default public key for verifying.

    :return: A new KeyChain.
    :rtype: KeyChain
    """
    identityStorage = MemoryIdentityStorage()
    keyChain = KeyChain(
        IdentityManager(identityStorage, MemoryPrivateKeyStorage()),
        SelfVerifyPolicyManager(identityStorage))

    # Initialize the storage.
    keyName = Name("/testname/DSK-123")
    identityStorage.addKey(keyName, KeyType.RSA,
                           Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False))

    return keyChain
Beispiel #17
0
def createVerifyKeyChain():
    """
    Create an in-memory KeyChain with a default public key for verifying.

    :return: A new KeyChain.
    :rtype: KeyChain
    """
    identityStorage = MemoryIdentityStorage()
    keyChain = KeyChain(
      IdentityManager(identityStorage, MemoryPrivateKeyStorage()),
      SelfVerifyPolicyManager(identityStorage))

    # Initialize the storage.
    keyName = Name("/testname/DSK-123")
    identityStorage.addKey(
      keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False))

    return keyChain
def main():
    data = Data()
    data.wireDecode(TlvData)
    dump("Decoded Data:")
    dumpData(data)

    # Set the content again to clear the cached encoding so we encode again.
    data.setContent(data.getContent())
    encoding = data.wireEncode()

    reDecodedData = Data()
    reDecodedData.wireDecode(encoding)
    dump("")
    dump("Re-decoded Data:")
    dumpData(reDecodedData)

    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)

    keyChain.verifyData(reDecodedData, makeOnVerified("Re-decoded Data"),
                        makeOnVerifyFailed("Re-decoded Data"))

    freshData = Data(Name("/ndn/abc"))
    freshData.setContent("SUCCESS!")
    freshData.getMetaInfo().setFreshnessPeriod(5000)
    freshData.getMetaInfo().setFinalBlockId(Name("/%00%09")[0])
    keyChain.sign(freshData, certificateName)
    dump("")
    dump("Freshly-signed Data:")
    dumpData(freshData)

    keyChain.verifyData(freshData, makeOnVerified("Freshly-signed Data"),
                        makeOnVerifyFailed("Freshly-signed Data"))
Beispiel #19
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.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 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)
    def __init__(self, face, username, memoryContentCache):
        # Set up face
        self.face = face

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

        identityName = Name(username)
        self.certificateName = self.keyChain.createIdentityAndCertificate(
            identityName)
        self.keyChain.getIdentityManager().setDefaultIdentity(identityName)

        self.face.setCommandSigningInfo(self.keyChain, self.certificateName)

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

        self.testDb = Sqlite3ProducerDb(self.databaseFilePath)
        self.catalogDb = Sqlite3ProducerDb(self.catalogDatabaseFilePath)

        # TODO: as of right now, catalog has a different suffix, so need another instance of producer; that producer cannot share
        # the same DB with the first producer, otherwise there won't be a self.onEncryptedKeys call; as the catalog producer uses
        # its own C-key, and that key won't be encrypted by an E-key as no interest goes out
        # This sounds like something problematic from the library
        prefix = Name(username)
        suffix = Name("fitness/physical_activity/time_location")

        self.producer = Producer(Name(prefix), suffix, self.face,
                                 self.keyChain, self.testDb)

        catalogSuffix = Name(suffix).append("catalog")
        self.catalogProducer = Producer(Name(prefix), catalogSuffix, self.face,
                                        self.keyChain, self.catalogDb)

        self.memoryContentCache = memoryContentCache
        return
Beispiel #22
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[:-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 signData(self, data, certificateName=None):
        if certificateName is None:
            certificateName = self.defaultCertName
        self.keyChain.sign(data, certificateName)

    def signDataWithSha256(self, data):
        self.keyChain.signWithSha256(data)

    def verifyData(self, data, verifiedCallback, failedCallback):
        self.keyChain.verifyData(data, verifiedCallback, failedCallback)
Beispiel #23
0
def createKeyChain():
    """
    Create an in-memory KeyChain with default keys.

    :return: A tuple with the new KeyChain and certificate name.
    :rtype: (KeyChain,Name)
    """
    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(
      IdentityManager(identityStorage, privateKeyStorage),
      NoVerifyPolicyManager())

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

    return keyChain, certificateName
    def loadKey(self):
        self.identityStorage = MemoryIdentityStorage()
        self.privateKeyStorage = MemoryPrivateKeyStorage()
        self.keychain = KeyChain(IdentityManager(self.identityStorage, self.privateKeyStorage))

        f = open(key_file, "r")
        self.key = RSA.importKey(f.read())
        self.key_name = Name(bld_root).append(getKeyID(self.key))
        key_pub_der = bytearray(self.key.publickey().exportKey(format="DER"))
        key_pri_der = bytearray(self.key.exportKey(format="DER"))
        self.identityStorage.addKey(self.key_name, KeyType.RSA, Blob(key_pub_der))
        self.privateKeyStorage.setKeyPairForKeyName(self.key_name, key_pub_der, key_pri_der)
        self.cert_name = self.key_name.getSubName(0, self.key_name.size() - 1).append(
            "KEY").append(self.key_name[-1]).append("ID-CERT").append("0")

        print 'KeyName = ' + self.key_name.toUri()
        print 'CertName = ' + self.cert_name.toUri()
    def test_verify_digest_sha256(self):
        # Create a KeyChain but we don't need to add keys.
        identityStorage = MemoryIdentityStorage()
        keyChain = KeyChain(
          IdentityManager(identityStorage, MemoryPrivateKeyStorage()),
          SelfVerifyPolicyManager(identityStorage))

        interest = Interest(Name("/test/signed-interest"))
        keyChain.signWithSha256(interest)

        # We create 'mock' objects to replace callbacks since we're not
        # interested in the effect of the callbacks themselves.
        failedCallback = Mock()
        verifiedCallback = Mock()

        keyChain.verifyInterest(interest, verifiedCallback, failedCallback)
        self.assertEqual(failedCallback.call_count, 0, 'Signature verification failed')
        self.assertEqual(verifiedCallback.call_count, 1, 'Verification callback was not used.')
Beispiel #26
0
    def setUp(self):
        self.decryptionKeys = {} # key: Name, value: Blob
        self.encryptionKeys = {} # key: Name, value: Data

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

        # Set up the keyChain.
        identityStorage = MemoryIdentityStorage()
        privateKeyStorage = MemoryPrivateKeyStorage()
        self.keyChain = KeyChain(
          IdentityManager(identityStorage, privateKeyStorage),
          NoVerifyPolicyManager())
        identityName = Name("TestProducer")
        self.certificateName = self.keyChain.createIdentityAndCertificate(identityName)
        self.keyChain.getIdentityManager().setDefaultIdentity(identityName)
    def __init__(self, face, groupManagerName, dataType, readAccessName,
                 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.face.setCommandSigningInfo(self.keyChain, self.certificateName)

        self.dKeyDatabaseFilePath = dKeyDatabaseFilePath
        try:
            os.remove(self.dKeyDatabaseFilePath)
        except OSError:
            # no such file
            pass

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

        self.memoryContentCache = MemoryContentCache(self.face)
        self.memoryContentCache.registerPrefix(
            Name(groupManagerName).append("READ"), self.onRegisterFailed,
            self.onDataNotFound)
        self.face.registerPrefix(readAccessName, self.onAccessInterest,
                                 self.onAccessTimeout)

        self.updateGroupKeys = False
        return
    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)
def benchmarkEncodeDataSeconds(nIterations, useComplex, useCrypto):
    """
    Loop to encode a data packet nIterations times.

    :param int nIterations: The number of iterations.
    :param bool useComplex: If true, use a large name, large content and all
      fields. If false, use a small name, small content and only required
      fields.
    :param bool useCrypto: If true, sign the data packet.  If false, use a blank
      signature.
    :return: A tuple (duration, encoding) where duration is the number of
      seconds for all iterations and encoding is the wire encoding.
    :rtype: (float, Blob)
    """
    if useComplex:
        # Use a large name and content.
        name = Name(
            "/ndn/ucla.edu/apps/lwndn-test/numbers.txt/%FD%05%05%E8%0C%CE%1D/%00"
        )

        contentString = ""
        count = 1
        contentString += "%d" % count
        count += 1
        while len(contentString) < 1115:
            contentString += " %d" % count
            count += 1
        content = Name.fromEscapedString(contentString)
    else:
        # Use a small name and content.
        name = Name("/test")
        content = Name.fromEscapedString("abc")
    finalBlockId = Name("/%00")[0]

    # 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))
    privateKeyStorage.setKeyPairForKeyName(keyName, KeyType.RSA,
                                           DEFAULT_RSA_PUBLIC_KEY_DER,
                                           DEFAULT_RSA_PRIVATE_KEY_DER)

    # Set up signatureBits in case useCrypto is false.
    signatureBits = Blob(bytearray(256))
    emptyBlob = Blob([])

    start = getNowSeconds()
    for i in range(nIterations):
        data = Data(name)
        data.setContent(content)
        if useComplex:
            data.getMetaInfo().setFreshnessPeriod(1000)
            data.getMetaInfo().setFinalBlockId(finalBlockId)

        if useCrypto:
            # This sets the signature fields.
            keyChain.sign(data, certificateName)
        else:
            # Imitate IdentityManager.signByCertificate to set up the signature
            # fields, but don't sign.
            sha256Signature = data.getSignature()
            keyLocator = sha256Signature.getKeyLocator()
            keyLocator.setType(KeyLocatorType.KEYNAME)
            keyLocator.setKeyName(certificateName)
            sha256Signature.setSignature(signatureBits)

        encoding = data.wireEncode()

    finish = getNowSeconds()

    return (finish - start, encoding)
Beispiel #30
0
    def setUp(self):
        # Reuse the policy_config subdirectory for the temporary SQLite files.
        self.dKeyDatabaseFilePath = "policy_config/manager-d-key-test.db"
        try:
            os.remove(self.dKeyDatabaseFilePath)
        except OSError:
            # no such file
            pass

        self.eKeyDatabaseFilePath = "policy_config/manager-e-key-test.db"
        try:
            os.remove(self.eKeyDatabaseFilePath)
        except OSError:
            # no such file
            pass

        self.intervalDatabaseFilePath = "policy_config/manager-interval-test.db"
        try:
            os.remove(self.intervalDatabaseFilePath)
        except OSError:
            # no such file
            pass

        self.groupKeyDatabaseFilePath = "policy_config/manager-group-key-test.db"
        try:
            os.remove(self.groupKeyDatabaseFilePath)
        except OSError:
            # no such file
            pass

        params = RsaKeyParams()
        memberDecryptKey = RsaAlgorithm.generateKey(params)
        self.decryptKeyBlob = memberDecryptKey.getKeyBits()
        memberEncryptKey = RsaAlgorithm.deriveEncryptKey(self.decryptKeyBlob)
        self.encryptKeyBlob = memberEncryptKey.getKeyBits()

        # Generate the certificate.
        self.certificate = IdentityCertificate()
        self.certificate.setName(Name("/ndn/memberA/KEY/ksk-123/ID-CERT/123"))
        contentPublicKey = PublicKey(self.encryptKeyBlob)
        self.certificate.setPublicKeyInfo(contentPublicKey)
        self.certificate.setNotBefore(0)
        self.certificate.setNotAfter(0)
        self.certificate.encode()

        signatureInfoBlob = Blob(SIG_INFO, False)
        signatureValueBlob = Blob(SIG_VALUE, False)

        signature = TlvWireFormat.get().decodeSignatureInfoAndValue(
            signatureInfoBlob.buf(), signatureValueBlob.buf())
        self.certificate.setSignature(signature)

        self.certificate.wireEncode()

        # Set up the keyChain.
        identityStorage = MemoryIdentityStorage()
        privateKeyStorage = MemoryPrivateKeyStorage()
        self.keyChain = KeyChain(
            IdentityManager(identityStorage, privateKeyStorage),
            NoVerifyPolicyManager())
        identityName = Name("TestGroupManager")
        self.keyChain.createIdentityAndCertificate(identityName)
        self.keyChain.getIdentityManager().setDefaultIdentity(identityName)
    def onRegisterFailed(self, prefix):
        self.dump("Data prefix registration failed.")


if __name__ == '__main__':
    rp = RepoCommandParameter()
    dataPrefix = Name("/example/data/1/test/test1")

    rp.setName(dataPrefix)
    rp.setStartBlockId(0)

    interest = Interest(
        Name("/example/repo/1").append("insert").append(rp.wireEncode()))

    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)
Beispiel #32
0
def main():
    # Uncomment these lines to print ChronoSync debug messages.
    # logging.getLogger('').addHandler(logging.StreamHandler(sys.stdout))
    # logging.getLogger('').setLevel(logging.INFO)

    screenName = promptAndInput("Enter your chat username: "******"ndn/edu/ucla/remap"
    hubPrefix = promptAndInput("Enter your hub prefix [" + defaultHubPrefix + "]: ")
    if hubPrefix == "":
        hubPrefix = defaultHubPrefix

    defaultChatRoom = "ndnchat"
    chatRoom = promptAndInput("Enter the chatroom name [" + defaultChatRoom + "]: ")
    if chatRoom == "":
        chatRoom = defaultChatRoom

    host = "localhost"
    print("Connecting to " + host + ", Chatroom: " + chatRoom + ", Username: "******"")

    # Set up the key chain.
    face = Face(host)

    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
                        NoVerifyPolicyManager())
    keyChain.setFace(face)
    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)
    face.setCommandSigningInfo(keyChain, certificateName)

    chat = Chat(
      screenName, chatRoom, Name(hubPrefix), face, keyChain, certificateName)

    # The main loop to process Chat while checking stdin to send a message.
    print("Enter your chat message. To quit, enter \"leave\" or \"exit\".")
    while True:
        # Set timeout to 0 for an immediate check.
        isReady, _, _ = select.select([sys.stdin], [], [], 0)
        if len(isReady) != 0:
            input = promptAndInput("")
            if input == "leave" or input == "exit":
                # We will send the leave message below.
                break

            chat.sendMessage(input)

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

    # The user entered the command to leave.
    chat.leave()
    # Wait a little bit to allow other applications to fetch the leave message.
    startTime = Chat.getNowMilliseconds()
    while True:
        if Chat.getNowMilliseconds() - startTime >= 1000.0:
            break

        face.processEvents()
        time.sleep(0.01)
class TestRegexMatching(ut.TestCase):
    def _certNameFromKeyName(self, keyName, keyIdx=-1):
        return keyName[:keyIdx].append("KEY").append(keyName[keyIdx:]).\
                append("ID-CERT").append("0")

    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)

    def test_name_relation(self):
        policyManagerPrefix = ConfigPolicyManager(
            "policy_config/relation_ruleset_prefix.conf")
        policyManagerStrict = ConfigPolicyManager(
            "policy_config/relation_ruleset_strict.conf")
        policyManagerEqual = ConfigPolicyManager(
            "policy_config/relation_ruleset_equal.conf")

        dataName = Name('/TestRule1')

        self.assertIsNotNone(
            policyManagerPrefix._findMatchingRule(dataName, 'data'),
            "Prefix relation should match prefix name")
        self.assertIsNotNone(
            policyManagerEqual._findMatchingRule(dataName, 'data'),
            "Equal relation should match prefix name")
        self.assertIsNone(
            policyManagerStrict._findMatchingRule(dataName, 'data'),
            "Strict-prefix relation should not match prefix name")

        dataName = Name('/TestRule1/hi')
        self.assertIsNotNone(
            policyManagerPrefix._findMatchingRule(dataName, 'data'),
            "Prefix relation should match longer name")
        self.assertIsNone(
            policyManagerEqual._findMatchingRule(dataName, 'data'),
            "Equal relation should not match longer name")
        self.assertIsNotNone(
            policyManagerStrict._findMatchingRule(dataName, 'data'),
            "Strict-prefix relation should match longer name")

        dataName = Name('/Bad/TestRule1/')
        self.assertIsNone(
            policyManagerPrefix._findMatchingRule(dataName, 'data'),
            "Prefix relation should not match inner components")
        self.assertIsNone(
            policyManagerEqual._findMatchingRule(dataName, 'data'),
            "Equal relation should not match inner components")
        self.assertIsNone(
            policyManagerStrict._findMatchingRule(dataName, 'data'),
            "Strict-prefix relation should  not match inner components")

    def test_simple_regex(self):
        policyManager = ConfigPolicyManager("policy_config/regex_ruleset.conf")
        dataName1 = Name('/SecurityTestSecRule/Basic')
        dataName2 = Name('/SecurityTestSecRule/Basic/More')
        dataName3 = Name('/SecurityTestSecRule/')
        dataName4 = Name('/SecurityTestSecRule/Other/TestData')
        dataName5 = Name('/Basic/Data')

        matchedRule1 = policyManager._findMatchingRule(dataName1, 'data')
        matchedRule2 = policyManager._findMatchingRule(dataName2, 'data')
        matchedRule3 = policyManager._findMatchingRule(dataName3, 'data')
        matchedRule4 = policyManager._findMatchingRule(dataName4, 'data')
        matchedRule5 = policyManager._findMatchingRule(dataName5, 'data')

        self.assertIsNotNone(matchedRule1)
        self.assertIsNone(matchedRule2)
        self.assertIsNotNone(matchedRule3)
        self.assertNotEqual(matchedRule3, matchedRule1,
                            "Rule regex matched extra components")
        self.assertIsNotNone(matchedRule4)
        self.assertNotEqual(matchedRule4, matchedRule1,
                            "Rule regex matched with missing component")

        self.assertIsNone(matchedRule5)

    def test_checker_hierarchical(self):
        policyManager = ConfigPolicyManager(
            "policy_config/hierarchical_ruleset.conf")

        dataName1 = Name('/SecurityTestSecRule/Basic/Data1')
        dataName2 = Name('/SecurityTestSecRule/Basic/Longer/Data2')

        data1 = Data(dataName1)
        data2 = Data(dataName2)

        matchedRule = policyManager._findMatchingRule(dataName1, 'data')
        self.assertEqual(matchedRule,
                         policyManager._findMatchingRule(dataName2, 'data'))

        self.keyChain.sign(data1, self.defaultCertName)
        self.keyChain.sign(data2, self.defaultCertName)

        signatureName1 = data1.getSignature().getKeyLocator().getKeyName()
        signatureName2 = data2.getSignature().getKeyLocator().getKeyName()

        self.assertFalse(
            policyManager._checkSignatureMatch(signatureName1, dataName1,
                                               matchedRule),
            "Hierarchical matcher matched short data name to long key name")

        self.assertTrue(
            policyManager._checkSignatureMatch(signatureName2, dataName2,
                                               matchedRule))

        self.keyChain.sign(data1, self.shortCertName)
        self.keyChain.sign(data2, self.shortCertName)

        signatureName1 = data1.getSignature().getKeyLocator().getKeyName()
        signatureName2 = data2.getSignature().getKeyLocator().getKeyName()

        self.assertTrue(
            policyManager._checkSignatureMatch(signatureName1, dataName1,
                                               matchedRule))
        self.assertTrue(
            policyManager._checkSignatureMatch(signatureName2, dataName2,
                                               matchedRule))

    def test_hyperrelation(self):
        policyManager = ConfigPolicyManager(
            "policy_config/hyperrelation_ruleset.conf")

        dataName = Name('/SecurityTestSecRule/Basic/Longer/Data2')
        data1 = Data(dataName)
        data2 = Data(dataName)

        matchedRule = policyManager._findMatchingRule(dataName, 'data')
        self.keyChain.sign(data1, self.defaultCertName)
        self.keyChain.sign(data2, self.shortCertName)

        signatureName1 = data1.getSignature().getKeyLocator().getKeyName()
        signatureName2 = data2.getSignature().getKeyLocator().getKeyName()

        self.assertTrue(
            policyManager._checkSignatureMatch(signatureName1, dataName,
                                               matchedRule))
        self.assertFalse(
            policyManager._checkSignatureMatch(signatureName2, dataName,
                                               matchedRule))

        dataName = Name('/SecurityTestSecRule/Basic/Other/Data1')
        data1 = Data(dataName)
        data2 = Data(dataName)

        matchedRule = policyManager._findMatchingRule(dataName, 'data')
        self.keyChain.sign(data1, self.defaultCertName)
        self.keyChain.sign(data2, self.shortCertName)

        signatureName1 = data1.getSignature().getKeyLocator().getKeyName()
        signatureName2 = data2.getSignature().getKeyLocator().getKeyName()

        self.assertFalse(
            policyManager._checkSignatureMatch(signatureName1, dataName,
                                               matchedRule))
        self.assertTrue(
            policyManager._checkSignatureMatch(signatureName2, dataName,
                                               matchedRule))

    def test_interest_matching(self):
        # make sure we chop off timestamp, nonce, and signature info from
        # signed interests
        pass
def startFileSync():
    global EXIT
    screenName = promptAndInput("Enter your name: ")

    defaultHubPrefix = "ndn/no/ntnu"
    hubPrefix = promptAndInput("Enter your hub prefix [" + defaultHubPrefix + "]: ")
    if hubPrefix == "":
        hubPrefix = defaultHubPrefix

    defaultpkList = "pklist"
    pkListName = promptAndInput("Sync with public key list [" + defaultpkList + "]: ")
    if pkListName == "":
        pkListName = defaultpkList

    host = "localhost" 
    # host = "129.241.208.115"
    logging.info("Connecting to " + host + ", public Key List: " + pkListName + ", Name: " + screenName)

    # Set up the key chain.
    face = Face(host)

    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    # privateKeyStorage = OSXPrivateKeyStorage()
    identityManager = IdentityManager(identityStorage, privateKeyStorage)
    # identityManager.createIdentity(Name("/name/"))
    keyChain = KeyChain(identityManager, NoVerifyPolicyManager())
    keyChain.setFace(face)
    
    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)
    face.setCommandSigningInfo(keyChain, certificateName)

    # keyName = Name("/ndn/no/ntnu/stud/haakonmo/ksk-1426537450856")
    # certificateName = Name("/ndn/no/ntnu/KEY/stud/haakonmo/ksk-1426537450856/ID-CERT/%FD%00%00%01L%26%D9E%92")

    # publicKey = privateKeyStorage.getPublicKey(keyName)
    # identityStorage.addKey(keyName, publicKey.getKeyType(), publicKey.getKeyDer())
    # face.setCommandSigningInfo(keyChain, certificateName)

    # print(identityStorage.getCertificate(certificateName))
    # print(identityStorage.getKey(keyName))

    path = './files/'
    fileSyncer = FileSync(screenName, pkListName, Name(hubPrefix), face, keyChain, certificateName, path)
    fileSyncer.initial()    

    fileWatcher = FileWatch(fileSyncer, path)
    # TODO:
    #    1. Generate new public key or use existing?
    #    2. Watch new public key
    #    3. sendUpdatedPublicKey if key is changed
    #    4. Download and store other keys
    #    5. Verify data packet
    while not EXIT:
        isReady, _, _ = select.select([sys.stdin], [], [], 0)
        if len(isReady) != 0:
            input = promptAndInput("")
            if input == "leave" or input == "exit":
                EXIT = True
                break
            #fileSyncer.onFileUpdate(input)

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

    fileSyncer.unsubscribe()
    startTime = FileSync.getNowMilliseconds()
    while True:
        if FileSync.getNowMilliseconds() - startTime >= 1000.0:
            break

        face.processEvents()
        time.sleep(0.01)

    # Shutdown all services
    fileSyncer.face.shutdown()
    fileWatcher.stopFileWatch()
Beispiel #35
0
        cipher = PKCS1_v1_5.new(self.usr_key)
        ciphertext = cipher.encrypt(self.symkey)
        
        symkey_name = self.prefix.append(bytearray(self.timestamp)).append(bytearray(keyid))
        symkey_data = Data(symkey_name)
        symkey_data.setContent(bytearray(ciphertext))
        self.keychain.sign(symkey_data, self.cert_name)

        self.publisher.put(symkey_data)
        print symkey_data.getName().toUri()
        print 'Simple KDS stop'


# Only for testing
if __name__ == "__main__":
    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage))
    key_file = "../keychain/keys/melnitz_root.pem"
    f = open(key_file, "r")
    key = RSA.importKey(f.read())
    keyid = hashlib.sha256(key.publickey().exportKey("DER")).digest()
    bld_root = Name("/ndn/ucla.edu/bms/melnitz")
    key_name = bld_root.append(bytearray(keyid))
    key_pub_der = bytearray(key.publickey().exportKey(format="DER"))
    key_pri_der = bytearray(key.exportKey(format="DER"))
    identityStorage.addKey(key_name, KeyType.RSA, Blob(key_pub_der))
    privateKeyStorage.setKeyPairForKeyName(key_name, key_pub_der, key_pri_der)
    cert_name = key_name.getSubName(0, key_name.size() - 1).append(
        "KEY").append(key_name[-1]).append("ID-CERT").append("0")
Beispiel #36
0
def main():
    # Uncomment these lines to print ChronoSync debug messages.
    # logging.getLogger('').addHandler(logging.StreamHandler(sys.stdout))
    # logging.getLogger('').setLevel(logging.INFO)

    screenName = promptAndInput("Enter your chat username: "******"ndn/edu/ucla/remap"
    hubPrefix = promptAndInput("Enter your hub prefix [" + defaultHubPrefix +
                               "]: ")
    if hubPrefix == "":
        hubPrefix = defaultHubPrefix

    defaultChatRoom = "ndnchat"
    chatRoom = promptAndInput("Enter the chatroom name [" + defaultChatRoom +
                              "]: ")
    if chatRoom == "":
        chatRoom = defaultChatRoom

    host = "localhost"
    print("Connecting to " + host + ", Chatroom: " + chatRoom +
          ", Username: "******"")

    # Set up the key chain.
    face = Face(host)

    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
                        NoVerifyPolicyManager())
    keyChain.setFace(face)
    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)
    face.setCommandSigningInfo(keyChain, certificateName)

    chat = Chat(screenName, chatRoom, Name(hubPrefix), face, keyChain,
                certificateName)

    # The main loop to process Chat while checking stdin to send a message.
    print("Enter your chat message. To quit, enter \"leave\" or \"exit\".")
    while True:
        # Set timeout to 0 for an immediate check.
        isReady, _, _ = select.select([sys.stdin], [], [], 0)
        if len(isReady) != 0:
            input = promptAndInput("")
            if input == "leave" or input == "exit":
                # We will send the leave message below.
                break

            chat.sendMessage(input)

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

    # The user entered the command to leave.
    chat.leave()
    # Wait a little bit to allow other applications to fetch the leave message.
    startTime = Chat.getNowMilliseconds()
    while True:
        if Chat.getNowMilliseconds() - startTime >= 1000.0:
            break

        face.processEvents()
        time.sleep(0.01)
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")).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()
    dump(freshInterest.toUri())

    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"))
class BACnetAggregator(BIPSimpleApplication, Logging):

    def __init__(self, config):
        if _debug: BACnetAggregator._debug("__init__ %r", config)

        # get local address from the config file
        laddr = config.get('BACpypes', 'address')
        
        # make a local device object
        local_device = \
          LocalDeviceObject( objectName=config.get('BACpypes','objectName')
                             , objectIdentifier=config.getint('BACpypes','objectIdentifier')
                             , maxApduLengthAccepted=config.getint('BACpypes','maxApduLengthAccepted')
                             , segmentationSupported=config.get('BACpypes','segmentationSupported')
                             , vendorIdentifier=config.getint('BACpypes','vendorIdentifier')
              )
        
        # build a bit string that knows about the bit names
        pss = ServicesSupported()
        pss['whoIs'] = 1
        pss['iAm'] = 1
        pss['readProperty'] = 1
        pss['writeProperty'] = 1
        
        # set the property value to be just the bits
        local_device.protocolServicesSupported = pss.value
        
        # make a simple application
        BIPSimpleApplication.__init__(self, local_device, laddr)

        
        # create logger
        self.logger = BACnetDataLogger(self, config)
        self.loadKey()
        # keep track of requests to line up responses
        self._request = None

        # connect to local repo
        self.publisher = RepoSocketPublisher(12345)
        self.interval = 5 # in seconds
    
    def loadKey(self):
        self.identityStorage = MemoryIdentityStorage()
        self.privateKeyStorage = MemoryPrivateKeyStorage()
        self.keychain = KeyChain(IdentityManager(self.identityStorage, self.privateKeyStorage))

        f = open(key_file, "r")
        self.key = RSA.importKey(f.read())
        self.key_name = Name(bld_root).append(getKeyID(self.key))
        key_pub_der = bytearray(self.key.publickey().exportKey(format="DER"))
        key_pri_der = bytearray(self.key.exportKey(format="DER"))
        self.identityStorage.addKey(self.key_name, KeyType.RSA, Blob(key_pub_der))
        self.privateKeyStorage.setKeyPairForKeyName(self.key_name, key_pub_der, key_pri_der)
        self.cert_name = self.key_name.getSubName(0, self.key_name.size() - 1).append(
            "KEY").append(self.key_name[-1]).append("ID-CERT").append("0")

        print 'KeyName = ' + self.key_name.toUri()
        print 'CertName = ' + self.cert_name.toUri()

    def publishData(self, name_str, payload, timestamp):
        data = Data(Name(name_str).append(bytearray(timestamp)))
        iv = Random.new().read(AES.block_size)
        encryptor = AES.new(key, AES.MODE_CBC, iv)
        data.setContent(bytearray(time_s + iv + encryptor.encrypt(pad(json.dumps(payload)))))
        data.getMetaInfo().setFreshnessPeriod(10000)
        self.keychain.sign(data, self.cert_name)
        self.publisher.put(data)
        #print payload
        #print 'Publish ' + data.getName().toUri()

    def request(self, apdu):
        if _debug: BACnetAggregator._debug("request %r", apdu)

        # save a copy of the request
        self._request = apdu

        # forward it along
        BIPSimpleApplication.request(self, apdu)

    def confirmation(self, apdu):
        #print thread.get_ident()
        global kds_count, key, time_s, point_count
        
        if _debug: BACnetAggregator._debug("confirmation %r", apdu)

        if isinstance(apdu, Error):
            sys.stdout.write("error: %s\n" % (apdu.errorCode,))
            sys.stdout.flush()

        elif isinstance(apdu, AbortPDU):
            apdu.debug_contents()

        elif (isinstance(self._request, ReadPropertyRequest)) and (isinstance(apdu, ReadPropertyACK)):
            # find the datatype
            datatype = get_datatype(apdu.objectIdentifier[0], apdu.propertyIdentifier)
            BACnetAggregator._debug("    - datatype: %r", datatype)
            if not datatype:
                raise TypeError, "unknown datatype"

            # special case for array parts, others are managed by cast_out
            if issubclass(datatype, Array) and (apdu.propertyArrayIndex is not None):
                if apdu.propertyArrayIndex == 0:
                    value = apdu.propertyValue.cast_out(Unsigned)
                else:
                    value = apdu.propertyValue.cast_out(datatype.subtype)
            else:
                value = apdu.propertyValue.cast_out(datatype)
            BACnetAggregator._debug("    - value: %r", value)

            #sys.stdout.write(str(value) + '\n')
            #sys.stdout.flush()

            # KDS
            if kds_count % 1200 == 0:
                time_t = int(time.time() * 1000)
                time_s = struct.pack("!Q", time_t)
                
                key = Random.new().read(32)
                kds_thread = kds.SimpleKDSPublisher(Name(bld_root), self.keychain, self.cert_name, key, time_s)
                kds_thread.start()
                kds_count = 0

            kds_count = kds_count + 1
            #
            
            now = int(time.time() * 1000) # in milliseconds
            
            payload = {'ts': now, 'val': value}
            
            timestamp = struct.pack("!Q", now)
            self.publishData(datapoints[point_count]['prefix'], payload, timestamp)
            point_count = (point_count + 1) % len(datapoints)

            #
            #
            # We could move the 'sleep&read' looping into logger thread so
            # that we could parallel read and write processes. For now we
            # only work on a single thread. The logger thread simply kicks 
            # off the initial request and then exits.
            #
            if point_count == 0:
                time.sleep(self.interval)

            self.logger.do_read()

    def indication(self, apdu):
        if _debug: BACnetAggregator._debug("indication %r", apdu)

        if (isinstance(self._request, WhoIsRequest)) and (isinstance(apdu, IAmRequest)):
            device_type, device_instance = apdu.iAmDeviceIdentifier
            if device_type != 'device':
                raise DecodingError, "invalid object type"

            if (self._request.deviceInstanceRangeLowLimit is not None) and \
                (device_instance < self._request.deviceInstanceRangeLowLimit):
                pass
            elif (self._request.deviceInstanceRangeHighLimit is not None) and \
                (device_instance > self._request.deviceInstanceRangeHighLimit):
                pass
            else:
                # print out the contents
                sys.stdout.write('pduSource = ' + repr(apdu.pduSource) + '\n')
                sys.stdout.write('iAmDeviceIdentifier = ' + str(apdu.iAmDeviceIdentifier) + '\n')
                sys.stdout.write('maxAPDULengthAccepted = ' + str(apdu.maxAPDULengthAccepted) + '\n')
                sys.stdout.write('segmentationSupported = ' + str(apdu.segmentationSupported) + '\n')
                sys.stdout.write('vendorID = ' + str(apdu.vendorID) + '\n')
                sys.stdout.flush()

        # forward it along
        BIPSimpleApplication.indication(self, apdu)
Beispiel #39
0
def main():
    # Uncomment these lines to print ChronoSync debug messages.
    # logging.getLogger('').addHandler(logging.StreamHandler(sys.stdout))
    # logging.getLogger('').setLevel(logging.INFO)

    defaultUserPrefix = "com/newspaper/USER/bob"
    userPrefix = promptAndInput("Enter user prefix: [" + defaultUserPrefix + "]")
    if userPrefix == "":
        userPrefix = defaultUserPrefix

    defaultNamespacePrefix = "/ndn/hackathon/cnl-demo/slides" #"com/newspaper"
    namespacePrefix = promptAndInput("Enter namespace prefix [" + defaultNamespacePrefix + "]: ")
    if namespacePrefix == "":
        namespacePrefix = defaultNamespacePrefix

    host = "localhost" #"memoria.ndn.ucla.edu"
    print("Connecting to " + host)
    print("")

    # Set up the key chain.
    face = Face(host)

    identityStorage = MemoryIdentityStorage()
    privateKeyStorage = MemoryPrivateKeyStorage()
    keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
                        NoVerifyPolicyManager())
    keyChain.setFace(face)
    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)
    face.setCommandSigningInfo(keyChain, certificateName)

    newspaper = Namespace(namespacePrefix)
    
    def onContentSet(namespace, contentNamespace, callbackId):
        global currentSlideName
        if contentNamespace == namespace:
            print("content size "+str(contentNamespace.content.size()))
            currentSlideName = contentNamespace.getName()
            displayImage(contentNamespace.content.toRawStr(), contentNamespace.getName().toUri())
            # dump("Got segmented content ", contentNamespace.content.toRawStr())

    def onNewName(namespace, addedNamespace, callbackId):
        print("namespace ("+addedNamespace.getName().toUri()+") added to "+namespace.getName().toUri())
        if addedNamespace.getName().get(-1).isSegment() and addedNamespace.getName().get(-1).toSegment() == 0:
            addedNamespace.getParent().addOnContentSet(onContentSet)
            SegmentedContent(addedNamespace.getParent()).start()

    newspaper.addOnNameAdded(onNewName)
    newspaper.setFace(face)

    namesync = NameSyncHandler(newspaper, userPrefix, keyChain, certificateName)

    # The main loop to process Chat while checking stdin to send a message.
    print("Enter your namespace update. To quit, enter \"exit\".")

    def process():
        # while True:
        # Set timeout to 0 for an immediate check.
        isReady, _, _ = select.select([sys.stdin], [], [], 0)
        if len(isReady) != 0:
            input = promptAndInput("")
            if input == "exit":
                stopGui()
                # We will send the leave message below.
                # break

            # before producer has namespace.publish call, we manually call onNameAdded as a hack to publish
            namesync.onNameAdded(None, Namespace(Name(input)), 0, True)
        face.processEvents()
        if root: 
            root.after(100, process)

    def leftKey(event):
        global currentSlideName
        allVersions = newspaper.getChildComponents()
        currentVersion = currentSlideName[-1]
        selected = allVersions[0]
        for c in allVersions:
            print(str(c.toVersion()))
            if c.toVersion() == currentVersion.toVersion():
                break
            selected = c
        currentSlideName = Name(newspaper.getName()).append(selected)
        displayImage(newspaper.getChild(selected).content.toRawStr(), currentSlideName.toUri())

    def rightKey(event):
        global currentSlideName
        allVersions = newspaper.getChildComponents()
        currentVersion = currentSlideName[-1]
        selected = None
        for c in allVersions[::-1]:
            if c.toVersion() == currentVersion.toVersion():
                break
            selected = c
        if selected:
            currentSlideName = Name(newspaper.getName()).append(selected)
            displayImage(newspaper.getChild(selected).content.toRawStr(), currentSlideName.toUri())
        else:
            print("no slides to show")

    runGui(process, leftKey, rightKey)
def benchmarkEncodeDataSeconds(nIterations, useComplex, useCrypto):
    """
    Loop to encode a data packet nIterations times.

    :param int nIterations: The number of iterations.
    :param bool useComplex: If true, use a large name, large content and all
      fields. If false, use a small name, small content and only required
      fields.
    :param bool useCrypto: If true, sign the data packet.  If false, use a blank
      signature.
    :return: A tuple (duration, encoding) where duration is the number of
      seconds for all iterations and encoding is the wire encoding.
    :rtype: (float, Blob)
    """
    if useComplex:
        # Use a large name and content.
        name = Name(
          "/ndn/ucla.edu/apps/lwndn-test/numbers.txt/%FD%05%05%E8%0C%CE%1D/%00")

        contentString = ""
        count = 1
        contentString += "%d" % count
        count += 1
        while len(contentString) < 1115:
            contentString += " %d" % count
            count += 1
        content = Name.fromEscapedString(contentString)
    else:
        # Use a small name and content.
        name = Name("/test")
        content = Name.fromEscapedString("abc")
    finalBlockId = Name("/%00")[0]

    # 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))
    privateKeyStorage.setKeyPairForKeyName(
      keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER)

    # Set up signatureBits in case useCrypto is false.
    signatureBits = Blob(bytearray(256))
    emptyBlob = Blob([])

    start = getNowSeconds()
    for i in range(nIterations):
        data = Data(name)
        data.setContent(content)
        if useComplex:
            data.getMetaInfo().setFreshnessPeriod(1000)
            data.getMetaInfo().setFinalBlockId(finalBlockId)

        if useCrypto:
            # This sets the signature fields.
            keyChain.sign(data, certificateName)
        else:
            # Imitate IdentityManager.signByCertificate to set up the signature
            # fields, but don't sign.
            sha256Signature = data.getSignature()
            keyLocator = sha256Signature.getKeyLocator()
            keyLocator.setType(KeyLocatorType.KEYNAME)
            keyLocator.setKeyName(certificateName)
            sha256Signature.setSignature(signatureBits)

        encoding = data.wireEncode()

    finish = getNowSeconds()

    return (finish - start, encoding)
    def onInterest(self, prefix, interest, transport, registeredPrefixId):
        self.dump("Interest received from repo, name:", interest.getName().toUri())
        
    def onRegisterFailed(self, prefix):
        self.dump("Data prefix registration failed.")
    
if __name__ == '__main__':
    rp = RepoCommandParameter()
    dataPrefix = Name("/example/data/1/test/test1")
    
    rp.setName(dataPrefix)
    rp.setStartBlockId(0)
    
    interest = Interest(Name("/example/repo/1").append("insert").append(rp.wireEncode()))
    
    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)
class TestRegexMatching(ut.TestCase):

    def _certNameFromKeyName(self, keyName, keyIdx=-1):
        return keyName[:keyIdx].append("KEY").append(keyName[keyIdx:]).\
                append("ID-CERT").append("0")

    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)

    def test_name_relation(self):
        policyManagerPrefix = ConfigPolicyManager("policy_config/relation_ruleset_prefix.conf")
        policyManagerStrict = ConfigPolicyManager("policy_config/relation_ruleset_strict.conf")
        policyManagerEqual = ConfigPolicyManager("policy_config/relation_ruleset_equal.conf")

        dataName = Name('/TestRule1')

        self.assertIsNotNone(
                policyManagerPrefix._findMatchingRule(dataName, 'data'),
                "Prefix relation should match prefix name")
        self.assertIsNotNone(
                policyManagerEqual._findMatchingRule(dataName, 'data'),
                "Equal relation should match prefix name")
        self.assertIsNone(
                policyManagerStrict._findMatchingRule(dataName, 'data'),
                "Strict-prefix relation should not match prefix name")

        dataName = Name('/TestRule1/hi')
        self.assertIsNotNone(
                policyManagerPrefix._findMatchingRule(dataName, 'data'),
                "Prefix relation should match longer name")
        self.assertIsNone(
                policyManagerEqual._findMatchingRule(dataName, 'data'),
                "Equal relation should not match longer name")
        self.assertIsNotNone(
                policyManagerStrict._findMatchingRule(dataName, 'data'),
                "Strict-prefix relation should match longer name")

        dataName = Name('/Bad/TestRule1/')
        self.assertIsNone(
                policyManagerPrefix._findMatchingRule(dataName, 'data'),
                "Prefix relation should not match inner components")
        self.assertIsNone(
                policyManagerEqual._findMatchingRule(dataName, 'data'),
                "Equal relation should not match inner components")
        self.assertIsNone(
                policyManagerStrict._findMatchingRule(dataName, 'data'),
                "Strict-prefix relation should  not match inner components")

    def test_simple_regex(self):
        policyManager = ConfigPolicyManager("policy_config/regex_ruleset.conf")
        dataName1 = Name('/SecurityTestSecRule/Basic')
        dataName2 = Name('/SecurityTestSecRule/Basic/More')
        dataName3 = Name('/SecurityTestSecRule/')
        dataName4 = Name('/SecurityTestSecRule/Other/TestData')
        dataName5 = Name('/Basic/Data')

        matchedRule1 = policyManager._findMatchingRule(dataName1, 'data')
        matchedRule2 = policyManager._findMatchingRule(dataName2, 'data')
        matchedRule3 = policyManager._findMatchingRule(dataName3, 'data')
        matchedRule4 = policyManager._findMatchingRule(dataName4, 'data')
        matchedRule5 = policyManager._findMatchingRule(dataName5, 'data')

        self.assertIsNotNone(matchedRule1)
        self.assertIsNone(matchedRule2)
        self.assertIsNotNone(matchedRule3)
        self.assertNotEqual(matchedRule3, matchedRule1,
                "Rule regex matched extra components")
        self.assertIsNotNone(matchedRule4)
        self.assertNotEqual(matchedRule4, matchedRule1,
                "Rule regex matched with missing component")

        self.assertIsNone(matchedRule5)

    def test_checker_hierarchical(self):
        policyManager = ConfigPolicyManager("policy_config/hierarchical_ruleset.conf")

        dataName1 = Name('/SecurityTestSecRule/Basic/Data1')
        dataName2 = Name('/SecurityTestSecRule/Basic/Longer/Data2')

        data1 = Data(dataName1)
        data2 = Data(dataName2)

        matchedRule = policyManager._findMatchingRule(dataName1, 'data')
        self.assertEqual(matchedRule,
                policyManager._findMatchingRule(dataName2, 'data'))

        self.keyChain.sign(data1, self.defaultCertName)
        self.keyChain.sign(data2, self.defaultCertName)

        signatureName1 = data1.getSignature().getKeyLocator().getKeyName()
        signatureName2 = data2.getSignature().getKeyLocator().getKeyName()

        self.assertFalse(policyManager._checkSignatureMatch(signatureName1,
            dataName1, matchedRule),
            "Hierarchical matcher matched short data name to long key name")

        self.assertTrue(policyManager._checkSignatureMatch(signatureName2,
            dataName2, matchedRule))

        self.keyChain.sign(data1, self.shortCertName)
        self.keyChain.sign(data2, self.shortCertName)

        signatureName1 = data1.getSignature().getKeyLocator().getKeyName()
        signatureName2 = data2.getSignature().getKeyLocator().getKeyName()

        self.assertTrue(policyManager._checkSignatureMatch(signatureName1,
            dataName1, matchedRule))
        self.assertTrue(policyManager._checkSignatureMatch(signatureName2,
            dataName2, matchedRule))


    def test_hyperrelation(self):
        policyManager = ConfigPolicyManager("policy_config/hyperrelation_ruleset.conf")

        dataName = Name('/SecurityTestSecRule/Basic/Longer/Data2')
        data1 = Data(dataName)
        data2 = Data(dataName)

        matchedRule = policyManager._findMatchingRule(dataName, 'data')
        self.keyChain.sign(data1, self.defaultCertName)
        self.keyChain.sign(data2, self.shortCertName)

        signatureName1 = data1.getSignature().getKeyLocator().getKeyName()
        signatureName2 = data2.getSignature().getKeyLocator().getKeyName()

        self.assertTrue(policyManager._checkSignatureMatch(signatureName1,
            dataName, matchedRule))
        self.assertFalse(policyManager._checkSignatureMatch(signatureName2,
            dataName, matchedRule))

        dataName = Name('/SecurityTestSecRule/Basic/Other/Data1')
        data1 = Data(dataName)
        data2 = Data(dataName)

        matchedRule = policyManager._findMatchingRule(dataName, 'data')
        self.keyChain.sign(data1, self.defaultCertName)
        self.keyChain.sign(data2, self.shortCertName)

        signatureName1 = data1.getSignature().getKeyLocator().getKeyName()
        signatureName2 = data2.getSignature().getKeyLocator().getKeyName()

        self.assertFalse(policyManager._checkSignatureMatch(signatureName1,
            dataName, matchedRule))
        self.assertTrue(policyManager._checkSignatureMatch(signatureName2,
            dataName, matchedRule))

    def test_interest_matching(self):
        # make sure we chop off timestamp, nonce, and signature info from
        # signed interests
        pass
class TestConfigPolicyManager(ut.TestCase):
    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 tearDown(self):
        self.privateKeyStorage.deleteKeyPair(self.keyName)
        self.face.shutdown()
        try:
            os.remove(self.testCertFile)
        except OSError:
            pass

    def test_no_verify(self):
        policyManager = NoVerifyPolicyManager()
        identityName = Name('TestValidator/Null').appendVersion(int(time.time()))

        keyChain = KeyChain(self.identityManager, policyManager)
        keyChain.createIdentityAndCertificate(identityName)
        data = Data(Name(identityName).append('data'))
        keyChain.signByIdentity(data, identityName)

        vr = doVerify(policyManager, data)

        self.assertFalse(vr.hasFurtherSteps,
                "NoVerifyPolicyManager returned a ValidationRequest")

        self.assertEqual(vr.failureCount, 0,
            "Verification failed with NoVerifyPolicyManager")
        self.assertEqual(vr.successCount, 1,
            "Verification success called {} times instead of 1".format(
            vr.successCount))

    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 test_interest_timestamp(self):
        interestName = Name('/ndn/ucla/edu/something')
        certName = self.identityManager.getDefaultCertificateNameForIdentity(
                self.identityName)
        self.face.setCommandSigningInfo(self.keyChain, certName)

        oldInterest = Interest(interestName)
        self.face.makeCommandInterest(oldInterest)

        time.sleep(0.1) # make sure timestamps are different
        newInterest = Interest(interestName)
        self.face.makeCommandInterest(newInterest)

        vr  = doVerify(self.policyManager,
                newInterest)

        self.assertFalse(vr.hasFurtherSteps,
                "ConfigPolicyManager returned ValidationRequest but certificate is known")
        self.assertEqual(vr.failureCount, 0,
                "Verification of valid interest failed")
        self.assertEqual(vr.successCount, 1,
                "Verification success called {} times instead of 1".format(
                      vr.successCount))

        vr  = doVerify(self.policyManager,
                oldInterest)

        self.assertFalse(vr.hasFurtherSteps,
                "ConfigPolicyManager returned ValidationRequest but certificate is known")
        self.assertEqual(vr.successCount, 0,
                "Verification of stale interest succeeded")
        self.assertEqual(vr.failureCount, 1,
                "Failure callback called {} times instead of 1".format(
                      vr.failureCount))

    def _removeFile(self, filename):
        try:
            os.remove(filename)
        except OSError:
            # no such file
            pass

    def test_refresh_10s(self):
        with open('policy_config/testData', 'r') as dataFile:
            encodedData = dataFile.read()
            data = Data()
            dataBlob = Blob(b64decode(encodedData))
            data.wireDecode(dataBlob)

        # needed, since the KeyChain will express interests in unknown
        # certificates
        vr = doVerify(self.policyManager, data)

        self.assertTrue(vr.hasFurtherSteps,
                "ConfigPolicyManager did not create ValidationRequest for unknown certificate")
        self.assertEqual(vr.successCount, 0,
                "ConfigPolicyManager called success callback with pending ValidationRequest")
        self.assertEqual(vr.failureCount, 0,
                "ConfigPolicyManager called failure callback with pending ValidationRequest")

        # now save the cert data to our anchor directory, and wait
        # we have to sign it with the current identity or the
        # policy manager will create an interest for the signing certificate

        with open(self.testCertFile, 'w') as certFile:
            cert = IdentityCertificate()
            certData = b64decode(CERT_DUMP)
            cert.wireDecode(Blob(certData, False))
            self.keyChain.signByIdentity(cert, self.identityName)
            encodedCert = b64encode(cert.wireEncode().toBytes())
            certFile.write(Blob(encodedCert, False).toRawStr())

        # still too early for refresh to pick it up
        vr = doVerify(self.policyManager, data)

        self.assertTrue(vr.hasFurtherSteps,
                "ConfigPolicyManager refresh occured sooner than specified")
        self.assertEqual(vr.successCount, 0,
                "ConfigPolicyManager called success callback with pending ValidationRequest")
        self.assertEqual(vr.failureCount, 0,
                "ConfigPolicyManager called failure callback with pending ValidationRequest")
        time.sleep(6)

        # now we should find it
        vr  = doVerify(self.policyManager, data)

        self.assertFalse(vr.hasFurtherSteps,
                "ConfigPolicyManager did not refresh certificate store")
        self.assertEqual(vr.successCount, 1,
                "Verification success called {} times instead of 1".format(
                    vr.successCount))
        self.assertEqual(vr.failureCount, 0,
                "ConfigPolicyManager did not verify valid signed data")
class SensorDataLogger:
    def __init__(self, data_interval):
        # connect to modbus
        self.master = modbus_tcp.TcpMaster("172.17.66.246", 502)
        # self.master.set_timeout(120) # in seconds
        
        # connect to local repo
        self.publisher = RepoSocketPublisher(12345)
        self.prefix = "/ndn/ucla.edu/bms/strathmore/data/demand"
        self.interval = data_interval # in seconds
        
        self.loadKey()
        
    def loadKey(self):
        self.identityStorage = MemoryIdentityStorage()
        self.privateKeyStorage = MemoryPrivateKeyStorage()
        self.keychain = KeyChain(IdentityManager(self.identityStorage, self.privateKeyStorage))

        f = open(key_file, "r")
        self.key = RSA.importKey(f.read())
        self.key_name = Name(bld_root).append(getKeyID(self.key))
        key_pub_der = bytearray(self.key.publickey().exportKey(format="DER"))
        key_pri_der = bytearray(self.key.exportKey(format="DER"))
        self.identityStorage.addKey(self.key_name, KeyType.RSA, Blob(key_pub_der))
        self.privateKeyStorage.setKeyPairForKeyName(self.key_name, key_pub_der, key_pri_der)
        self.cert_name = self.key_name.getSubName(0, self.key_name.size() - 1).append(
            "KEY").append(self.key_name[-1]).append("ID-CERT").append("0")

        print 'KeyName = ' + self.key_name.toUri()
        print 'CertName = ' + self.cert_name.toUri()

    def publishData(self, key, key_ts, payload, timestamp):
        data = Data(Name(self.prefix).append(bytearray(timestamp)))
        iv = Random.new().read(AES.block_size)
        encryptor = AES.new(key, AES.MODE_CBC, iv)
        data.setContent(bytearray(key_ts + iv + encryptor.encrypt(pad(json.dumps(payload)))))
        data.getMetaInfo().setFreshnessPeriod(5000)
        self.keychain.sign(data, self.cert_name)
        self.publisher.put(data)
        #print payload
        #print data.getName().toUri()

    def run(self):
        key_ts = struct.pack('!Q', int(time.time() * 1000))
        key = Random.new().read(32)
        kds_count = -1
        
        while (True):
            # KDS
            kds_count = kds_count + 1
            if kds_count % 120 == 0:
                key_ts = struct.pack("!Q", int(time.time() * 1000))
                key = Random.new().read(32)
                kds_thread = kds.SimpleKDSPublisher(Name(bld_root), self.keychain, self.cert_name, key, key_ts)
                kds_thread.start()
                kds_count = 0

            # Data
            now = int(time.time() * 1000) # in milliseconds

            a = self.master.execute(100, cst.READ_HOLDING_REGISTERS, 166, 1)
            b = self.master.execute(100, cst.READ_HOLDING_REGISTERS, 167, 1)
            vln = (b[0] << 16) + a[0]
            c = self.master.execute(1, cst.READ_HOLDING_REGISTERS, 150, 1)
            la = c[0]
            
            payload = {'ts': now, 'vlna': vln, 'la': la}
            timestamp = struct.pack("!Q", now) # timestamp is in milliseconds

            self.publishData(key, key_ts, payload, timestamp)

            time.sleep(self.interval)