def benchmarkDecodeDataSeconds(nIterations, useCrypto, keyType, encoding):
    """
    Loop to decode a data packet nIterations times.

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

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

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

    finish = getNowSeconds()

    return finish - start
Exemplo n.º 2
0
def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

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

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

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

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

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

    while enabled[0]:
        face.processEvents()
        # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
        time.sleep(0.01)
Exemplo n.º 3
0
 def delete_security_object(name, kind):
     key_chain = KeyChain()
     logging.info("Delete security object %s %s", name, kind)
     if kind == "c":
         id_name = CertificateV2.extractIdentityFromCertName(Name(name))
         key_name = CertificateV2.extractKeyNameFromCertName(Name(name))
         cur_id = key_chain.getPib().getIdentity(id_name)
         cur_key = cur_id.getKey(key_name)
         key_chain.deleteCertificate(cur_key, Name(name))
     elif kind == "k":
         id_name = PibKey.extractIdentityFromKeyName(Name(name))
         cur_id = key_chain.getPib().getIdentity(id_name)
         cur_key = cur_id.getKey(Name(name))
         key_chain.deleteKey(cur_id, cur_key)
     else:
         key_chain.deleteIdentity(Name(name))
Exemplo n.º 4
0
 def create_identity(name):
     key_chain = KeyChain()
     try:
         cur_id = key_chain.getPib().getIdentity(Name(name))
         key_chain.createKey(cur_id)
     except Pib.Error:
         key_chain.createIdentityV2(Name(name))
def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

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

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

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

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

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

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

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

    validator.validate(
      reDecodedFreshInterest, makeSuccessCallback("Freshly-signed Interest"),
      makeFailureCallback("Freshly-signed Interest"))
Exemplo n.º 6
0
def main():
    # Silence the warning from Interest wire encode.
    Interest.setDefaultCanBePrefix(True)

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

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

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

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

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

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

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

    validator.validate(reDecodedFreshInterest,
                       makeSuccessCallback("Freshly-signed Interest"),
                       makeFailureCallback("Freshly-signed Interest"))
Exemplo n.º 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.
    keyChain = KeyChain("pib-memory:", "tpm-memory:")
    keyChain.importSafeBag(
        SafeBag(Name("/testname/KEY/123"),
                Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False),
                Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False)))
    validator = Validator(ValidationPolicyFromPib(keyChain.getPib()))

    validator.validate(reDecodedData, makeSuccessCallback("Re-decoded Data"),
                       makeFailureCallback("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)

    validator.validate(freshData, makeSuccessCallback("Freshly-signed Data"),
                       makeFailureCallback("Freshly-signed Data"))
Exemplo n.º 8
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.
    keyChain = KeyChain("pib-memory:", "tpm-memory:")
    keyChain.importSafeBag(SafeBag
      (Name("/testname/KEY/123"),
       Blob(DEFAULT_RSA_PRIVATE_KEY_DER, False),
       Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False)))
    validator = Validator(ValidationPolicyFromPib(keyChain.getPib()))

    validator.validate(reDecodedData, makeSuccessCallback("Re-decoded Data"),
      makeFailureCallback("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)

    validator.validate(freshData, makeSuccessCallback("Freshly-signed Data"),
      makeFailureCallback("Freshly-signed Data"))
def benchmarkDecodeDataSeconds(nIterations, useCrypto, keyType, encoding):
    """
    Loop to decode a data packet nIterations times.

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

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

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

    finish = getNowSeconds()

    return finish - start
Exemplo n.º 10
0
class TestPolicyManagerV2(ut.TestCase):
    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)

    def tearDown(self):
        try:
            os.remove(self.testCertFile)
        except OSError:
            pass

    def test_interest_timestamp(self):
        interestName = Name('/ndn/ucla/edu/something')
        certName = self.keyChain.getPib().getIdentity(
            self.identityName).getKey(
                self.keyName).getDefaultCertificate().getName()
        face = Face("localhost")
        face.setCommandSigningInfo(self.keyChain, certName)

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

        time.sleep(0.1)  # make sure timestamps are different
        newInterest = Interest(interestName)
        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 test_refresh_10s(self):
        with open('policy_config/testData', 'r') as dataFile:
            encodedData = dataFile.read()
            data = Data()
            dataBlob = Blob(b64decode(encodedData))
            data.wireDecode(dataBlob)

        # This test is 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.

        cert = CertificateV2()
        certData = b64decode(CERT_DUMP)
        cert.wireDecode(Blob(certData, False))
        signingInfo = SigningInfo()
        signingInfo.setSigningIdentity(self.identityName)
        # Make sure the validity period is current for two years.
        now = Common.getNowMilliseconds()
        signingInfo.setValidityPeriod(
            ValidityPeriod(now, now + 2 * 365 * 24 * 3600 * 1000.0))

        self.keyChain.sign(cert, signingInfo)
        encodedCert = b64encode(cert.wireEncode().toBytes())
        with open(self.testCertFile, 'w') as certFile:
            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")
Exemplo n.º 11
0
class Experiment:

    _maxSegmentPayloadLength = 8192

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

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

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

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

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

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

    #     self.attributes = [b'attribute%d' % i for i in range(1, nAttributes + 1)]
    #     self._setupAbs(absPath)
    #     self._readDataAndCreateManifests(filename, groupSize, keepData)

    def setupAbs(self, nAttributes):
        self.attributes = [
            b'attribute%d' % i for i in range(1, nAttributes + 1)
        ]

    def _createManifest(self, name, manifestBuffer, nManifests):
        manifest = Data(name)
        manifest.setContent(manifestBuffer[0:nManifests * SHA256_DIGEST_SIZE])
        return manifest

    def readDataAndCreateManifests(self, filename, groupSize, keepData):
        if groupSize < 1:
            raise RuntimeError("Group size cannot be less than 1")

        self.allChunks = [
        ]  # for holding the generated data packets, including unsigned manifests
        self.allManifests = [
        ]  # for storing first unsigned manifest packets, which are then signed in-place
        self.rawDataCount = 0
        self.ndnChunkCount = 0

        seqNo = 0  # sequence number of data packets
        chunkNo = 0  # number of the chunk in the group

        with open(filename, 'rb') as f:

            # prepare space to store all manifests of the group (last manifest will not use all the space)
            def allocateBufferForDigests():
                return bytearray(groupSize * SHA256_DIGEST_SIZE)

            digests = allocateBufferForDigests()

            while f.readable():
                chunkPayload = f.read(self._maxSegmentPayloadLength)
                if len(chunkPayload) == 0:
                    break
                self.rawDataCount = self.rawDataCount + len(chunkPayload)

                chunk = Data(
                    Name("/icn2019/test/data").appendSequenceNumber(seqNo))
                seqNo = seqNo + 1
                chunk.setContent(chunkPayload)

                digestSignature = DigestSha256Signature()
                digestSignature.setSignature(
                    Blob(bytearray(SHA256_DIGEST_SIZE))
                )  # not real a valid signature, but ok for the experiment
                chunk.setSignature(digestSignature)

                if keepData:
                    self.allChunks.append(chunk)

                # only data chunks; manifest sizes counted separatedly, as they are signed
                self.ndnChunkCount = self.ndnChunkCount + chunk.wireEncode(
                ).size()

                # For storing data packet to a file
                # with open(writepath + "-1.txt", "wb") as dataf
                #     dataf.write(dpacket_bytes)

                implicitDigest = chunk.getFullName()[-1].getValue()

                offset = chunkNo * SHA256_DIGEST_SIZE
                digests[offset:offset +
                        SHA256_DIGEST_SIZE] = implicitDigest.toBytes()[:]

                chunkNo = chunkNo + 1

                if chunkNo == groupSize:
                    manifest = self._createManifest(
                        Name("/icn2019/test/data").appendSequenceNumber(seqNo),
                        digests, groupSize)  # full group
                    seqNo = seqNo + 1
                    self.allChunks.append(manifest)
                    self.allManifests.append(manifest)
                    chunkNo = 0
                    digests = allocateBufferForDigests()

            if chunkNo != 0:
                manifest = self._createManifest(
                    Name("/icn2019/test/data").appendSequenceNumber(seqNo),
                    digests, groupSize)  # partial group
                self.allChunks.append(manifest)
                self.allManifests.append(manifest)

            self.nDataChunks = seqNo - len(
                self.allManifests
            )  # number of data packets, excluding the manifests

    def signManifestsABS(self):
        self.manifestCount = 0
        self.signatureCounts = []
        for manifest in self.allManifests:
            self.signer.sign(manifest, self.attributes)
            self.manifestCount = self.manifestCount + manifest.wireEncode(
            ).size()
            self.signatureCounts.append(
                manifest.getSignature().getSignature().size())

    def verifyManifestsABS(self):
        for manifest in self.allManifests:
            if not self.signer.verify(manifest.wireEncode()):
                sys.stderr.write("Failed to verify %s\n" % manifest.getName())

    def signManifestsRSA(self):
        self.manifestCount = 0
        self.signatureCounts = []
        for manifest in self.allManifests:
            self.keyChain.sign(manifest)
            self.manifestCount = self.manifestCount + manifest.wireEncode(
            ).size()
            self.signatureCounts.append(
                manifest.getSignature().getSignature().size())

    def verifyManifestsRSA(self):
        def onSuccess(*k, **kw):
            pass

        def onFailure(data, *k, **kw):
            sys.stderr.write("Failed to verify %s\n" % manifest.getName())

        for manifest in self.allManifests:
            self.validator.validate(manifest, onSuccess, onFailure)
Exemplo n.º 12
0
class ClientModule():
    def __init__(self, caPrefix):
        self.ecdh = ECDHState()
        self.face = Face()
        self.keyChain = KeyChain()
        self.key = None
        self.caPrefix = caPrefix
        self.anchor = CertificateV2()
        self.anchor.wireDecode(
            Blob(
                b64decode(
                    "Bv0DgQc7CANuZG4IA2VkdQgHbWVtcGhpcwgIYWdhd2FuZGUIA0tFWQgIo6cuGT4GVKEIAk5BCAn9AAABbQxT3hEUCRgBAhkEADbugBX9ASYwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDII1sLOE7cCQVTKoGjeM5o/mxWqhMx0siLHJ81Ee/eUCNAMxA0w1oxAoTGQ8HbNP3vShZfvMJ/11Jiqus2wAWlNjRWvQShNv5MueU8kYtOGTbiqr/I1EpSRQ2aJX3s49CoskoWMzf6knK4ELleH3/EBUPGJK0cpHHdFOjwlzO3Y3Rtc/DhHVTVsBWvPS1wKgnzBFO36k73gAQJi4bOc0ggPPcK3UfVzpz8XTe+IcS2N9jew+kDqoZaL+HHz26PIAwQvXQFXPhE6y/nH/4yes24DlK3u+vHTQHXRKcLNSpYvmS6KrHvt2t01Fk0hXxeFkbh4XaE73eXB9AzNw+AccovAgMBAAEW/QEHGwEBHCQHIggDbmRuCANlZHUIB21lbXBoaXMIA0tFWQgI9bIQPIJIGTf9AP0m/QD+DzIwMTkwOTA2VDE1MjQ0Nf0A/w8yMDIwMDkwNlQxNTI0NDX9AQKw/QIAD/0CAQdhZHZpc29y/QICAP0CACH9AgEFZW1haWz9AgIUYWdhd2FuZGVAbWVtcGhpcy5lZHX9AgAf/QIBCGZ1bGxuYW1l/QICD0FzaGxlc2ggR2F3YW5kZf0CAA39AgEFZ3JvdXD9AgIA/QIAD/0CAQdob21ldXJs/QICAP0CAC39AgEMb3JnYW5pemF0aW9u/QICGVRoZSBVbml2ZXJzaXR5IG9mIE1lbXBoaXMX/QEAMZ4XLBqFjABr/k58Gq6GrNfaDMb+NLyJYF5X2mDwKnUgp1is83eg/90LqO8AVGYdyirKfr23HP4565iJXhOmFgRbP+faN++0oUTXdUSvDm43Rp+OCHr9uGPPYjUjUeNhrD7Fxfq5m3EHNMxQqnVJOODpVrF3D0EYJ4Q4IETmxrSmuDpH9I92fs7rU/51aNAZbU7DewPmcq/IrY4RO5G9pfYR+gu/gyO/L8gN39EhBbsOYWOh3EYOdAJlSktP1evL/5yRdQq7bVLyG6dZSsYQ1x4XDJ9epUesZ+TbCK/lXfRrmFG9uk8TI/rZNAYfUiQifnsNvRu34PcyELiFJ/h2xA=="
                )))
        self.identityName = ""
        self.status = None
        self.requestId = None
        self.challenges = None

    def sendProbeInterest(self):
        probeInterest = Interest(
            Name(self.caPrefix).append("CA").append("_PROBE"))

        probeInterest.setMustBeFresh(True)
        probeInterest.setCanBePrefix(False)

        probeInterest.setApplicationParameters(
            json.dumps({"email": "*****@*****.**"}, indent=4))
        probeInterest.appendParametersDigestToName()

        print("Expressing interest: {}".format(probeInterest.getName()))
        self.face.expressInterest(probeInterest, self.onProbeData,
                                  self.onTimeout)

    def onProbeData(self, interest, data):
        """ Content:
          {
              "email": "*****@*****.**",
              "UID": "",
              "name: "\/ndn\/edu\/memphis\/agawande\/6046888920342781294"
          }
          1) Verify signature
          2) Extract name component from the json to use as identity
        """
        if not VerificationHelpers.verifyDataSignature(data, self.anchor):
            print("Cannot verify signature from: {}".format(self.caPrefix))
        else:
            print("Successfully verified data with hard-coded certificate")

        try:
            self.identityName = Name(
                json.loads(data.getContent().__str__())['name'])
            if self.identityName == "":
                print("Name received from server is empty")
                sys.exit(0)
        except Exception as e:
            print(e)

        print("Got namespace {} from server".format(self.identityName))
        self.generateKeyAndSendNewInterest(data)

    def generateKeyAndSendNewInterest(self, probeTokenData):
        """
        """
        pib = self.keyChain.getPib()
        try:
            identity = pib.getIdentity(self.identityName)
            self.key = self.keyChain.createKey(identity)
        except Exception as e:
            identity = self.keyChain.createIdentityV2(self.identityName)
            self.key = identity.getDefaultKey()

        cert = CertificateV2()
        cert.setName(
            Name(self.key.getName()).append("cert-request").appendVersion(
                int(time.time())))
        cert.getMetaInfo().setType(ContentType.KEY)
        cert.getMetaInfo().setFreshnessPeriod(24 * 3600)
        cert.setContent(self.key.getPublicKey())

        signingInfo = SigningInfo(self.key)
        now = Common.getNowMilliseconds()
        signingInfo.setValidityPeriod(
            ValidityPeriod(now, now + 24 * 3600 * 1000.0))
        self.keyChain.sign(cert, signingInfo)
        #cert = self.keyChain.selfSign(self.key) # Does not work because validity period is greater than certserver default

        interestName = Name(self.caPrefix).append("CA").append("_NEW")
        newInterest = Interest(interestName)
        newInterest.setMustBeFresh(True)
        newInterest.setCanBePrefix(False)

        ecdhPub = "{}\n".format(self.ecdh.getBase64PubKey())
        ecdhCertReq = "{}\n".format(
            b64encode(cert.wireEncode().toBytes()).decode('utf-8'))
        probeToken = "{}\n".format(
            b64encode(probeTokenData.wireEncode().toBytes()).decode('utf-8'))

        jsonDump = json.dumps(
            {
                "ecdh-pub": ecdhPub,
                "cert-request": ecdhCertReq,
                "probe-token": probeToken
            },
            indent=4)
        print(jsonDump)
        newInterest.setApplicationParameters(jsonDump)
        newInterest.appendParametersDigestToName()

        self.keyChain.sign(newInterest, SigningInfo(self.key))

        print(newInterest.getName())

        self.face.expressInterest(newInterest, self.onNewData, self.onTimeout)

    def onNewData(self, interest, data):
        """
        !! Again \n in public key??
        Got data:  {
            "ecdh-pub": "Aqxofe3QdsAfgbtS8TMxv31oudNKoSV307ci5gNXm88h\n",
            "salt": "12935684137560555161",
            "request-id": "14275252044236690531",
            "status": "0",
            "challenges": [
                {
                    "challenge-id": "Email"
                }
            ]
        }
        1. Verify data
        2. Derive shared secret
        """
        content = data.getContent()
        print("Got data: ", content)
        if not VerificationHelpers.verifyDataSignature(data, self.anchor):
            print("Cannot verify signature from: {}".format(self.caPrefix))
        else:
            print("Successfully verified data with hard-coded certificate")

        contentJson = json.loads(content.__str__())
        peerKeyBase64 = contentJson['ecdh-pub']
        self.status = contentJson['status']
        self.requestId = contentJson['request-id']
        self.challenges = contentJson['challenges']

        print(peerKeyBase64)

        serverPubKey = ec.EllipticCurvePublicKey.from_encoded_point(
            ec.SECP256R1(), b64decode(peerKeyBase64))

        shared_key = self.ecdh.private_key.exchange(ec.ECDH(), serverPubKey)
        derived_key = HKDF(algorithm=hashes.SHA256(),
                           length=32,
                           salt=contentJson['salt'].encode(),
                           info=b'handshake data',
                           backend=default_backend()).derive(shared_key)

        self.ecdh.derived_key = derived_key
        print(shared_key)
        for t in shared_key:
            print(t)

        challengeInterestName = Name(
            self.caPrefix).append("CA").append("_CHALLENGE").append(
                self.requestId)
        challengeInterest = Interest(challengeInterestName)
        challengeInterest.setMustBeFresh(True)
        challengeInterest.setCanBePrefix(False)

        # Encrypt the interest parameters
        challengeJson = json.dumps(
            {
                "selected-challenge": "Email",
                "email": "*****@*****.**"
            },
            indent=4)
        raw = self.pad(challengeJson, 16)
        print("raw", raw)
        iv = Random.new().read(AES.block_size)
        #cipher = AES.new(self.ecdh.derived_key, AES.MODE_CBC, iv)
        cipher = AES.new(shared_key, AES.MODE_CBC, iv)
        print(iv)
        xx = cipher.encrypt(raw)

        print(cipher.decrypt(xx))

        print("Printing iv:")
        for t in iv:
            print(t)

        encoder = TlvEncoder(256)
        saveLength = len(encoder)
        encoder.writeBlobTlv(632, iv)
        encoder.writeBlobTlv(630, cipher.encrypt(raw))
        #encoder.writeTypeAndLength(36, len(encoder) - saveLength)

        challengeInterest.setApplicationParameters(Blob(encoder.getOutput()))
        challengeInterest.appendParametersDigestToName()

        self.keyChain.sign(challengeInterest, SigningInfo(self.key))

        with open('foobar.tlv', 'wb') as f:
            f.write(challengeInterest.wireEncode().buf())
        self.face.expressInterest(challengeInterest, self.onChallengeData,
                                  self.onTimeout)

    def onChallengeData(self, interest, data):
        print("Got data: ", data)

    def pad(self, s, blocksize):
        return s + (blocksize - len(s) % blocksize) * ' '

    def onTimeout(self, interest):
        print("Got timeout for interest: {}".format(interest.getName()))

    def start(self):
        while True:
            self.face.processEvents()
            # We need to sleep for a few milliseconds so we don't use 100% of the CPU.
            time.sleep(0.01)
Exemplo n.º 13
0
class TestPolicyManagerV2(ut.TestCase):
    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)

    def tearDown(self):
        try:
            os.remove(self.testCertFile)
        except OSError:
            pass

    def test_interest_timestamp(self):
        interestName = Name('/ndn/ucla/edu/something')
        certName = self.keyChain.getPib().getIdentity(self.identityName).getKey(
          self.keyName).getDefaultCertificate().getName()
        face = Face("localhost")
        face.setCommandSigningInfo(self.keyChain, certName)

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

        time.sleep(0.1) # make sure timestamps are different
        newInterest = Interest(interestName)
        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 test_refresh_10s(self):
        with open('policy_config/testData', 'r') as dataFile:
            encodedData = dataFile.read()
            data = Data()
            dataBlob = Blob(b64decode(encodedData))
            data.wireDecode(dataBlob)

        # This test is 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.

        cert = CertificateV2()
        certData = b64decode(CERT_DUMP)
        cert.wireDecode(Blob(certData, False))
        signingInfo = SigningInfo()
        signingInfo.setSigningIdentity(self.identityName)
        # Make sure the validity period is current for two years.
        now = Common.getNowMilliseconds()
        signingInfo.setValidityPeriod(ValidityPeriod
          (now, now + 2 * 365 * 24 * 3600 * 1000.0))

        self.keyChain.sign(cert, signingInfo)
        encodedCert = b64encode(cert.wireEncode().toBytes())
        with open(self.testCertFile, 'w') as certFile:
            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")