コード例 #1
0
    def setUp(self):
        testCertDirectory = 'policy_config/certs'
        self.testCertFile = os.path.join(testCertDirectory, 'test.cert')

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

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

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

        pibKey = self.keyChain.getPib().getIdentity(self.identityName).getKey(
            self.keyName)
        # selfSign adds to the PIB.
        self.keyChain.selfSign(pibKey)
コード例 #2
0
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()
    freshInterest.getForwardingHint().add(1, Name("/A"))
    dump(freshInterest.toUri())

    # Set up the KeyChain.
    pibImpl = PibMemory()
    keyChain = KeyChain(pibImpl, TpmBackEndMemory(),
                        SelfVerifyPolicyManager(pibImpl))
    # This puts the public key in the pibImpl used by the SelfVerifyPolicyManager.
    keyChain.importSafeBag(
        SafeBag(Name("/testname/KEY/123"),
                Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False),
                Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False)))

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

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

    keyChain.verifyInterest(reDecodedFreshInterest,
                            makeOnVerified("Freshly-signed Interest"),
                            makeOnValidationFailed("Freshly-signed Interest"))
コード例 #3
0
    def _makeSelfSignedCertificate(keyName, privateKeyBag, publicKeyEncoding,
                                   password, digestAlgorithm, wireFormat):
        certificate = CertificateV2()

        # Set the name.
        now = Common.getNowMilliseconds()
        certificateName = Name(keyName)
        certificateName.append("self").appendVersion(int(now))
        certificate.setName(certificateName)

        # Set the MetaInfo.
        certificate.getMetaInfo().setType(ContentType.KEY)
        # Set a one-hour freshness period.
        certificate.getMetaInfo().setFreshnessPeriod(3600 * 1000.0)

        # Set the content.
        publicKey = PublicKey(publicKeyEncoding)
        certificate.setContent(publicKey.getKeyDer())

        # Create a temporary in-memory Tpm and import the private key.
        tpm = Tpm("", "", TpmBackEndMemory())
        tpm._importPrivateKey(keyName, privateKeyBag.toBytes(), password)

        # Set the signature info.
        if publicKey.getKeyType() == KeyType.RSA:
            certificate.setSignature(Sha256WithRsaSignature())
        elif publicKey.getKeyType() == KeyType.EC:
            certificate.setSignature(Sha256WithEcdsaSignature())
        else:
            raise ValueError("Unsupported key type")
        signatureInfo = certificate.getSignature()
        KeyLocator.getFromSignature(signatureInfo).setType(
            KeyLocatorType.KEYNAME)
        KeyLocator.getFromSignature(signatureInfo).setKeyName(keyName)

        # Set a 20-year validity period.
        ValidityPeriod.getFromSignature(signatureInfo).setPeriod(
            now, now + 20 * 365 * 24 * 3600 * 1000.0)

        # Encode once to get the signed portion.
        encoding = certificate.wireEncode(wireFormat)
        signatureBytes = tpm.sign(encoding.toSignedBytes(), keyName,
                                  digestAlgorithm)
        signatureInfo.setSignature(signatureBytes)

        # Encode again to include the signature.
        certificate.wireEncode(wireFormat)

        return certificate
コード例 #4
0
def main():

    backboneFace = Face()

    pibImpl = PibMemory()
    keyChain = KeyChain(pibImpl, TpmBackEndMemory(),
                        SelfVerifyPolicyManager(pibImpl))
    # This puts the public key in the pibImpl used by the SelfVerifyPolicyManager.
    keyChain.importSafeBag(
        SafeBag(Name("/testname/KEY/123"),
                Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False),
                Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False)))

    backboneFace.setCommandSigningInfo(keyChain,
                                       keyChain.getDefaultCertificateName())

    prefix = Name("/farm1")
    backboneFace.registerPrefix(prefix, onInterest, onRegisterFailed)
    print("Ready to go...")

    while 1:
        try:
            backboneFace.processEvents()

            e.acquire()
            frame = ieee.wait_read_frame(0.01)
            e.release()

            if frame is not None:
                if frame['rf_data'][0] == b'\x06' or frame['rf_data'][
                        0] == b'\x05':  #if Data or Interest
                    buffData[0] = frame['rf_data'][0]
                    buffData[1] = ord(frame['rf_data'][1]) + lCP
                    buffData[2] = frame['rf_data'][2]
                    buffData[3] = ord(frame['rf_data'][3]) + lCP
                    buffData[4:lCP + 4] = eCP
                    buffData[lCP + 4:] = frame['rf_data'][4:]
                    print(str(datetime.now().strftime('%X.%f')))
                    backboneFace.send(buffData)
                else:
                    print(frame['rf_data'][:])
            #time.sleep(0.1)
            gc.collect()
        except KeyboardInterrupt:
            backboneFace.shutdown()
            ser.close()
            break
コード例 #5
0
    def setUp(self):
        self.backEndMemory = TpmBackEndMemory()

        locationPath = os.path.abspath("policy_config/ndnsec-key-file")
        if os.path.exists(locationPath):
            # Delete files from a previous test.
            for fileName in os.listdir(locationPath):
                filePath = os.path.join(locationPath, fileName)
                if os.path.isfile(filePath):
                    os.remove(filePath)
        self.backEndFile = TpmBackEndFile(locationPath)

        self.backEndOsx = TpmBackEndOsx()

        self.backEndList = [None, None, None]
        self.backEndList[0] = self.backEndMemory
        self.backEndList[1] = self.backEndFile
        self.backEndList[2] = self.backEndOsx
コード例 #6
0
    def setUp(self):
        self.backEndMemory = TpmBackEndMemory()

        locationPath = os.path.abspath("policy_config/ndnsec-key-file")
        if os.path.exists(locationPath):
            # Delete files from a previous test.
            for fileName in os.listdir(locationPath):
                filePath = os.path.join(locationPath, fileName)
                if os.path.isfile(filePath):
                    os.remove(filePath)
        self.backEndFile = TpmBackEndFile(locationPath)

        self.backEndOsx = TpmBackEndOsx()

        self.backEndList = []
        self.backEndList.append(self.backEndMemory)
        self.backEndList.append(self.backEndFile)
        if sys.platform == 'darwin':
            self.backEndList.append(self.backEndOsx)
コード例 #7
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)

    # Set up the KeyChain.
    pibImpl = PibMemory()
    keyChain = KeyChain(
      pibImpl, TpmBackEndMemory(), SelfVerifyPolicyManager(pibImpl))
    # This puts the public key in the pibImpl used by the SelfVerifyPolicyManager.
    keyChain.importSafeBag(SafeBag
      (Name("/testname/KEY/123"),
       Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False),
       Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False)))

    keyChain.verifyData(reDecodedData, makeOnVerified("Re-decoded Data"),
                        makeOnValidationFailed("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)
    dump("")
    dump("Freshly-signed Data:")
    dumpData(freshData)

    keyChain.verifyData(freshData, makeOnVerified("Freshly-signed Data"),
                        makeOnValidationFailed("Freshly-signed Data"))
コード例 #8
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.
    pibImpl = PibMemory()
    keyChain = KeyChain(pibImpl, TpmBackEndMemory(),
                        SelfVerifyPolicyManager(pibImpl))
    # This puts the public key in the pibImpl used by the SelfVerifyPolicyManager.
    keyChain.importSafeBag(
        SafeBag(
            Name("/testname/KEY/123"),
            Blob(
                DEFAULT_EC_PRIVATE_KEY_DER if keyType == KeyType.ECDSA else
                DEFAULT_RSA_PRIVATE_KEY_DER, False),
            Blob(
                DEFAULT_EC_PUBLIC_KEY_DER if keyType == KeyType.ECDSA else
                DEFAULT_RSA_PUBLIC_KEY_DER, False)))

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

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

    finish = getNowSeconds()

    return finish - start
コード例 #9
0
def benchmarkEncodeDataSeconds(nIterations, useComplex, useCrypto, keyType):
    """
    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.
    :param KeyType keyType: KeyType.RSA or EC, used if useCrypto is True.
    :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.
    pibImpl = PibMemory()
    keyChain = KeyChain(pibImpl, TpmBackEndMemory(),
                        SelfVerifyPolicyManager(pibImpl))
    keyChain.importSafeBag(
        SafeBag(
            Name("/testname/KEY/123"),
            Blob(
                DEFAULT_EC_PRIVATE_KEY_DER if keyType == KeyType.ECDSA else
                DEFAULT_RSA_PRIVATE_KEY_DER, False),
            Blob(
                DEFAULT_EC_PUBLIC_KEY_DER if keyType == KeyType.ECDSA else
                DEFAULT_RSA_PUBLIC_KEY_DER, False)))
    certificateName = keyChain.getDefaultCertificateName()

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

    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)
        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)