Debian Codegraph @

utils/proc-sanitize.c

raw
1 /*
2 * proc-sanitize.c - Shared terminal sanitization helpers for proc text
3 * Copyright (c) 2026 Steve Grubb
4 * All Rights Reserved.
5 *
6 * This software may be freely redistributed and/or modified under the
7 * terms of the GNU General Public License as published by the Free
8 * Software Foundation; either version 2, or (at your option) any
9 * later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; see the file COPYING. If not, write to the
18 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor
19 * Boston, MA 02110-1335, USA.
20 *
21 * Authors:
22 * Steve Grubb <[email protected]>
23 */
24
25 #include "config.h"
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include "proc-sanitize.h"
30
31 /*
32 * sanitize_untrusted_field - escape terminal control bytes in untrusted text.
33 * @src: source text gathered from procfs/cgroup metadata.
34 *
35 * Returns caller-owned sanitized text, or NULL on allocation failure.
36 * Side effects/assumptions: Operates on in-memory data and may read
37 * procfs/netns state; it does not change kernel configuration.
38 */
39 char *sanitize_untrusted_field(const char *src)
40 {
41 size_t in_len;
42 char *dst;
43 char *out;
44 size_t i;
45
46 if (!src)
47 return NULL;
48 in_len = strlen(src);
49 dst = malloc(in_len * 4 + 1);
50 if (!dst)
51 return NULL;
52 out = dst;
53 for (i = 0; i < in_len; i++) {
54 unsigned char c = (unsigned char)src[i];
55
56 if (c < 0x20 || c == 0x7f) {
57 snprintf(out, 5, "\\x%02X", c);
58 out += 4;
59 } else {
60 *out++ = (char)c;
61 }
62 }
63 *out = '\0';
64 return dst;
65 }
66
67 /*
68 * sanitize_untrusted_owned - replace owned string with sanitized version.
69 * @s: pointer to owned string pointer that will be replaced in place.
70 *
71 * Returns 0 on success, -1 on allocation failure.
72 * Side effects/assumptions: Operates on in-memory data and may read
73 * procfs/netns state; it does not change kernel configuration.
74 */
75 int sanitize_untrusted_owned(char **s)
76 {
77 char *safe;
78
79 if (!s || !*s)
80 return 0;
81 safe = sanitize_untrusted_field(*s);
82 if (!safe)
83 return -1;
84 free(*s);
85 *s = safe;
86 return 0;
87 }