def loadAndPublishKey(self): self.ksk = pyccn.Key() self.ksk.generateRSA(1024) #self.ksk.fromPEM(filename = keyFile) self.ksk_name = self.prefix.appendKeyID(self.ksk) self.ksk_si = pyccn.SignedInfo(self.ksk.publicKeyID, pyccn.KeyLocator(self.ksk_name)) self.data_dsk = pyccn.Key() self.data_dsk.generateRSA(1024) self.data_dskname = self.prefix.append( 'data').appendVersion().appendKeyID(self.data_dsk) self.data_si = pyccn.SignedInfo(self.data_dsk.publicKeyID, pyccn.KeyLocator(self.data_dskname)) self.publish_dsk(self.data_dsk, self.data_dskname) print 'Publish data DSK: ' + str(self.data_dskname) self.kds_dsk = pyccn.Key() self.kds_dsk.generateRSA(1024) self.kds_dskname = self.prefix.append( 'kds').appendVersion().appendKeyID(self.kds_dsk) self.kds_si = pyccn.SignedInfo(self.kds_dsk.publicKeyID, pyccn.KeyLocator(self.kds_dskname)) self.publish_dsk(self.kds_dsk, self.kds_dskname) print 'Publish data DSK: ' + str(self.kds_dskname)
def upcall(self, kind, upcallInfo): if kind == pyccn.UPCALL_CONTENT or kind == pyccn.UPCALL_CONTENT_UNVERIFIED: co = upcallInfo.ContentObject #how to decript print 'G on data' co_content = json.loads(co.content) txt = co_content['ciphertxt'] #iv = encrypted_content[0:16] #ciphertxt = encrypted_content[16:len(encrypted_content)] #decipher = AES.new(symkey, AES.MODE_CBC, iv) #txt = unpad(decipher.decrypt(ciphertxt)) m = hashlib.sha256() m.update(symkey) m.update(co_content['uncripted']) if txt == m.hexdigest() and self.logger == None: content = json.loads(co_content['uncripted']) print 'content' print content aclname = pyccn.Name(str(content['acl_name'])) print aclname self.logger = SensorDataLogger(1000, content['trust_anchor'], content['prefix']) aclclosure = AclClosure(self.logger, self.device_prefix) handler0.expressInterest(aclname, aclclosure, interest_tmpl0) InterestBaseName = pyccn.Name(self.device_prefix).append('acl') print InterestBaseName handler0.setInterestFilter(InterestBaseName, aclclosure) elif kind == pyccn.UPCALL_INTEREST: print 'G on interest' interest = upcallInfo.Interest print interest.name pubkey = ksk.publicToDER() #iv = Random.new().read(AES.block_size) m = hashlib.sha256() m.update(symkey) m.update(pubkey) digest = m.hexdigest() #cipher = AES.new(symkey, AES.MODE_CBC, iv) #cipherkey = cipher.encrypt(pad(digest)) print 'digest' print digest sendpubkey = pyccn.Key() sendpubkey.fromDER(public=pubkey) co = pyccn.ContentObject( name=interest.name, content=digest, signed_info=pyccn.SignedInfo( ksk.publicKeyID, pyccn.KeyLocator(sendpubkey), type=pyccn.CONTENT_KEY, final_block=b'\x00')) #################### co.sign(ksk) handler0.put(co) elif kind == pyccn.UPCALL_INTEREST_TIMED_OUT: return pyccn.RESULT_REEXPRESS return pyccn.RESULT_OK
def __init__(self): self.key = pyccn.Key() self.key.fromPEM(filename='./keychain/keys/bms_root.pem') self.keyname = pyccn.Name('/ndn/ucla.edu/bms').appendKeyID(self.key) self.publisher = RepoSocketPublisher(12345) self.device = device self.usrlist = usrlist self.acl_count = 1 self.acl_tree = None self.FormAclTree() self.GenerateAcl() self.dsk = pyccn.Key() self.dsk.fromPEM(filename='./keychain/keys/user_root.pem') self.dskname = pyccn.Name('/ndn/ucla.edu/bms/users').appendKeyID( self.dsk) i = 0 while i < len(self.device): #add version self.device[i]['acl_name'] = str( pyccn.Name(self.device[i]['acl_name']).appendVersion()) i = i + 1
def upcall(self, kind, upcallInfo): if kind == pyccn.UPCALL_CONTENT or kind == pyccn.UPCALL_CONTENT_UNVERIFIED: co = upcallInfo.ContentObject root_key = pyccn.Key() root_key.fromPEM(public=self.logger.anchor[0]['pubkey']) flag = co.verify_signature(root_key) if flag == True: if co.name.components[len(co.name.components) - 1] == 'acl': print 'getting acl name' inst_name = pyccn.Name(str(co.content)) handler0.expressInterest(inst_name, self, interest_tmpl) elif co.name.components[len(co.name.components) - 2] == 'acl': print 'getting acl' if self.logger.acl == None: self.logger.acl = json.loads(co.content)['acl'] self.logger.start() else: #self.logger.lock.acquire() self.logger.acl = json.loads(co.content)['acl'] #self.logger.lock.release() kds_prefix = str(self.logger.prefix.append('kds')) kds_thread = kds.KDSPublisher( key, time_s, self.logger.kds_dsk, self.logger.kds_si, self.logger.anchor, self.logger.acl, kds_prefix) #,self.logger.lock) kds_thread.start() #I need to trigger the kds to fetch symkey######## #self.logger.join() elif kind == pyccn.UPCALL_INTEREST: interest = upcallInfo.Interest content = 'received' co = pyccn.ContentObject(name=interest.name, content=content, signed_info=pyccn.SignedInfo( ksk.publicKeyID, pyccn.KeyLocator( self.logger.ksk_name))) co.sign(ksk) handler0.put(co) inst_name = pyccn.Name('/local/manager' + self.device_prefix).append('acl') handler0.expressInterest(inst_name, self, interest_tmpl0) elif kind == pyccn.UPCALL_INTEREST_TIMED_OUT: return pyccn.RESULT_REEXPRESS return pyccn.RESULT_OK
def upcall(self, kind, upcallInfo): if kind == pyccn.UPCALL_CONTENT or kind == pyccn.UPCALL_CONTENT_UNVERIFIED: co = upcallInfo.ContentObject print 'manager on data' print str(co.name) if co.name.components[len(co.name.components) - 1] == 'pubkey': device_name = co.name.components[len(co.name.components) - 3] serial = co.name.components[len(co.name.components) - 2] test = co.signedInfo.keyLocator.key.publicToDER() print 'publicToDER' print test prefix = self.cm.decoder(device_name, serial, co.content, test, 'data') if (prefix != None): keyname = pyccn.Name(prefix).appendVersion().appendKeyID( co.signedInfo.keyLocator.key) content = pyccn.ContentObject(name=keyname, content=test, signed_info=pyccn.SignedInfo( self.cm.key.publicKeyID, pyccn.KeyLocator( self.cm.keyname))) content.sign(self.cm.key) self.cm.publisher.put(content) print 'publish G\'s public key to repo' elif co.name.components[len(co.name.components) - 1] != 'acl': content = json.loads(co.content) userkey = pyccn.Key() userkey.fromDER(public=binascii.unhexlify(content['pubkey'])) userkey_co = pyccn.ContentObject() userkey_co.name = pyccn.Name(str( content['name'])).appendKeyID(userkey) userkey_co.content = binascii.unhexlify(content['pubkey']) userkey_co.signedInfo = pyccn.SignedInfo( self.cm.dsk.publicKeyID, pyccn.KeyLocator(self.cm.dskname), type=pyccn.CONTENT_KEY, final_block=b'\x00') userkey_co.sign(self.cm.dsk) self.cm.publisher.put(userkey_co) newuser = { 'usrname': str(userkey_co.name), 'prefix': content['data_prefix'] } self.cm.usrlist.append(newuser) self.cm.AddUser(newuser) #publish user's data point list device_prefix = [] name_t = pyccn.Name(str(content['name'])).components username = pyccn.Name(name_t[0:len(name_t) - 1]).append('acl').appendVersion() for prefix in content['data_prefix']: name_t = pyccn.Name(str(prefix)) if (len(name_t.components) > 5): name_t = pyccn.Name(name_t.components[0:5]) name_str = str(name_t) if ((name_str in self.cm.acl_tree) == True): self.cm.node = [] self.cm.find_device(name_str) for device_name in self.cm.node: index = self.cm.findbyprefix(device_name) flag = (device_name + '/data_points') in device_prefix if (index != -1 and flag == False): device_prefix.append(device_name + '/data_points') data_prefix = pyccn.ContentObject( name=username, content=json.dumps({'prefix': device_prefix}), signed_info=pyccn.SignedInfo( self.cm.key.publicKeyID, pyccn.KeyLocator(self.cm.keyname))) data_prefix.sign(self.cm.dsk) self.cm.publisher.put(data_prefix) print device_prefix print 'Publish Data Points' #elif co.name.components[len(co.name.components)-1]=='acl': #verify? elif kind == pyccn.UPCALL_INTEREST: interest = upcallInfo.Interest print 'manager on interest' print interest.name if interest.name.components[len(interest.name.components) - 1] == 'userreg': user_prefix = pyccn.Name( interest.name.components[2:len(interest.name.components) - 1]) print user_prefix handler.expressInterest(user_prefix, self, interest_tmpl) elif interest.name.components[len(interest.name.components) - 1] != 'acl': device_name = interest.name.components[ len(interest.name.components) - 3] serial = interest.name.components[len(interest.name.components) - 2] info = interest.name.components[len(interest.name.components) - 1] test = interest.name.components[2:len(interest.name.components ) - 1] test = str(pyccn.Name(test)) sendtxt = self.cm.decoder(device_name, serial, info, test, 'interest') print 'sendtxt:' print sendtxt if (sendtxt != -1): co = pyccn.ContentObject(name=interest.name, content=sendtxt, signed_info=pyccn.SignedInfo( self.cm.key.publicKeyID, pyccn.KeyLocator( self.cm.keyname))) co.sign(self.cm.key) handler.put(co) #express interest for pubkey with the prefix it receive as well as listen acl inst_name = pyccn.Name(test).append('pubkey') #dataclosure = ConfigClosure() handler.expressInterest(inst_name, self, interest_tmpl) print 'M express Interest' print inst_name else: device_name = interest.name.components[ len(interest.name.components) - 3] serial = interest.name.components[len(interest.name.components) - 2] index = self.cm.find(device_name, serial) if index != -1: acl_name = self.cm.device[index]['acl_name'] print 'acl_name:' + acl_name co = pyccn.ContentObject(name=interest.name, content=acl_name, signed_info=pyccn.SignedInfo( self.cm.key.publicKeyID, pyccn.KeyLocator( self.cm.keyname))) co.sign(self.cm.key) handler.put(co) #it's the acl interest asking elif kind == pyccn.UPCALL_INTEREST_TIMED_OUT: print 'Reexpress interest' return pyccn.RESULT_REEXPRESS return pyccn.RESULT_OK
def run(self): #print "child thread started..." # For test purpose, run for 10 seconds only # Push content to repo every second global key, time_s i = 40 data_dsk_count = 1 kds_count = 0 kds_dsk_count = 1 point_count = 0 time_s = struct.pack("!Q", 0) point_con = pyccn.ContentObject() point_con.name = self.prefix.append('data_points') point_con.content = json.dumps({'datapoints': [str(self.data_prefix)] }) ################## point_con.signedInfo = self.data_si point_con.sign(self.data_dsk) self.publisher.put(point_con) print 'publish data points' print point_con.name while (True): # now = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) now = int(time.time() * 1000000000) # in nanoseconds payload = {'ts': str(now), 'val': random.randint(0, 100)} if kds_count % 120 == 0: if kds_dsk_count % 2 == 0: self.kds_dsk = pyccn.Key() self.kds_dsk.generateRSA(1024) self.kds_dskname = self.prefix.append( "kds").appendVersion().appendKeyID(self.kds_dsk) self.kds_si = pyccn.SignedInfo( self.kds_dsk.publicKeyID, pyccn.KeyLocator(self.kds_dskname)) self.publish_dsk(self.kds_dsk, self.kds_dskname) print 'Publish kds DSK: ' + str(self.kds_dskname) kds_dsk_count = 0 kds_dsk_count = kds_dsk_count + 1 time_t = int(time.time() * 1000) time_s = struct.pack("!Q", time_t) key = Random.new().read(32) kds_prefix = str(self.prefix.append('kds')) kds_thread = kds.KDSPublisher(key, time_s, self.kds_dsk, self.kds_si, self.anchor, self.acl, kds_prefix) #, self.lock) kds_thread.start() kds_count = 0 kds_count = kds_count + 1 timestamp = struct.pack("!Q", int( int(payload['ts']) / 1000000)) # timestamp is in milliseconds co = pyccn.ContentObject() co.name = self.data_prefix.append(timestamp) iv = Random.new().read(AES.block_size) encryptor = AES.new(key, AES.MODE_CBC, iv) co.content = time_s + iv + encryptor.encrypt( pad(json.dumps(payload))) co.signedInfo = self.data_si co.sign(self.data_dsk) self.publisher.put(co) if data_dsk_count % 120 == 0: self.data_dsk = pyccn.Key() self.data_dsk.generateRSA(1024) self.data_dskname = self.prefix.append( 'data').appendVersion().appendKeyID(self.data_dsk) self.data_si = pyccn.SignedInfo( self.data_dsk.publicKeyID, pyccn.KeyLocator(self.data_dskname)) self.publish_dsk(self.data_dsk, self.data_dskname) print 'Publish data DSK: ' + str(self.data_dskname) data_dsk_count = 0 data_dsk_count = data_dsk_count + 1 time.sleep(self.interval / 1000.0) print "leave child thread"
answerOriginKind=AOK_NONE, interestLifetime=1000.0) interest_tmpl0 = pyccn.Interest(scope=2) handler0 = pyccn.CCN() flag_terminate0 = 0 BS = 16 pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS) unpad = lambda s: s[0:-ord(s[-1])] keyFile = "./keychain/keys/boelter4809.pem" key = binascii.unhexlify( '14fe923dd3ac6e8945ea02e892db6b3192f2081cbab26b44147d308af58f5609') time_s = None ksk = pyccn.Key() ksk.generateRSA(1024) serial = '002' symkey = '\x8a\x1c\xe7\x8c\xd5\xdae#:\x91H\xfbU\xfc\x83\x19\xb9\xfeQH5\xcf$\x99\x84R\xcf\x11y\n1\xff' class RepoSocketPublisher(pyccn.Closure): def __init__(self, repo_port): self.repo_dest = ('127.0.0.1', int(repo_port)) self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect(self.repo_dest) def put(self, content): self.sock.send(_pyccn.dump_charbuf(content.ccn_data))
def put(self, content): self.sock.send(_pyccn.dump_charbuf(content.ccn_data)) publisher = RepoSocketPublisher(12345) for pair in keychain_config.keychain: signee_name = pair[0] signer_name = pair[1] signee_keyfile = keychain_config.keyfile_folder + keychain_config.keyfiles[ signee_name] signer_keyfile = keychain_config.keyfile_folder + keychain_config.keyfiles[ signer_name] signee_key = pyccn.Key() signee_key.fromPEM(filename=signee_keyfile) signer_key = pyccn.Key() signer_key.fromPEM(filename=signer_keyfile) signee_name = pyccn.Name(signee_name).appendKeyID(signee_key) signer_name = pyccn.Name(signer_name).appendKeyID(signer_key) key_co = pyccn.ContentObject() key_co.name = signee_name key_co.content = signee_key.publicToDER() key_co.signedInfo = pyccn.SignedInfo(signer_key.publicKeyID, pyccn.KeyLocator(signer_name), type=pyccn.CONTENT_KEY, final_block=b'\x00') key_co.sign(signer_key)
def upcall(self, kind, upcallInfo): global flag_terminate if kind == pyccn.UPCALL_CONTENT or kind == pyccn.UPCALL_CONTENT_UNVERIFIED: co = upcallInfo.ContentObject print "kds on data" print co.name keylocator = str(co.signedInfo.keyLocator.keyName) anchor_pubkey = self.authorize_by_anchor(str(co.name), keylocator) if anchor_pubkey != None: root_key = pyccn.Key() root_key.fromPEM(public=anchor_pubkey) flag = co.verify_signature(root_key) while flag == True and len(self.stack) > 0: key = pyccn.Key() key.fromDER(public=co.content) flag = self.stack[len(self.stack) - 1].verify_signature(key) co = self.stack.pop() if len(self.stack) == 0: usrpubkey = co.content print usrpubkey #publish usrkey = pyccn.Key() usrkey.fromDER(public=usrpubkey) key_t = RSA.importKey(usrpubkey) cipher = PKCS1_v1_5.new(key_t) ciphertext = cipher.encrypt(self.symkey) userdataname = self.prefix.append( self.timestamp).appendKeyID(usrkey) CO = pyccn.ContentObject(name=userdataname, content=ciphertext, signed_info=self.kds_si) CO.sign(self.kds_key) self.publisher.put(CO) print CO.name self.index = self.index + 1 if self.index < len(self.acl): nextname = pyccn.Name(str(self.acl[self.index])) handler.expressInterest(nextname, self, interest_tmpl) else: #print "overrrrrrrrrr" flag_terminate = 1 #print flag_terminate elif self.authorize_by_rule(str(co.name), keylocator) == True: self.stack.append(co) handler.expressInterest(pyccn.Name(keylocator), self, interest_tmpl) else: print "verification failed" flag_terminate = 1 elif kind == pyccn.UPCALL_INTEREST_TIMED_OUT: return pyccn.RESULT_REEXPRESS return pyccn.RESULT_OK
def getVerifiedKey(self, keyname, spaces): latestVersion = self.getLatestVersion( keyname) # will cache, if necessary if not latestVersion: return None if self.args.check_meta: timestamp = latestVersion.signedInfo.timeStamp key_digest = latestVersion.signedInfo.publisherPublicKeyDigest meta = self.getMetaInfo(latestVersion.name, key_digest, spaces[4:]) try: if not self.isValidMeta(meta, timestamp, spaces[4:]): return None except: if self.args.verbose: print "%s %s!!! corrupt or missing META data !!!%s" % ( spaces, bcolors.FAIL, bcolors.ENDC) # i.e., corrupt meta return None keyLocator = latestVersion.signedInfo.keyLocator if keyLocator: if keyLocator.keyName and str(keyLocator.keyName) != str(keyname): auth = self.authorizeKey(latestVersion.name, keyLocator.keyName) if self.args.verbose: print "%s|" % spaces print "%s+-> %s" % (spaces, auth["formattedName"]) if not auth["authorized"]: return False keyObject = self.getVerifiedKey(keyLocator.keyName, "%s " % spaces) if not keyObject: if self.args.verbose: print "%s %s!!! key cannot be fetched or verified !!!%s" % ( spaces, bcolors.FAIL, bcolors.ENDC) return False key = pyccn.Key() key.fromDER(public=keyObject.content) elif keyLocator.keyName: # self-signed if str(latestVersion.name) == NDN_root: if self.args.verbose: print "%s|" % spaces if latestVersion.signedInfo.publisherPublicKeyDigest == NDN_rootKeySha256: if self.args.verbose: print "%s--> %sself-signed NDN root%s" % ( spaces, bcolors.OKGREEN, bcolors.ENDC) key = pyccn.Key() key.fromDER(public=latestVersion.content) else: if self.args.verbose: print "%s %s!!! fake NDN root key !!!%s" % ( spaces, bcolors.FAIL, bcolors.ENDC) return None else: if self.args.verbose: print "%s|" % spaces print "%s--> %sinvalid self-signed trust anchor%s" % ( spaces, bcolors.FAIL, bcolors.ENDC) return None else: # another way to self-sign if str(latestVersion.name) == NDN_root: if self.args.verbose: print "%s|" % spaces if latestVersion.signedInfo.publisherPublicKeyDigest == NDN_rootKeySha256: if self.args.verbose: print "%s--> %sself-signed NDN root%s" % ( spaces, bcolors.OKGREEN, bcolors.ENDC) key = keyLocator.key else: if self.args.verbose: print "%s %s!!! fake NDN root key !!!%s" % ( spaces, bcolors.FAIL, bcolors.ENDC) return None else: if self.args.verbose: print "%s|" % spaces print "%s--> %sinvalid self-signed trust anchor%s" % ( spaces, bcolors.FAIL, bcolors.ENDC) return None else: if self.args.verbose: print "%s Key locator missing" return None if latestVersion.verify_signature(key): if self.args.check_meta: if meta.verify_signature(key): return latestVersion else: if self.args.verbose: print "%s--> %sinvalid signature for META data%s" % ( spaces, bcolors.FAIL, bcolors.ENDC) return None else: return latestVersion else: if self.args.verbose: print "%s--> %sinvalid signature%s" % (spaces, bcolors.FAIL, bcolors.ENDC) return None
#get the verified key keyLocator = slurp.co.signedInfo.keyLocator if keyLocator.keyName: #print "VERIFYING key " + str(keyLocator.keyName) keyBase = str(keyLocator.keyName[:-1]) keyEnd = str(pyccn.Name().append(keyLocator.keyName[-1])) print "[%sVERIFYING%s] key name %s%s%s%s" % ( verify.bcolors.OKBLUE, verify.bcolors.ENDC, verify.bcolors.OKGREEN, keyBase, verify.bcolors.ENDC, keyEnd) vkeyobj = kv.getVerifiedKey(keyLocator.keyName, spaces=" ") if not vkeyobj: print "%sUNSAFE CONTENT: key name%s %s%s%s%s %snot verified!!%s" % ( verify.bcolors.FAIL, verify.bcolors.ENDC, verify.bcolors.OKGREEN, keyBase, verify.bcolors.ENDC, keyEnd, verify.bcolors.FAIL, verify.bcolors.ENDC) else: vkey = pyccn.Key() vkey.fromDER(public=vkeyobj.content) if slurp.co.verify_signature(vkey): text = unicode(slurp.co.content, "utf-8", "replace") print("\n\n%s" % (text)) else: print "%sUNSAFE CONTENT: returned verified key for key name%s %s%s%s%s %sdoes not match signing key!!%s" % ( verify.bcolors.FAIL, verify.bcolors.ENDC, verify.bcolors.OKGREEN, keyBase, verify.bcolors.ENDC, keyEnd, verify.bcolors.FAIL, verify.bcolors.ENDC) else: print "no key locator key name"