Wiki
  • Introduction
  • 👾Penetration Testing
    • Application Security
      • Mobile App Security
        • Android Application Testing
          • Security Checklist
          • SSL Pinning Bypasses
          • Non-Proxy Aware Applications
            • Setting up VPN Server
            • Bypasses
          • Common Proxying Issues
          • Android Local Storage Checks
          • Android Task Hijacking
          • Kiosk Mode / Breakout Testing
          • Magisk on GenyMotion
        • iOS Application Testing
          • iOS Testing Using Objection
          • IPA Analysis Using MobSF
          • iOS Jailbreak Bypass
          • Decrypting iOS Apps
          • iOS Reverse Engineering
          • Jailbreak Detection Bypasses
          • iOS Local Storage Checks
          • Installing IPA
          • ATS Auditing
          • iOS Jailbreaking
          • Frida Pinning Bypasses
          • iOS Jailbreaking
        • Code Security
        • Frida on Windows
      • Web Application Security
        • Web Shells
        • CSV Injection
        • Measure Response Time using CURL
        • OSINT
          • EyeWitness
        • GraphQL Hacking
      • API Security
        • Security Checklist
        • Postman and Burp
        • CURL via BurpSuite
        • SOAP API Pentesting
    • Infrastructure Security
      • Network Infrastructure
        • Red Team Powershell Scripts
        • Mounting NFS Shares
        • Password Cracking/Auditing
        • Remote Access Sheet
        • Password Cracking Using Hashcat
        • Calculate IP Addresses from CIDR
        • Grep IP addresses or IP Ranges from a File
        • Default Credentials Checking
        • Check SSL/TLS Certificates
        • Log a terminal session
        • Unauthenticated Mongo DB
        • Microsoft SQL Server (MSSQL)
        • NTP Mode 6 Vulnerabilities
        • BloodHound
        • AD Offensive Testing
        • CrackMapExec
        • Select all IP addresses in Sublime Text
        • Convert CIDRs to an IP address list
        • Microsoft Exchange Client Access Server Information Disclosure
        • Web Server HTTP Header Internal IP Disclosure
        • smbclient.py
        • GetUserSPNs.py
        • Get-GPPPassword.py
        • SMBMap
        • Mounting Shares
        • mitm6
        • AD Attacks
        • Weak IKE Security Configurations
        • Locked BIOS Password Bypass
      • Wireless Security
        • Cached Wireless Keys
        • Aircrack Suite
    • SSL/TLS Security
    • Secure Code Review
      • Python
      • Semgrep
        • Semgrep to HTML Report
    • Cloud Security
      • Cloud Penetration Testing
    • Social Engineering
      • Simulated Phishing
        • GoPhish
    • Tool Usage
      • Docker
      • Split
      • PhantomJS
      • Aquatone
      • Tmux
      • Ipainstaller
      • Public IP From Command Line
      • Wifite
      • IKE Scan
      • Grep
      • Pulling APKs
      • Bitsadmin
      • Drozer
      • Iptables
      • Python Web Server
      • Crackmapexec
      • Impacket
      • Nessus
      • Adding SUDO User
      • Nmap
      • Metasploit Payloads
      • SMTP Open Relay
      • SQLMap
      • Screen
      • Remove All After Colon
      • Remove Old Linux Kernels
      • CURL
      • Hashcat
      • Secure Copy Protocol (SCP)
      • SSH & PGP Tools
      • IP Calculator
      • BloodHound
      • Netcat File Transfer
      • OpenVAS
      • BurpSuite
      • Exiftool
      • Python Virtual Environments
    • Errors and Solutions
      • Kill Process On Specific Port
      • Kill SSH Port Forwarding
      • SSH Key
      • Expanding Disk on Kali VM
    • Scoping
      • Scoping Questionnaires
        • Mobile App Testing
    • OSINT
      • Dark Web OSINT
      • Certificate Chain Check
      • EyeWitness - Web Service Screenshot
      • Tor to Browse Onion Links
      • DarkDump - Scan Dark Web for Onion Links
      • Domain related File Search
      • Google Dorking
      • IP / Network Blocks owned by a Company
  • ⌨️Programming
    • Automation
      • Running a Service at Boot
      • Network Connectivity Cron
    • Python
      • Adding Columns in Pandas
      • Copy Entire Column Data To New Column Pandas
      • Loading Progress Bar
      • Reorder Columns in Pandas
      • Filename with Date/Time Stamp
      • Command Line Arguments
      • Changing Date Format
      • Removing Index Column Pandas
      • Regex - Remove HTML Tags
      • Column Header Mapping
  • 🌐Miscellaneous
    • Scripts
      • Clickjacking Checker
      • Bulk WHOIS
      • SMB Signing Check
      • FDQN to IP Address
      • Grep IP Addresses
      • Nessus Parser
      • Build Review Audit
      • Nessus Merger
      • Nmap2CSV
      • Remove Audio From Videos
    • Favourite Reads/Links
    • Hacking Posters
    • Windows Developer VMs
    • Windows Workspaces
    • GitHub Pages
    • Interview Prep
      • Senior Penetration Tester
    • CVSS Formula
    • Android Rooting
      • Lineage OS 18.1 on OnePlus X
      • TWRP Recover on OnePlus X
      • Magisk Rooting
    • Presentation Slides
      • BlackHat - USA [2022]
  • 🐞Vulnerability Wiki
    • 🌐APPLICATION LEVEL
      • 🔒AUTHENTICATION
        • Authentication Bypass
        • Lack of Password Confirmation
        • 2FA Code Brute-forceable
        • Lack of Verification
        • Lack of Throttling on Form Submissions
        • Lack of Rate Limiting on Login
        • Weak Password Complexity Rules
        • 🖥️SESSION MANAGEMENT
        • 🔑ACCESS CONTROL
      • 🔢INPUT VALIDATION
      • ➗CRYPTOGRAPHY
      • 📉LOGGING
      • 📕DATA PROTECTION
      • 📲COMMUNICATION
      • 👨‍💻MALICIOUS CODE
      • 💡LOGIC
      • 🗄️FILE UPLOAD
      • ⚙️API ISSUES
      • 🔍CONFIGURATIONS
    • 💾INFRASTRUCTURE LEVEL
      • ICMP Timestamp Request Remote Date Disclosure (CVE-1999-0524)
      • ASP.NET Debug Mode Validation
Powered by GitBook
On this page
  • Input Sanitisation
  • SQL Injection
  • Usage of Virtual Envrionments
  • Disable Debugging Mode
  • String Formatting

Was this helpful?

  1. Penetration Testing
  2. Secure Code Review

Python

PreviousSecure Code ReviewNextSemgrep

Last updated 2 years ago

Was this helpful?

Taken and summarised from https://snyk.io/blog/python-security-best-practices-cheat-sheet/

Input Sanitisation

  • is “a library for validating Python data structures, such as those obtained from config-files, forms, external services or command-line parsing, converted from JSON/YAML (or something else) to Python data-types.

  • is “an allowed-list-based HTML sanitizing library that escapes or strips markup and attributes.”

Major frameworks come with their own sanitation functions, like ’s flask.escape() or ’s django.utils.html.escape(). The goal of any of these functions is to secure potentially malicious HTML input like:

>>> import bleach
>>> bleach.clean('an XSS <script>navigate(...)</script> example')
'an XSS &lt;script&gt;navigate(...)&lt;/script&gt; example'

SQL Injection

A typical example is an . Instead of stitching strings and variables together to generate an SQL query, it is advisable to use named-parameters to tell the database what to treat as a command and what as data.

# Instead of this …
cursor.execute(f"SELECT admin FROM users WHERE username = '{username}'");
# ...do this...
cursor.execute("SELECT admin FROM users WHERE username = %(username)s", {'username': username}); 

Or even better, use Object-Relational Mapping (ORM), such as , which would make the example query look like this:

query = session.query(User).filter(User.name.like('%{username}'))

Here you get more readable code, as well as ORM optimizations like caching, plus more security and performance!

Usage of Virtual Envrionments

This means that instead of using a global Python version and global Python dependencies for all your projects, you can have project-specific virtual environments that can use their own Python (and Python dependency) versions!

As of Python version 3.5, the use of venv is recommended and with version 3.6 pyvenv was deprecated.

Disable Debugging Mode

By default, most frameworks have debugging switched on. For example, Django has it enabled in settings.py. Make sure to switch debugging to False in production to prevent leaking sensitive application information to attackers.

String Formatting

Python has a built-in module named string. This module includes the Template class, which is used to create template strings.

Consider the following example.

from string import Template
greeting_template = Template(“Hello World, my name is $name.”)
greeting = greeting_template.substitute(name=”Hayley”)

For the above code, the variable greeting is evaluated as: “Hello World, my name is Hayley.”

This string format is a bit cumbersome because it requires an import statement and is less flexible with types. It also doesn’t evaluate Python statements the way f-strings do. These constraints make template strings an excellent choice when dealing with user input.

👾
schema
bleach
Flask
Django
SQL injection
sqlalchemy