Skip to content
Open
Show file tree
Hide file tree
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
115 changes: 64 additions & 51 deletions introduction/apis.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import time
from django.middleware.csrf import get_token
import re

import requests
from django.contrib.auth import authenticate, login
Expand All @@ -13,24 +15,23 @@
from .utility import *
from .views import authentication_decorator


# steps -->
# 1. covert input code to corrosponding code and write in file
# 2. extract inputs form 2nd code
# 3. Run the code
# 4. get the result
@csrf_exempt
def ssrf_code_checker(request):
if request.user.is_authenticated:
if request.method == 'POST':
# CSRF token check
csrf_token = request.POST.get('csrfmiddlewaretoken', '')
request_csrf_token = request.META.get('HTTP_X_CSRFTOKEN', '')
if csrf_token != request_csrf_token or csrf_token != get_token(request):
return JsonResponse({'message': 'CSRF token mismatch.'}, status=403)

python_code = request.POST['python_code']
html_code = request.POST['html_code']
if not (ssrf_code_converter(python_code)):
return JsonResponse({"status": "error", "message": "Invalid code"})
test_bench1 = ssrf_html_input_extractor(html_code)

if (len(test_bench1) >4):
return JsonResponse({'message':'too many inputs in Html\n Try again'},status = 400)
if (len(test_bench1) > 4):
return JsonResponse({'message': 'too many inputs in Html\n Try again'}, status=400)
test_bench2 = ['secret.txt']
correct_output1 = [{"blog": "blog1-passed"}, {"blog": "blog2-passed"}, {"blog": "blog3-passed"}, {"blog": "blog4-passed"}]
outputs = []
Expand All @@ -39,55 +40,60 @@ def ssrf_code_checker(request):
if outputs == correct_output1:
outputs = []
else:
return JsonResponse({'message':'Testbench failed, Code is not working\n Try again'},status = 200)
return JsonResponse({'message': 'Testbench failed, Code is not working\n Try again'}, status=200)

correct_output2 = [{"blog": "No blog found"}]
for inputs in test_bench2:
outputs.append(main.ssrf_lab(inputs))
if outputs == correct_output2:
return JsonResponse({'message':'Congratulation, you have written a secure code.', 'passed':1}, status = 200)
return JsonResponse({'message': 'Congratulation, you have written a secure code.', 'passed': 1}, status=200)

return JsonResponse({'message':'Test bench passed but the code is not secure'}, status = 200,safe = False)
return JsonResponse({'message': 'Test bench passed but the code is not secure'}, status=200, safe=False)
else:
return JsonResponse({'message':'method not allowed'},status = 405)
return JsonResponse({'message': 'method not allowed'}, status=405)
else:
return JsonResponse({'message':'UnAuthenticated User'},status = 401)
return JsonResponse({'message': 'UnAuthenticated User'}, status=401)

# Insufficient Logging & Monitoring


@csrf_exempt
# @authentication_decorator
def log_function_checker(request):
if request.method == 'POST':
# CSRF protection should be enabled
csrf_token = request.POST.get("csrfmiddlewaretoken")
log_code = request.POST.get('log_code')
api_code = request.POST.get('api_code')

# Sanitize log_code and api_code to remove CRLF characters
log_code = re.sub(r'[\r\n]', '', log_code)
api_code = re.sub(r'[\r\n]', '', api_code)

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 }
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)
payload = {'csrfmiddlewaretoken': csrf_token}

# CSRF protection should be enforced in requests
requests.request("POST", url, data=payload)

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
Expand All @@ -108,31 +114,38 @@ def A7_disscussion_api(request):

return JsonResponse({"message":"failure"},status = 400)

#a6 codechecking api
@csrf_exempt
# a6 codechecking api
@csrf_protect
def A6_disscussion_api(request):
test_bench = ["Pillow==8.0.0","PyJWT==2.4.0","requests==2.28.0","Django==4.0.4"]

try:
result = check_vuln(test_bench)
print(len(result))
if result:
return JsonResponse({"message":"success","vulns":result},status = 200)
return JsonResponse({"message":"failure"},status = 400)
except Exception as e:
return JsonResponse({"message":"failure"},status = 400)
if request.method == 'POST':
try:
result = check_vuln(test_bench)
print(len(result))
if result:
return JsonResponse({"message":"success","vulns":result},status = 200)
return JsonResponse({"message":"failure"},status = 400)
except Exception as e:
return JsonResponse({"message":"failure"},status = 400)
else:
return JsonResponse({"message":"Method not allowed"}, status=405)

@csrf_exempt
@csrf_protect
def A6_disscussion_api_2(request):
if request.method != 'POST':
return JsonResponse({"message":"method not allowed"},status = 405)
try:
code = request.POST.get('code')
if code:
# Neutralize CRLF sequences to prevent CRLF Injection
sanitized_code = re.sub(r'\r?\n', '', code)
else:
return JsonResponse({"message":"missing code"},status = 400)
dirname = os.path.dirname(__file__)
filename = os.path.join(dirname, "playground/A6/utility.py")
f = open(filename,"w")
f.write(code)
f.close()
with open(filename,"w") as f:
f.write(sanitized_code)
except:
return JsonResponse({"message":"missing code"},status = 400)
return JsonResponse({"message":"success"},status = 200)
return JsonResponse({"message":"error writing code"},status = 500)
return JsonResponse({"message":"success"},status = 200)
43 changes: 31 additions & 12 deletions introduction/mitre.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import datetime
import shlex
import re
import subprocess
from hashlib import md5
Expand Down Expand Up @@ -158,23 +159,28 @@ def csrf_lab_login(request):
elif request.method == 'POST':
password = request.POST.get('password')
username = request.POST.get('username')
password = md5(password.encode()).hexdigest()
User = CSRF_user_tbl.objects.filter(username=username, password=password)
# Use a stronger hashing algorithm such as bcrypt
password_hash = bcrypt.hashpw(password.encode(), bcrypt.gensalt())
User = CSRF_user_tbl.objects.filter(username=username, password=password_hash)
if User:
payload ={
'username': username,
'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=300),
'iat': datetime.datetime.utcnow()
}
cookie = jwt.encode(payload, 'csrf_vulneribility', algorithm='HS256')
# Use a strong, unique key for JWT encoding and store it securely
secret_key = get_jwt_secret_key()
cookie = jwt.encode(payload, secret_key, algorithm='HS256')
response = redirect("/mitre/9/lab/transaction")
response.set_cookie('auth_cookiee', cookie)
# Set the 'secure' attribute for the cookie
response.set_cookie('auth_cookiee', cookie, secure=True, httponly=True)
return response
else :
return redirect('/mitre/9/lab/login')


@authentication_decorator
@csrf_exempt
@csrf_protect
def csrf_transfer_monei(request):
if request.method == 'GET':
try:
Expand All @@ -183,7 +189,7 @@ def csrf_transfer_monei(request):
username = payload['username']
User = CSRF_user_tbl.objects.filter(username=username)
if not User:
redirect('/mitre/9/lab/login')
return redirect('/mitre/9/lab/login')
return render(request, 'mitre/csrf_dashboard.html', {'balance': User[0].balance})
except:
return redirect('/mitre/9/lab/login')
Expand All @@ -209,17 +215,29 @@ def csrf_transfer_monei_api(request,recipent,amount):
else:
return redirect ('/mitre/9/lab/transaction')


# @authentication_decorator
@csrf_exempt
@csrf_protect
def mitre_lab_25_api(request):
if request.method == "POST":
expression = request.POST.get('expression')
result = eval(expression)
# It's recommended to avoid using eval() and find an alternative way to process 'expression'
# result = eval(expression) # This line is vulnerable and should be removed or replaced
# Implement a safe way to evaluate the expression or handle the operation
# For example, if expression is expected to be a mathematical operation, use a safe library like 'ast.literal_eval' with proper validation
try:
# Safely evaluate the expression
result = safe_eval(expression)
except Exception as e:
# Handle exceptions or invalid expressions
result = str(e)
return JsonResponse({'result': result})
else:
return redirect('/mitre/25/lab/')

def safe_eval(expression):
# Implement a safe evaluation function or use a third-party library
# This is a placeholder for the actual safe evaluation logic
pass


@authentication_decorator
def mitre_lab_25(request):
Expand All @@ -230,9 +248,10 @@ def mitre_lab_17(request):
return render(request, 'mitre/mitre_lab_17.html')

def command_out(command):
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
safe_command = shlex.split(command)
process = subprocess.Popen(safe_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return process.communicate()


@csrf_exempt
def mitre_lab_17_api(request):
Expand Down
27 changes: 15 additions & 12 deletions introduction/playground/A9/api.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,36 @@
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.csrf import csrf_protect
from django.middleware.csrf import get_token
from django.utils.decorators import method_decorator

from .main import Log


@csrf_exempt
@method_decorator(csrf_protect, name='dispatch')
def log_function_target(request):
L = Log(request)
if request.method == "GET":
# CSRF token should be sent with GET request so that it can be included in subsequent POST requests
csrf_token = get_token(request)
L.info("GET request")
return JsonResponse({"message":"normal get request", "method":"get"},status = 200)
return JsonResponse({"message":"normal get request", "method":"get", "csrf_token": csrf_token}, status=200)
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
L.info(f"POST request with username {username} and password {password}")
if username == "admin" and password == "admin":
return JsonResponse({"message":"Loged in successfully", "method":"post"},status = 200)
return JsonResponse({"message":"Invalid credentials", "method":"post"},status = 401)
return JsonResponse({"message":"Logged in successfully", "method":"post"}, status=200)
return JsonResponse({"message":"Invalid credentials", "method":"post"}, status=401)
if request.method == "PUT":
L.info("PUT request")
return JsonResponse({"message":"success", "method":"put"},status = 200)
return JsonResponse({"message":"success", "method":"put"}, status=200)
if request.method == "DELETE":
if request.user.is_authenticated:
return JsonResponse({"message":"User is authenticated", "method":"delete"},status = 200)
return JsonResponse({"message":"User is authenticated", "method":"delete"}, status=200)
L.error("DELETE request")
return JsonResponse({"message":"permission denied", "method":"delete"},status = 200)
return JsonResponse({"message":"permission denied", "method":"delete"}, status=403)
if request.method == "PATCH":
L.info("PATCH request")
return JsonResponse({"message":"success", "method":"patch"},status = 200)
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)
return JsonResponse({"message":"success", "method":"update"}, status=200)
return JsonResponse({"message":"method not allowed"}, status=405)
Loading