-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.c
More file actions
297 lines (260 loc) · 11.2 KB
/
Copy pathparser.c
File metadata and controls
297 lines (260 loc) · 11.2 KB
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
#include "parser.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <pwd.h>
#include <unistd.h>
#include <sys/stat.h>
#define INITIAL_CAPACITY 64
#define LINE_MAX_LEN 8192
/* Defense against a maliciously (or just accidentally) huge input
* file. khm_entry_t is large — KHM_MAX_HOSTS * KHM_MAX_HOSTNAME alone
* is 4KB, plus KHM_MAX_KEYDATA — so an unbounded parse of an
* attacker-controlled file is a real memory-amplification DoS, not a
* theoretical one. Both limits are generous relative to any real
* known_hosts file (even a large fleet rarely exceeds low tens of
* thousands of lines) and exist purely as a ceiling:
* - KHM_MAX_FILE_SIZE: checked via stat() before opening, so a
* clearly-oversized file is rejected in O(1) without reading a
* single byte of it.
* - KHM_MAX_LINES: checked during the parse loop itself, as a
* backstop for inputs stat() can't size up front (a pipe, FIFO,
* or /dev/stdin) and as defense in depth generally.
*/
#define KHM_MAX_FILE_SIZE (100L * 1024 * 1024) /* 100 MiB */
#define KHM_MAX_LINES 200000L
/* ------------------------------------------------------------------ */
/* helpers */
/* ------------------------------------------------------------------ */
static char *ltrim(char *s) {
while (*s && isspace((unsigned char)*s)) s++;
return s;
}
static void rtrim(char *s) {
size_t n = strlen(s);
while (n > 0 && isspace((unsigned char)s[n - 1])) s[--n] = '\0';
}
khm_keytype_t khm_keytype_from_str(const char *s) {
if (strcmp(s, "ssh-rsa") == 0) return KHM_KEY_RSA;
if (strcmp(s, "ecdsa-sha2-nistp256") == 0) return KHM_KEY_ECDSA_256;
if (strcmp(s, "ecdsa-sha2-nistp384") == 0) return KHM_KEY_ECDSA_384;
if (strcmp(s, "ecdsa-sha2-nistp521") == 0) return KHM_KEY_ECDSA_521;
if (strcmp(s, "ssh-ed25519") == 0) return KHM_KEY_ED25519;
return KHM_KEY_UNKNOWN;
}
void khm_default_path(char *buf, size_t len) {
const char *home = getenv("HOME");
if (!home) {
struct passwd *pw = getpwuid(getuid());
home = pw ? pw->pw_dir : "/root";
}
snprintf(buf, len, "%s/.ssh/known_hosts", home);
}
/* ------------------------------------------------------------------ */
/* hostname field parser */
/* */
/* Formats: */
/* hostname */
/* hostname,hostname2 */
/* [hostname]:port */
/* |1|salt|hash| (hashed) */
/* ------------------------------------------------------------------ */
static int parse_hostnames(char *field, khm_entry_t *e) {
e->hostname_count = 0;
e->port = 0;
e->hashed = 0;
/* hashed entry */
if (field[0] == '|') {
e->hashed = 1;
if (e->hostname_count < KHM_MAX_HOSTS) {
snprintf(e->hostnames[e->hostname_count],
KHM_MAX_HOSTNAME, "%s", field);
e->hostname_count++;
}
return 0;
}
/* split on comma */
char *save = NULL;
char *tok = strtok_r(field, ",", &save);
while (tok) {
if (e->hostname_count >= KHM_MAX_HOSTS) break;
/* [host]:port */
if (tok[0] == '[') {
char *close = strchr(tok, ']');
if (close && *(close + 1) == ':') {
*close = '\0';
char *host = tok + 1;
int port = atoi(close + 2);
strncpy(e->hostnames[e->hostname_count], host,
KHM_MAX_HOSTNAME - 1);
e->hostname_count++;
if (e->port == 0) e->port = port;
tok = strtok_r(NULL, ",", &save);
continue;
}
}
strncpy(e->hostnames[e->hostname_count], tok, KHM_MAX_HOSTNAME - 1);
e->hostname_count++;
tok = strtok_r(NULL, ",", &save);
}
return e->hostname_count > 0 ? 0 : -1;
}
/* ------------------------------------------------------------------ */
/* parse one line → entry */
/* Returns: 1 = valid entry parsed */
/* 0 = skip (comment/blank) */
/* -1 = parse error */
/* ------------------------------------------------------------------ */
static int parse_line(char *line, khm_entry_t *e) {
memset(e, 0, sizeof(*e));
line = ltrim(line);
rtrim(line);
if (!*line || *line == '#') return 0;
/* "@cert-authority" / "@revoked" markers never reach here in
* practice — khm_parse_file() intercepts them earlier (see
* khm_marker_t) so they're preserved instead of dropped. This
* stays as a defensive fallback for any other caller of
* parse_line() that doesn't do that interception itself. */
if (*line == '@') return 0;
/* field 1: hostnames */
char *p = line;
char *space = strpbrk(p, " \t");
if (!space) return -1;
*space = '\0';
if (parse_hostnames(p, e) < 0) return -1;
p = ltrim(space + 1);
/* field 2: key type */
space = strpbrk(p, " \t");
if (!space) return -1;
*space = '\0';
strncpy(e->keytype_str, p, KHM_MAX_KEYTYPE - 1);
e->keytype = khm_keytype_from_str(e->keytype_str);
p = ltrim(space + 1);
/* field 3: base64 key data */
/* strip trailing comment if any */
char *comment = strpbrk(p, " \t");
if (comment) *comment = '\0';
strncpy(e->keydata_b64, p, KHM_MAX_KEYDATA - 1);
return 1;
}
/* ------------------------------------------------------------------ */
/* public API */
/* ------------------------------------------------------------------ */
int khm_parse_file(const char *path, khm_db_t *db) {
struct stat st;
if (stat(path, &st) == 0 && S_ISREG(st.st_mode) && st.st_size > KHM_MAX_FILE_SIZE) {
fprintf(stderr, "khm: '%s' is %.0f MiB, over the %ld MiB limit — refusing to parse "
"(this is a sanity ceiling, not a real known_hosts size; if you "
"genuinely have a file this large, something upstream of khm is "
"probably generating it wrong)\n",
path, (double)st.st_size / (1024 * 1024), KHM_MAX_FILE_SIZE / (1024 * 1024));
return -1;
}
FILE *f = fopen(path, "r");
if (!f) return -1;
db->entries = malloc(INITIAL_CAPACITY * sizeof(khm_entry_t));
if (!db->entries) { fclose(f); return -1; }
db->count = 0;
db->capacity = INITIAL_CAPACITY;
db->errors = NULL;
db->error_count = 0;
db->error_capacity = 0;
db->markers = NULL;
db->marker_count = 0;
db->marker_capacity = 0;
char line[LINE_MAX_LEN];
long lineno = 0;
while (fgets(line, sizeof(line), f)) {
lineno++;
if (lineno > KHM_MAX_LINES) {
fprintf(stderr, "khm: '%s' has more than %ld lines — refusing to parse further "
"(sanity ceiling, see khm_parse_file in parser.c)\n",
path, KHM_MAX_LINES);
fclose(f);
khm_db_free(db);
return -1;
}
/* Keep a trimmed copy for error reporting before parse_line
* mutates the buffer in place (ltrim/rtrim/strtok). Bounded
* copy done manually (not snprintf) since `line` can be up to
* LINE_MAX_LEN and truncation here is intentional, not a bug
* gcc needs to warn about. */
char raw_copy[256];
size_t copy_len = strlen(line);
if (copy_len >= sizeof(raw_copy)) copy_len = sizeof(raw_copy) - 1;
memcpy(raw_copy, line, copy_len);
raw_copy[copy_len] = '\0';
size_t rl = copy_len;
while (rl > 0 && (raw_copy[rl - 1] == '\n' || raw_copy[rl - 1] == '\r'))
raw_copy[--rl] = '\0';
/* "@cert-authority" / "@revoked" marker lines: preserved
* verbatim rather than parsed as a host entry — see
* khm_marker_t. Detected here (before parse_line, which would
* otherwise just skip and drop it) so every consumer of the
* db, not just khm_parse_file's caller, can see these exist. */
char *marker_check = raw_copy;
while (*marker_check == ' ' || *marker_check == '\t') marker_check++;
if (*marker_check == '@') {
if (db->marker_count == db->marker_capacity) {
size_t newcap = db->marker_capacity ? db->marker_capacity * 2 : 8;
khm_marker_t *tmp = realloc(db->markers, newcap * sizeof(khm_marker_t));
if (tmp) { db->markers = tmp; db->marker_capacity = newcap; }
/* on realloc failure, drop this one marker rather than
* aborting the whole parse — same policy as errors[] */
}
if (db->marker_count < db->marker_capacity) {
db->markers[db->marker_count].line_number = lineno;
snprintf(db->markers[db->marker_count].raw,
sizeof(db->markers[db->marker_count].raw), "%s", marker_check);
db->marker_count++;
}
continue;
}
khm_entry_t e;
int r = parse_line(line, &e);
if (r == 1) {
e.line_number = lineno;
if (db->count == db->capacity) {
size_t newcap = db->capacity * 2;
khm_entry_t *tmp = realloc(db->entries,
newcap * sizeof(khm_entry_t));
if (!tmp) { fclose(f); return -1; }
db->entries = tmp;
db->capacity = newcap;
}
db->entries[db->count++] = e;
} else if (r == -1) {
if (db->error_count == db->error_capacity) {
size_t newcap = db->error_capacity ? db->error_capacity * 2 : 8;
khm_parse_error_t *tmp = realloc(db->errors, newcap * sizeof(khm_parse_error_t));
if (tmp) { db->errors = tmp; db->error_capacity = newcap; }
/* on realloc failure, just drop this one error rather
* than aborting the whole parse over a cosmetic issue */
}
if (db->error_count < db->error_capacity) {
db->errors[db->error_count].line_number = lineno;
snprintf(db->errors[db->error_count].raw,
sizeof(db->errors[db->error_count].raw), "%s", raw_copy);
db->error_count++;
}
}
/* r == 0: comment or blank line — legitimately skipped */
}
fclose(f);
return 0;
}
void khm_db_free(khm_db_t *db) {
free(db->entries);
free(db->errors);
free(db->markers);
db->entries = NULL;
db->count = 0;
db->capacity = 0;
db->errors = NULL;
db->error_count = 0;
db->error_capacity = 0;
db->markers = NULL;
db->marker_count = 0;
db->marker_capacity = 0;
}