PenTest Playbook
  • Welcome!
  • Web App Pentesting
    • SQL Injection
    • NoSQL Injection
    • XSS
    • CSRF
    • SSRF
    • XXE
    • IDOR
    • SSTI
    • Broken Access Control/Privilege Escalation
    • Open Redirect
    • File Inclusion
    • File Upload
    • Insecure Deserialization
      • XMLDecoder
    • LDAP Injection
    • XPath Injection
    • JWT
    • Parameter Pollution
    • Prototype Pollution
    • Race Conditions
    • CRLF Injection
    • LaTeX Injection
    • CORS Misconfiguration
    • Handy Commands & Payloads
  • Active Directory Pentest
    • Domain Enumeration
      • User Enumeration
      • Group Enumeration
      • GPO & OU Enumeration
      • ACLs
      • Trusts
      • User Hunting
    • Domain Privilege Escalation
      • Kerberoast
        • AS-REP Roast (Kerberoasting)
        • CRTP Lab 14
      • Targeted Kerberoasting
        • AS-REP Roast
        • Set SPN
      • Kerberos Delegation
        • Unconstrained Delegation
          • CRTP Lab 15
        • Constrained Delegation
          • CRTP Lab 16
        • Resource Based Constrained Delegation (RBCD)
          • CRTP Lab 17
      • Across Trusts
        • Child to Parent (Cross Domain)
          • Using Trust Tickets
            • CRTP Lab 18
          • Using KRBTGT Hash
            • CRTP Lab 19
        • Cross Forest
          • Lab 20
        • AD CS (Across Domain Trusts)
          • ESC1
            • CRTP Lab 21
        • Trust Abuse - MSSQL Servers
          • CRTP Lab 22
    • Lateral Movement
      • PowerShell Remoting
      • Extracting Creds, Hashes, Tickets
      • Over-PassTheHash
      • DCSync
    • Evasion
      • Evasion Cheetsheet
    • Persistence
      • Golden Ticket
        • CRTP Lab 8
      • Silver Ticket
        • CRTP Lab 9
      • Diamond Ticket
        • CRTP Lab 10
      • Skeleton Key
      • DSRM
        • CRTP Lab 11
      • Custom SSP
      • Using ACLs
        • AdminSDHolder
        • Rights Abuse
          • CRTP Lab 12
        • Security Descriptors
          • CRTP Lab 13
    • Tools
    • PowerShell
  • AI Security
    • LLM Security Checklist
    • GenAI Vision Security Checklist
    • Questionnaire for AI/ML/GenAI Engineering Teams
  • Network Pentesting
    • Information Gathering
    • Scanning
    • Port/Service Enumeration
      • 21 FTP
      • 22 SSH
      • 25, 465, 587 SMTP
      • 53 DNS
      • 80, 443 HTTP/s
      • 88 Kerberos
      • 135, 593 MSRPC
      • 137, 138, 139 NetBios
      • 139, 445 SMB
      • 161, 162, 10161, 10162/udp SNMP
      • 389, 636, 3268, 3269 LDAP
      • Untitled
      • Page 14
      • Page 15
      • Page 16
      • Page 17
      • Page 18
      • Page 19
      • Page 20
    • Nessus
    • Checklist
  • Mobile Pentesting
    • Android
      • Android PenTest Setup
      • Tools
    • iOS
  • DevSecOps
    • Building CI Pipeline
    • Threat Modeling
    • Secure Coding
      • Code Review Examples
        • Broken Access Control
        • Broken Authentication
        • Command Injection
        • SQLi
        • XSS
        • XXE
        • SSRF
        • SSTI
        • CSRF
        • Insecure Deserialization
        • XPath Injection
        • LDAP Injection
        • Insecure File Uploads
        • Path Traversal
        • LFI
        • RFI
        • Prototype Pollution
        • Connection String Injection
        • Sensitive Data Exposure
        • Security Misconfigurations
        • Buffer Overflow
        • Integer Overflow
        • Symlink Attack
        • Use After Free
        • Out of Bounds
      • C/C++ Secure Coding
      • Java/JS Secure Coding
      • Python Secure Coding
  • Malware Dev
    • Basics - Get detected!
    • Not so easy to stage!
    • Base64 Encode Shellcode
    • Caesar Cipher (ROT 13) Encrypt Shellcode
    • XOR Encrypt Shellcode
    • AES Encrypt Shellcode
  • Handy
    • Reverse Shells
    • Pivoting
    • File Transfers
    • Tmux
  • Wifi Pentesting
    • Monitoring
    • Cracking
  • Buffer Overflows
  • Cloud Security
    • AWS
    • GCP
    • Azure
  • Container Security
  • Todo
Powered by GitBook
On this page
  • Java Example
  • Python Example
  • NoSQL Injection
  1. DevSecOps
  2. Secure Coding
  3. Code Review Examples

SQLi

SQL Injection in Java

Vulnerability: SQL Injection

Vulnerable Code:

javaCopy codeString query = "SELECT * FROM users WHERE username = '" + username + "' AND password = '" + password + "'";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);

Reason for vulnerability: This code directly concatenates user input into the SQL query, which allows an attacker to inject malicious SQL code.

Fixed Code:

javaCopy codeString query = "SELECT * FROM users WHERE username = ? AND password = ?";
PreparedStatement pstmt = connection.prepareStatement(query);
pstmt.setString(1, username);
pstmt.setString(2, password);
ResultSet rs = pstmt.executeQuery();

Reason for fix: Using PreparedStatement with parameterized queries prevents SQL injection by treating user input as data, not code.


Vulnerable Code

import java.sql.*;

public class UserDao {
    public User getUser(String username, String password) throws SQLException {
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/users", "root", "password");
        String sql = "SELECT * FROM users WHERE username = '" + username + "' AND password = '" + password + "'";
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(sql);
        // Process result set and return user
    }
}

Reason for Vulnerability:

This code constructs an SQL query by directly concatenating user input, allowing an attacker to manipulate the query structure.

Fixed Code:

javaCopyimport java.sql.*;

public class UserDao {
    public User getUser(String username, String password) throws SQLException {
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/users", "root", "password");
        String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, username);
        pstmt.setString(2, password);
        ResultSet rs = pstmt.executeQuery();
        // Process result set and return user
    }
}

Reason for Fix:

The fixed code uses a PreparedStatement with parameterized queries, which separates SQL code from user input, preventing SQL injection attacks.

Java Example

Vulnerable Code:

javaCopy@Repository
public class ProductRepository {
    @PersistenceContext
    private EntityManager entityManager;

    public List<Product> searchProducts(String category) {
        String jpql = "SELECT p FROM Product p WHERE p.category = '" + category + "'";
        return entityManager.createQuery(jpql, Product.class).getResultList();
    }
}

Reason for Vulnerability:

This JPA query is constructed by directly concatenating user input, allowing potential manipulation of the query structure.

Fixed Code:

javaCopy@Repository
public class ProductRepository {
    @PersistenceContext
    private EntityManager entityManager;

    public List<Product> searchProducts(String category) {
        String jpql = "SELECT p FROM Product p WHERE p.category = :category";
        return entityManager.createQuery(jpql, Product.class)
                            .setParameter("category", category)
                            .getResultList();
    }
}

Reason for Fix:

The fixed code uses a parameterized JPQL query, which binds the user input as a parameter, preventing SQL injection attacks in JPA queries.

Python Example

Vulnerable Code:

pythonCopyimport sqlite3

def get_user(username):
    conn = sqlite3.connect('users.db')
    cursor = conn.cursor()
    cursor.execute(f"SELECT * FROM users WHERE username = '{username}'")
    return cursor.fetchone()

Reason for Vulnerability:

This code uses string formatting to construct the SQL query, allowing an attacker to inject malicious SQL code.

Fixed Code:

pythonCopyimport sqlite3

def get_user(username):
    conn = sqlite3.connect('users.db')
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM users WHERE username = ?", (username,))
    return cursor.fetchone()

Reason for Fix:

The fixed code uses parameterized queries, which treat user input as data rather than part of the SQL command, preventing SQL injection attacks.


Vulnerable Code:

pythonCopy codequery = "SELECT * FROM users WHERE username = '%s'" % username
cursor.execute(query)

Reason for vulnerability: User input is directly used in the SQL query, allowing SQL injection.

Fixed Code:

pythonCopy codequery = "SELECT * FROM users WHERE username = %s"
cursor.execute(query, (username,))

Reason for fix: Use parameterized queries to prevent SQL injection.


NoSQL Injection

Example 1: JavaScript (Node.js with MongoDB)

Vulnerable Code:

javascriptCopy codeapp.post('/login', (req, res) => {
    const username = req.body.username;
    const password = req.body.password;
    db.collection('users').findOne({ username: username, password: password }, (err, user) => {
        if (user) {
            res.send('Login successful');
        } else {
            res.send('Login failed');
        }
    });
});

Reason for vulnerability: User input is directly used in the query, allowing NoSQL injection.

Fixed Code:

javascriptCopy codeapp.post('/login', (req, res) => {
    const username = req.body.username;
    const password = req.body.password;
    db.collection('users').findOne({ username: username, password: hash(password) }, (err, user) => {
        if (user) {
            res.send('Login successful');
        } else {
            res.send('Login failed');
        }
    });
});

Reason for fix: Hash the password before querying the database to prevent injection.

Example 2: Python (Flask with MongoDB)

Vulnerable Code:

pythonCopy code@app.route('/login', methods=['POST'])
def login():
    username = request.form['username']
    password = request.form['password']
    user = db.users.find_one({'username': username, 'password': password})
    if user:
        return 'Login successful'
    else:
        return 'Login failed'

Reason for vulnerability: User input is directly used in the query, allowing NoSQL injection.

Fixed Code:

pythonCopy code@app.route('/login', methods=['POST'])
def login():
    username = request.form['username']
    password = hash_password(request.form['password'])
    user = db.users.find_one({'username': username, 'password': password})
    if user:
        return 'Login successful'
    else:
        return 'Login failed'

Reason for fix: Hash the password before querying the database to prevent injection.

PreviousCommand InjectionNextXSS

Last updated 9 months ago