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
Example #2
0
    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])))
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"))
Example #4
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"))
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
Example #7
0
    def __init__(self, policy):
        super(ValidatorFixture, self).__init__()

        self._face = ValidatorFixture.TestFace()
        # Set maxLifetime to 100 days.
        self._cache = CertificateCacheV2(100 * 24 * 3600 * 1000.0)

        self._validator = Validator(policy, CertificateFetcherFromNetwork(self._face))
        self._policy = policy

        def processInterest(interest, onData, onTimeout, onNetworkNack):
            certificate = self._cache.find(interest)
            if certificate != None:
                onData(interest, certificate)
            else:
                onTimeout(interest)
        self._face._processInterest = processInterest
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"))
Example #9
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)