예제 #1
0
    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)
예제 #2
0
    def _sendNextInterest(self, name):
        interest = Interest(name)
        uri = name.toUri()

        interest.setApplicationParameters(self.prefixesToSend)
        interest.setInterestLifetimeMilliseconds(4000)
        interest.setMustBeFresh(True)

        if uri not in self.outstanding:
            self.outstanding[uri] = 1

        self.face.expressInterest(interest, self._onData, self._onTimeout)
        print "Sent Chat Prefixes to host " + str(self.host)
예제 #3
0
    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 _sendNextInterest(self, name):
        interest = Interest(name)
        uri = name.toUri()

        interest.setApplicationParameters(self.parameter)
        interest.setInterestLifetimeMilliseconds(4000)
        interest.setMustBeFresh(True)

        if uri not in self.outstanding:
            self.outstanding[uri] = 1

        self.face.expressInterest(interest, self._onData, self._onTimeout)
        print "Sent Interest for %s" % uri
        print interest
예제 #5
0
    def test_set_application_parameters(self):
        interest = Interest("/ndn")
        self.assertTrue(not interest.hasApplicationParameters())
        applicationParameters = Blob(bytearray([ 0x23, 0x00 ]))
        interest.setApplicationParameters(applicationParameters)
        self.assertTrue(interest.hasApplicationParameters())
        self.assertTrue(interest.getApplicationParameters().equals
                        (applicationParameters))

        decodedInterest = Interest()
        decodedInterest.wireDecode(interest.wireEncode())
        self.assertTrue(decodedInterest.getApplicationParameters().equals
                        (applicationParameters))

        interest.setApplicationParameters(Blob())
        self.assertTrue(not interest.hasApplicationParameters())
예제 #6
0
    def test_append_parameters_digest(self):
        name = Name("/local/ndn/prefix")
        interest = Interest(name)

        self.assertTrue(not interest.hasApplicationParameters())
        # No parameters yet, so it should do nothing.
        interest.appendParametersDigestToName()
        self.assertEqual("/local/ndn/prefix", interest.getName().toUri())

        applicationParameters = Blob(bytearray([ 0x23, 0x01, 0xC0 ]))
        interest.setApplicationParameters(applicationParameters)
        self.assertTrue(interest.hasApplicationParameters())
        interest.appendParametersDigestToName()
        self.assertEqual(name.size() + 1, interest.getName().size())
        self.assertTrue(interest.getName().getPrefix(-1).equals(name))
        SHA256_LENGTH = 32
        self.assertEqual(SHA256_LENGTH, interest.getName().get(-1).getValue().size())
        
        self.assertEqual(interest.getName().toUri(), "/local/ndn/prefix/" +
          "params-sha256=a16cc669b4c9ef6801e1569488513f9523ffb28a39e53aa6e11add8d00a413fc")
예제 #7
0
    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)