def get_candidates(): commandInterestName = ndn.Name() commandInterestName.wireDecode( # ndn.Blob(buffer(base64.b64decode(request.form['commandInterest'])))) ndn.Blob(base64.b64decode(request.form['commandInterest']))) site_prefix = ndn.Name() site_prefix.wireDecode(commandInterestName[-1].getValue().toBuffer()) timestamp = commandInterestName[-2] # TODO: haitao remove this hack after test #signature = ndn.WireFormat.getDefaultWireFormat().decodeSignatureInfoAndValue(commandInterestName[-2].getValue().toBuffer(), # commandInterestName[-1].getValue().toBuffer()) #keyLocator = signature.getKeyLocator().getKeyName() #operator = mongo.db.operators.find_one({'site_prefix': site_prefix.toUri()}) operator = { '_id': 1, 'site_name': 'UCLA', 'email': '*****@*****.**', 'doNotSendOpRequests': False, 'name': 'haitao' } if operator == None: abort(403) # @todo Command Interest verificateion requests = mongo.db.requests.find({'operator_id': str(operator['_id'])}) output = [] for req in requests: output.append(req) # return json.dumps (output) return json.dumps(output, default=json_util.default)
def handleCompletion(self): # print(self.segments) content = bytearray() for i in sorted(self.segments): segment = self.segments[i] content.extend(segment.getContent().buf()) blob = pyndn.Blob(content) data = pyndn.Data(self.interest.getName()) data.setContent(blob) self.data = data self.onData(self)
def get_candidates(): commandInterestName = ndn.Name() commandInterestName.wireDecode( # ndn.Blob(buffer(base64.b64decode(request.form['commandInterest'])))) ndn.Blob(base64.b64decode(request.form['commandInterest']))) site_prefix = ndn.Name() site_prefix.wireDecode(commandInterestName[-3].getValue().toBuffer()) timestamp = commandInterestName[-4] signature = ndn.WireFormat.getDefaultWireFormat( ).decodeSignatureInfoAndValue( commandInterestName[-2].getValue().toBuffer(), commandInterestName[-1].getValue().toBuffer()) keyLocator = signature.getKeyLocator().getKeyName() operator = mongo.db.operators.find_one( {'site_prefix': site_prefix.toUri()}) if operator == None: abort(403) try: keyChain = KeyChain( policyManager=OperatorVerifyPolicyManager(operator)) def onVerified(interest): pass def onVerifyFailed(interest): raise RuntimeError("Operator verification failed") keyChain.verifyInterest(ndn.Interest(commandInterestName), onVerified, onVerifyFailed, stepCount=1) except Exception as e: print("ERROR: %s" % e) abort(403) # Will get here if verification succeeds requests = mongo.db.requests.find({'operator_id': str(operator['_id'])}) output = [] for req in requests: output.append(req) return json.dumps(output, default=json_util.default)
def onInterest(self, prefix, interest, face, interestFilterId, filter): #print interest.getName() interestName = interest.getName() if interestName.isPrefixOf( Name( "/org/openmhealth/KEY/ksk-1490231565751/ID-CERT/%FD%00%00%01Z%F8%B9%1Et" )): face.putData( self.keyChain.getCertificate( Name( "/org/openmhealth/KEY/ksk-1490231565751/ID-CERT/%FD%00%00%01Z%F8%B9%1Et" ))) return with app.app_context(): certCursor = current_app.mongo.db.certs.find({}) for record in certCursor: print record['name'] if interestName.isPrefixOf(Name(record['name'])): data = Data() data.wireDecode( ndn.Blob(buffer(base64.b64decode(record['cert'])))) face.putData(data)
def get_candidates(): commandInterestName = ndn.Name() commandInterestName.wireDecode( ndn.Blob(buffer(base64.b64decode(request.form['commandInterest'])))) timestamp = commandInterestName[-3] keyLocator = ndn.Name() keyLocator.wireDecode(commandInterestName[-2].getValue()) signature = commandInterestName[-1] operator = mongo.db.operators.find_one({'site_prefix': keyLocator.toUri()}) if operator == None: abort(403) # @todo Command Interest verification requests = mongo.db.requests.find({'operator_id': str(operator['_id'])}) output = [] for req in requests: output.append(req) # return json.dumps (output) return json.dumps(output, default=json_util.default)
def submit_certificate(): data = ndn.Data() # data.wireDecode(ndn.Blob(buffer(base64.b64decode(request.form['data'])))) data.wireDecode( ndn.Blob(memoryview(base64.b64decode(request.form['data'])))) cert_request = mongo.db.requests.find_one( {'_id': ObjectId(str(request.form['id']))}) if cert_request == None: abort(403) operator = mongo.db.operators.find_one( {"_id": ObjectId(cert_request['operator_id'])}) if operator == None: mongo.db.requests.remove(cert_request) # remove invalid request abort(403) # # @todo verify data packet # # @todo verify timestamp if len(data.getContent()) == 0: # (no deny reason for now) # eventually, need to check data.type: if NACK, then content contains reason for denial # if KEY, then content is the certificate msg = Message("[NDN Certification] Rejected certification", sender=app.config['MAIL_FROM'], recipients=[cert_request['email']], body=render_template('cert-rejected-email.txt', URL=app.config['URL'], **cert_request), html=render_template('cert-rejected-email.html', URL=app.config['URL'], **cert_request)) mail.send(msg) mongo.db.requests.remove(cert_request) return "OK. Certificate has been denied" else: cert = { 'name': data.getName().toUri(), 'cert': request.form['data'], 'operator': operator, 'created_on': datetime.datetime.utcnow( ), # to periodically remove unverified tokens } mongo.db.certs.insert(cert) msg = Message("[NDN Certification] NDN certificate issued", sender=app.config['MAIL_FROM'], recipients=[cert_request['email']], body=render_template('cert-issued-email.txt', URL=app.config['URL'], quoted_cert_name=urllib.parse.quote( cert['name'], ''), cert_id=str(data.getName()[-3]), **cert_request), html=render_template('cert-issued-email.html', URL=app.config['URL'], quoted_cert_name=urllib.parse.quote( cert['name'], ''), cert_id=str(data.getName()[-3]), **cert_request)) mail.send(msg) mongo.db.requests.remove(cert_request) return "OK. Certificate has been approved and notification sent to the requester"
def submit_request(): if request.method == 'GET': # Email and token (to authorize the request==validate email) user_email = request.args.get('email') user_token = request.args.get('token') token = mongo.db.tokens.find_one({ 'email': user_email, 'token': user_token }) if (token == None): abort(403) site_prefix = token['site_prefix'] if site_prefix != "": try: params = get_operator_for_guest_site(user_email, site_prefix) except: abort(403) else: # infer parameters from email try: # pre-validation params = get_operator_for_email(user_email) except: abort(403) # don't delete token for now, just give user a form to input stuff return render_template('request-form.html', URL=app.config['URL'], email=user_email, token=user_token, **params) else: # 'POST' # Email and token (to authorize the request==validate email) user_email = request.form['email'] user_token = request.form['token'] token = mongo.db.tokens.find_one({ 'email': user_email, 'token': user_token }) if (token == None): abort(403) # Now, do basic validation of correctness of user input, save request in the database # and notify the operator #optional parameters user_fullname = request.form[ 'fullname'] if 'fullname' in request.form else "" user_homeurl = request.form[ 'homeurl'] if 'homeurl' in request.form else "" user_group = request.form['group'] if 'group' in request.form else "" user_advisor = request.form[ 'advisor'] if 'advisor' in request.form else "" site_prefix = token['site_prefix'] if site_prefix != "": try: params = get_operator_for_guest_site(user_email, site_prefix) except: abort(403) else: # infer parameters from email try: # pre-validation params = get_operator_for_email(user_email) except: abort(403) if site_prefix == "" and user_fullname == "": return render_template('request-form.html', error="Full Name field cannot be empty", URL=app.config['URL'], email=user_email, token=user_token, **params) try: user_cert_request = base64.b64decode(request.form['cert-request']) user_cert_data = ndn.Data() # user_cert_data.wireDecode(ndn.Blob(buffer(user_cert_request))) user_cert_data.wireDecode(ndn.Blob(memoryview(user_cert_request))) except: return render_template( 'request-form.html', error="Incorrectly generated NDN certificate request, " "please try again", URL=app.config['URL'], email=user_email, token=user_token, **params) # check if the user supplied correct name for the certificate request if not params['assigned_namespace'].isPrefixOf( user_cert_data.getName()): return render_template( 'request-form.html', error="Incorrectly generated NDN certificate request, " "please try again", URL=app.config['URL'], email=user_email, token=user_token, **params) # cert_name = extract_cert_name(user_cert_data.getName()).toUri() # # remove any previous requests for the same certificate name # mongo.db.requests.remove({'cert_name': cert_name}) cert_request = { 'operator_id': str(params['operator']['_id']), 'site_prefix': token['site_prefix'], 'assigned_namespace': str(params['assigned_namespace']), 'fullname': user_fullname, 'organization': params['operator']['site_name'], 'email': user_email, 'homeurl': user_homeurl, 'group': user_group, 'advisor': user_advisor, 'cert_request': base64.b64encode(user_cert_request), 'created_on': datetime.datetime.utcnow( ), # to periodically remove unverified tokens } mongo.db.requests.insert(cert_request) # OK. authorized, proceed to the next step mongo.db.tokens.remove(token) if (token['site_prefix'] != "" and not params['operator']['doNotSendOpRequestsForGuests']) or \ (token['site_prefix'] == "" and not params['operator']['doNotSendOpRequests']): msg = Message( "[NDN Certification] User certification request", sender=app.config['MAIL_FROM'], recipients=[params['operator']['email']], body=render_template('operator-notify-email.txt', URL=app.config['URL'], operator_name=params['operator']['name'], **cert_request), html=render_template('operator-notify-email.html', URL=app.config['URL'], operator_name=params['operator']['name'], **cert_request)) mail.send(msg) return render_template('request-thankyou.html')
def process_submitted_cert(cert_data, email, user_fullname): data = ndn.Data() data.wireDecode(ndn.Blob(buffer(base64.b64decode(cert_data)))) # @todo verify data packet # Additional operator verification needed? Operator key should be verified operator_prefix = extract_cert_name( data.getSignature().getKeyLocator().getKeyName()) operator = mongo.db.operators.find_one( {'site_prefix': operator_prefix.toUri()}) if operator == None: return json.dumps({ "status": 500, "message": "operator not found [%s]" % operator_prefix }) # @todo verify timestamp if (not app.config['AUTO_APPROVE']): cert_name = extract_cert_name(data.getName()) cert_request = mongo.db.requests.find_one( {'cert_name': cert_name.toUri()}) if cert_request == None: return json.dumps({ "status": 403, "message": "No cert request entry" }) if len(data.getContent()) == 0: # (no deny reason for now) # eventually, need to check data.type: if NACK, then content contains reason for denial # if KEY, then content is the certificate msg = Message( "[NDN Open mHealth Certification] Rejected certification", sender=app.config['MAIL_FROM'], recipients=[email], body=render_template('cert-rejected-email.txt', URL=app.config['URL'], fullname=user_fullname), html=render_template('cert-rejected-email.html', URL=app.config['URL'], fullname=user_fullname)) mail.send(msg) if (not app.config['AUTO_APPROVE']): mongo.db.requests.remove(cert_request) return json.dumps({ "status": 200, "message": "Certificate request denied" }) else: # may want to store assigned_namespace here as well cert = { 'name': data.getName().toUri(), 'cert': cert_data, 'operator': operator, 'created_on': datetime.datetime.utcnow(), } mongo.db.certs.insert(cert) msg = Message("[NDN Open mHealth Certification] Certificate issued", sender=app.config['MAIL_FROM'], recipients=[email], body=render_template('cert-issued-email.txt', URL=app.config['URL'], quoted_cert_name=urllib.quote( cert['name'], ), cert_id=str(data.getName()[-3]), fullname=user_fullname), html=render_template('cert-issued-email.html', URL=app.config['URL'], quoted_cert_name=urllib.quote( cert['name'], ''), cert_id=str(data.getName()[-3]), fullname=user_fullname)) mail.send(msg) if (not app.config['AUTO_APPROVE']): mongo.db.requests.remove(cert_request) return json.dumps({ "status": 200, "message": "OK. Certificate has been approved and notification sent to the requester" })
def submit_request(): if request.method == 'GET': # print 'GET' # Email and token (to authorize the request==validate email) user_email = request.args.get('email') user_token = request.args.get('token') token = mongo.db.tokens.find_one({ 'email': user_email, 'token': user_token }) if (token == None): abort(403, "No such token for this email address") # if getting operator fails, don't process this get request try: operator = get_operator() except Exception as e: print(e) abort(500, str(e)) # don't delete token for now, just give user a form to input stuff return render_template('request-form.html', URL=app.config['URL'], email=user_email, token=user_token, assigned_namespace=token['assigned_namespace']) else: # 'POST' # print "POST" # Email and token (to authorize the request==validate email) if ('email' in request.form): user_email = request.form['email'] else: print('Expected email in request') abort(400, 'Expected email in request') if ('token' in request.form): user_token = request.form['token'] else: print('Expected token in request') abort(400, 'Expected token in request') if ('full_name' in request.form): user_fullname = request.form['full_name'] else: print('Expected full_name in request') abort(400, 'Expected full_name in request') token = mongo.db.tokens.find_one({ 'email': user_email, 'token': user_token }) if (token == None): print("No such token for this email address") abort(403, "No such token for this email address") # Now, do basic validation of correctness of user input, save request in the database # and notify the operator # if getting operator fails, don't process this post request try: operator = get_operator() except Exception as e: print(e) abort(500, str(e)) if user_fullname == "": print("User full name should not be empty") abort(400, "User full name should not be empty") try: user_cert_request = base64.b64decode(request.form['cert_request']) user_cert_data = ndn.Data() user_cert_data.wireDecode(ndn.Blob(buffer(user_cert_request))) except: print("Malformed cert request") abort(400, "Malformed cert request") # check if the user supplied correct name for the certificate request if not ndn.Name(token['assigned_namespace']).match( user_cert_data.getName()): print("cert name does not match with assigned namespace") abort(400, "cert name does not match with assigned namespace") cert_name = extract_cert_name(user_cert_data.getName()).toUri() if (not app.config['AUTO_APPROVE']): # manual approval of request needed # remove any previous requests for the same certificate name mongo.db.requests.remove({'cert_name': cert_name}) cert_request = { 'operator_id': str(operator['_id']), 'full_name': user_fullname, 'organization': operator['site_name'], 'email': user_email, 'cert_name': cert_name, 'cert_request': base64.b64encode(user_cert_request), 'created_on': datetime.datetime.utcnow( ), # to periodically remove unverified tokens } mongo.db.requests.insert(cert_request) # OK. authorized, proceed to the next step mongo.db.tokens.remove(token) msg = Message( "[NDN Open mHealth Certification] User certification request", sender=app.config['MAIL_FROM'], recipients=[operator['email']], body=render_template('operator-notify-email.txt', URL=app.config['URL'], operator_name=operator['name'], **cert_request), html=render_template('operator-notify-email.html', URL=app.config['URL'], operator_name=operator['name'], **cert_request)) mail.send(msg) return json.dumps({"status": 200}) else: # automatically approve any cert request # print request try: mongo.db.tokens.remove(token) cert = issue_certificate(request.form) ret = process_submitted_cert(cert, user_email, user_fullname) ret_obj = json.loads(ret) if (ret_obj['status'] != 200): abort(ret_obj['status'], ret_obj['message']) else: return json.dumps({"status": 200}) except Exception as e: print(e) abort(500)
def submit_certificate(): data = ndn.Data() # data.wireDecode(ndn.Blob(buffer(base64.b64decode(request.form['data'])))) data.wireDecode( ndn.Blob(memoryview(base64.b64decode(request.form['data'])))) cert_request = mongo.db.requests.find_one( {'_id': ObjectId(str(request.form['id']))}) if cert_request == None: abort(403) # TODO: haitao remove this hack after test # operator = mongo.db.operators.find_one({"_id": ObjectId(cert_request['operator_id'])}) operator = { '_id': 1, 'site_name': 'UCLA', 'email': '*****@*****.**', 'doNotSendOpRequests': False, 'name': 'haitao' } if operator == None: mongo.db.requests.remove(cert_request) # remove invalid request abort(403) # # @todo verify data packet # # @todo verify timestamp if len(data.getContent()) == 0: # (no deny reason for now) # eventually, need to check data.type: if NACK, then content contains reason for denial # if KEY, then content is the certificate msg = Message("[NDN Certification] Rejected certification", sender=app.config['MAIL_FROM'], recipients=[cert_request['email']], body=render_template('cert-rejected-email.txt', URL=app.config['URL'], **cert_request), html=render_template('cert-rejected-email.html', URL=app.config['URL'], **cert_request)) mail.send(msg) mongo.db.requests.remove(cert_request) return "OK. Certificate has been denied" else: cert = { 'name': data.getName().toUri(), 'cert': request.form['data'], 'operator': operator, 'created_on': datetime.datetime.utcnow( ), # to periodically remove unverified tokens, 'token': cert_request['token'] if 'token' in cert_request else '' } mongo.db.certs.insert(cert) # for nfd-android applicatin, use a token to fetch the certificate but not install it # using command line if 'token' in cert and len(cert['token']) != 0: msg = Message( "[NDN Certification] NDN certificate issued", sender=app.config['MAIL_FROM'], recipients=[cert_request['email']], body=render_template('nfd-android-cert-issued-email.txt', URL=app.config['URL'], quoted_cert_name=urllib.parse.quote( cert['name'], ''), cert_id=str(data.getName()[-3]), **cert_request), html=render_template('nfd-android-cert-issued-email.html', URL=app.config['URL'], quoted_cert_name=urllib.parse.quote( cert['name'], ''), cert_id=str(data.getName()[-3]), **cert_request)) else: msg = Message( "[NDN Certification] NDN certificate issued", sender=app.config['MAIL_FROM'], recipients=[cert_request['email']], body=render_template('web-cert-issued-email.txt', URL=app.config['URL'], quoted_cert_name=urllib.parse.quote( cert['name'], ''), cert_id=str(data.getName()[-3]), **cert_request), html=render_template('web-cert-issued-email.html', URL=app.config['URL'], quoted_cert_name=urllib.parse.quote( cert['name'], ''), cert_id=str(data.getName()[-3]), **cert_request)) mail.send(msg) mongo.db.requests.remove(cert_request) return "OK. Certificate has been approved and notification sent to the requester"