11import datetime
2+ from django .core .exceptions import ImproperlyConfigured
3+ import ast
4+ import operator as op
5+ import shlex
26import re
37import subprocess
48from hashlib import md5
@@ -158,21 +162,32 @@ def csrf_lab_login(request):
158162 elif request .method == 'POST' :
159163 password = request .POST .get ('password' )
160164 username = request .POST .get ('username' )
161- password = md5 (password .encode ()).hexdigest ()
165+ # Use SHA-256 instead of MD5 for password hashing
166+ password = sha256 (password .encode ()).hexdigest ()
162167 User = CSRF_user_tbl .objects .filter (username = username , password = password )
163168 if User :
164169 payload = {
165170 'username' : username ,
166171 'exp' : datetime .datetime .utcnow () + datetime .timedelta (seconds = 300 ),
167172 'iat' : datetime .datetime .utcnow ()
168173 }
169- cookie = jwt .encode (payload , 'csrf_vulneribility' , algorithm = 'HS256' )
174+ # Ensure the secret key is not hardcoded and is sufficiently random
175+ secret_key = get_secret_key ()
176+ cookie = jwt .encode (payload , secret_key , algorithm = 'HS256' )
170177 response = redirect ("/mitre/9/lab/transaction" )
171- response .set_cookie ('auth_cookiee' , cookie )
178+ # Set the 'secure' attribute for the cookie to ensure it's only sent over HTTPS
179+ response .set_cookie ('auth_cookiee' , cookie , secure = True , httponly = True )
172180 return response
173181 else :
174182 return redirect ('/mitre/9/lab/login' )
175183
184+ def get_secret_key ():
185+ # Retrieve the secret key from a secure configuration or environment variable
186+ secret_key = os .environ .get ('JWT_SECRET_KEY' )
187+ if not secret_key :
188+ raise ImproperlyConfigured ('Missing secret key for JWT encoding' )
189+ return secret_key
190+
176191@authentication_decorator
177192@csrf_exempt
178193def csrf_transfer_monei (request ):
@@ -209,14 +224,46 @@ def csrf_transfer_monei_api(request,recipent,amount):
209224 else :
210225 return redirect ('/mitre/9/lab/transaction' )
211226
212-
213227# @authentication_decorator
214228@csrf_exempt
215229def mitre_lab_25_api (request ):
216230 if request .method == "POST" :
217231 expression = request .POST .get ('expression' )
218- result = eval (expression )
219- return JsonResponse ({'result' : result })
232+
233+ # Define supported operators
234+ allowed_operators = {ast .Add : op .add , ast .Sub : op .sub , ast .Mult : op .mul ,
235+ ast .Div : op .truediv , ast .Pow : op .pow , ast .BitXor : op .xor ,
236+ ast .USub : op .neg }
237+
238+ def eval_expr (expr ):
239+ """
240+ Safely evaluate an arithmetic expression using ast module
241+ """
242+ try :
243+ parsed_expr = ast .parse (expr , mode = 'eval' ).body
244+ return eval_ (parsed_expr )
245+ except (ValueError , SyntaxError ):
246+ raise ValueError ("Invalid input" )
247+
248+ def eval_ (node ):
249+ if isinstance (node , ast .Num ): # <number>
250+ return node .n
251+ elif isinstance (node , ast .BinOp ): # <left> <operator> <right>
252+ if type (node .op ) not in allowed_operators :
253+ raise ValueError ("Unsupported operator" )
254+ return allowed_operators [type (node .op )](eval_ (node .left ), eval_ (node .right ))
255+ elif isinstance (node , ast .UnaryOp ): # <operator> <operand> e.g., -1
256+ if type (node .op ) not in allowed_operators :
257+ raise ValueError ("Unsupported operator" )
258+ return allowed_operators [type (node .op )](eval_ (node .operand ))
259+ else :
260+ raise TypeError ("Unsupported type" )
261+
262+ try :
263+ result = eval_expr (expression )
264+ return JsonResponse ({'result' : result })
265+ except ValueError as e :
266+ return JsonResponse ({'error' : str (e )}, status = 400 )
220267 else :
221268 return redirect ('/mitre/25/lab/' )
222269
@@ -230,9 +277,9 @@ def mitre_lab_17(request):
230277 return render (request , 'mitre/mitre_lab_17.html' )
231278
232279def command_out (command ):
233- process = subprocess .Popen (command , shell = True , stdout = subprocess .PIPE , stderr = subprocess .PIPE )
280+ safe_command = shlex .split (command )
281+ process = subprocess .Popen (safe_command , stdout = subprocess .PIPE , stderr = subprocess .PIPE )
234282 return process .communicate ()
235-
236283
237284@csrf_exempt
238285def mitre_lab_17_api (request ):
0 commit comments