Debian Codegraph @

tests/issue/GHSA-hx93-w8p2-ffh5/poc_encode_highcolor_overflow.c

raw
1 /*
2 * Regression test for GHSA-hx93-w8p2-ffh5.
3 *
4 * The vulnerable high-color encoder calculated work-buffer sizes with
5 * signed int arithmetic. 65536 * 65536 wraps to zero on typical
6 * two's-complement int implementations, so the first high-color
7 * allocation could become smaller than the number of input pixels.
8 *
9 * This test uses a custom allocator to observe the requested allocation
10 * size and stops before the encoder can enter the pixel loop. It does
11 * not need a multi-gigabyte input buffer; seeing an allocation request
12 * smaller than width * height is enough to reproduce the root cause.
13 */
14
15 #include <stdio.h>
16 #include <stdlib.h>
17
18 #include <sixel.h>
19
20 static size_t minimum_allocation;
21 static int guard_enabled;
22 static int undersized_request;
23
24
25 static void *
26 watched_malloc(size_t size)
27 {
28 if (guard_enabled && size < minimum_allocation) {
29 undersized_request = 1;
30 return NULL;
31 }
32
33 return malloc(size);
34 }
35
36
37 static int
38 discard_write(char *data, int size, void *priv)
39 {
40 (void) data;
41 (void) priv;
42
43 return size;
44 }
45
46
47 int
48 main(void)
49 {
50 int nret = EXIT_FAILURE;
51 SIXELSTATUS status;
52 sixel_allocator_t *allocator = NULL;
53 sixel_dither_t *dither = NULL;
54 sixel_output_t *output = NULL;
55 unsigned char pixels[3];
56 int width;
57 int height;
58
59 width = 65536;
60 height = 65536;
61
62 if ((size_t)-1 <= 4294967295UL) {
63 nret = EXIT_SUCCESS;
64 goto end;
65 }
66
67 pixels[0] = 0;
68 pixels[1] = 0;
69 pixels[2] = 0;
70
71 minimum_allocation = (size_t)width * (size_t)height;
72
73 status = sixel_allocator_new(&allocator,
74 watched_malloc,
75 NULL,
76 NULL,
77 free);
78 if (SIXEL_FAILED(status)) {
79 goto end;
80 }
81
82 status = sixel_dither_new(&dither, -1, allocator);
83 if (SIXEL_FAILED(status)) {
84 goto end;
85 }
86
87 status = sixel_output_new(&output, discard_write, NULL, allocator);
88 if (SIXEL_FAILED(status)) {
89 goto end;
90 }
91
92 guard_enabled = 1;
93 (void) sixel_encode(pixels, width, height, 3, dither, output);
94 guard_enabled = 0;
95
96 if (undersized_request) {
97 fprintf(stderr, "high-color allocation size wrapped\n");
98 goto end;
99 }
100
101 nret = EXIT_SUCCESS;
102
103 end:
104 guard_enabled = 0;
105 sixel_output_unref(output);
106 sixel_dither_unref(dither);
107 sixel_allocator_unref(allocator);
108 return nret;
109 }