<summary><strong>htARTE (HackTricks AWS Red Team Expert)</strong><ahref="https://training.hacktricks.xyz/courses/arte"><strong>!HackTricks</strong></a><strong>!</strong></summary>
* If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks_live)**.**
* **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
* **`master.dbo.fn_varbintohexstr(SUSER_SID('DOMAIN\Administrator'))`**: If you know the name of the domain (_DOMAIN_ in this example) this function will return the **SID of the user Administrator** in hex format. This will look like `0x01050000000[...]0000f401`, note how the **last 4 bytes** are the number **500** in **big endian** format, which is the **common ID of the user administrator**.\
* **`SUSER_SNAME(0x01050000000[...]0000e803)`** : This function will return the **username of the ID indicated** (if any), in this case **0000e803** in big endian == **1000** (usually this is the ID of the first regular user ID created). Then you can imagine that you can brute-force user IDs from 1000 to 2000 and probably get all the usernames of the users of the domain. For example using a function like the following one:
Error-based SQL injections typically resemble constructions such as `+AND+1=@@version--` and variants based on the «OR» operator. Queries containing such expressions are usually blocked by WAFs. As a bypass, concatenate a string using the %2b character with the result of specific function calls that trigger a data type conversion error on sought-after data.
Stored procedures like `xp_dirtree`, though not officially documented by Microsoft, have been described by others online due to their utility in network operations within MSSQL. These procedures are often used in Out of Band Data exfiltration, as showcased in various [examples](https://www.notsosecure.com/oob-exploitation-cheatsheet/) and [posts](https://gracefulsecurity.com/sql-injection-out-of-band-exploitation/).
The `xp_dirtree` stored procedure, for instance, is used to make network requests, but it's limited to only TCP port 445. The port number isn't modifiable, but it allows reading from network shares. The usage is demonstrated in the SQL script below:
Stored procedures like `xp_dirtree`, though not officially documented by Microsoft, have been described by others online due to their utility in network operations within MSSQL. These procedures are often used in Out of Band Data exfiltration, as showcased in various [examples](https://www.notsosecure.com/oob-exploitation-cheatsheet/) and [posts](https://gracefulsecurity.com/sql-injection-out-of-band-exploitation/).
The `xp_dirtree` stored procedure, for instance, is used to make network requests, but it's limited to only TCP port 445. The port number isn't modifiable, but it allows reading from network shares. The usage is demonstrated in the SQL script below:
**CLR UDF** (Common Language Runtime User Defined Function) **Creating**, **authored****code****DLL****compiled**, **language****.NET** **any****in**, **loaded****be****MSSQL****within****functions****custom****executing**, **requires****process****is****access****dbo**. **means****usually****feasible****only****role****Administrator****an****with****or****sa****as****connection****database****the****when****only****usually****is**.
A concise method for extracting the full content of a table in a single query involves utilizing the `FOR JSON` clause. This approach is more succinct than using the `FOR XML` clause, which requires a specific mode like "raw". The `FOR JSON` clause is preferred for its brevity.
In situations where error-based vectors are used, it's crucial to provide an alias or a name. This is because the output of expressions, if not provided with either, cannot be formatted as JSON. Here's an example of how this is done:
SQL Injection is a web application vulnerability that allows an attacker to manipulate the SQL queries executed by the application's database. By injecting malicious SQL code, an attacker can bypass authentication, retrieve sensitive information, modify or delete data, and even gain remote code execution.
#### MSSQL Injection
MSSQL Injection refers specifically to SQL Injection attacks targeting Microsoft SQL Server databases. MSSQL Injection attacks can be devastating if successful, as they can provide unauthorized access to sensitive data and compromise the entire system.
#### Exploiting MSSQL Injection
To exploit MSSQL Injection, an attacker needs to identify vulnerable input fields in the target web application. These input fields are typically used to construct SQL queries that interact with the database.
One common technique used in MSSQL Injection is the UNION-based attack. This technique involves injecting a UNION statement into the SQL query to combine the results of two separate queries. By carefully crafting the injected code, an attacker can retrieve data from different database tables.
Another technique is the Error-based attack, which exploits error messages generated by the database server. By injecting code that triggers an error, an attacker can extract valuable information from the error message, such as table and column names.
In this example, the attacker is injecting SQL code after the `id` parameter. The injected code attempts to retrieve the names of all database tables and their corresponding column names using the `information_schema.columns` table. The retrieved data is then concatenated using the `concat_ws` function and returned as a JSON object.
#### Prevention
To prevent MSSQL Injection attacks, it is crucial to implement secure coding practices and input validation techniques. Here are some preventive measures:
- Use parameterized queries or prepared statements to ensure that user input is properly sanitized.
- Implement strict input validation to reject any input that does not conform to the expected format.
- Regularly update and patch the database server to fix any known vulnerabilities.
- Employ a web application firewall (WAF) to detect and block SQL Injection attempts.
- Limit the privileges of database accounts used by the application to minimize the potential impact of a successful attack.
Remember, preventing SQL Injection requires a combination of secure coding practices, regular security assessments, and ongoing monitoring of your web application.
For users granted the `VIEW SERVER STATE` permission on the server, it's possible to see all executing sessions on the SQL Server instance. However, without this permission, users can only view their current session. The currently executing SQL query can be retrieved by accessing sys.dm_exec_requests and sys.dm_exec_sql_text:
SQL Injection is a common vulnerability that allows an attacker to manipulate the SQL queries executed by an application. In MSSQL, this vulnerability can be exploited to extract sensitive information from the database.
#### Exploiting MSSQL Injection
To exploit MSSQL Injection, you can use various techniques. One of them is the UNION-based attack. This attack involves injecting a malicious SQL statement into the original query using the UNION operator.
Here is an example of a UNION-based MSSQL Injection:
In this example, the injection is performed by appending the following payload to the original query:
```plaintext
-1 union select null,(select text from sys.dm_exec_requests cross apply sys.dm_exec_sql_text(sql_handle)),null,null
```
The injected SQL statement retrieves the text of the currently executing SQL query using the `sys.dm_exec_requests` and `sys.dm_exec_sql_text` system views.
#### Impact
By successfully exploiting MSSQL Injection, an attacker can gain unauthorized access to sensitive information stored in the database. This can include usernames, passwords, and other confidential data.
#### Prevention
To prevent MSSQL Injection, it is important to implement secure coding practices such as:
- Using parameterized queries or prepared statements.
- Validating and sanitizing user input.
- Implementing least privilege principles for database access.
- Keeping the database software up to date with the latest security patches.
By following these best practices, you can significantly reduce the risk of SQL Injection vulnerabilities in your MSSQL applications.
MSSQL Injection is a type of SQL Injection attack that targets Microsoft SQL Server databases. It allows an attacker to manipulate the SQL queries executed by the application, potentially gaining unauthorized access to sensitive data or performing unauthorized actions.
#### Exploiting MSSQL Injection
To exploit MSSQL Injection, you need to identify vulnerable input fields that are not properly sanitized or validated by the application. These fields are typically used in SQL queries without proper parameterization or input validation, allowing an attacker to inject malicious SQL code.
One common technique used in MSSQL Injection is the UNION-based attack. This technique leverages the UNION operator to combine the results of two or more SELECT statements into a single result set. By injecting a UNION statement into the original query, an attacker can retrieve data from other tables or even execute arbitrary SQL commands.
In this example, the `id` parameter is vulnerable to MSSQL Injection. The attacker appends a UNION-based payload to the original query, which retrieves the version of the MSSQL Server.
#### Mitigation
To prevent MSSQL Injection attacks, it is crucial to implement proper input validation and parameterization techniques. Here are some recommended mitigation measures:
- Use parameterized queries or prepared statements to ensure that user input is properly sanitized and treated as data, rather than executable code.
- Implement strict input validation to reject any input that does not conform to the expected format or range.
- Apply the principle of least privilege by ensuring that database accounts used by the application have limited permissions and access only the necessary data.
- Regularly update and patch the MSSQL Server to address any known security vulnerabilities.
SQL Injection is a common web application vulnerability that allows an attacker to manipulate the SQL queries executed by the application's database. This can lead to unauthorized access, data leakage, and other security breaches.
#### MSSQL Injection
MSSQL Injection refers specifically to SQL Injection attacks targeting Microsoft SQL Server databases. MSSQL Injection can be used to extract sensitive information, modify data, or even execute arbitrary commands on the database server.
#### Exploiting MSSQL Injection
To exploit MSSQL Injection, an attacker needs to identify vulnerable input fields in the web application. These are typically found in URL parameters, form inputs, or cookies.
The following examples demonstrate how an attacker can exploit MSSQL Injection in a web application:
In both examples, the attacker appends malicious SQL code (`union select null,@@version,null--`) to the `id` parameter. This code performs a UNION-based SQL Injection attack, retrieving the version of the MSSQL Server (`@@version`) and displaying it as a result.
#### Prevention
To prevent MSSQL Injection attacks, it is crucial to implement secure coding practices and input validation techniques. Some recommended measures include:
- Using parameterized queries or prepared statements to prevent SQL injection.
- Implementing input validation and sanitization to filter out malicious input.
- Applying the principle of least privilege to database accounts, limiting their permissions.
- Keeping database software and web application frameworks up to date with the latest security patches.
By following these best practices, developers can significantly reduce the risk of MSSQL Injection vulnerabilities in their web applications.
SQL Injection is a common vulnerability that allows an attacker to manipulate the SQL queries executed by an application. In the case of MSSQL, it can lead to unauthorized access, data leakage, and other security risks.
#### Exploiting MSSQL Injection
To exploit MSSQL Injection, you need to identify the vulnerable parameter in the application's URL or form input. In this case, the vulnerable parameter is `id`, which is being used in a SQL query without proper sanitization.
The URL `https://vuln.app/getItem?id=1+union+select+null,@@version,null+from.users--` is an example of an MSSQL Injection attack. The payload `1 union select null,@@version,null from users--` is injected into the `id` parameter.
MSSQL Injection is a technique used to exploit vulnerabilities in web applications that use Microsoft SQL Server as their database management system. By injecting malicious SQL queries into user input fields, an attacker can manipulate the application's database and potentially gain unauthorized access to sensitive information.
## Exploiting MSSQL Injection
To exploit MSSQL Injection, an attacker needs to identify vulnerable input fields in the target web application. These input fields are typically used to construct SQL queries that interact with the database. By injecting carefully crafted SQL statements, an attacker can manipulate the behavior of these queries and extract or modify data.
### Union-Based SQL Injection
One common technique used in MSSQL Injection is Union-Based SQL Injection. This technique involves injecting a UNION SELECT statement into an input field to retrieve data from other database tables. The UNION SELECT statement allows an attacker to combine the result sets of multiple SELECT queries into a single result set.
To perform a Union-Based SQL Injection in MSSQL, the following steps can be followed:
1. Identify a vulnerable input field that is used in a SQL query.
2. Craft a UNION SELECT statement that retrieves data from other tables.
3. Inject the UNION SELECT statement into the input field.
4. Observe the application's response to determine if the injection was successful.
5. Extract the retrieved data from the application's response.
In this example, the `id` parameter is vulnerable to Union-Based SQL Injection. The injected payload `0xunion+select\Nnull,@@version,null+from+users--` attempts to retrieve the version of the MSSQL Server from the `users` table.
In this example, the `id` parameter is vulnerable to Union-Based SQL Injection. The injected payload `0xunion+select\Nnull,@@version,null+from+users--` attempts to retrieve the version of the MSSQL Server from the `users` table.
```
## Conclusion
MSSQL Injection is a powerful technique that can be used to exploit vulnerabilities in web applications. By understanding the underlying SQL queries and injecting malicious payloads, an attacker can gain unauthorized access to sensitive data. It is important for developers to implement proper input validation and parameterized queries to mitigate the risk of MSSQL Injection attacks.
According to [**this blog post**](https://www.gosecure.net/blog/2023/06/21/aws-waf-clients-left-vulnerable-to-sql-injection-due-to-unorthodox-mssql-design-choice/) it's possible to stack queries in MSSQL without using ";":
MSSQL Injection is a type of SQL Injection attack that targets Microsoft SQL Server databases. It allows an attacker to manipulate the SQL queries executed by the application, potentially gaining unauthorized access to the database or performing other malicious actions.
In this section, we will explore various techniques for exploiting MSSQL Injection vulnerabilities and provide examples to illustrate each technique.
---
#### Basic MSSQL Injection
Basic MSSQL Injection involves injecting malicious SQL code into user input fields to manipulate the SQL query executed by the application. The injected code can modify the query's logic, extract sensitive information, or perform other unauthorized actions.
To demonstrate a basic MSSQL Injection, consider the following vulnerable code snippet:
```sql
SELECT * FROM users WHERE username = '<user_input>';
```
An attacker can exploit this vulnerability by injecting a malicious input such as `' OR '1'='1' --`. The resulting query would be:
```sql
SELECT * FROM users WHERE username = '' OR '1'='1' --';
```
This modified query will always return all rows from the `users` table, effectively bypassing any authentication mechanism.
---
#### Error-Based MSSQL Injection
Error-Based MSSQL Injection involves exploiting SQL errors to extract information from the database. By injecting malicious code that triggers an error, an attacker can obtain valuable information about the database structure or the data stored within it.
Consider the following vulnerable code snippet:
```sql
SELECT * FROM users WHERE id = <user_input>;
```
An attacker can exploit this vulnerability by injecting a malicious input such as `1 OR 1=1`. The resulting query would be:
```sql
SELECT * FROM users WHERE id = 1 OR 1=1;
```
If the application does not properly handle errors, an error message may be displayed, revealing sensitive information about the database. For example, an error message like `Column 'password' does not exist` indicates that the `users` table has a column named `password`.
---
#### Union-Based MSSQL Injection
Union-Based MSSQL Injection involves leveraging the `UNION` operator to combine the results of two or more SQL queries into a single result set. By injecting malicious code that includes a `UNION` statement, an attacker can extract data from other tables in the database.
Consider the following vulnerable code snippet:
```sql
SELECT username, password FROM users WHERE id = <user_input>;
```
An attacker can exploit this vulnerability by injecting a malicious input such as `1 UNION SELECT username, password FROM admin`. The resulting query would be:
```sql
SELECT username, password FROM users WHERE id = 1 UNION SELECT username, password FROM admin;
```
This modified query will return the usernames and passwords from both the `users` and `admin` tables, allowing the attacker to extract sensitive information.
---
#### Time-Based MSSQL Injection
Time-Based MSSQL Injection involves exploiting time delays in SQL queries to infer information about the database. By injecting malicious code that introduces a time delay, an attacker can determine whether a specific condition is true or false.
Consider the following vulnerable code snippet:
```sql
SELECT * FROM users WHERE id = <user_input>;
```
An attacker can exploit this vulnerability by injecting a malicious input such as `1 AND SLEEP(5)`. The resulting query would be:
```sql
SELECT * FROM users WHERE id = 1 AND SLEEP(5);
```
If the application experiences a delay of 5 seconds before responding, it indicates that the injected condition is true. This technique can be used to extract information or perform other actions based on the application's response time.
---
#### Boolean-Based MSSQL Injection
Boolean-Based MSSQL Injection involves exploiting boolean conditions in SQL queries to infer information about the database. By injecting malicious code that evaluates to either true or false, an attacker can determine whether a specific condition is true or false.
Consider the following vulnerable code snippet:
```sql
SELECT * FROM users WHERE id = <user_input>;
```
An attacker can exploit this vulnerability by injecting a malicious input such as `1 AND 1=1`. The resulting query would be:
```sql
SELECT * FROM users WHERE id = 1 AND 1=1;
```
If the application returns a result, it indicates that the injected condition is true. This technique can be used to extract information or perform other actions based on the application's response.
---
#### Conclusion
MSSQL Injection is a serious security vulnerability that can lead to unauthorized access, data leakage, and other malicious activities. It is essential for developers to implement proper input validation and parameterized queries to prevent these types of attacks.
By understanding the various techniques used in MSSQL Injection attacks, security professionals can better protect their applications and databases from exploitation.
<summary><strong>Learn AWS hacking from zero to hero with</strong><ahref="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>
* If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks_live)**.**
* **Share your hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.