Integer Overflow

Reading time: 4 minutes

tip

Jifunze na fanya mazoezi ya AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Jifunze na fanya mazoezi ya GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE)

Support HackTricks

Basic Information

Katika msingi wa integer overflow kuna kikomo kinachowekwa na ukubwa wa aina za data katika programu za kompyuta na ufafanuzi wa data.

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.

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

Kwa uwezekano wa web vulnerabilities ni muhimu kujua thamani za juu zinazoungwa mkono:

rust
fn main() {

let mut quantity = 2147483647;

let (mul_result, _) = i32::overflowing_mul(32767, quantity);
let (add_result, _) = i32::overflowing_add(1, quantity);

println!("{}", mul_result);
println!("{}", add_result);
}

Mifano

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

Signed to Unsigned Conversion

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

// 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);
}

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.

Mifano Mingine

(((argv[1] * 0x1064deadbeef4601) & 0xffffffffffffffff) == 0xD1038D2E07B42569)

ARM64

Hii haiwezi kubadilika katika ARM64 kama unavyoona katika hiki kipande cha blog.

tip

Jifunze na fanya mazoezi ya AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Jifunze na fanya mazoezi ya GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE)

Support HackTricks