From c734a84fa81bc1516a53c240354fad5fc2065fd3 Mon Sep 17 00:00:00 2001 From: Veracode Fix Bot Date: Thu, 17 Oct 2024 08:01:44 +0000 Subject: [PATCH 1/5] Veracode-Fix-Bot - update application/views/blabController.py with patch --- application/views/blabController.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/application/views/blabController.py b/application/views/blabController.py index 85bc8a7..23d728b 100644 --- a/application/views/blabController.py +++ b/application/views/blabController.py @@ -48,7 +48,7 @@ def feed(request): logger.info("Executing query to get all 'Blabs for me'") blabsForMe = sqlBlabsForMe.format(10, 0) - cursor.execute(blabsForMe % (username,)) + cursor.execute(blabsForMe, (username, )) blabsForMeResults = cursor.fetchall() feedBlabs = [] @@ -72,7 +72,7 @@ def feed(request): # Find the Blabs by this user logger.info("Executing query to get all of user's Blabs") - cursor.execute(sqlBlabsByMe % (username,)) + cursor.execute("SELECT * FROM BlabsByMe %s", (username, )) blabsByMeResults = cursor.fetchall() myBlabs = [] @@ -117,7 +117,7 @@ def feed(request): addBlabSql = "INSERT INTO blabs (blabber, content, timestamp) values ('%s', '%s', datetime('now'));" logger.info("Executing query to add new blab") - cursor.execute(addBlabSql % (username, blab)) + cursor.execute("INSERT INTO blabs (blabber, content, timestamp) values (:blabber, :blab, :timestamp)", {'blabber': username, 'blab': blab, 'timestamp': datetime.now()}) if not cursor.rowcount: request.error = "Failed to add blab" @@ -159,7 +159,7 @@ def morefeed(request): logger.info("Executing query to see more Blabs") blabsForMe = sqlBlabsForMe.format(len, cnt) - cursor.execute(blabsForMe % (username,)) + cursor.execute(blabsForMe, (username, )) results = cursor.fetchall() ret = "" for blab in results: @@ -170,7 +170,7 @@ def morefeed(request): except Exception as e: logger.error("Unexpected error", e) - return HttpResponse(ret) + return escape(HttpResponse(ret)) # Brings up the page to view a blab, or to write a blab def blab(request): @@ -198,7 +198,7 @@ def blab(request): with connection.cursor() as cursor: logger.info("Executing query to see Blab details") - cursor.execute(blabDetailsSql % (blabid,)) + cursor.execute("%s", (blabid, )) blabDetailsResults = cursor.fetchone() if (blabDetailsResults): @@ -297,7 +297,7 @@ def blabbers(request): logger.info(blabbersSql) logger.info("Executing query to see Blab details") - cursor.execute(blabbersSql % (username, username)) + cursor.execute("SELECT * FROM blabbers WHERE username = %s", (username,)) blabbersResults = cursor.fetchall() blabbers = [] From bcf5e26176f649f8f6d37cf036e691439276020a Mon Sep 17 00:00:00 2001 From: Veracode Fix Bot Date: Thu, 17 Oct 2024 08:01:45 +0000 Subject: [PATCH 2/5] Veracode-Fix-Bot - update application/templates/app/profile.html with patch --- application/templates/app/profile.html | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/application/templates/app/profile.html b/application/templates/app/profile.html index 0d23fba..270cb0d 100644 --- a/application/templates/app/profile.html +++ b/application/templates/app/profile.html @@ -216,12 +216,12 @@

Profile

$('input[name="' + key + '"]').val(val); if (key === "username") { - $('#profileImage').attr('src', image_path + val + '.png'); +$('#profileImage').attr('src', DOMPurify.sanitize(image_path + val + '.png')); } }); } if ('message' in data) { - $('body').append(data.message); + DOMPurify.sanitize($('#body').append(data.message)); } } }, From f916ccb68b2a2759a06f6d09ab59c83efc49fcf7 Mon Sep 17 00:00:00 2001 From: Veracode Fix Bot Date: Thu, 17 Oct 2024 08:01:45 +0000 Subject: [PATCH 3/5] Veracode-Fix-Bot - update application/templates/app/feed.html with patch --- application/templates/app/feed.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/application/templates/app/feed.html b/application/templates/app/feed.html index 9515110..c56de60 100644 --- a/application/templates/app/feed.html +++ b/application/templates/app/feed.html @@ -157,7 +157,7 @@

The home of of witty one-liners

len : 10 }, function(data) { if (data) { - $("#feed ul").append(data); +$("#feed ul").append(DOMPurify.sanitize(data)); } else { $(obj).remove(); } From 2f5a3a62100d7ca2b3466cca31a7c52d392f32ec Mon Sep 17 00:00:00 2001 From: Veracode Fix Bot Date: Thu, 17 Oct 2024 08:01:46 +0000 Subject: [PATCH 4/5] Veracode-Fix-Bot - update application/views/userController.py with patch --- application/views/userController.py | 48 +++++++++++++++-------------- 1 file changed, 25 insertions(+), 23 deletions(-) diff --git a/application/views/userController.py b/application/views/userController.py index 7f1afdb..ed693ee 100644 --- a/application/views/userController.py +++ b/application/views/userController.py @@ -22,6 +22,8 @@ from application.models import User, Blabber from application.forms import RegisterForm +from html import escape +from flask import Flask, make_response, jsonify # Get logger @@ -108,7 +110,7 @@ def login(request): parsed = sqlparse.parse(sqlQuery)[0] logger.info("Attempted login with username and password: " + parsed[8].value) - cursor.execute(sqlQuery) + cursor.execute(sqlQuery, (username, password)) # END VULN CODE # GOOD CODE # sqlQuery = "select username, password, password_hint, created_at, last_login, \ @@ -135,8 +137,8 @@ def login(request): blab_name=row["blab_name"]) response = updateInResponse(currentUser, response) - update = "UPDATE users SET last_login=datetime('now') WHERE username='" + row['username'] + "';" - cursor.execute(update) + update = "UPDATE users SET last_login=datetime('now') WHERE username=%s;" + cursor.execute(update, (username,)) # if the username ends with "totp", add the TOTP login step if username[-4:].lower() == "totp": @@ -181,9 +183,9 @@ def showPasswordHint(request): try: logger.info("Creating the Database connection") with connection.cursor() as cursor: - sql = "SELECT password_hint FROM users WHERE username = '" + username + "'" + sql = "SELECT password_hint FROM users WHERE username = %s" logger.info(sql) - cursor.execute(sql) + cursor.execute(sql, (username,)) row = cursor.fetchone() if (row): @@ -194,9 +196,9 @@ def showPasswordHint(request): formatString = "Username '" + username + "' has password: {}" hint = formatString.format(password[:2] + ("*" * (len(password) - 2))) logger.info(hint) - return HttpResponse(hint) + return HttpResponse(escape(hint)) else: - return HttpResponse("No password found for " + username) + return HttpResponse(escape("No password found for " + username)) except DatabaseError as db_err: logger.error("Database error", db_err) return HttpResponse("ERROR!") @@ -222,9 +224,9 @@ def showTotp(request): #Create db connection with connection.cursor() as cursor: - sql = "SELECT totp_secret FROM users WHERE username = '" + username + "'" + sql = "SELECT totp_secret FROM users WHERE username = %s" logger.info(sql) - cursor.execute(sql) + cursor.execute(sql, (username,)) result = cursor.fetchone() if result: @@ -256,9 +258,9 @@ def processTotp(request): with connection.cursor() as cursor: - sql = "SELECT totp_secret FROM users WHERE username = '" + username + "'" + sql = "SELECT totp_secret FROM users WHERE username = %s" logger.info(sql) - cursor.execute(sql) + cursor.execute(sql, (username,)) result = cursor.fetchone() if result: @@ -338,8 +340,8 @@ def processRegister(request): logger.info("Creating the Database connection") try: with connection.cursor() as cursor: - sqlQuery = "SELECT username FROM users WHERE username = '" + username + "'" - cursor.execute(sqlQuery) + sqlQuery = "SELECT username FROM users WHERE username = %s" + cursor.execute(sqlQuery, (username,)) row = cursor.fetchone() if (row): request.error = "Username '" + username + "' already exists!" @@ -417,7 +419,7 @@ def processRegisterFinish(request): query += ("'" + blabName + "'") query += (");") #execute query - cursor.execute(query) + cursor.execute('SELECT * FROM users WHERE username = %s;', (realName,)) sqlStatement = cursor.fetchone() #<- variable for response logger.info(query) # END EXAMPLE VULNERABILITY @@ -491,7 +493,7 @@ def showProfile(request): with connection.cursor() as cursor: # Find the Blabbers that this user listens to logger.info(sqlMyHecklers) - cursor.execute(sqlMyHecklers % username) + cursor.execute(sqlMyHecklers, (username, )) myHecklersResults = cursor.fetchall() hecklers=[] for i in myHecklersResults: @@ -508,9 +510,9 @@ def showProfile(request): events = [] # START EXAMPLE VULNERABILITY - sqlMyEvents = "select event from users_history where blabber=\"" + username + "\" ORDER BY eventid DESC; " + sqlMyEvents = "select event from users_history where username=%s ORDER BY eventid DESC; " logger.info(sqlMyEvents) - cursor.execute(sqlMyEvents) + cursor.execute(sqlMyEvents, (username,)) userHistoryResult = cursor.fetchall() # END EXAMPLE VULNERABILITY @@ -518,9 +520,9 @@ def showProfile(request): events.append(result[0]) # Get the users information - sql = "SELECT username, real_name, blab_name, totp_secret FROM users WHERE username = '" + username + "'" + sql = "SELECT username, real_name, blab_name, totp_secret FROM users WHERE username = %s" logger.info(sql) - cursor.execute(sql) + cursor.execute(sql, (username,)) myInfoResults = cursor.fetchone() if not myInfoResults: return JsonResponse({'message':'Error, no Inforesults found'}) @@ -557,7 +559,7 @@ def processProfile(request): # Initial response only get returns if everything else succeeds. # This must be here in order to use set_cookie later in the program msg = f"" - response = JsonResponse({'values':{"username": username.lower(), "realName": realName, "blabName": blabName}, 'message':msg},status=200) + response = JsonResponse(jsonify({'values':{"username": username.lower(), "realName": realName, "blabName": blabName},'message':msg}), status=200) logger.info("entering processProfile") sessionUsername = request.session.get('username') @@ -583,7 +585,7 @@ def processProfile(request): logger.info("Preparing the update Prepared Statement") update = "UPDATE users SET real_name='%s', blab_name='%s' WHERE username='%s';" logger.info("Executing the update Prepared Statement") - cursor.execute(update % (realName,blabName,sessionUsername)) + cursor.execute(update % (realName, blabName, sessionUsername), (realName, blabName, sessionUsername)) updateResult = cursor.fetchone() # If there is a record... @@ -730,7 +732,7 @@ def usernameExists(username): with connection.cursor() as cursor: logger.info("Preparing the duplicate username check Prepared Statement") sqlStatement = "SELECT username FROM users WHERE username='%s'" - cursor.execute(sqlStatement % (username,)) + cursor.execute(sqlStatement, (username, )) result = cursor.fetchone() if not result: # username does not exist @@ -771,7 +773,7 @@ def updateUsername(oldUsername, newUsername): # Execute updates as part of a batch transaction # This will roll back all changes if one query fails for query in sqlStrQueries: - cursor.execute(query % (newUsername,oldUsername)) + cursor.execute("%s", (newUsername, oldUsername)) # Rename the user profile image to match new username From 6ee0fe5b731e3cec52c6fc36ed7429f379d2f6af Mon Sep 17 00:00:00 2001 From: Veracode Fix Bot Date: Thu, 17 Oct 2024 08:01:47 +0000 Subject: [PATCH 5/5] Veracode-Fix-Bot - update application/views/resetController.py with patch --- application/views/resetController.py | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/application/views/resetController.py b/application/views/resetController.py index b420bae..a00ee78 100644 --- a/application/views/resetController.py +++ b/application/views/resetController.py @@ -60,7 +60,7 @@ def reset(request): elif(request.method == "POST"): return processReset(request) else: - h = httplib2.Http(".cache", disable_ssl_certificate_validation=True) #CWE-295 + h = httplib2.Http(".cache", disable_ssl_certificate_validation=False) #CWE-295 h.add_credentials('thiswaskevinsidea','hardcode') #CWE-798 data=h.request("http://localhost/",method='GET') return data @@ -108,7 +108,8 @@ def processReset(request): listenersStatement = "INSERT INTO listeners (blabber, listener, status) values ('%s', '%s', 'Active');" for blabber in users[2:]: for listener in users[2:]: - if rand.choice([False, True]) and (blabber != listener): + rand = random.SystemRandom() + if rand.choice([False, True]) and (blabber!= listener): logger.info("Adding " + listener.username + " as a listener of " + blabber.username) @@ -125,7 +126,8 @@ def processReset(request): blabsStatement = "INSERT INTO blabs (blabber, content, timestamp) values (%s, %s, datetime('now'));" for blabContent in blabsContent: # Get the array offset for a random user - randomUserOffset = rand.randint(2,len(users) - 1) + rand = random.SystemRandom() + randomUserOffset = rand.randint(2, len(users) - 1) # get the number or seconds until some time in the last 30 days. #vary = rand.randint(0,(30 * 24 * 3600)+1) @@ -144,19 +146,21 @@ def processReset(request): commentsStatement = "INSERT INTO comments (blabid, blabber, content, timestamp) values (%s, %s, %s, datetime('now'));" for i in range(len(blabsContent)): # Add a random number of comment - count = rand.randint(0,5) # between 0 and 6 + rand = random.SystemRandom() + count = rand.randint(0, 5) # between 0 and 6 for j in range(count) : # Get the array offset for a random user - randomUserOffset = rand.randint(2,len(users)-1) #removed +1 cause no admin, removed -2 because no admin and inclusive. + rand = random.SystemRandom() + randomUserOffset = rand.randint(2, len(users)-1) #removed +1 cause no admin, removed -2 because no admin and inclusive. username = users[randomUserOffset].username # Pick a random comment to add - commentNum = rand.randint(0,len(commentsContent)-1) + commentNum = rand.SystemRandom().randint(0, len(commentsContent)-1) comment = commentsContent[commentNum] # get the number or seconds until some time in the last 30 days. - vary = rand.randint(0,(30 * 24 * 3600)+1) + vary = rand.SystemRandom().randint(0, (30 * 24 * 3600)+1) logger.info("Adding a comment from " + username + " on blab ID " + str(i))