Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

exxpresion value change test #15

Closed
wants to merge 1 commit into from
Closed

exxpresion value change test #15

wants to merge 1 commit into from

Conversation

sa-ny
Copy link
Owner

@sa-ny sa-ny commented Sep 19, 2024

No description provided.

Copy link

Caution

Breaking Flaws identified in code!

Fixes for app/views/userController.py:
Falws found for this file:
CWE 89 - Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') - Severity 4 on line 586 for issue 1083
CWE 80 - Improper Neutralization of Script-Related HTML Tags in a Web Page (Basic XSS) - Severity 3 on line 197 for issue 1022
CWE 89 - Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') - Severity 4 on line 227 for issue 1066
CWE 89 - Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') - Severity 4 on line 774 for issue 1097
CWE 89 - Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') - Severity 4 on line 186 for issue 1040
CWE 73 - External Control of File Name or Path - Severity 3 on line 661 for issue 1084
CWE 73 - External Control of File Name or Path - Severity 3 on line 787 for issue 1095
CWE 89 - Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') - Severity 4 on line 342 for issue 1072
CWE 89 - Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') - Severity 4 on line 513 for issue 1078
CWE 89 - Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') - Severity 4 on line 261 for issue 1069
CWE 89 - Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') - Severity 4 on line 733 for issue 1094
CWE 327 - Use of a Broken or Risky Cryptographic Algorithm - Severity 3 on line 105 for issue 1012
CWE 80 - Improper Neutralization of Script-Related HTML Tags in a Web Page (Basic XSS) - Severity 3 on line 707 for issue 1056
CWE 89 - Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') - Severity 4 on line 111 for issue 1031
CWE 327 - Use of a Broken or Risky Cryptographic Algorithm - Severity 3 on line 412 for issue 1014
CWE 601 - URL Redirection to Untrusted Site ('Open Redirect') - Severity 3 on line 96 for issue 1027
CWE 601 - URL Redirection to Untrusted Site ('Open Redirect') - Severity 3 on line 437 for issue 1075
CWE 73 - External Control of File Name or Path - Severity 3 on line 701 for issue 1059
CWE 89 - Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') - Severity 4 on line 420 for issue 1074
CWE 73 - External Control of File Name or Path - Severity 3 on line 702 for issue 1058
CWE 89 - Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') - Severity 4 on line 523 for issue 1076
CWE 80 - Improper Neutralization of Script-Related HTML Tags in a Web Page (Basic XSS) - Severity 3 on line 560 for issue 1087
CWE 73 - External Control of File Name or Path - Severity 3 on line 648 for issue 1086
CWE 89 - Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') - Severity 4 on line 494 for issue 1080
CWE 80 - Improper Neutralization of Script-Related HTML Tags in a Web Page (Basic XSS) - Severity 3 on line 199 for issue 1039
CWE 601 - URL Redirection to Untrusted Site ('Open Redirect') - Severity 3 on line 93 for issue 1029
CWE 89 - Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') - Severity 4 on line 139 for issue 1020

Fix suggestions:

--- app/views/userController.py
+++ app/views/userController.py
@@ -22,6 +22,8 @@
 
 from app.models import User, Blabber
 from app.forms import RegisterForm
+from html import escape
+from flask import Flask, make_response, jsonify
 
 
 # Get logger
@@ -108,7 +110,7 @@
                 parsed = sqlparse.parse(sqlQuery)[0]
                 logger.info("Attempted login with username and password: " + parsed[8].value)
 
-                cursor.execute(sqlQuery)
+                cursor.execute("%s;" % sqlQuery, (username,))
                 # END VULN CODE
                 # GOOD CODE
                 # sqlQuery = "select username, password, password_hint, created_at, last_login, \
@@ -135,8 +137,8 @@
                                     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=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 @@
     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 @@
                 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 @@
         #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 @@
         
         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 @@
     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 @@
                 query += ("'" + blabName + "'")
                 query += (");")
                 #execute query
-                cursor.execute(query)
+                cursor.execute('%s', (password,))
                 sqlStatement = cursor.fetchone() #<- variable for response
                 logger.info(query)
                 # END EXAMPLE VULNERABILITY
@@ -508,9 +510,9 @@
             events = []
 
             # START EXAMPLE VULNERABILITY 
-            sqlMyEvents = "select event from users_history where blabber=\"" + username + "\" ORDER BY eventid DESC; "
-            logger.info(sqlMyEvents)
-            cursor.execute(sqlMyEvents)
+            sqlMyEvents = "select event from users_history where blabber=%s ORDER BY eventid DESC; "
+            logger.info(sqlMyEvents, (username,))
+            cursor.execute(sqlMyEvents, (username,))
             userHistoryResult = cursor.fetchall()
             # END EXAMPLE VULNERABILITY 
 
@@ -518,9 +520,9 @@
                 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 @@
     # 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"<script>alert('Successfully changed values!\\nusername: {username.lower()}\\nReal Name: {realName}\\nBlab Name: {blabName}');</script>"
-    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')
@@ -704,7 +706,7 @@
                 if mime_type is None:
                     mime_type = "application/octet-stream"
                 logger.info("MIME type: " + mime_type)
-                response = HttpResponse(file.read(), content_type=mime_type)
+                response = HttpResponse(escape(file.read()), content_type=mime_type)
                 response.headers['Content-Disposition'] = 'attachment; filename=' + imageName
                 return response
     except ValueError as ve:
@@ -730,7 +732,7 @@
         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

Copy link

Caution

Breaking Flaws identified in code!

Fixes for app/views/resetController.py:
Falws found for this file:
CWE 331 - Insufficient Entropy - Severity 3 on line 111 for issue 1006
CWE 331 - Insufficient Entropy - Severity 3 on line 147 for issue 1008
CWE 331 - Insufficient Entropy - Severity 3 on line 151 for issue 1009
CWE 331 - Insufficient Entropy - Severity 3 on line 159 for issue 1011
CWE 331 - Insufficient Entropy - Severity 3 on line 155 for issue 1010
CWE 295 - Improper Certificate Validation - Severity 3 on line 63 for issue 1004
CWE 331 - Insufficient Entropy - Severity 3 on line 128 for issue 1007

Fix suggestions:

--- app/views/resetController.py
+++ app/views/resetController.py
@@ -60,7 +60,7 @@
     elif(request.method == "POST"):
         return processReset(request)
     else:
-        h = httplib2.Http(".cache", disable_ssl_certificate_validation=True) #CWE-295
+        h = httplib2.Http(".cache", verify=True) #CWE-295
         h.add_credentials('thiswaskevinsidea','hardcode') #CWE-798
         data=h.request("http://localhost/",method='GET')
         return data
@@ -108,7 +108,8 @@
                 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 @@
                 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 @@
                 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
+                    count = rand.SystemRandom().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.
+                        randomUserOffset = rand.SystemRandom().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)
+                        rand = random.SystemRandom()
+                        commentNum = rand.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)
+                        rand = random.SystemRandom()
+                        vary = rand.randint(0, (30 * 24 * 3600)+1)
 
                         logger.info("Adding a comment from " + username + " on blab ID " + str(i))
 

Copy link

Caution

Breaking Flaws identified in code!

Fixes for app/models.py:
Falws found for this file:
CWE 327 - Use of a Broken or Risky Cryptographic Algorithm - Severity 3 on line 29 for issue 1000

Fix suggestions:

undefined

Copy link

Caution

Breaking Flaws identified in code!

Fixes for app/templates/app/feed.html:
Falws found for this file:
CWE 80 - Insufficient Entropy - Severity 3 on line 160 for issue 1002

Fix suggestions:

--- app/templates/app/feed.html
+++ app/templates/app/feed.html
@@ -157,7 +157,7 @@
 				len : 10
 			}, function(data) {
 				if (data) {
-					$("#feed ul").append(data);
+$("#feed ul").append(DOMPurify.sanitize(data));
 				} else {
 					$(obj).remove();
 				}

Copy link

Caution

Breaking Flaws identified in code!

Fixes for app/views/toolsController.py:
Falws found for this file:
CWE 78 - Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') - Severity 5 on line 43 for issue 1089
CWE 78 - Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') - Severity 5 on line 68 for issue 1092

Fix suggestions:

--- app/views/toolsController.py
+++ app/views/toolsController.py
@@ -6,6 +6,7 @@
 
 from django.shortcuts import render
 from app.fortune.fortuneData import FortuneData, RiddleData
+import uuid
 
 
 
@@ -65,7 +66,8 @@
         return RiddleData()
     # OS Command Injection CWE-78
     else:
-        os.system(f'cat {file}')
+        directory_name = f'/tmp/{str(uuid.uuid4())}'
+        os.makedirs(directory_name)
    
         
 

Copy link

Caution

Breaking Flaws identified in code!

Fixes for app/views/blabController.py:
Falws found for this file:
CWE 89 - Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') - Severity 4 on line 257 for issue 1019
CWE 89 - Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') - Severity 4 on line 201 for issue 1065
CWE 89 - Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') - Severity 4 on line 162 for issue 1047
CWE 89 - Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') - Severity 4 on line 300 for issue 1053
CWE 80 - Improper Neutralization of Script-Related HTML Tags in a Web Page (Basic XSS) - Severity 3 on line 173 for issue 1018
CWE 89 - Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') - Severity 4 on line 51 for issue 1046
CWE 601 - URL Redirection to Untrusted Site ('Open Redirect') - Severity 3 on line 262 for issue 1062
CWE 89 - Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') - Severity 4 on line 211 for issue 1064
CWE 89 - Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') - Severity 4 on line 120 for issue 1017
CWE 89 - Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') - Severity 4 on line 75 for issue 1045

Fix suggestions:

--- app/views/blabController.py
+++ app/views/blabController.py
@@ -72,7 +72,7 @@
                 # Find the Blabs by this user
 
                 logger.info("Executing query to get all of user's Blabs")
-                cursor.execute(sqlBlabsByMe % (username,))
+                cursor.execute(sqlBlabsByMe, (username, ))
                 blabsByMeResults = cursor.fetchall()
 
                 myBlabs = []
@@ -117,7 +117,7 @@
                 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 (%s, %s, datetime('now'))", (username, blab))
 
                 if not cursor.rowcount:
                     request.error = "Failed to add blab"
@@ -159,7 +159,7 @@
 
             logger.info("Executing query to see more Blabs")
             blabsForMe = sqlBlabsForMe.format(len, cnt)
-            cursor.execute(blabsForMe % (username,))
+            cursor.execute("%s", (username, ))
             results = cursor.fetchall()
             ret = ""
             for blab in results:
@@ -170,7 +170,7 @@
     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 @@
             with connection.cursor() as cursor:
 
                 logger.info("Executing query to see Blab details")
-                cursor.execute(blabDetailsSql % (blabid,))
+                cursor.execute("SELECT * FROM blabber %s", (blabid, ))
                 blabDetailsResults = cursor.fetchone()
 
                 if (blabDetailsResults):

Copy link

Caution

Breaking Flaws identified in code!

Fixes for app/templates/app/profile.html:
Falws found for this file:
CWE 80 - Insufficient Entropy - Severity 3 on line 224 for issue 1003
CWE 80 - Use of Hard-coded Password - Severity 3 on line 219 for issue 1001

Fix suggestions:

--- app/templates/app/profile.html
+++ app/templates/app/profile.html
@@ -216,12 +216,12 @@
 								$('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);
+$('body').append(DOMPurify.sanitize(data.message));
 						}
 					}
 				},

@sa-ny sa-ny closed this Sep 24, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant