From 8db53ef85c4190a86a6403327beefa34588dcc9d Mon Sep 17 00:00:00 2001 From: "patched.codes[bot]" <298395+patched.codes[bot]@users.noreply.github.com> Date: Tue, 25 Jun 2024 09:30:29 +0800 Subject: [PATCH 01/14] Patched /private/var/folders/61/dwx9fsqs2k931dkwz6dg1ymw0000gn/T/tmp980zihnh/introduction/templates/Lab/XSS/xss_lab_3.html --- introduction/templates/Lab/XSS/xss_lab_3.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/introduction/templates/Lab/XSS/xss_lab_3.html b/introduction/templates/Lab/XSS/xss_lab_3.html index a550b9a..b88d0e5 100644 --- a/introduction/templates/Lab/XSS/xss_lab_3.html +++ b/introduction/templates/Lab/XSS/xss_lab_3.html @@ -19,7 +19,7 @@

Welcome to XSS Challenge

{{code}}


From a3760442b4f0bf19d896ff99063a2d68eee1d79f Mon Sep 17 00:00:00 2001 From: "patched.codes[bot]" <298395+patched.codes[bot]@users.noreply.github.com> Date: Tue, 25 Jun 2024 09:30:29 +0800 Subject: [PATCH 02/14] Patched /private/var/folders/61/dwx9fsqs2k931dkwz6dg1ymw0000gn/T/tmp980zihnh/introduction/templates/Lab_2021/A1_BrokenAccessControl/broken_access_lab_1.html --- .../A1_BrokenAccessControl/broken_access_lab_1.html | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/introduction/templates/Lab_2021/A1_BrokenAccessControl/broken_access_lab_1.html b/introduction/templates/Lab_2021/A1_BrokenAccessControl/broken_access_lab_1.html index 1fa4c91..26849e0 100644 --- a/introduction/templates/Lab_2021/A1_BrokenAccessControl/broken_access_lab_1.html +++ b/introduction/templates/Lab_2021/A1_BrokenAccessControl/broken_access_lab_1.html @@ -9,12 +9,11 @@

Admins Have the Secretkey

+ {% csrf_token %}

- -
@@ -34,7 +33,6 @@

{{not_admin}}

{% if no_creds %}

Please Provide Credentials

{% endif %} -
@@ -43,4 +41,4 @@

Please Provide Credentials

-{% endblock %} \ No newline at end of file +{% endblock %} From 8587c751b6af8b6d8601e440d21c07faec6d1781 Mon Sep 17 00:00:00 2001 From: "patched.codes[bot]" <298395+patched.codes[bot]@users.noreply.github.com> Date: Tue, 25 Jun 2024 09:30:29 +0800 Subject: [PATCH 03/14] Patched /private/var/folders/61/dwx9fsqs2k931dkwz6dg1ymw0000gn/T/tmp980zihnh/introduction/templates/Lab/CMD/cmd_lab2.html --- introduction/templates/Lab/CMD/cmd_lab2.html | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/introduction/templates/Lab/CMD/cmd_lab2.html b/introduction/templates/Lab/CMD/cmd_lab2.html index a71a605..7319130 100644 --- a/introduction/templates/Lab/CMD/cmd_lab2.html +++ b/introduction/templates/Lab/CMD/cmd_lab2.html @@ -7,6 +7,7 @@

Evaluate any expression!

+ {% csrf_token %}

@@ -29,4 +30,4 @@
Output

-{% endblock %} \ No newline at end of file +{% endblock %} From 0451ff0aa4b1893a22a894a186dbd90ee8ccae4f Mon Sep 17 00:00:00 2001 From: "patched.codes[bot]" <298395+patched.codes[bot]@users.noreply.github.com> Date: Tue, 25 Jun 2024 09:30:29 +0800 Subject: [PATCH 04/14] Patched /private/var/folders/61/dwx9fsqs2k931dkwz6dg1ymw0000gn/T/tmp980zihnh/introduction/templates/Lab_2021/A1_BrokenAccessControl/broken_access_lab_2.html --- .../Lab_2021/A1_BrokenAccessControl/broken_access_lab_2.html | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/introduction/templates/Lab_2021/A1_BrokenAccessControl/broken_access_lab_2.html b/introduction/templates/Lab_2021/A1_BrokenAccessControl/broken_access_lab_2.html index cce8b6e..dce89af 100644 --- a/introduction/templates/Lab_2021/A1_BrokenAccessControl/broken_access_lab_2.html +++ b/introduction/templates/Lab_2021/A1_BrokenAccessControl/broken_access_lab_2.html @@ -9,6 +9,7 @@

Can you log in as an admin and get the secretkey?

+ {% csrf_token %}

@@ -50,4 +51,4 @@

Please Provide Credentials

-{% endblock %} \ No newline at end of file +{% endblock %} From abf94df1ff05792521c820a64fc49d565951d95b Mon Sep 17 00:00:00 2001 From: "patched.codes[bot]" <298395+patched.codes[bot]@users.noreply.github.com> Date: Tue, 25 Jun 2024 09:30:29 +0800 Subject: [PATCH 05/14] Patched /private/var/folders/61/dwx9fsqs2k931dkwz6dg1ymw0000gn/T/tmp980zihnh/introduction/templates/Lab/BrokenAuth/otp.html --- introduction/templates/Lab/BrokenAuth/otp.html | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/introduction/templates/Lab/BrokenAuth/otp.html b/introduction/templates/Lab/BrokenAuth/otp.html index 3d12cda..973191b 100644 --- a/introduction/templates/Lab/BrokenAuth/otp.html +++ b/introduction/templates/Lab/BrokenAuth/otp.html @@ -7,15 +7,15 @@
Login Through Otp

+ {% csrf_token %} - -
+ {% csrf_token %}

@@ -25,13 +25,9 @@
Login Through Otp

{% if otp %}

Your 3 Digit Verification Code:{{otp}}

{% endif %} - {% if email %}

Login Successful as user : {{email}}

{% endif %} - - -
-{% endblock %} \ No newline at end of file +{% endblock %} From 085d418727ea9c67b234e8ce4dcf646e34e39e46 Mon Sep 17 00:00:00 2001 From: "patched.codes[bot]" <298395+patched.codes[bot]@users.noreply.github.com> Date: Tue, 25 Jun 2024 09:30:29 +0800 Subject: [PATCH 06/14] Patched /private/var/folders/61/dwx9fsqs2k931dkwz6dg1ymw0000gn/T/tmp980zihnh/introduction/apis.py --- introduction/apis.py | 61 +++++++++++++++++++++++++++----------------- 1 file changed, 37 insertions(+), 24 deletions(-) diff --git a/introduction/apis.py b/introduction/apis.py index 7926708..b22e1c0 100644 --- a/introduction/apis.py +++ b/introduction/apis.py @@ -58,36 +58,44 @@ def ssrf_code_checker(request): @csrf_exempt # @authentication_decorator +import os + def log_function_checker(request): if request.method == 'POST': csrf_token = request.POST.get("csrfmiddlewaretoken") log_code = request.POST.get('log_code') api_code = request.POST.get('api_code') + + # Sanitize user-controlled data before writing to files + log_code = log_code[:1000] # Limit to 1000 characters + api_code = api_code[:1000] # Limit to 1000 characters + dirname = os.path.dirname(__file__) log_filename = os.path.join(dirname, "playground/A9/main.py") api_filename = os.path.join(dirname, "playground/A9/api.py") - f = open(log_filename,"w") - f.write(log_code) - f.close() - f = open(api_filename,"w") - f.write(api_code) - f.close() + + with open(log_filename, "w") as f: + f.write(log_code) + with open(api_filename, "w") as f: + f.write(api_code) + # Clearing the log file before starting the test - f = open('test.log', 'w') - f.write("") - f.close() + with open('test.log', 'w') as f: + f.write("") + url = "http://127.0.0.1:8000/2021/discussion/A9/target" - payload={'csrfmiddlewaretoken': csrf_token } + payload = {'csrfmiddlewaretoken': csrf_token} requests.request("GET", url) requests.request("POST", url) requests.request("PATCH", url, data=payload) requests.request("DELETE", url) - f = open('test.log', 'r') - lines = f.readlines() - f.close() - return JsonResponse({"message":"success", "logs": lines},status = 200) + + with open('test.log', 'r') as f: + lines = f.readlines() + + return JsonResponse({"message": "success", "logs": lines}, status=200) else: - return JsonResponse({"message":"method not allowed"},status = 405) + return JsonResponse({"message": "method not allowed"}, status=405) #a7 codechecking api @csrf_exempt @@ -123,16 +131,21 @@ def A6_disscussion_api(request): return JsonResponse({"message":"failure"},status = 400) @csrf_exempt +import os + def A6_disscussion_api_2(request): if request.method != 'POST': - return JsonResponse({"message":"method not allowed"},status = 405) + return JsonResponse({"message": "method not allowed"}, status=405) try: code = request.POST.get('code') - dirname = os.path.dirname(__file__) - filename = os.path.join(dirname, "playground/A6/utility.py") - f = open(filename,"w") - f.write(code) - f.close() - except: - return JsonResponse({"message":"missing code"},status = 400) - return JsonResponse({"message":"success"},status = 200) \ No newline at end of file + if code: + dirname = os.path.dirname(__file__) + filename = os.path.join(dirname, "playground/A6/utility.py") + with open(filename, "w") as f: + f.write(code) + else: + return JsonResponse({"message": "missing code"}, status=400) + except Exception as e: + return JsonResponse({"message": "error occurred", "error": str(e)}, status=400) + + return JsonResponse({"message": "success"}, status=200) From 423406cca444dbcb9cfd48b7e5cfac4db708f550 Mon Sep 17 00:00:00 2001 From: "patched.codes[bot]" <298395+patched.codes[bot]@users.noreply.github.com> Date: Tue, 25 Jun 2024 09:30:29 +0800 Subject: [PATCH 07/14] Patched /private/var/folders/61/dwx9fsqs2k931dkwz6dg1ymw0000gn/T/tmp980zihnh/docker-compose.yml --- docker-compose.yml | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/docker-compose.yml b/docker-compose.yml index 3d39f83..ab88e2f 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -9,6 +9,9 @@ services: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres + security_opt: + - "no-new-privileges:true" + read_only: true web: build: . image: pygoat/pygoat @@ -20,6 +23,9 @@ services: depends_on: - migration - db + security_opt: + - "no-new-privileges:true" + read_only: true migration: image: pygoat/pygoat command: python pygoat/manage.py migrate --noinput @@ -27,3 +33,6 @@ services: - .:/app depends_on: - db + security_opt: + - "no-new-privileges:true" + read_only: true From 16c4dc7defbe72fa59722b194ce0778f7c5738b8 Mon Sep 17 00:00:00 2001 From: "patched.codes[bot]" <298395+patched.codes[bot]@users.noreply.github.com> Date: Tue, 25 Jun 2024 09:30:29 +0800 Subject: [PATCH 08/14] Patched /private/var/folders/61/dwx9fsqs2k931dkwz6dg1ymw0000gn/T/tmp980zihnh/introduction/mitre.py --- introduction/mitre.py | 35 +++++++++++++++++++++++++++-------- 1 file changed, 27 insertions(+), 8 deletions(-) diff --git a/introduction/mitre.py b/introduction/mitre.py index c899c21..f9afaa2 100644 --- a/introduction/mitre.py +++ b/introduction/mitre.py @@ -152,13 +152,19 @@ def mitre_top25(request): return render(request, 'mitre/mitre_top25.html') @authentication_decorator +import hashlib +import os +import jwt +from django.shortcuts import render, redirect +from .models import CSRF_user_tbl + def csrf_lab_login(request): if request.method == 'GET': return render(request, 'mitre/csrf_lab_login.html') elif request.method == 'POST': password = request.POST.get('password') username = request.POST.get('username') - password = md5(password.encode()).hexdigest() + password = hashlib.scrypt(password.encode(), salt=os.urandom(16), n=2**14, r=8, p=1).hex() User = CSRF_user_tbl.objects.filter(username=username, password=password) if User: payload ={ @@ -166,20 +172,25 @@ def csrf_lab_login(request): 'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=300), 'iat': datetime.datetime.utcnow() } - cookie = jwt.encode(payload, 'csrf_vulneribility', algorithm='HS256') + jwt_secret = os.getenv('JWT_SECRET') + cookie = jwt.encode(payload, jwt_secret, algorithm='HS256') response = redirect("/mitre/9/lab/transaction") - response.set_cookie('auth_cookiee', cookie) + response.set_cookie('auth_cookiee', cookie, secure=True, httponly=True, samesite='Lax') return response - else : + else: return redirect('/mitre/9/lab/login') @authentication_decorator @csrf_exempt +import os + +SECRET_KEY = os.getenv('SECRET_KEY') + def csrf_transfer_monei(request): if request.method == 'GET': try: cookie = request.COOKIES['auth_cookiee'] - payload = jwt.decode(cookie, 'csrf_vulneribility', algorithms=['HS256']) + payload = jwt.decode(cookie, SECRET_KEY, algorithms=['HS256']) username = payload['username'] User = CSRF_user_tbl.objects.filter(username=username) if not User: @@ -188,10 +199,14 @@ def csrf_transfer_monei(request): except: return redirect('/mitre/9/lab/login') +import os + +SECRET_KEY = os.getenv('SECRET_KEY', 'default_secret_key') + def csrf_transfer_monei_api(request,recipent,amount): if request.method == "GET": cookie = request.COOKIES['auth_cookiee'] - payload = jwt.decode(cookie, 'csrf_vulneribility', algorithms=['HS256']) + payload = jwt.decode(cookie, SECRET_KEY, algorithms=['HS256']) username = payload['username'] User = CSRF_user_tbl.objects.filter(username=username) if not User: @@ -212,10 +227,12 @@ def csrf_transfer_monei_api(request,recipent,amount): # @authentication_decorator @csrf_exempt +import ast + def mitre_lab_25_api(request): if request.method == "POST": expression = request.POST.get('expression') - result = eval(expression) + result = ast.literal_eval(expression) return JsonResponse({'result': result}) else: return redirect('/mitre/25/lab/') @@ -229,8 +246,10 @@ def mitre_lab_25(request): def mitre_lab_17(request): return render(request, 'mitre/mitre_lab_17.html') +import subprocess + def command_out(command): - process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + process = subprocess.Popen(command, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return process.communicate() From b855ae4612b3e0e85cf684865c8e93177450b5c2 Mon Sep 17 00:00:00 2001 From: "patched.codes[bot]" <298395+patched.codes[bot]@users.noreply.github.com> Date: Tue, 25 Jun 2024 09:30:29 +0800 Subject: [PATCH 09/14] Patched /private/var/folders/61/dwx9fsqs2k931dkwz6dg1ymw0000gn/T/tmp980zihnh/introduction/templates/Lab/CMD/cmd_lab.html --- introduction/templates/Lab/CMD/cmd_lab.html | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/introduction/templates/Lab/CMD/cmd_lab.html b/introduction/templates/Lab/CMD/cmd_lab.html index 2998cd3..6175ff5 100644 --- a/introduction/templates/Lab/CMD/cmd_lab.html +++ b/introduction/templates/Lab/CMD/cmd_lab.html @@ -7,6 +7,7 @@

Name Server Lookup

+ {% csrf_token %}

@@ -33,4 +34,4 @@
Output

-{% endblock %} \ No newline at end of file +{% endblock %} From 803000176a1c51485c08907dd96dec4cd8cc994f Mon Sep 17 00:00:00 2001 From: "patched.codes[bot]" <298395+patched.codes[bot]@users.noreply.github.com> Date: Tue, 25 Jun 2024 09:30:29 +0800 Subject: [PATCH 10/14] Patched /private/var/folders/61/dwx9fsqs2k931dkwz6dg1ymw0000gn/T/tmp980zihnh/introduction/playground/A9/archive.py --- introduction/playground/A9/archive.py | 1 - 1 file changed, 1 deletion(-) diff --git a/introduction/playground/A9/archive.py b/introduction/playground/A9/archive.py index c9db8fc..67082e1 100644 --- a/introduction/playground/A9/archive.py +++ b/introduction/playground/A9/archive.py @@ -4,7 +4,6 @@ from .main import Log -@csrf_exempt def log_function_target(request): L = Log(request) if request.method == "GET": From 7bf828987f61cb2f0c0c1cf45ffe8063808993f7 Mon Sep 17 00:00:00 2001 From: "patched.codes[bot]" <298395+patched.codes[bot]@users.noreply.github.com> Date: Tue, 25 Jun 2024 09:30:29 +0800 Subject: [PATCH 11/14] Patched /private/var/folders/61/dwx9fsqs2k931dkwz6dg1ymw0000gn/T/tmp980zihnh/introduction/templates/Lab/BrokenAccess/ba_lab.html --- introduction/templates/Lab/BrokenAccess/ba_lab.html | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/introduction/templates/Lab/BrokenAccess/ba_lab.html b/introduction/templates/Lab/BrokenAccess/ba_lab.html index d45da9b..29b37f9 100644 --- a/introduction/templates/Lab/BrokenAccess/ba_lab.html +++ b/introduction/templates/Lab/BrokenAccess/ba_lab.html @@ -9,12 +9,10 @@

Admins Have the Secretkey

@@ -43,4 +41,4 @@

Please Provide Credentials

-{% endblock %} \ No newline at end of file +{% endblock %} From 9e0b1e32bad154b3a3079d40f0aafd8398a2af18 Mon Sep 17 00:00:00 2001 From: "patched.codes[bot]" <298395+patched.codes[bot]@users.noreply.github.com> Date: Tue, 25 Jun 2024 09:30:29 +0800 Subject: [PATCH 12/14] Patched /private/var/folders/61/dwx9fsqs2k931dkwz6dg1ymw0000gn/T/tmp980zihnh/introduction/views.py --- introduction/views.py | 308 ++++++++++++++++++++++-------------------- 1 file changed, 160 insertions(+), 148 deletions(-) diff --git a/introduction/views.py b/introduction/views.py index 0f550c4..dde0d3a 100644 --- a/introduction/views.py +++ b/introduction/views.py @@ -146,42 +146,39 @@ def sql(request): def sql_lab(request): if request.user.is_authenticated: - name=request.POST.get('name') - - password=request.POST.get('pass') + name = request.POST.get('name') + password = request.POST.get('pass') if name: - if login.objects.filter(user=name): - - sql_query = "SELECT * FROM introduction_login WHERE user='"+name+"'AND password='"+password+"'" + sql_query = "SELECT * FROM introduction_login WHERE user=%s AND password=%s" print(sql_query) try: print("\nin try\n") - val=login.objects.raw(sql_query) + val = login.objects.raw(sql_query, [name, password]) except: print("\nin except\n") return render( - request, + request, 'Lab/SQL/sql_lab.html', { - "wrongpass":password, - "sql_error":sql_query + "wrongpass": password, + "sql_error": sql_query }) if val: - user=val[0].user - return render(request, 'Lab/SQL/sql_lab.html',{"user1":user}) + user = val[0].user + return render(request, 'Lab/SQL/sql_lab.html', {"user1": user}) else: return render( - request, + request, 'Lab/SQL/sql_lab.html', { - "wrongpass":password, - "sql_error":sql_query + "wrongpass": password, + "sql_error": sql_query }) else: - return render(request, 'Lab/SQL/sql_lab.html',{"no": "User not found"}) + return render(request, 'Lab/SQL/sql_lab.html', {"no": "User not found"}) else: return render(request, 'Lab/SQL/sql_lab.html') else: @@ -201,13 +198,17 @@ class TestUser: pickled_user = pickle.dumps(TestUser()) encoded_user = base64.b64encode(pickled_user) +import base64 +import pickle +from django.shortcuts import render, redirect + def insec_des_lab(request): if request.user.is_authenticated: response = render(request,'Lab/insec_des/insec_des_lab.html', {"message":"Only Admins can see this page"}) token = request.COOKIES.get('token') if token == None: token = encoded_user - response.set_cookie(key='token',value=token.decode('utf-8')) + response.set_cookie(key='token', value=token.decode('utf-8'), secure=True, httponly=True, samesite='Lax') else: token = base64.b64decode(token) admin = pickle.loads(token) @@ -270,59 +271,66 @@ def auth_home(request): def auth_lab(request): return render(request,'Lab/AUTH/auth_lab.html') +from django.template.loader import render_to_string +from django.http import HttpResponse +from django.shortcuts import render +from django.utils.http import http_date + def auth_lab_signup(request): if request.method == 'GET': - return render(request,'Lab/AUTH/auth_lab_signup.html') + return render(request, 'Lab/AUTH/auth_lab_signup.html') elif request.method == 'POST': try: name = request.POST['name'] user_name = request.POST['username'] - passwd = request.POST['pass'] - obj = authLogin.objects.create(name=name,username=user_name,password=passwd) + passwd = request.POST['pass'] + obj = authLogin.objects.create(name=name, username=user_name, password=passwd) try: - rendered = render_to_string('Lab/AUTH/auth_success.html', {'username': obj.username,'userid':obj.userid,'name':obj.name,'err_msg':'Cookie Set'}) + rendered = render_to_string('Lab/AUTH/auth_success.html', {'username': obj.username, 'userid': obj.userid, 'name': obj.name, 'err_msg': 'Cookie Set'}) response = HttpResponse(rendered) - response.set_cookie('userid', obj.userid, max_age=31449600, samesite=None, secure=False) + response.set_cookie('userid', obj.userid, max_age=31449600, samesite='Lax', secure=True, httponly=True) print('Setting cookie successful') return response except: - render(request,'Lab/AUTH/auth_lab_signup.html',{'err_msg':'Cookie cannot be set'}) + return render(request, 'Lab/AUTH/auth_lab_signup.html', {'err_msg': 'Cookie cannot be set'}) except: - return render(request,'Lab/AUTH/auth_lab_signup.html',{'err_msg':'Username already exists'}) + return render(request, 'Lab/AUTH/auth_lab_signup.html', {'err_msg': 'Username already exists'}) +from django.template.loader import render_to_string +from django.http import HttpResponse +from django.shortcuts import render +from django.views.decorators.csrf import ensure_csrf_cookie +from django.utils.decorators import method_decorator + +@method_decorator(ensure_csrf_cookie, name='dispatch') def auth_lab_login(request): if request.method == 'GET': try: obj = authLogin.objects.filter(userid=request.COOKIES['userid'])[0] - rendered = render_to_string('Lab/AUTH/auth_success.html', {'username': obj.username,'userid':obj.userid,'name':obj.name, 'err_msg':'Login Successful'}) - response = HttpResponse(rendered) - response.set_cookie('userid', obj.userid, max_age=31449600, samesite=None, secure=False) - print('Login successful') - return response + context = {'username': obj.username, 'userid': obj.userid, 'name': obj.name, 'err_msg': 'Login Successful'} + return render(request, 'Lab/AUTH/auth_success.html', context) except: - return render(request,'Lab/AUTH/auth_lab_login.html') + return render(request, 'Lab/AUTH/auth_lab_login.html') elif request.method == 'POST': try: user_name = request.POST['username'] - passwd = request.POST['pass'] - print(user_name,passwd) - obj = authLogin.objects.filter(username=user_name,password=passwd)[0] - try: - rendered = render_to_string('Lab/AUTH/auth_success.html', {'username': obj.username,'userid':obj.userid,'name':obj.name, 'err_msg':'Login Successful'}) - response = HttpResponse(rendered) - response.set_cookie('userid', obj.userid, max_age=31449600, samesite=None, secure=False) - print('Login successful') - return response - except: - render(request,'Lab/AUTH/auth_lab_login.html',{'err_msg':'Cookie cannot be set'}) + passwd = request.POST['pass'] + obj = authLogin.objects.get(username=user_name, password=passwd) + context = {'username': obj.username, 'userid': obj.userid, 'name': obj.name, 'err_msg': 'Login Successful'} + response = HttpResponse(render_to_string('Lab/AUTH/auth_success.html', context)) + response.set_cookie('userid', obj.userid, max_age=31449600, samesite='Lax', secure=True, httponly=True) + print('Login successful') + return response + except authLogin.DoesNotExist: + return render(request, 'Lab/AUTH/auth_lab_login.html', {'err_msg': 'Check your credentials'}) except: - return render(request,'Lab/AUTH/auth_lab_login.html',{'err_msg':'Check your credentials'}) + return render(request, 'Lab/AUTH/auth_lab_login.html', {'err_msg': 'Cookie cannot be set'}) + +from django.shortcuts import render +from django.http import HttpResponse def auth_lab_logout(request): - rendered = render_to_string('Lab/AUTH/auth_lab.html',context={'err_msg':'Logout successful'}) - response = HttpResponse(rendered) - response.delete_cookie('userid') - return response + return render(request, 'Lab/AUTH/auth_lab.html', {'err_msg': 'Logout successful'}) #***************************************************************Broken Access Control************************************************************# @@ -406,6 +414,8 @@ def cmd(request): else: return redirect('login') @csrf_exempt +import subprocess + def cmd_lab(request): if request.user.is_authenticated: if(request.method=="POST"): @@ -414,22 +424,19 @@ def cmd_lab(request): os=request.POST.get('os') print(os) if(os=='win'): - command="nslookup {}".format(domain) + command=["nslookup", domain] else: - command = "dig {}".format(domain) + command = ["dig", domain] try: - # output=subprocess.check_output(command,shell=True,encoding="UTF-8") process = subprocess.Popen( command, - shell=True, + shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = process.communicate() data = stdout.decode('utf-8') stderr = stderr.decode('utf-8') - # res = json.loads(data) - # print("Stdout\n" + data) output = data + stderr print(data + stderr) except: @@ -443,19 +450,22 @@ def cmd_lab(request): return redirect('login') @csrf_exempt +import ast + def cmd_lab2(request): if request.user.is_authenticated: - if (request.method=="POST"): - val=request.POST.get('val') + if request.method == "POST": + val = request.POST.get('val') print(val) try: - output = eval(val) + parsed_val = ast.literal_eval(val) + output = parsed_val except: output = "Something went wrong" - return render(request,'Lab/CMD/cmd_lab2.html',{"output":output}) - print("Output = ", output) - return render(request,'Lab/CMD/cmd_lab2.html',{"output":output}) + return render(request, 'Lab/CMD/cmd_lab2.html', {"output": output}) + print("Output =", output) + return render(request, 'Lab/CMD/cmd_lab2.html', {"output": output}) else: return render(request, 'Lab/CMD/cmd_lab2.html') else: @@ -546,16 +556,13 @@ def a9_lab(request): if request.method=="GET": return render(request,"Lab/A9/a9_lab.html") else: - - try : - file=request.FILES["file"] - try : - data = yaml.load(file,yaml.Loader) - + try: + file = request.FILES["file"] + try: + data = yaml.safe_load(file,Loader=yaml.Loader) return render(request,"Lab/A9/a9_lab.html",{"data":data}) except: return render(request, "Lab/A9/a9_lab.html", {"data": "Error"}) - except: return render(request, "Lab/A9/a9_lab.html", {"data":"Please Upload a Yaml file."}) else: @@ -845,51 +852,33 @@ def injection(request): @csrf_exempt +from django.db import connection + def injection_sql_lab(request): if request.user.is_authenticated: - - name=request.POST.get('name') - password=request.POST.get('pass') + name = request.POST.get('name') + password = request.POST.get('pass') print(name) print(password) if name: - sql_query = "SELECT * FROM introduction_sql_lab_table WHERE id='"+name+"'AND password='"+password+"'" - - sql_instance = sql_lab_table(id="admin", password="65079b006e85a7e798abecb99e47c154") - sql_instance.save() - sql_instance = sql_lab_table(id="jack", password="jack") - sql_instance.save() - sql_instance = sql_lab_table(id="slinky", password="b4f945433ea4c369c12741f62a23ccc0") - sql_instance.save() - sql_instance = sql_lab_table(id="bloke", password="f8d1ce191319ea8f4d1d26e65e130dd5") - sql_instance.save() + sql_query = "SELECT * FROM introduction_sql_lab_table WHERE id=%s AND password=%s" - print(sql_query) + with connection.cursor() as cursor: + cursor.execute(sql_query, [name, password]) + results = cursor.fetchall() - try: - user = sql_lab_table.objects.raw(sql_query) - user = user[0].id + if results: + user = results[0][0] print(user) - - except: - return render( - request, - 'Lab_2021/A3_Injection/sql_lab.html', - { - "wrongpass":password, - "sql_error":sql_query - }) - - if user: - return render(request, 'Lab_2021/A3_Injection/sql_lab.html',{"user1":user}) + return render(request, 'Lab_2021/A3_Injection/sql_lab.html', {"user1": user}) else: return render( - request, + request, 'Lab_2021/A3_Injection/sql_lab.html', { - "wrongpass":password, - "sql_error":sql_query + "wrongpass": password, + "sql_error": sql_query }) else: return render(request, 'Lab_2021/A3_Injection/sql_lab.html') @@ -908,18 +897,22 @@ def ssrf(request): else: return redirect('login') +import os + def ssrf_lab(request): if request.user.is_authenticated: - if request.method=="GET": - return render(request,"Lab/ssrf/ssrf_lab.html",{"blog":"Read Blog About SSRF"}) + if request.method == "GET": + return render(request, "Lab/ssrf/ssrf_lab.html", {"blog": "Read Blog About SSRF"}) else: - file=request.POST["blog"] - try : + file = request.POST["blog"] + try: dirname = os.path.dirname(__file__) - filename = os.path.join(dirname, file) - file = open(filename,"r") - data = file.read() - return render(request,"Lab/ssrf/ssrf_lab.html",{"blog":data}) + filename = os.path.abspath(os.path.join(dirname, file)) + if not filename.startswith(dirname): + raise Exception("Invalid path") + with open(filename, "r") as file: + data = file.read() + return render(request, "Lab/ssrf/ssrf_lab.html", {"blog": data}) except: return render(request, "Lab/ssrf/ssrf_lab.html", {"blog": "No blog found"}) else: @@ -946,16 +939,23 @@ def ssrf_target(request): return render(request,"Lab/ssrf/ssrf_target.html",{"access_denied":True}) @authentication_decorator +import requests +from urllib.parse import urlparse + def ssrf_lab2(request): if request.method == "GET": return render(request, "Lab/ssrf/ssrf_lab2.html") elif request.method == "POST": url = request.POST["url"] - try: - response = requests.get(url) - return render(request, "Lab/ssrf/ssrf_lab2.html", {"response": response.content.decode()}) - except: + parsed_url = urlparse(url) + if parsed_url.scheme in ['http', 'https'] and parsed_url.netloc: # Validate only http or https schemes + try: + response = requests.get(url) + return render(request, "Lab/ssrf/ssrf_lab2.html", {"response": response.content.decode()}) + except: + return render(request, "Lab/ssrf/ssrf_lab2.html", {"error": "Invalid URL"}) + else: return render(request, "Lab/ssrf/ssrf_lab2.html", {"error": "Invalid URL"}) #--------------------------------------- Server-side template injection --------------------------------------# @@ -965,29 +965,33 @@ def ssti(request): else: return redirect('login') +from django.shortcuts import render +from django.shortcuts import redirect +from django.template.loader import render_to_string +from django.utils.html import escape +from .models import Blogs +import os +import uuid + def ssti_lab(request): if request.user.is_authenticated: - if request.method=="GET": + if request.method == "GET": users_blogs = Blogs.objects.filter(author=request.user) - return render(request,"Lab_2021/A3_Injection/ssti_lab.html", {"blogs":users_blogs}) - elif request.method=="POST": - blog = request.POST["blog"] + return render(request, "Lab_2021/A3_Injection/ssti_lab.html", {"blogs": users_blogs}) + elif request.method == "POST": + blog = escape(request.POST["blog"]) id = str(uuid.uuid4()).split('-')[-1] blog = filter_blog(blog) - prepend_code = "{% extends 'introduction/base.html' %}\ - {% block content %}{% block title %}\ - SSTI-Blogs\ - {% endblock %}" + prepend_code = render_to_string('introduction/base.html') + '{% block content %}{% block title %}SSTI-Blogs{% endblock %}' - blog = prepend_code + blog + "{% endblock %}" - new_blog = Blogs.objects.create(author = request.user, blog_id = id) + blog = prepend_code + blog + '{% endblock %}' + new_blog = Blogs.objects.create(author=request.user, blog_id=id) new_blog.save() dirname = os.path.dirname(__file__) filename = os.path.join(dirname, f"templates/Lab_2021/A3_Injection/Blogs/{id}.html") - file = open(filename, "w+") - file.write(blog) - file.close() + with open(filename, "w+") as file: + file.write(blog) return redirect(f'blog/{id}') else: return redirect('login') @@ -1008,6 +1012,8 @@ def crypto_failure(request): else: redirect('login') +import hashlib + def crypto_failure_lab(request): if request.user.is_authenticated: if request.method=="GET": @@ -1016,12 +1022,12 @@ def crypto_failure_lab(request): username = request.POST["username"] password = request.POST["password"] try: - password = md5(password.encode()).hexdigest() - user = CF_user.objects.get(username=username,password=password) - return render(request,"Lab_2021/A2_Crypto_failur/crypto_failure_lab.html",{"user":user, "success":True,"failure":False}) - except: - return render(request,"Lab_2021/A2_Crypto_failur/crypto_failure_lab.html",{"success":False, "failure":True}) - else : + password = hashlib.scrypt(password.encode(), salt=b'salt', n=16384, r=8, p=1) + user = CF_user.objects.get(username=username, password=password) + return render(request,"Lab_2021/A2_Crypto_failur/crypto_failure_lab.html", {"user":user, "success":True, "failure":False}) + except CF_user.DoesNotExist: + return render(request,"Lab_2021/A2_Crypto_failur/crypto_failure_lab.html", {"success":False, "failure":True}) + else: return redirect('login') def crypto_failure_lab2(request): @@ -1039,15 +1045,17 @@ def crypto_failure_lab2(request): return render(request,"Lab_2021/A2_Crypto_failur/crypto_failure_lab2.html",{"success":False, "failure":True}) # based on CWE-319 +from django.utils import timezone + def crypto_failure_lab3(request): if request.user.is_authenticated: if request.method == "GET": try : - cookie = request.COOKIES["cookie"] + cookie = request.COOKIES.get("cookie") print(cookie) expire = cookie.split('|')[1] - expire = datetime.datetime.fromisoformat(expire) - now = datetime.datetime.now() + expire = timezone.datetime.fromisoformat(expire) + now = timezone.now() if now > expire : return render(request,"Lab_2021/A2_Crypto_failur/crypto_failure_lab3.html",{"success":False,"failure":False}) elif cookie.split('|')[0] == 'admin': @@ -1063,15 +1071,15 @@ def crypto_failure_lab3(request): password = request.POST["password"] try: if username == "User" and password == "P@$$w0rd": - expire = datetime.datetime.now() + datetime.timedelta(minutes=60) + expire = timezone.now() + timezone.timedelta(minutes=60) cookie = f"{username}|{expire}" response = render(request,"Lab_2021/A2_Crypto_failur/crypto_failure_lab3.html",{"success":True, "failure":False , "admin":False}) - response.set_cookie("cookie", cookie) + response.set_cookie("cookie", cookie, secure=True, httponly=True, samesite='Lax') response.status_code = 200 return response else: response = render(request,"Lab_2021/A2_Crypto_failur/crypto_failure_lab3.html",{"success":False, "failure":True}) - response.set_cookie("cookie", None) + response.delete_cookie("cookie") return response except: return render(request,"Lab_2021/A2_Crypto_failur/crypto_failure_lab2.html",{"success":False, "failure":True}) @@ -1087,19 +1095,19 @@ def sec_misconfig_lab3(request): cookie = request.COOKIES["auth_cookie"] payload = jwt.decode(cookie, SECRET_COOKIE_KEY, algorithms=['HS256']) if payload['user'] == 'admin': - return render(request,"Lab/sec_mis/sec_mis_lab3.html", {"admin":True} ) + return render(request, "Lab/sec_mis/sec_mis_lab3.html", {"admin": True}) else: - return render(request,"Lab/sec_mis/sec_mis_lab3.html", {"admin":False} ) + return render(request, "Lab/sec_mis/sec_mis_lab3.html", {"admin": False}) except: payload = { - 'user':'not_admin', + 'user': 'not_admin', 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60), 'iat': datetime.datetime.utcnow(), } cookie = jwt.encode(payload, SECRET_COOKIE_KEY, algorithm='HS256') - response = render(request,"Lab/sec_mis/sec_mis_lab3.html", {"admin":False} ) - response.set_cookie(key = "auth_cookie", value = cookie) + response = render(request, "Lab/sec_mis/sec_mis_lab3.html", {"admin": False}) + response.set_cookie(key="auth_cookie", value=cookie, secure=True, httponly=True, samesite='Lax') return response # - ------------------------Identification and Authentication Failures-------------------------------- @@ -1172,13 +1180,17 @@ def auth_failure_lab2(request): def auth_failure_lab3(request): if request.method == "GET": try: - cookie = request.COOKIES["session_id"] - session = AF_session_id.objects.get(session_id=cookie) - if session : - return render(request,"Lab_2021/A7_auth_failure/lab3.html", {"username":session.user,"success":True}) + cookie = request.COOKIES.get("session_id") + if cookie: + session = AF_session_id.objects.get(session_id=cookie) + if session: + response = render(request, "Lab_2021/A7_auth_failure/lab3.html", {"username": session.user, "success": True}) + response.set_cookie("session_id", cookie, secure=True, httponly=True, samesite='Lax') + return response except: pass - return render(request, "Lab_2021/A7_auth_failure/lab3.html") + response = render(request, "Lab_2021/A7_auth_failure/lab3.html") + return response elif request.method == "POST": token = str(uuid.uuid4()) try: @@ -1187,14 +1199,14 @@ def auth_failure_lab3(request): password = hashlib.sha256(password.encode()).hexdigest() except: response = render(request, "Lab_2021/A7_auth_failure/lab3.html") - response.set_cookie("session_id", None) + response.set_cookie("session_id", None, secure=True, httponly=True, samesite='Lax') return response - if USER_A7_LAB3[username]['password'] == password: + if USER_A7_LAB3.get(username) and USER_A7_LAB3[username]['password'] == password: session_data = AF_session_id.objects.create(session_id=token, user=USER_A7_LAB3[username]['username']) session_data.save() - response = render(request, "Lab_2021/A7_auth_failure/lab3.html", {"success":True, "failure":False, "username":username}) - response.set_cookie("session_id", token) + response = render(request, "Lab_2021/A7_auth_failure/lab3.html", {"success": True, "failure": False, "username": username}) + response.set_cookie("session_id", token, secure=True, httponly=True, samesite='Lax') return response #-- coding playground for lab2 From bc36a67e900714fa872ac6d8fa5a30be446a78fe Mon Sep 17 00:00:00 2001 From: "patched.codes[bot]" <298395+patched.codes[bot]@users.noreply.github.com> Date: Tue, 25 Jun 2024 09:30:29 +0800 Subject: [PATCH 13/14] Patched /private/var/folders/61/dwx9fsqs2k931dkwz6dg1ymw0000gn/T/tmp980zihnh/introduction/playground/A9/api.py --- introduction/playground/A9/api.py | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/introduction/playground/A9/api.py b/introduction/playground/A9/api.py index 35e1bd2..eae79e8 100644 --- a/introduction/playground/A9/api.py +++ b/introduction/playground/A9/api.py @@ -1,10 +1,6 @@ from django.http import JsonResponse -from django.views.decorators.csrf import csrf_exempt - from .main import Log - -@csrf_exempt def log_function_target(request): L = Log(request) if request.method == "GET": @@ -30,4 +26,4 @@ def log_function_target(request): return JsonResponse({"message":"success", "method":"patch"},status = 200) if request.method == "UPDATE": return JsonResponse({"message":"success", "method":"update"},status = 200) - return JsonResponse({"message":"method not allowed"},status = 403) \ No newline at end of file + return JsonResponse({"message":"method not allowed"},status = 403) From d011e69a4bd373cde9fa4604daee0dd634ac7590 Mon Sep 17 00:00:00 2001 From: "patched.codes[bot]" <298395+patched.codes[bot]@users.noreply.github.com> Date: Tue, 25 Jun 2024 09:30:29 +0800 Subject: [PATCH 14/14] Patched /private/var/folders/61/dwx9fsqs2k931dkwz6dg1ymw0000gn/T/tmp980zihnh/introduction/templates/Lab/A9/a9_lab.html --- introduction/templates/Lab/A9/a9_lab.html | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/introduction/templates/Lab/A9/a9_lab.html b/introduction/templates/Lab/A9/a9_lab.html index 5a70b46..7145c34 100644 --- a/introduction/templates/Lab/A9/a9_lab.html +++ b/introduction/templates/Lab/A9/a9_lab.html @@ -8,6 +8,7 @@

Yaml To Json Converter

+ {% csrf_token %}

@@ -34,4 +35,4 @@
Here is your output:

-{% endblock %} \ No newline at end of file +{% endblock %}