def run(self): log = Logger('PassVerifyerThread') tag = 'run' print 'In PassVerify\'s POST' loader = Loader("/opt/toppatch/mv/media/app/") passwd = str(self.request.get_argument('password', None)) enrollment_id = self.request.get_argument('hidden', None) log.e(tag, 'enrollment id : ' + enrollment_id) ### check type of enrollment id ### try: enrollment_id = int(enrollment_id) invalid_enrollment_id = False enrollment_id = str(enrollment_id) except ValueError: invalid_enrollment_id = True # No enrollment ID sent if enrollment_id is None or invalid_enrollment_id: # print 'Some Error in enrollID not present corresponding\ # to the password or of invalid format' log.e(tag, 'Some Error in program deviceID not present \ corresponding to the password or of invalid format') self.request.write(loader.load("error_invalid.html").generate( message='Invalid link, Mr. intruder. :D ;)', status='alert-danger')) tornado.ioloop.IOLoop.instance().add_callback(self.callback) # Password not found elif passwd is None: redirect_url = ''' /enroll/{0}?err=Try+again+with+correct+password'''.format(enrollment_id) self.request.redirect(redirect_url) log.i(tag, 'password is incorrect') tornado.ioloop.IOLoop.instance().add_callback(self.callback) # Enrollent ID and Password found else: enrollment = EnrollmentDBHelper() ret_dict = enrollment.get_enrollment(enrollment_id) # print ret_dict ret = None if ret_dict is not None: ret = str(ret_dict[c.ENROLLMENT_TABLE_PASSWORD]) else: log.e(tag, 'Enrollment password cannot be reterived') if ret is None: log.e( tag, 'DB did not sent the password from Enrollment table') self.request.write(loader.load("error_invalid.html").generate( message='Invalid link, Mr. intruder. :D ;)', status='alert-danger')) tornado.ioloop.IOLoop.instance().add_callback(self.callback) else: # Password matched if ret == passwd: print 'download the profile' # Now find out the browser details # Create the profile to download thread = CreateProfileThread(enrollment_id) thread.start() thread.join() filename = enrollment_id + '.mobileconfig' signed_filename = 'mdm_' + enrollment_id + '.mobileconfig' log.i(tag, 'Downloading the iOS profile') log.i(tag, 'Signing the iOS profile') sign_command = """ openssl smime \ -sign \ -signer /etc/ssl/star_toppatch_com.pem \ -inkey /etc/ssl/star_toppatch_com.key \ -certfile /opt/toppatch/assets/ios/DigiCertPersonal_chain.pem \ -nodetach \ -outform der \ -in {0} \ -out {1} """.format(filename, signed_filename) os.system(sign_command) f = file(signed_filename, 'rb') self.request.set_header( 'Content-Type', 'application/x-apple-aspen-config; chatset=utf-8') self.request.set_header( 'Content-Disposition', 'attachment; filename=' + filename + '') self.request.write(f.read()) tornado.ioloop.IOLoop.instance().add_callback( self.callback) # Delete the file from server after download 'Delay can be # introduced'. os.remove(filename) os.remove(signed_filename) else: redirect_url = ''' /enroll/{0}?err=Try+again+with+correct+password'''.format(enrollment_id) self.request.redirect(redirect_url) tornado.ioloop.IOLoop.instance().add_callback( self.callback) log.i(tag, 'Incorrect Password for enrollment')
def run(self): log = Logger('CheckInHandler PUT') TAG = 'run' # print ' In deviceCheckin PUT Handler\n\n\n' # parse the body of PUT # First extract the XML arguments = cgi.parse_qsl(self.request.request.body) intermediate = arguments[0] currentxml = intermediate[1] final = currentxml[25:-1] enrollment_id = str(self.data) # print final # Actual Parsing #tree = ET.ElementTree(ET.fromstring(final)) # tree = ET.parse('temp.xml') ### For testing only node = etree.fromstring(final) device_data = [] for text_of_child in node.itertext(): if len(text_of_child.strip()) > 0: device_data.append(text_of_child.strip()) device_data = dict(zip(device_data[::2], device_data[1::2])) if device_data.get('PushMagic'): self.push_magic = str(device_data.get('PushMagic')) if device_data.get('Token'): self.device_token = str(device_data.get('Token')) self.device_token = self.device_token.replace(' ', '+') self.device_token = self.device_token.replace('\n', '') self.device_token = self.device_token.replace('\t', '') # print len(self.device_token) # print self.device_token if device_data.get('MessageType'): message = device_data.get('MessageType') if message == 'TokenUpdate': self.do_entry = True elif message == 'Authenticate': self.do_initial_entry = True if device_data.get('UnlockToken'): self.unlock_token = device_data.get('UnlockToken') self.unlock_token = self.unlock_token.replace(' ', '+') self.unlock_token = self.unlock_token.replace('\n', '') self.unlock_token = self.unlock_token.replace('\t', '') if device_data.get('UDID'): self.udid = device_data.get('UDID') ### Initial Device DB Entries ### if self.do_entry: enrolled_success = False device_id = None # fetch info from enrollment table enrollment = EnrollmentDBHelper() enrollment_dict = enrollment.get_enrollment(enrollment_id) # print 'enrollment_dict = ' + str(enrollment_dict) if enrollment_dict is None: log.e(TAG, 'No user ID in Enrollment table. Enrollment ID = ' + str(enrollment_id)) reply = """ <html> <body>401</body> </html> """ self.request.set_status(401) self.request.write(reply) ioloop.IOLoop.instance().add_callback(self.callback) else: reply = """ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> </dict> </plist> """ print 'inner write' self.request.write(reply) ioloop.IOLoop.instance().add_callback(self.callback) device = DeviceDBHelper() violation = ViolationsDBHelper() user_id = str(enrollment_dict[c.ENROLLMENT_TABLE_USER]) device_id = enrollment_dict.get(c.ENROLLMENT_TABLE_DEVICE) devices = device.get_device_with_udid( str(self.udid), status=True) # print "\n print devices list if available \n\n",devices device_detail = DeviceDetailsDBHelper() device_details_dict = { 'token': self.device_token, 'push_magic': self.push_magic, 'unlock_token': self.unlock_token } if device_id: enrolled_success = True device.update_device(str(device_id), {c.DEVICE_TABLE_DELETED: False, c.DEVICE_TABLE_UDID: str(self.udid)}) device_detail.update_device_details(str(device_id), device_details_dict) print "Device details table updated." elif devices: device_id = devices[0][c.DEVICE_TABLE_ID] device.update_device(str(device_id), {c.DEVICE_TABLE_DELETED: False}) device_detail.update_device_details(str(device_id), device_details_dict) enrollment.update_enrollment( enrollment_id, { c.ENROLLMENT_TABLE_DEVICE: str(device_id)}) enrollment.set_enrolled(enrollment_id) enrolled_success = True else: # print 'user_id = ' + user_id device_dict = {c.DEVICE_TABLE_USER: user_id, c.DEVICE_TABLE_OS: 'ios', c.DEVICE_TABLE_UDID: str(self.udid), c.DEVICE_TABLE_DELETED: False} device_id = device.add_device(device_dict) if device_id is None: log.e(TAG, 'Not Able to insert in Device table UDID = ' + str(self.udid) + 'userID = ' + str(user_id)) else: device_details_dict_new = {} device_details_dict_new[ c.DEVICE_DETAILS_TABLE_DEVICE] = device_id device_details_dict_new[ c.DEVICE_DETAILS_TABLE_EXTRAS] = device_details_dict device_details_id = device_detail.add_device_detail( device_details_dict_new) # print 'device_details_id = ' + str(device_details_id) if device_details_id is None: log.e(TAG, 'Not Able to insert in Device Details \ table UDID = ' + str(self.udid) + 'userID = ' + str(user_id) + 'DeviceID = ' + str(device_id)) else: success = enrollment.update_enrollment( enrollment_id, {c.ENROLLMENT_TABLE_DEVICE: str(device_id)}) if not success: log.e(TAG, 'enrollment device table not linked') else: success1 = enrollment.set_enrolled( enrollment_id) if success1: enrolled_success = True else: log.e( TAG, 'EnrolledOn time is not updated in \ the Enrollment Table') if device_id and enrolled_success: violation_status = violation.update_violations( str(device_id)) user = UserDBHelper() user_info = user.get_user(user_id) if violation_status: log.i(TAG, "Violation table updated for device_id" + str( device_id)) else: log.e( TAG, "Violation table not updated for device_id" + str(device_id)) ### Add task to Queue for celery Worker. ### json_data = {'to': 'user', 'action': 'device_information', 'id': user_id} json_data['company_id'] = user_info.get('company_id') create_command_handler_task.delay(json_data) ### Now send polling Signal to device ### wrapper = APNSNotificationWrapper( '/opt/toppatch/assets/ios/PushCert.pem', False) message = APNSNotification() message.appendProperty(APNSProperty("mdm", str(self.push_magic))) message.tokenBase64(str(self.device_token)) wrapper.append(message) wrapper.notify() print 'Payload Sent' elif device_data.get('MessageType') == 'CheckOut': reply = """ <html> <body>401</body> </html> """ self.request.set_status(401) self.request.write(reply) ioloop.IOLoop.instance().add_callback(self.callback) violation = ViolationsDBHelper() device = DeviceDBHelper() enrollment = EnrollmentDBHelper() devices = device.get_device_with_udid(self.udid) if devices is None: log.e(TAG, 'No User ID Associated with Device UDID = ' + self.udid) else: device_id = devices[0][c.DEVICE_TABLE_ID] violation_id = violation.add_violation(str(device_id)) if violation_id is None: log.e(TAG, 'Not able to insert in Violation Table.\ DeviceID = ' + str(device_id)) else: device.delete_device(device_id) enrollment.update_enrollment( str(enrollment_id), { 'device_id': "null", 'is_enrolled': False}) log.i(TAG, 'Violation added for device id = ' + str(device_id)) admin_mailer(device_id, violation_id) else: reply = """ <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> </dict> </plist> """ print 'outer write' self.request.write(reply) ioloop.IOLoop.instance().add_callback(self.callback)
def run(self): log = Logger('PassVerifyerThread') tag = 'run' print 'In PassVerify\'s POST' loader = Loader("/opt/toppatch/mv/media/app/") passwd = str(self.request.get_argument('password', None)) enrollment_id = self.request.get_argument('hidden', None) log.e(tag, 'enrollment id : ' + enrollment_id) ### check type of enrollment id ### try: enrollment_id = int(enrollment_id) invalid_enrollment_id = False enrollment_id = str(enrollment_id) except ValueError: invalid_enrollment_id = True # No enrollment ID sent if enrollment_id is None or invalid_enrollment_id: # print 'Some Error in enrollID not present corresponding\ # to the password or of invalid format' log.e( tag, 'Some Error in program deviceID not present \ corresponding to the password or of invalid format') self.request.write( loader.load("error_invalid.html").generate( message='Invalid link, Mr. intruder. :D ;)', status='alert-danger')) tornado.ioloop.IOLoop.instance().add_callback(self.callback) # Password not found elif passwd is None: redirect_url = ''' /enroll/{0}?err=Try+again+with+correct+password'''.format(enrollment_id) self.request.redirect(redirect_url) log.i(tag, 'password is incorrect') tornado.ioloop.IOLoop.instance().add_callback(self.callback) # Enrollent ID and Password found else: enrollment = EnrollmentDBHelper() ret_dict = enrollment.get_enrollment(enrollment_id) # print ret_dict ret = None if ret_dict is not None: ret = str(ret_dict[c.ENROLLMENT_TABLE_PASSWORD]) else: log.e(tag, 'Enrollment password cannot be reterived') if ret is None: log.e(tag, 'DB did not sent the password from Enrollment table') self.request.write( loader.load("error_invalid.html").generate( message='Invalid link, Mr. intruder. :D ;)', status='alert-danger')) tornado.ioloop.IOLoop.instance().add_callback(self.callback) else: # Password matched if ret == passwd: print 'download the profile' # Now find out the browser details # Create the profile to download thread = CreateProfileThread(enrollment_id) thread.start() thread.join() filename = enrollment_id + '.mobileconfig' signed_filename = 'mdm_' + enrollment_id + '.mobileconfig' log.i(tag, 'Downloading the iOS profile') log.i(tag, 'Signing the iOS profile') sign_command = """ openssl smime \ -sign \ -signer /etc/ssl/star_toppatch_com.pem \ -inkey /etc/ssl/star_toppatch_com.key \ -certfile /opt/toppatch/assets/ios/DigiCertPersonal_chain.pem \ -nodetach \ -outform der \ -in {0} \ -out {1} """.format(filename, signed_filename) os.system(sign_command) f = file(signed_filename, 'rb') self.request.set_header( 'Content-Type', 'application/x-apple-aspen-config; chatset=utf-8') self.request.set_header( 'Content-Disposition', 'attachment; filename=' + filename + '') self.request.write(f.read()) tornado.ioloop.IOLoop.instance().add_callback( self.callback) # Delete the file from server after download 'Delay can be # introduced'. os.remove(filename) os.remove(signed_filename) else: redirect_url = ''' /enroll/{0}?err=Try+again+with+correct+password'''.format(enrollment_id) self.request.redirect(redirect_url) tornado.ioloop.IOLoop.instance().add_callback( self.callback) log.i(tag, 'Incorrect Password for enrollment')
def run(self): # Find all the POST arguments required company_id = self.company_id # company_name = str(self.company_name) loader = Loader("/opt/toppatch/mv/media/app/") # thread1 = {} log = Logger('EnrollDevice') tag = 'POST' request_body = json.loads(self.request.request.body) try: self.user_email = str(request_body.get('user_email', None)) self.user_name = str(request_body.get('user_name', None)) self.team_id = str(request_body.get('team_id', None)) self.role_id = str(request_body.get('role_id', None)) self.company_id = str(company_id) except: self.request.write('Some arguments are not supplied') opJson = json.dumps({ 'pass': False, 'user_name': None, 'link': None, 'password': None, 'error': 'Some argument not supplied' }) self.request.write(opJson) tornado.ioloop.IOLoop.instance().add_callback(self.callback) log.e(tag, 'Some arguments not sent in POST request for enrollment') return if self.user_email is None or self.user_name is None or\ self.company_id is None: log.e(tag, 'Email or user_name is NULL') opJson = json.dumps({ 'pass': False, 'user_name': None, 'link': None, 'password': None, 'error': 'user_name or Email or Company \ is None' }) self.request.write(opJson) tornado.ioloop.IOLoop.instance().add_callback(self.callback) if self.user_name == '' or self.user_email == '': log.e(tag, 'Email or user_name is empty') opJson = json.dumps({ 'pass': False, 'user_name': None, 'link': None, 'password': None, 'error': 'email or user_name or company \ is empty' }) self.request.write(opJson) tornado.ioloop.IOLoop.instance().add_callback(self.callback) password = generate_password() user = UserDBHelper() user_dict = { c.USER_TABLE_NAME: str(self.user_name), c.USER_TABLE_TEAM: str(self.team_id), c.USER_TABLE_ROLE: str(self.role_id), c.USER_TABLE_EMAIL: str(self.user_email), c.USER_TABLE_COMPANY: str(self.company_id) } user_id, duplicate = user.add_user_if_not_exists(user_dict) if duplicate: log.e(tag, 'No id from primary key ') opJson = json.dumps({ 'pass': False, 'user_name': self.user_name, 'link': None, 'password': None, 'duplicate': True, 'error': 'DB has problem' }) self.request.write(opJson) tornado.ioloop.IOLoop.instance().add_callback(self.callback) else: enrollment_dict = { c.ENROLLMENT_TABLE_USER: user_id, c.ENROLLMENT_TABLE_PASSWORD: password, c.ENROLLMENT_TABLE_IS_ENROLLED: False } enrollment = EnrollmentDBHelper() enrollment_id = str(enrollment.add_enrollment(enrollment_dict)) enrollment_dict = enrollment.get_enrollment(enrollment_id) if enrollment_id is not None: self.link += enrollment_id try: message = loader.load('user_enroll_mail.html').generate( company_name=self.company_name, user_passwd=password, activation_link=self.link) ses_conn.send_email('*****@*****.**', 'MDM Enrollment verification', message, [self.user_email], format='html') print 'No error found' log.i(tag, 'Enrollment request successful') opJson = json.dumps({ 'pass': True, 'user_name': self.user_name, 'link': 'link', 'password': '******', 'error': None }) except Exception as err: print 'Mail Sending error exception is :', repr(err) log.e(tag, 'Incorrect EmailID sent') opJson = json.dumps({ 'pass': False, 'user_name': self.user_name, 'link': None, 'password': None, 'error': 'Wrong emailID' }) else: log.e( tag, 'Entry is not done in Enrollment table for UserID = ' + str(user_id)) opJson = json.dumps({ 'pass': False, 'user_name': self.user_name, 'link': None, 'password': None, 'error': 'Wrong emailID' }) self.request.write(opJson) tornado.ioloop.IOLoop.instance().add_callback(self.callback)
def run(self): #Find all the POST arguments required company_id = self.company_id company_name = str(self.company_name) loader = Loader("/opt/toppatch/mv/media/app/") thread1 = {} log = Logger('EnrollDevice') tag = 'POST' request_body = json.loads(self.request.request.body) try: self.user_email = str(request_body.get('user_email', None)) self.user_name = str(request_body.get('user_name', None)) self.team_id = str(request_body.get('team_id', None)) self.role_id = str(request_body.get('role_id', None)) self.company_id = str(company_id) except: self.request.write('Some arguments are not supplied') opJson = json.dumps({'pass':False, 'user_name': None, 'link' : None, 'password':None, 'error':'Some argument not supplied'}) self.request.write(opJson) tornado.ioloop.IOLoop.instance().add_callback(self.callback) log.e(tag, 'Some arguments not sent in POST request for enrollment') return if self.user_email is None or self.user_name is None or\ self.company_id is None: log.e(tag, 'Email or user_name is NULL') opJson = json.dumps({'pass':False, 'user_name': None, 'link' : None, 'password':None, 'error':'user_name or Email or Company is None'}) self.request.write(opJson) tornado.ioloop.IOLoop.instance().add_callback(self.callback) if self.user_name == '' or self.user_email == '': log.e(tag, 'Email or user_name is empty') opJson = json.dumps({'pass':False, 'user_name': None, 'link' : None, 'password':None, 'error':'email or user_name or company is empty'}) self.request.write(opJson) tornado.ioloop.IOLoop.instance().add_callback(self.callback) password = generate_password() user = UserDBHelper() user_dict = { c.USER_TABLE_NAME: str(self.user_name), c.USER_TABLE_TEAM : str(self.team_id), c.USER_TABLE_ROLE: str(self.role_id), c.USER_TABLE_EMAIL: str(self.user_email), c.USER_TABLE_COMPANY: str(self.company_id) } user_id, duplicate = user.add_user_if_not_exists(user_dict) if duplicate: log.e(tag,'No id from primary key ') opJson = json.dumps({'pass':False, 'user_name': self.user_name, 'link' : None, 'password':None, 'duplicate': True, 'error':'DB has problem'}) self.request.write(opJson) tornado.ioloop.IOLoop.instance().add_callback(self.callback) else: enrollment_dict = { c.ENROLLMENT_TABLE_USER: user_id, c.ENROLLMENT_TABLE_PASSWORD: password, c.ENROLLMENT_TABLE_IS_ENROLLED: False } enrollment = EnrollmentDBHelper() enrollment_id = str(enrollment.add_enrollment(enrollment_dict)) enrollment_dict = enrollment.get_enrollment(enrollment_id) if enrollment_id is not None: self.link += enrollment_id try: message = loader.load('user_enroll_mail.html').generate( company_name=self.company_name, user_passwd=password, activation_link=self.link) ses_conn.send_email('*****@*****.**', 'MDM Enrollment verification', message, [self.user_email], format='html') print 'No error found' log.i(tag, 'Enrollment request successful') opJson = json.dumps({'pass':True, 'user_name': self.user_name, 'link' : 'link', 'password':'******', 'error':None}) except Exception, err: print 'Mail Sending error exception is :', repr(err) log.e(tag, 'Incorrect EmailID sent') opJson = json.dumps({'pass':False, 'user_name': self.user_name, 'link' : None, 'password':None, 'error':'Wrong emailID'}) else: