Exemplo n.º 1
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
Exemplo n.º 2
0
    def beforeLoopStart(self):
        if not self._policyManager.hasRootSignedCertificate():
            # make one....
            self.log.warn('Generating controller certificate...')
            newKey = self._identityManager.generateRSAKeyPairAsDefault(
                self.prefix, isKsk=True)
            newCert = self._identityManager.selfSign(newKey)
            self._identityManager.addCertificateAsDefault(newCert)
        # Trusting root's own certificate upon each run
        # TODO: debug where application starts first and controller starts second, application's interest cannot be verified
        self._rootCertificate = self._keyChain.getCertificate(
            self.getDefaultCertificateName())
        self._policyManager._certificateCache.insertCertificate(
            self._rootCertificate)

        self._memoryContentCache = MemoryContentCache(self.face)
        self.face.setCommandSigningInfo(self._keyChain,
                                        self.getDefaultCertificateName())
        self._memoryContentCache.registerPrefix(
            self.prefix,
            onRegisterFailed=self.onRegisterFailed,
            onRegisterSuccess=None,
            onDataNotFound=self._onCommandReceived)
        # Serve root certificate in our memoryContentCache
        self._memoryContentCache.add(self._rootCertificate)
        self.loadApplications()
        self.loop.call_soon(self.onStartup)
Exemplo n.º 3
0
    def __init__(self, face, encryptResult, link = None):
        # Set up face
        self.face = face
        self._encryptResult = encryptResult
        self._link = link

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

        self.groupName = Name("/org/openmhealth/haitao")

        # Set up the keyChain.
        identityStorage = BasicIdentityStorage()
        privateKeyStorage = FilePrivateKeyStorage()
        self.keyChain = KeyChain(
          IdentityManager(identityStorage, privateKeyStorage),
          NoVerifyPolicyManager())
        # Authorized identity
        identityName = Name("/ndn/edu/basel/dpu")
        # Function name: the function that this DPU provides
        self._functionName = "bounding_box"
        self._identityName = identityName
        
        self.certificateName = self.keyChain.createIdentityAndCertificate(identityName)
        # TODO: if using BasicIdentityStorage and FilePrivateKeyStorage
        #   For some reason this newly generated cert is not installed by default, calling keyChain sign later would result in error
        #self.keyChain.installIdentityCertificate()
        
        self.face.setCommandSigningInfo(self.keyChain, self.certificateName)

        consumerKeyName = IdentityCertificate.certificateNameToPublicKeyName(self.certificateName)
        consumerCertificate = identityStorage.getCertificate(self.certificateName)
        self.consumer = Consumer(
          face, self.keyChain, self.groupName, identityName,
          Sqlite3ConsumerDb(self.databaseFilePath))

        # TODO: Read the private key to decrypt d-key...this may or may not be ideal
        base64Content = None
        with open(privateKeyStorage.nameTransform(consumerKeyName.toUri(), ".pri")) as keyFile:
            print privateKeyStorage.nameTransform(consumerKeyName.toUri(), ".pri")
            base64Content = keyFile.read()
            #print base64Content
        der = Blob(base64.b64decode(base64Content), False)
        self.consumer.addDecryptionKey(consumerKeyName, der)

        self.memoryContentCache = MemoryContentCache(self.face)
        self.memoryContentCache.registerPrefix(identityName, self.onRegisterFailed, self.onDataNotFound)
        self.memoryContentCache.add(consumerCertificate)

        accessRequestInterest = Interest(Name(self.groupName).append("read_access_request").append(self.certificateName).appendVersion(int(time.time())))
        self.face.expressInterest(accessRequestInterest, self.onAccessRequestData, self.onAccessRequestTimeout)
        print "Access request interest name: " + accessRequestInterest.getName().toUri()

        self._tasks = dict()

        return
Exemplo n.º 4
0
    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 onDataNotFound(prefix, interest, face, interestFilterId, filter):
    print "Data not found for interest: " + interest.getName().toUri()
    return


def onRegisterFailed(prefix):
    print "Prefix registration failed"
    return


if __name__ == "__main__":
    print "Start NAC producer test"
    face = Face()
    memoryContentCache = MemoryContentCache(face)
    # Produce encrypted data for this user
    username = "******"
    # Insert into this repo
    repoPrefix = "/ndn/edu/ucla/remap/ndnfit/repo"
    testProducer = SampleProducer(face, username, memoryContentCache)

    basetimeString = "20161024T080"
    baseZFill = 3
    baseLat = 34
    baseLng = -118
    # This should be less than 1 minute
    dataNum = 2

    # Create the content key once
    originalTimeString = basetimeString + str(0).zfill(baseZFill)
Exemplo n.º 6
0
    def startPublishing(self):
        # One-time security setup
        self.prepareLogging()

        privateKeyStorage = FilePrivateKeyStorage()
        identityStorage = BasicIdentityStorage()
        policyManager = ConfigPolicyManager(self._trustSchemaFile)

        self._keyChain = KeyChain(
            IdentityManager(identityStorage, privateKeyStorage), policyManager)
        self._certificateName = self._keyChain.createIdentityAndCertificate(
            self._identityName)

        print("My Identity name: " + self._identityName.toUri())
        print("My certificate name: " + self._certificateName.toUri())
        certificateData = self._keyChain.getIdentityManager(
        )._identityStorage.getCertificate(self._certificateName)
        print("My certificate string: " +
              b64encode(certificateData.wireEncode().toBuffer()))
        # self._keyChain.getIdentityCertificate(self._certificateName).)

        self._loop = asyncio.get_event_loop()
        self._face = ThreadsafeFace(self._loop)
        self._keyChain.setFace(self._face)

        self._face.setCommandSigningInfo(self._keyChain, self._certificateName)
        self._memoryContentCache = MemoryContentCache(self._face)

        # We should only ask for cert to be signed upon the first run of a certain aggregator
        if DO_CERT_SETUP:
            if (KeyLocator.getFromSignature(
                    certificateData.getSignature()).getKeyName().equals(
                        self._certificateName.getPrefix(-1))):
                # Need to configure for mini-ndn; aggregation node runs outside of mini-ndn first so that signed cert get installed and mini-ndn won't ask for this again
                print("certificate " + self._certificateName.toUri() +
                      " asking for signature")
                response = urllib2.urlopen(
                    "http://192.168.56.1:5000/bms-cert-hack?cert=" +
                    b64encode(certificateData.wireEncode().toBuffer()) +
                    "&cert_prefix=" + self._identityName.toUri() +
                    '&subject_name=' + self._identityName.toUri()).read()

                signedCertData = Data()
                signedCertData.wireDecode(Blob(b64decode(response)))

                self._memoryContentCache.add(signedCertData)
                cmdline = ['ndnsec-install-cert', '-']
                p = subprocess.Popen(cmdline,
                                     stdin=subprocess.PIPE,
                                     stdout=subprocess.PIPE)
                # desanitize + sign in GET request
                cert, err = p.communicate(response)
                if p.returncode != 0:
                    raise RuntimeError("ndnsec-install-cert error")
            else:
                self._memoryContentCache.add(certificateData)
        else:
            self._memoryContentCache.add(certificateData)

        dataNode = self.conf.getDataNode()
        childrenNode = self.conf.getChildrenNode()

        self._memoryContentCache.registerPrefix(Name(self._identityName),
                                                self.onRegisterFailed,
                                                self.onDataNotFound)

        # For each type of data, we refresh each type of aggregation according to the interval in the configuration
        for i in range(len(dataNode.subtrees)):
            dataType = dataNode.subtrees.keys()[i]
            aggregationParams = self.conf.getProducingParamsForAggregationType(
                dataNode.subtrees.items()[i][1])

            if childrenNode == None:
                self._dataQueue[dataType] = DataQueue(None, None, None)
                self.generateData(dataType, 2, 0)

            for aggregationType in aggregationParams:
                childrenList = OrderedDict()
                if childrenNode != None:

                    for j in range(len(childrenNode.subtrees)):
                        if dataType in childrenNode.subtrees.items(
                        )[j][1].subtrees['data'].subtrees:
                            if aggregationType in childrenNode.subtrees.items(
                            )[j][1].subtrees['data'].subtrees[
                                    dataType].subtrees:
                                childrenList[childrenNode.subtrees.items()[j][
                                    0]] = self.conf.getProducingParamsForAggregationType(
                                        childrenNode.subtrees.items()[j]
                                        [1].subtrees['data'].subtrees[dataType]
                                    )[aggregationType]

                self.startPublishingAggregation(
                    aggregationParams[aggregationType], childrenList, dataType,
                    aggregationType)
        return
    def __init__(self, face):
        # Set up face
        self.face = face

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

        self.groupName = Name("/org/openmhealth/haitao")

        # Set up the keyChain.
        identityStorage = BasicIdentityStorage()
        privateKeyStorage = FilePrivateKeyStorage()
        self.keyChain = KeyChain(
            IdentityManager(identityStorage, privateKeyStorage),
            NoVerifyPolicyManager())
        # Authorized identity
        identityName = Name("/org/openmhealth/dvu-python-3")
        # Unauthorized identity
        #identityName = Name("/org/openmhealth/dvu-python-1")

        self.certificateName = self.keyChain.createIdentityAndCertificate(
            identityName)

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

        consumerKeyName = IdentityCertificate.certificateNameToPublicKeyName(
            self.certificateName)
        consumerCertificate = identityStorage.getCertificate(
            self.certificateName)
        self.consumer = Consumer(face, self.keyChain, self.groupName,
                                 identityName,
                                 Sqlite3ConsumerDb(self.databaseFilePath))

        # TODO: Read the private key to decrypt d-key...this may or may not be ideal
        base64Content = None
        with open(
                privateKeyStorage.nameTransform(consumerKeyName.toUri(),
                                                ".pri")) as keyFile:
            print privateKeyStorage.nameTransform(consumerKeyName.toUri(),
                                                  ".pri")
            base64Content = keyFile.read()
            #print base64Content
        der = Blob(base64.b64decode(base64Content), False)
        self.consumer.addDecryptionKey(consumerKeyName, der)

        self.memoryContentCache = MemoryContentCache(self.face)
        self.memoryContentCache.registerPrefix(identityName,
                                               self.onRegisterFailed,
                                               self.onDataNotFound)
        self.memoryContentCache.add(consumerCertificate)

        accessRequestInterest = Interest(
            Name(self.groupName).append("read_access_request").append(
                self.certificateName).appendVersion(int(time.time())))
        self.face.expressInterest(accessRequestInterest,
                                  self.onAccessRequestData,
                                  self.onAccessRequestTimeout)
        print "Access request interest name: " + accessRequestInterest.getName(
        ).toUri()

        self.consumeCatalog = True
        return
Exemplo n.º 8
0
    def __init__(self,
                 face,
                 identityName,
                 groupName,
                 catalogPrefix,
                 rawDataPrefix,
                 producerDbFilePath,
                 consumerDbFilePath,
                 encrypted=False):
        self.face = face
        # Set up the keyChain.
        identityStorage = BasicIdentityStorage()
        privateKeyStorage = FilePrivateKeyStorage()
        self.keyChain = KeyChain(
            IdentityManager(identityStorage, privateKeyStorage),
            NoVerifyPolicyManager())
        self.identityName = Name(identityName)
        self.groupName = Name(groupName)
        self.rawDataPrefix = rawDataPrefix
        self.catalogPrefix = catalogPrefix

        self.certificateName = self.keyChain.createIdentityAndCertificate(
            self.identityName)
        self.face.setCommandSigningInfo(self.keyChain, self.certificateName)

        # Set up the memoryContentCache
        self.memoryContentCache = MemoryContentCache(self.face)
        self.memoryContentCache.registerPrefix(self.identityName,
                                               self.onRegisterFailed,
                                               self.onDataNotFound)

        self.producerPrefix = Name(identityName)
        self.producerSuffix = Name()

        self.producer = DPUProducer(face, self.memoryContentCache,
                                    self.producerPrefix, self.producerSuffix,
                                    self.keyChain, self.certificateName,
                                    producerDbFilePath)

        # Put own (consumer) certificate in memoryContentCache
        consumerKeyName = IdentityCertificate.certificateNameToPublicKeyName(
            self.certificateName)
        consumerCertificate = identityStorage.getCertificate(
            self.certificateName, True)

        # TODO: request that this DPU be added as a trusted group member

        self.remainingTasks = dict()

        try:
            os.remove(consumerDbFilePath)
        except OSError:
            # no such file
            pass

        self.consumer = Consumer(face, self.keyChain, self.groupName,
                                 consumerKeyName,
                                 Sqlite3ConsumerDb(consumerDbFilePath))

        # TODO: Read the private key to decrypt d-key...this may or may not be ideal
        base64Content = None
        with open(
                privateKeyStorage.nameTransform(consumerKeyName.toUri(),
                                                ".pri")) as keyFile:
            base64Content = keyFile.read()
        der = Blob(base64.b64decode(base64Content), False)
        self.consumer.addDecryptionKey(consumerKeyName, der)

        self.memoryContentCache.add(consumerCertificate)

        self.encrypted = encrypted

        self.rawData = []

        self.catalogFetchFinished = False
        self.remainingData = 0
        return