├── README.md └── (YouTube) Secure Code Review Snippets ├── E05 - XSS ├── xss.py ├── xss-fix.py └── dom-xss.py ├── E04- XXE ├── xxe-fix.py └── xxe.py ├── E02 - Path Traversal ├── path-traversal.py └── path-traversal-fix.py ├── E03 - Remote Command Injection ├── rce.py └── rce-fix.py └── E01 - SQL Injection ├── sqli.py └── sqli-fix.py /README.md: -------------------------------------------------------------------------------- 1 | # Awesome Secure Code Review 2 | All the code snippets from my Secure Code Review series on YouTube (youtube.com/@muqsitbaig)! 3 | 4 | # Future plans 5 | This repo will be populated with all the secure code review series as well as other industry resources in the future. 6 | -------------------------------------------------------------------------------- /(YouTube) Secure Code Review Snippets/E05 - XSS/xss.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, request, render_template_string 2 | 3 | app = Flask(__name__) 4 | 5 | @app.route('/') 6 | def index(): 7 | name = request.args.get('name', 'World') 8 | 9 | # Vulnerable to XSS 10 | return render_template_string('

Hello, {}!

'.format(name)) 11 | 12 | if __name__ == '__main__': 13 | app.run(debug=True) 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /(YouTube) Secure Code Review Snippets/E04- XXE/xxe-fix.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, request 2 | from defusedxml.ElementTree import fromstring, tostring 3 | 4 | app = Flask(__name__) 5 | 6 | @app.route('/parse', methods=['POST']) 7 | def parse_xml(): 8 | xml_data = request.data 9 | 10 | # Safely parse XML data 11 | tree = fromstring(xml_data) 12 | 13 | return f"Parsed XML: {tostring(tree)}" 14 | 15 | if __name__ == '__main__': 16 | app.run(debug=True) 17 | -------------------------------------------------------------------------------- /(YouTube) Secure Code Review Snippets/E05 - XSS/xss-fix.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, request, render_template_string 2 | from markupsafe import escape 3 | 4 | app = Flask(__name__) 5 | 6 | @app.route('/') 7 | def index(): 8 | name = request.args.get('name', 'World') 9 | 10 | # Sanitize user input to prevent XSS 11 | safe_name = escape(name) 12 | 13 | return render_template_string('

Hello, {}!

'.format(safe_name)) 14 | 15 | if __name__ == '__main__': 16 | app.run(debug=True) 17 | -------------------------------------------------------------------------------- /(YouTube) Secure Code Review Snippets/E02 - Path Traversal/path-traversal.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, request, send_file 2 | import os 3 | 4 | app = Flask(__name__) 5 | 6 | @app.route('/download', methods=['GET']) 7 | def download_file(): 8 | filename = request.args.get('filename') 9 | 10 | # Vulnerable path traversal 11 | filepath = os.path.join(os.getcwd(), filename) 12 | 13 | # Check if file exists and send it 14 | if os.path.exists(filepath): 15 | return send_file(filepath, as_attachment=True) 16 | else: 17 | return "File not found", 404 18 | 19 | if __name__ == '__main__': 20 | app.run(debug=True) -------------------------------------------------------------------------------- /(YouTube) Secure Code Review Snippets/E05 - XSS/dom-xss.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, request 2 | from markupsafe import escape 3 | import re 4 | 5 | app = Flask(__name__) 6 | 7 | @app.route('/checkout', methods=['GET']) 8 | def checkout(): 9 | backTo = request.args.get('backTo', '/') 10 | pattern = r'^(?:[a-zA-Z]+:|/)' 11 | 12 | # Forbidden keyword found, set to default value 13 | if re.match(pattern, backTo): 14 | backTo = '/' 15 | 16 | # The vulnerable part: no escaping here 17 | return f''' 18 | ... 19 | Back 20 | ... 21 | ''' 22 | 23 | if __name__ == '__main__': 24 | app.run(debug=True, port=8080) 25 | -------------------------------------------------------------------------------- /(YouTube) Secure Code Review Snippets/E04- XXE/xxe.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, request 2 | from lxml import etree 3 | 4 | app = Flask(__name__) 5 | 6 | @app.route('/parse', methods=['POST']) 7 | def parse_xml(): 8 | # Read XML data from the request 9 | xml_data = request.data 10 | 11 | # Parse XML data (vulnerable to XXE) 12 | try: 13 | parser = etree.XMLParser(resolve_entities=True) 14 | tree = etree.fromstring(xml_data, parser) 15 | return f"Parsed XML: {etree.tostring(tree, pretty_print=True).decode()}" 16 | except etree.XMLSyntaxError as e: 17 | return f"XML parsing error: {str(e)}" 18 | 19 | if __name__ == '__main__': 20 | app.run(debug=True) 21 | 22 | # xml.etree.ElementTree 23 | # 3rd party XML parsers -------------------------------------------------------------------------------- /(YouTube) Secure Code Review Snippets/E03 - Remote Command Injection/rce.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, request 2 | import os 3 | 4 | app = Flask(__name__) 5 | 6 | @app.route('/ping', methods=['GET']) 7 | def ping(): 8 | host = request.args.get('host') 9 | 10 | # Vulnerable to command injection 11 | command = f"ping -c 1 {host}" 12 | result = os.popen(command).read() 13 | 14 | return f"
{result}
" 15 | 16 | if __name__ == '__main__': 17 | app.run(debug=True) 18 | 19 | 20 | # API calls 21 | # Functionalities which invoke 22 | # system commands 23 | # system services 24 | 25 | # Functions which execute system commands (Python): 26 | # os.popen() 27 | # os.system() 28 | # subprocess.Popen() 29 | # subprocess.run() 30 | # exec() -------------------------------------------------------------------------------- /(YouTube) Secure Code Review Snippets/E02 - Path Traversal/path-traversal-fix.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, request, send_file, abort 2 | import os 3 | 4 | app = Flask(__name__) 5 | 6 | UPLOAD_DIRECTORY = 'uploads' 7 | 8 | @app.route('/download', methods=['GET']) 9 | def download_file(): 10 | filename = request.args.get('filename') 11 | 12 | # Securely sanitize and validate the filename 13 | safe_filename = os.path.basename(filename) 14 | filepath = os.path.join(UPLOAD_DIRECTORY, safe_filename) 15 | 16 | # Ensure the file is within the upload directory 17 | if os.path.commonprefix([UPLOAD_DIRECTORY, filepath]) == UPLOAD_DIRECTORY and os.path.exists(filepath): 18 | return send_file(filepath, as_attachment=True) 19 | else: 20 | abort(404) 21 | 22 | if __name__ == '__main__': 23 | app.run(debug=True) 24 | -------------------------------------------------------------------------------- /(YouTube) Secure Code Review Snippets/E03 - Remote Command Injection/rce-fix.py: -------------------------------------------------------------------------------- 1 | from flask import Flask, request, abort 2 | import re 3 | import subprocess 4 | 5 | app = Flask(__name__) 6 | 7 | def validate_host(host): 8 | # Simple regex to validate hostnames and IP addresses 9 | pattern = re.compile(r'^[a-zA-Z0-9.-]+$') 10 | return pattern.match(host) 11 | 12 | @app.route('/ping', methods=['GET']) 13 | def ping(): 14 | host = request.args.get('host') 15 | 16 | # Validate host parameter 17 | if not validate_host(host): 18 | abort(400, description="Invalid host") 19 | 20 | command = ["ping", "-c", "1", host] 21 | try: 22 | result = subprocess.check_output(command, universal_newlines=True) 23 | return f"
{result}
" 24 | except subprocess.CalledProcessError as e: 25 | return f"
Error: {e}
" 26 | 27 | if __name__ == '__main__': 28 | app.run(debug=True) -------------------------------------------------------------------------------- /(YouTube) Secure Code Review Snippets/E01 - SQL Injection/sqli.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | from flask import Flask, request 3 | 4 | app = Flask(__name__) 5 | 6 | def create_database(): 7 | conn = sqlite3.connect('example.db') 8 | c = conn.cursor() 9 | c.execute('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username TEXT, password TEXT)''') 10 | c.execute("INSERT INTO users (username, password) VALUES ('admin', 'adminpass')") 11 | conn.commit() 12 | conn.close() 13 | 14 | @app.route('/login', methods=['GET', 'POST']) 15 | def login(): 16 | username = request.args.get('username') 17 | password = request.args.get('password') 18 | conn = sqlite3.connect('example.db') 19 | c = conn.cursor() 20 | 21 | query = f"SELECT * FROM users WHERE username = '{username}' AND password = '{password}'" 22 | print("Executing query:", query) 23 | c.execute(query) 24 | result = c.fetchone() 25 | conn.close() 26 | if result: 27 | return "Login successful" 28 | else: 29 | return "Login failed" 30 | 31 | if __name__ == '__main__': 32 | create_database() 33 | app.run(debug=True) -------------------------------------------------------------------------------- /(YouTube) Secure Code Review Snippets/E01 - SQL Injection/sqli-fix.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | from flask import Flask, request 3 | 4 | app = Flask(__name__) 5 | 6 | def create_database(): 7 | conn = sqlite3.connect('example.db') 8 | c = conn.cursor() 9 | c.execute('''CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username TEXT, password TEXT)''') 10 | c.execute("INSERT INTO users (username, password) VALUES ('admin', 'adminpass')") 11 | conn.commit() 12 | conn.close() 13 | 14 | @app.route('/login', methods=['GET', 'POST']) 15 | def login(): 16 | username = request.args.get('username') 17 | password = request.args.get('password') 18 | conn = sqlite3.connect('example.db') 19 | c = conn.cursor() 20 | query = "SELECT * FROM users WHERE username = ? AND password = ?" 21 | print("Executing query with parameters:", query, (username, password)) 22 | c.execute(query, (username, password)) 23 | result = c.fetchone() 24 | conn.close() 25 | if result: 26 | return "Login successful" 27 | else: 28 | return "Login failed" 29 | 30 | if __name__ == '__main__': 31 | create_database() 32 | app.run(debug=True) --------------------------------------------------------------------------------