@app.route('/users/<id>',methods=['GET'])defget_user(id):user=db.get_user(id)ifuser:returnjsonify(user)else:returnjsonify({'error':'User not found'}),404
✅ compliance
@app.route('/users/<id>',methods=['GET'])defget_user(id):user=db.get_user(id)ifuser:sanitized_user={'id':user['id'],'name':user['name']# Include only necessary non-sensitive information}returnjsonify(sanitized_user)else:returnjsonify({'error':'User not found'}),404
Insertion of Sensitive Information Into Sent Data
🐞 non-compliance
defsend_email(user_email,message):subject="Important Message"body=f"Hello {user_email},\n\n{message}\n\nRegards,\nAdmin"# Code to send email using SMTP# ...
✅ compliance
defsend_email(user_email,message):subject="Important Message"body=f"Hello,\n\n{message}\n\nRegards,\nAdmin"# Code to send email using SMTP# ...
Cross-Site Request Forgery (CSRF)
🐞 non-compliance
fromflaskimportFlask,render_template,requestapp=Flask(__name__)@app.route('/transfer',methods=['POST'])deftransfer():# Transfer fundsamount=request.form['amount']destination_account=request.form['destination_account']# ... logic to transfer funds ...@app.route('/dashboard')defdashboard():returnrender_template('dashboard.html')if__name__=='__main__':app.run()
✅ compliance
fromflaskimportFlask,render_template,requestfromflask_wtf.csrfimportCSRFProtectapp=Flask(__name__)app.config['SECRET_KEY']='your-secret-key'csrf=CSRFProtect(app)@app.route('/transfer',methods=['POST'])@csrf.exemptdeftransfer():# Transfer fundsamount=request.form['amount']destination_account=request.form['destination_account']# ... logic to transfer funds ...@app.route('/dashboard')defdashboard():returnrender_template('dashboard.html')if__name__=='__main__':app.run()
importgetpassdeflogin(username,password):stored_password=retrieve_password_from_database(username)ifpassword_matches(stored_password,password):# Login successfulreturnTrueelse:# Login failedreturnFalsedefretrieve_password_from_database(username):# Code to retrieve the hashed password from the database# ...defpassword_matches(stored_password,entered_password):# Code to compare the stored password with the entered password# ...if__name__=='__main__':username=input("Username: ")password=getpass.getpass("Password: ")login(username,password)
importsqlite3defget_user_data(username):conn=sqlite3.connect('mydb.db')cursor=conn.cursor()query="SELECT * FROM users WHERE username = '"+username+"'"cursor.execute(query)result=cursor.fetchall()conn.close()returnresult
✅ compliance
importsqlite3defget_user_data(username):conn=sqlite3.connect('mydb.db')cursor=conn.cursor()query="SELECT * FROM users WHERE username = ?"cursor.execute(query,(username,))result=cursor.fetchall()conn.close()returnresult
External Control of File Name or Path
🐞 non-compliance
importosdefdelete_file(file_name):path="/path/to/files/"+file_nameifos.path.exists(path):os.remove(path)print("File deleted.")else:print("File not found.")
✅ compliance
importosimportos.pathdefdelete_file(file_name):base_path="/path/to/files/"path=os.path.join(base_path,file_name)ifos.path.exists(path)andos.path.isfile(path):os.remove(path)print("File deleted.")else:print("File not found.")
Generation of Error Message Containing Sensitive Information
importsubprocessdefprocess_user_input(user_input):# Assume user_input comes from an untrusted sourcecmd=f"echo '{user_input}'"output=subprocess.check_output(cmd,shell=True)print(output)
✅ compliance
importsubprocessimportshlexdefprocess_user_input(user_input):# Assume user_input comes from an untrusted sourcecmd_args=shlex.split(f"echo {user_input}")output=subprocess.check_output(cmd_args)print(output)
Insufficiently Protected Credentials
🐞 non-compliance
importrequestsdeflogin(username,password):# Assume username and password come from user inputurl="https://example.com/login"data={"username":username,"password":password}response=requests.post(url,data=data)ifresponse.status_code==200:print("Login successful")else:print("Login failed")
✅ compliance
importrequestsfromrequests.authimportHTTPDigestAuthdeflogin(username,password):# Assume username and password come from user inputurl="https://example.com/login"auth=HTTPDigestAuth(username,password)response=requests.post(url,auth=auth)ifresponse.status_code==200:print("Login successful")else:print("Login failed")
Restriction of XML External Entity Reference
🐞 non-compliance
importxml.etree.ElementTreeasETdefparse_xml(xml_string):tree=ET.fromstring(xml_string)# Process the XML data...
✅ compliance
importxml.etree.ElementTreeasETdefparse_xml(xml_string):parser=ET.XMLParser()parser.entity_declaration=False# Disable external entity resolutiontree=ET.fromstring(xml_string,parser=parser)# Process the XML data...
Vulnerable and Outdated Components
🐞 non-compliance
fromflaskimportFlask,render_templateimportrequestsapp=Flask(__name__)@app.route('/')defindex():# Use a vulnerable function to fetch dataresponse=requests.get('http://example.com/api/v1/users')data=response.json()returnrender_template('index.html',data=data)if__name__=='__main__':app.run()
✅ compliance
fromflaskimportFlask,render_templateimportrequestsfromrequests.packages.urllib3.utilimportssl_# Disable SSL verification warningsssl_.DEFAULT_CIPHERS+=':HIGH:!DH:!aNULL'app=Flask(__name__)@app.route('/')defindex():# Use a secure function to fetch dataresponse=requests.get('https://example.com/api/v1/users',verify=False)data=response.json()returnrender_template('index.html',data=data)if__name__=='__main__':app.run()
Improper Validation of Certificate with Host Mismatch
🐞 non-compliance
importrequestsdefget_secure_data(url):# Perform a request without proper certificate validationresponse=requests.get(url,verify=False)returnresponse.text# Example usagedata=get_secure_data('https://example.com')print(data)
✅ compliance
importrequestsdefget_secure_data(url):# Perform a request with proper certificate validationresponse=requests.get(url)response.raise_for_status()# Raise an exception if the request failsreturnresponse.text# Example usagedata=get_secure_data('https://example.com')print(data)
Improper Authentication
🐞 non-compliance
importrequestsdeflogin(username,password):credentials={'username':username,'password':password}response=requests.post('https://example.com/login',data=credentials)ifresponse.status_code==200:return'Login successful'else:return'Login failed'# Example usageresult=login('admin','password')print(result)
✅ compliance
importrequestsfromrequests.authimportHTTPBasicAuthdeflogin(username,password):credentials=HTTPBasicAuth(username,password)response=requests.post('https://example.com/login',auth=credentials)ifresponse.status_code==200:return'Login successful'else:return'Login failed'# Example usageresult=login('admin','password')print(result)
Session Fixation
🐞 non-compliance
fromflaskimportFlask,request,sessionapp=Flask(__name__)app.secret_key='insecure_secret_key'@app.route('/login',methods=['POST'])deflogin():username=request.form['username']password=request.form['password']# Authenticate userifusername=='admin'andpassword=='password':session['username']=usernamereturn'Login successful'else:return'Login failed'@app.route('/profile')defprofile():if'username'insession:returnf"Welcome, {session['username']}!"else:return'Please login'# Example usageapp.run()
importrequests# Fetch and execute code from an untrusted sourceuntrusted_code=requests.get('http://example.com/untrusted_code.py').textexec(untrusted_code)
✅ compliance
importrequestsimportast# Fetch and evaluate code from an untrusted sourceuntrusted_code=requests.get('http://example.com/untrusted_code.py').textast.parse(untrusted_code)
Download of Code Without Integrity Check
🐞 non-compliance
importrequests# Download code without integrity checkcode_url='http://example.com/malicious_code.py'response=requests.get(code_url)code=response.text# Execute the downloaded codeexec(code)
importpickledefdeserialize_data(data):# WARNING: This code is noncompliant and insecureobj=pickle.loads(data)returnobj
✅ compliance
importpickledefdeserialize_data(data):try:obj=pickle.loads(data)# Validate the deserialized object or perform additional security checks# ...returnobjexcept(pickle.UnpicklingError,AttributeError,ImportError,TypeError)ase:# Handle deserialization errors# Log or raise an exception, or return a default value# ...returnNone
Insufficient Logging
🐞 non-compliance
importloggingdefprocess_data(data):# Process the data# ...# Log the resultlogging.info("Data processed successfully")
✅ compliance
importloggingdefprocess_data(data):# Process the data# ...# Log the result with additional informationlogging.info("Data processed successfully: %s",data)
Improper Output Neutralization for Logs
🐞 non-compliance
importloggingdeflog_user_input(username):# Log user inputlogging.info("Received username: "+username)
✅ compliance
importloggingdeflog_user_input(username):# Log user input with proper output neutralizationlogging.info("Received username: %s",username)
importloggingdeflogin(username,password):ifusername=="admin"andpassword=="password":logging.info("Successful login for user: %s",username)else:logging.warning("Failed login attempt for user: %s",username)
Sensitive Information into Log File
🐞 non-compliance
importloggingdefprocess_payment(payment_data):logging.info("Payment processed for user: %s",payment_data['user'])
✅ compliance
importloggingdefprocess_payment(payment_data):logging.info("Payment processed for user: %s",obfuscate_user(payment_data['user']))defobfuscate_user(user):# Code to obfuscate or mask sensitive informationreturn"****"+user[-4:]
importrequestsdeffetch_url(url):ifis_valid_url(url):response=requests.get(url)returnresponse.textelse:raiseValueError("Invalid URL")defis_valid_url(url):# Perform URL validation to ensure it's safe to access# Implement whitelist-based validation or restrict access to specific domains# Example: Allow access to certain domainsallowed_domains=['example.com','api.example.com']parsed_url=urlparse(url)returnparsed_url.netlocinallowed_domains