def deleteCookie(self, cookie, ip): if not self._validate(ip, cookie): print("Cookie not valid!") return False else: DB_Manager.execute("AUTH", '''DELETE FROM Sessions WHERE (cookie='%s');''', cookie) return True
def login(): global cookies username = request.form.get("usernameInput") password = request.form.get("passwordInput") + P_VALUE u_UUID = DB_Manager.getUUID(username) if u_UUID == None: ret = {"code": "warning", "reason": "Username or Password incorrect."} return jsonify(ret) u_salt = DB_Manager.execute( "AUTH", '''SELECT salt FROM User_Auth WHERE (UUID = '%s');''', u_UUID) if (len(u_salt) == 0): ret = {"code": "warning", "reason": "Username or Password incorrect."} return jsonify(ret) else: u_salt = u_salt[0][0] u_salt = bytearray.fromhex(u_salt) e_password = pbkdf2(password, u_salt).digest() ip = request.environ['REMOTE_ADDR'] if DB_Manager.authenticateUser(username, e_password) == True: userCookie = cookies.createCookie(u_UUID, ip) ret = {"code": "success"} response = make_response(jsonify(ret)) c_response = Headers.addCookie(response, 'S_ID', userCookie) c_response = Headers.addCookie(response, 'USR_ID', u_UUID) return c_response else: ret = {"code": "warning", "reason": "Username or Password incorrect."} return jsonify(ret)
def changePassword(): usr_cookie = request.cookies.get("S_ID") ip = request.environ['REMOTE_ADDR'] user_UUID = cookies.getUUID(usr_cookie, ip) csrf_token = request.form.get("token") if user_UUID == None: return logoutResponse({ "code": "danger", "reason": "You have been automatically logged out. Please log in again." }) captcha_code = request.form.get("g-recaptcha-response") captcha_resp = Verification.verifyCaptchaCode(captcha_code, ip) if captcha_resp != True: ret = {"code": "warning", "reason": "Captcha failed"} return jsonify(ret) elif not cookies.validateCSRF(usr_cookie, csrf_token): ret = {"code": "warning", "reason": "CSRF Error."} else: old_password = request.form.get("old_p") + P_VALUE new_password = request.form.get("new_p") + P_VALUE veri_password = request.form.get("ver_p") + P_VALUE if new_password != veri_password: ret = {"code": "warning", "reason": "New passwords do not match"} else: username = DB_Manager.getUsername(user_UUID) u_salt = DB_Manager.execute( "AUTH", '''SELECT salt FROM User_Auth WHERE (UUID = '%s');''', user_UUID) if (len(u_salt) == 0): ret = {"code": "warning", "reason": "Unknown error"} else: u_salt = u_salt[0][0] u_salt = bytearray.fromhex(u_salt) e_password = pbkdf2(old_password, u_salt).digest() if DB_Manager.authenticateUser(username, e_password) == True: new_salt = Token_generator.new_crypto_bytes(20) salted_pwd = pbkdf2(new_password, new_salt).digest() veri_code = Token_generator.new_crypto_bytes(16).hex() x2 = DB_Manager.changePassword(username, salted_pwd, new_salt.hex(), veri_code) if x2 == None: ret = { "code": "warning", "reason": "Error with new password" } else: ret = {"code": "success"} else: ret = {"code": "warning", "reason": "Old password incorrect."} return jsonify(ret)
def createPost(): print("IN CREATE POST --------------------------------") print("REQUEST FORM ARGS: ", request.form) print("REQUEST COOKIES: ", request.cookies) #print("HEADERS FROM REQUEST: ", request.headers) usr_cookie = request.cookies.get("S_ID") ip = request.environ['REMOTE_ADDR'] user_UUID = cookies.getUUID(usr_cookie, ip) csrf_token = request.form.get("token") print("CSRF TOKEN: ", csrf_token) print("TOKEN VALIDATION", cookies.validateCSRF(usr_cookie, csrf_token)) if user_UUID == None: print("NO USER") return logoutResponse({ "code": "danger", "reason": "You have been automatically logged out. Please log in again." }) elif not cookies.validateCSRF(usr_cookie, csrf_token): ret = {"code": "warning", "reason": "CSRF Error."} else: heading = request.form.get("titleInput") body = request.form.get("postInput") date = datetime.datetime.now().strftime("%Y-%m-%d") time = datetime.datetime.now().strftime("%H:%M:%S") username = DB_Manager.getUsername(user_UUID) UUID = Token_generator.new_crypto_bytes(10).hex() print("INSERTING INTO DATABASE") #toExecute = ( code = DB_Manager.execute( "ALTER", '''INSERT INTO Posts VALUES ('%s', '%s', '%s', '%s', '%s', '%s');''', UUID, heading, body, date, time, user_UUID) print("response: ", code) if code == None: ret = { "code": "warning", "reason": "Oops! Something went wrong. Please try again." } else: ret = { "code": "success", "post": { "UUID": UUID, "heading": heading, "body": body, "date": date, "time": time, "username": username, "user_UUID": user_UUID } } return jsonify(ret)
def createUser(): global cookies #print("fields: ", request.form) UUID = Token_generator.new_crypto_bytes(16).hex() verification_code = Token_generator.new_crypto_bytes(16).hex() username = request.form.get("usernameInput") password = request.form.get("passwordInput") + P_VALUE email = request.form.get("emailInput") forename = request.form.get("forenameInput") surname = request.form.get("surnameInput") DOB = request.form.get("dobInput") ip = request.environ['REMOTE_ADDR'] password_blacklist = [ "uea", "pirate", "cove", "piratecove", "password", "topsecret", "123", "12345", "qwerty", "abc", email, forename, surname, username ] flag, level, mess = checkValidPassword(password, password_blacklist) if flag == False: ret = {"code": level, "reason": mess} return jsonify(ret) captcha_code = request.form.get("g-recaptcha-response") captcha_resp = Verification.verifyCaptchaCode(captcha_code, ip) if captcha_resp == False: ret = {"code": "warning", "reason": "Captcha failed"} return jsonify(ret) print("Passed captcha veri") salt = Token_generator.new_crypto_bytes(20) salted_pwd = pbkdf2(password, salt).digest() x1 = DB_Manager.execute( "ALTER", '''INSERT INTO Users VALUES ('%s', '%s', '%s', '%s', '%s', '%s')''', UUID, username, email, forename, surname, DOB) x2 = DB_Manager.changePassword(username, salted_pwd, salt.hex(), verification_code) if x1 == None or x2 == None: ret = { "code": "warning", "reason": "There was an issue with your request" } return jsonify(ret) else: Verification.sendVerificationEmail(email, forename, verification_code) ret = {"code": "success"} return jsonify(ret) ret = {"code": "warning", "reason": "There was an issue with your request"} return jsonify(ret)
def deletePost(): usr_cookie = request.cookies.get("S_ID") ip = request.environ['REMOTE_ADDR'] user_UUID = cookies.getUUID(usr_cookie, ip) csrf_token = request.form.get("token") if user_UUID == None: return logoutResponse({ "code": "danger", "reason": "You have been automatically logged out. Please log in again." }) else: UUID = request.form.get("post_UUID") post_to_delete = DB_Manager.execute( "LOW", '''SELECT * FROM Posts WHERE (UUID='%s');''', UUID) if post_to_delete == None: ret = { "code": "warning", "reason": "There was an error deleting your post." } elif len(post_to_delete) == 0: ret = { "code": "warning", "reason": "There was an error deleting your post." } elif post_to_delete[0][5] != user_UUID: ret = { "code": "warning", "reason": "There was an error deleting your post." } else: x1 = DB_Manager.execute( "ALTER", '''DELETE FROM Comments WHERE (post_UUID='%s')''', UUID) x2 = DB_Manager.execute("ALTER", '''DELETE FROM Posts WHERE (UUID='%s')''', UUID) if x1 == None or x2 == None: ret = { "code": "warning", "reason": "There was an error deleting your post." } else: ret = {"code": "success"} return jsonify(ret)
def createComment(): usr_cookie = request.cookies.get("S_ID") ip = request.environ['REMOTE_ADDR'] user_UUID = cookies.getUUID(usr_cookie, ip) csrf_token = request.form.get("token") if user_UUID == None: return logoutResponse({ "code": "danger", "reason": "You have been automatically logged out. Please log in again." }) elif not cookies.validateCSRF(usr_cookie, csrf_token): ret = {"code": "warning", "reason": "CSRF Error."} else: body = request.form.get("comment_body") date = datetime.datetime.now().strftime("%Y-%m-%d") time = datetime.datetime.now().strftime("%H:%M:%S") UUID = Token_generator.new_crypto_bytes(10).hex() username = DB_Manager.getUsername(user_UUID) post_UUID = request.form.get("post_id") code = DB_Manager.execute( "ALTER", '''INSERT INTO Comments VALUES ('%s', '%s', '%s', '%s', '%s', '%s');''', UUID, body, date, time, user_UUID, post_UUID) if code == None: ret = { "code": "warning", "reason": "Oops! Something went wrong. Please try again." } else: ret = { "code": "success", "comment": { "UUID": UUID, "body": body, "date_posted": date, "time_posted": time, "username": username, "user_UUID": user_UUID, "post_UUID": post_UUID } } return jsonify(ret)
def getPosts(): posts = DB_Manager.execute("LOW", '''SELECT * FROM Posts''') posts_dict = {} if posts != None: for p in posts: username = DB_Manager.getUsername(p[5]) dic_rec = { "UUID": str(p[0]), "heading": str(p[1]), "body": str(p[2]), "date_posted": str(p[3]), "time_posted": str(p[4]), "user_UUID": str(p[5]), "username": username } posts_dict[p[0]] = dic_rec return jsonify(posts_dict)
def createCookie(self, UUID, ip): #https://owasp.org/www-project-cheat-sheets/cheatsheets/Session_Management_Cheat_Sheet.html #cookie length - at least 16 bytes #must be meaningless - to prevent information dislosure attacks currCookie = self.getCookieByUUID(UUID) if currCookie == None: currCookie = [] for c in currCookie: self.deleteCookie(c[1], c[2]) cookie = Token_generator.new_crypto_bytes(20).hex() csrf_token = Token_generator.new_crypto_bytes(20).hex() creation_datetime = datetime.datetime.now() DB_Manager.execute("AUTH", '''INSERT INTO Sessions VALUES ('%s', '%s', '%s', '%s')''', UUID, cookie, ip, csrf_token) return cookie
def getComments(): post_UUID = request.args.get("post_id") #print("UUID requested: ", post_UUID) comments = DB_Manager.execute( "LOW", '''SELECT * FROM Comments WHERE (post_UUID='%s')''', post_UUID) comments_dict = {} if comments != None: for c in comments: username = DB_Manager.getUsername(c[4]) dict_rec = { "UUID": str(c[0]), "body": str(c[1]), "date_posted": str(c[2]), "time_posted": str(c[3]), "username": username, "post_UUID": str(c[5]), "user_UUID": str(c[4]) } comments_dict[c[0]] = dict_rec return jsonify(comments_dict)
def verifyUser(): new_random_UUID = Token_generator.new_crypto_bytes(16).hex() verification_Code = request.args.get("id") x1 = DB_Manager.execute( "AUTH", '''UPDATE User_Auth SET verified='TRUE', verification_code='%s' WHERE (verification_code='%s')''', new_random_UUID, verification_Code) if x1 == None: ret = {"code": "warning", "reason": "Verification ID incorrect"} else: ret = {"code": "success"} return render_template("verification.html", code=ret["code"])
def deleteAccount(): usr_cookie = request.cookies.get("S_ID") ip = request.environ['REMOTE_ADDR'] user_UUID = cookies.getUUID(usr_cookie, ip) csrf_token = request.form.get("token") if user_UUID == None: return logoutResponse({ "code": "danger", "reason": "You have been automatically logged out. Please log in again." }) elif not cookies.validateCSRF(usr_cookie, csrf_token): ret = {"code": "warning", "reason": "CSRF Error."} return jsonify(ret) captcha_code = request.form.get("g-recaptcha-response") captcha_resp = Verification.verifyCaptchaCode(captcha_code, ip) if captcha_resp != True: ret = {"code": "warning", "reason": "Captcha failed"} return jsonify(ret) else: cookies.deleteCookie(usr_cookie, ip) x1 = DB_Manager.execute( "ALTER", '''DELETE FROM Comments WHERE (user_UUID='%s')''', user_UUID) x2 = DB_Manager.execute( "ALTER", '''DELETE FROM Posts WHERE (user_UUID='%s')''', user_UUID) x3 = DB_Manager.execute("ALTER", '''DELETE FROM User_Auth WHERE (UUID='%s')''', user_UUID) x4 = DB_Manager.execute("ALTER", '''DELETE FROM Users WHERE (UUID='%s')''', user_UUID) if x1 == None or x2 == None or x3 == None or x4 == None: ret = {"code": "warning", "reason": "Unknown error deleting user."} else: ret = {"code": "success"} return jsonify(ret)
def searchPosts(): search_term = request.args.get('search_term') posts = DB_Manager.execute( "LOW", '''SELECT * FROM Posts WHERE (heading LIKE '%s')''', '%' + search_term + '%', ) posts_dict = {} if posts != None: for p in posts: username = DB_Manager.getUsername(p[5]) dic_rec = { "UUID": p[0], "heading": p[1], "body": p[2], "date_posted": p[3], "time_posted": p[4], "user_UUID": p[5], "username": username } posts_dict[p[0]] = dic_rec return jsonify(posts_dict)
def _validate(self, ip, cookie): #ensure the IP is the same for the two cookie usage requests. print("MY COOKIE: ", cookie) all_cookies = self.getAllCookies() print("COOKIE STRUCT: ", all_cookies) #if cookie not in self.cookies: # return False #if ip != self.cookies[cookie]["ip"]: # return False fetched_cookies = DB_Manager.execute("AUTH", '''SELECT * FROM Sessions WHERE (cookie='%s')''', cookie) if fetched_cookies == None: return False elif len(fetched_cookies) == 0: return False else: return True #ensure the cookie is still within lifetime #dateDiff = datetime.datetime.now() - self.cookies[cookie]["datetime"] #if (dateDiff.total_seconds()/3600) > self.lifetime: # return False return True
def getCookieByToken(self, token): cookies = DB_Manager.execute("AUTH", '''SELECT * FROM Sessions WHERE (cookie='%s')''', token) if cookies == None: return None elif len(cookies) == 0: return None else: return cookies
def clearCookies(self): DB_Manager.execute("AUTH", '''DELETE FROM Sessions;''')
def getCookieByUUID(self, UUID): cookies = DB_Manager.execute("AUTH", '''SELECT * FROM Sessions WHERE (UUID='%s')''', UUID) if cookies == None: return None elif len(cookies) == 0: return None else: return cookies
def getAllCookies(self): total_cookies = DB_Manager.execute("AUTH", '''SELECT * FROM Sessions''') if total_cookies == None: return [] else:return total_cookies