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

flow test #29

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion application/views/userController.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import smtplib
import pyotp
import pickle, base64

# usercontroller test
import sqlparse
from email.mime.multipart import MIMEMultipart
from passeo import passeo
Expand All @@ -19,13 +19,13 @@
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.clickjacking import xframe_options_exempt
import mimetypes

from application.models import User, Blabber
from application.forms import RegisterForm


# Get logger
logger = logging.getLogger("VeraDemo:userController")

Check warning on line 28 in application/views/userController.py

View workflow job for this annotation

GitHub Actions / Veracode Fix suggestions

Securityy findings

from application.models import User, Blabber from application.forms import RegisterForm +from html import escape # Get logger
image_dir = os.path.join(os.path.dirname(__file__), '../../resources/images')

# xframe_options_exempt makes this function unprotected from clickjacking
Expand Down Expand Up @@ -105,14 +105,14 @@
and password='" + hashlib.md5(password.encode('utf-8')).hexdigest() + "';"
logger.info(sqlQuery)

parsed = sqlparse.parse(sqlQuery)[0]
logger.info("Attempted login with username and password: " + parsed[8].value)

cursor.execute(sqlQuery)
# END VULN CODE
# GOOD CODE
# sqlQuery = "select username, password, password_hint, created_at, last_login, \
# real_name, blab_name from users where username=:username and password=:password;"

Check warning on line 115 in application/views/userController.py

View workflow job for this annotation

GitHub Actions / Veracode Fix suggestions

Securityy findings

parsed = sqlparse.parse(sqlQuery)[0] logger.info("Attempted login with username and password: " + parsed[8].value) - cursor.execute(sqlQuery) + cursor.execute("%s", (username,)) # END VULN CODE # GOOD CODE # sqlQuery = "select username, password, password_hint, created_at, last_login, \

# logger.info(sqlQuery, {"username": username, "password": hashlib.md5(password.encode('utf-8')).hexdigest()})
# cursor.execute(sqlQuery, {"username": username, "password": hashlib.md5(password.encode('utf-8')).hexdigest()})
Expand All @@ -132,15 +132,15 @@
currentUser = User(username=row["username"],
password_hint=row["password_hint"], created_at=row["created_at"],
last_login=row["last_login"], real_name=row["real_name"],
blab_name=row["blab_name"])
response = updateInResponse(currentUser, response)

update = "UPDATE users SET last_login=datetime('now') WHERE username='" + row['username'] + "';"
cursor.execute(update)

# if the username ends with "totp", add the TOTP login step
if username[-4:].lower() == "totp":
logger.info("User " + username + " has TOTP enabled")

Check warning on line 143 in application/views/userController.py

View workflow job for this annotation

GitHub Actions / Veracode Fix suggestions

Securityy findings

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":
request.session['totp_username'] = row['username']
response = redirect('totp')
else:
Expand Down Expand Up @@ -178,29 +178,29 @@

logger.info("Entering password-hint with username: " + username)

try:
logger.info("Creating the Database connection")
with connection.cursor() as cursor:
sql = "SELECT password_hint FROM users WHERE username = '" + username + "'"
logger.info(sql)
cursor.execute(sql)
row = cursor.fetchone()

if (row):
password = row[0]

Check warning on line 190 in application/views/userController.py

View workflow job for this annotation

GitHub Actions / Veracode Fix suggestions

Securityy findings

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):

logger.info(f"Password: {password}")

formatString = "Username '" + username + "' has password: {}"
hint = formatString.format(password[:2] + ("*" * (len(password) - 2)))
logger.info(hint)
return HttpResponse(hint)
else:
return HttpResponse("No password found for " + username)
except DatabaseError as db_err:
logger.error("Database error", db_err)
return HttpResponse("ERROR!")
except Exception as e:

Check warning on line 203 in application/views/userController.py

View workflow job for this annotation

GitHub Actions / Veracode Fix suggestions

Securityy findings

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!")
logger.error("Unexpected error", e)

return HttpResponse("ERROR!")
Expand All @@ -219,16 +219,16 @@
# lookup the TOTP secret
# really here to display back to the user (it's a hack for a demo app ;) )
try:
#Create db connection
with connection.cursor() as cursor:

sql = "SELECT totp_secret FROM users WHERE username = '" + username + "'"
logger.info(sql)
cursor.execute(sql)

result = cursor.fetchone()
if result:
totpSecret = result[0]

Check warning on line 231 in application/views/userController.py

View workflow job for this annotation

GitHub Actions / Veracode Fix suggestions

Securityy findings

#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:
logger.info("Found TOTP secret")
request.totpSecret = totpSecret
else:
Expand All @@ -253,16 +253,16 @@

# lookup the TOTP secret
try:

with connection.cursor() as cursor:

sql = "SELECT totp_secret FROM users WHERE username = '" + username + "'"
logger.info(sql)
cursor.execute(sql)

result = cursor.fetchone()
if result:
columns = [col[0] for col in cursor.description]

Check warning on line 265 in application/views/userController.py

View workflow job for this annotation

GitHub Actions / Veracode Fix suggestions

Securityy findings

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:
result = dict(zip(columns, result))
totpSecret = result["totp_secret"]
logger.info("Found TOTP secret")
Expand Down Expand Up @@ -335,15 +335,15 @@
return render(request, 'app/register.html')

# Get the Database Connection
logger.info("Creating the Database connection")
try:
with connection.cursor() as cursor:
sqlQuery = "SELECT username FROM users WHERE username = '" + username + "'"
cursor.execute(sqlQuery)
row = cursor.fetchone()
if (row):
request.error = "Username '" + username + "' already exists!"
return render(request, 'app/register.html')

Check warning on line 346 in application/views/userController.py

View workflow job for this annotation

GitHub Actions / Veracode Fix suggestions

Securityy findings

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!"
else:
rand_pass = passeo().generate(10, numbers=True, symbols=True)
sk = SigningKey.generate()
Expand Down Expand Up @@ -414,14 +414,14 @@
query += ("'" + pyotp.random_base32() + "',")
query += ("datetime('now'),")
query += ("'" + realName + "',")
query += ("'" + blabName + "'")
query += (");")
#execute query
cursor.execute(query)
sqlStatement = cursor.fetchone() #<- variable for response
logger.info(query)
# END EXAMPLE VULNERABILITY
except IntegrityError as ie:

Check warning on line 424 in application/views/userController.py

View workflow job for this annotation

GitHub Actions / Veracode Fix suggestions

Securityy findings

query += ("'" + blabName + "'") query += (");") #execute query - cursor.execute(query) + cursor.execute("%s", (password,)) sqlStatement = cursor.fetchone() #<- variable for response logger.info(query) # END EXAMPLE VULNERABILITY
logger.error("Integrity error", ie)
return render(request, 'app/register.html')
except ValueError as ve:
Expand Down Expand Up @@ -488,14 +488,14 @@
try:

logger.info("Getting Database connection")
with connection.cursor() as cursor:
# Find the Blabbers that this user listens to
logger.info(sqlMyHecklers)
cursor.execute(sqlMyHecklers % username)
myHecklersResults = cursor.fetchall()
hecklers=[]
for i in myHecklersResults:

Check warning on line 498 in application/views/userController.py

View workflow job for this annotation

GitHub Actions / Veracode Fix suggestions

Securityy findings

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:
heckler = Blabber()
heckler.setUsername(i[0])
heckler.setBlabName(i[1])
Expand All @@ -505,26 +505,26 @@


# Get the audit trail for this user
events = []

# START EXAMPLE VULNERABILITY
sqlMyEvents = "select event from users_history where blabber=\"" + username + "\" ORDER BY eventid DESC; "
logger.info(sqlMyEvents)
cursor.execute(sqlMyEvents)
userHistoryResult = cursor.fetchall()
# END EXAMPLE VULNERABILITY

for result in userHistoryResult :

Check warning on line 517 in application/views/userController.py

View workflow job for this annotation

GitHub Actions / Veracode Fix suggestions

Securityy findings

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
events.append(result[0])

# Get the users information
sql = "SELECT username, real_name, blab_name, totp_secret FROM users WHERE username = '" + username + "'"
logger.info(sql)
cursor.execute(sql)
myInfoResults = cursor.fetchone()
if not myInfoResults:
return JsonResponse({'message':'Error, no Inforesults found'})
# Send these values to our View

Check warning on line 527 in application/views/userController.py

View workflow job for this annotation

GitHub Actions / Veracode Fix suggestions

Securityy findings

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'})
columns = [col[0] for col in cursor.description]
myInfoResults = dict(zip(columns, myInfoResults))
request.hecklers = hecklers
Expand Down Expand Up @@ -554,14 +554,14 @@
username = request.POST.get('username')
file = request.FILES.get('file')
#TODO: Experiment with safe=False on JsonResponse, send in non-dict objects for serialization
# 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)

logger.info("entering processProfile")
sessionUsername = request.session.get('username')

Check warning on line 564 in application/views/userController.py

View workflow job for this annotation

GitHub Actions / Veracode Fix suggestions

Securityy findings

# 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({'values':escape({"username": username.lower(), "realName": realName, "blabName": blabName}),'message':msg}, status=200) logger.info("entering processProfile") sessionUsername = request.session.get('username')
# Ensure user is logged in
if not sessionUsername:
logger.info("User is not Logged In = redirecting...")
Expand Down
Loading