xref: /netbsd-src/external/bsd/file/dist/src/der.c (revision f3cfa6f6ce31685c6c4a758bc430e69eb99f50a4)
1 /*	$NetBSD: der.c,v 1.5 2019/05/22 17:26:05 christos Exp $	*/
2 
3 /*-
4  * Copyright (c) 2016 Christos Zoulas
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
17  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
18  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
20  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
22  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
23  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
24  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
25  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
26  * POSSIBILITY OF SUCH DAMAGE.
27  */
28 /*
29  * DER (Distinguished Encoding Rules) Parser
30  *
31  * Sources:
32  * https://en.wikipedia.org/wiki/X.690
33  * http://fm4dd.com/openssl/certexamples.htm
34  * http://blog.engelke.com/2014/10/17/parsing-ber-and-der-encoded-asn-1-objects/
35  */
36 #ifndef TEST_DER
37 #include "file.h"
38 
39 #ifndef lint
40 #if 0
41 FILE_RCSID("@(#)$File: der.c,v 1.16 2019/02/20 02:35:27 christos Exp $")
42 #else
43 __RCSID("$NetBSD: der.c,v 1.5 2019/05/22 17:26:05 christos Exp $");
44 #endif
45 #endif
46 #endif
47 
48 #include <sys/types.h>
49 
50 #include <stdio.h>
51 #include <fcntl.h>
52 #include <stdlib.h>
53 #include <string.h>
54 #include <ctype.h>
55 
56 #ifndef TEST_DER
57 #include "magic.h"
58 #include "der.h"
59 #else
60 #include <sys/mman.h>
61 #include <sys/stat.h>
62 #include <err.h>
63 #endif
64 
65 #define DER_BAD	CAST(uint32_t, -1)
66 
67 #define DER_CLASS_UNIVERSAL	0
68 #define	DER_CLASS_APPLICATION	1
69 #define	DER_CLASS_CONTEXT	2
70 #define	DER_CLASS_PRIVATE	3
71 #ifdef DEBUG_DER
72 static const char der_class[] = "UACP";
73 #endif
74 
75 #define DER_TYPE_PRIMITIVE	0
76 #define DER_TYPE_CONSTRUCTED	1
77 #ifdef DEBUG_DER
78 static const char der_type[] = "PC";
79 #endif
80 
81 #define	DER_TAG_EOC			0x00
82 #define	DER_TAG_BOOLEAN			0x01
83 #define	DER_TAG_INTEGER			0x02
84 #define	DER_TAG_BIT STRING		0x03
85 #define	DER_TAG_OCTET_STRING		0x04
86 #define	DER_TAG_NULL			0x05
87 #define	DER_TAG_OBJECT_IDENTIFIER	0x06
88 #define	DER_TAG_OBJECT_DESCRIPTOR	0x07
89 #define	DER_TAG_EXTERNAL		0x08
90 #define	DER_TAG_REAL			0x09
91 #define	DER_TAG_ENUMERATED		0x0a
92 #define	DER_TAG_EMBEDDED_PDV		0x0b
93 #define	DER_TAG_UTF8_STRING		0x0c
94 #define	DER_TAG_RELATIVE_OID		0x0d
95 #define DER_TAG_RESERVED_1		0x0e
96 #define DER_TAG_RESERVED_2		0x0f
97 #define	DER_TAG_SEQUENCE		0x10
98 #define	DER_TAG_SET			0x11
99 #define	DER_TAG_NUMERIC_STRING		0x12
100 #define	DER_TAG_PRINTABLE_STRING	0x13
101 #define	DER_TAG_T61_STRING		0x14
102 #define	DER_TAG_VIDEOTEX_STRING		0x15
103 #define	DER_TAG_IA5_STRING		0x16
104 #define	DER_TAG_UTCTIME			0x17
105 #define	DER_TAG_GENERALIZED_TIME	0x18
106 #define	DER_TAG_GRAPHIC_STRING		0x19
107 #define	DER_TAG_VISIBLE_STRING		0x1a
108 #define	DER_TAG_GENERAL_STRING		0x1b
109 #define	DER_TAG_UNIVERSAL_STRING	0x1c
110 #define	DER_TAG_CHARACTER_STRING	0x1d
111 #define	DER_TAG_BMP_STRING		0x1e
112 #define	DER_TAG_LONG			0x1f
113 
114 static const char *der__tag[] = {
115 	"eoc", "bool", "int", "bit_str", "octet_str",
116 	"null", "obj_id", "obj_desc", "ext", "real",
117 	"enum", "embed", "utf8_str", "oid", "res1",
118 	"res2", "seq", "set", "num_str", "prt_str",
119 	"t61_str", "vid_str", "ia5_str", "utc_time",
120 	"gen_time", "gr_str", "vis_str", "gen_str",
121 	"char_str", "bmp_str", "long"
122 };
123 
124 #ifdef DEBUG_DER
125 #define DPRINTF(a) printf a
126 #else
127 #define DPRINTF(a)
128 #endif
129 
130 #ifdef TEST_DER
131 static uint8_t
132 getclass(uint8_t c)
133 {
134 	return c >> 6;
135 }
136 
137 static uint8_t
138 gettype(uint8_t c)
139 {
140 	return (c >> 5) & 1;
141 }
142 #endif
143 
144 static uint32_t
145 gettag(const uint8_t *c, size_t *p, size_t l)
146 {
147 	uint32_t tag;
148 
149 	if (*p >= l)
150 		return DER_BAD;
151 
152 	tag = c[(*p)++] & 0x1f;
153 
154 	if (tag != 0x1f)
155 		return tag;
156 
157 	if (*p >= l)
158 		return DER_BAD;
159 
160 	while (c[*p] >= 0x80) {
161 		tag = tag * 128 + c[(*p)++] - 0x80;
162 		if (*p >= l)
163 			return DER_BAD;
164 	}
165 	return tag;
166 }
167 
168 /*
169  * Read the length of a DER tag from the input.
170  *
171  * `c` is the input, `p` is an output parameter that specifies how much of the
172  * input we consumed, and `l` is the maximum input length.
173  *
174  * Returns the length, or DER_BAD if the end of the input is reached or the
175  * length exceeds the remaining input.
176  */
177 static uint32_t
178 getlength(const uint8_t *c, size_t *p, size_t l)
179 {
180 	uint8_t digits, i;
181 	size_t len;
182 	int is_onebyte_result;
183 
184 	if (*p >= l)
185 		return DER_BAD;
186 
187 	/*
188 	 * Digits can either be 0b0 followed by the result, or 0b1
189 	 * followed by the number of digits of the result. In either case,
190 	 * we verify that we can read so many bytes from the input.
191 	 */
192 	is_onebyte_result = (c[*p] & 0x80) == 0;
193 	digits = c[(*p)++] & 0x7f;
194 	if (*p + digits >= l)
195 		return DER_BAD;
196 
197 	if (is_onebyte_result)
198 		return digits;
199 
200 	/*
201 	 * Decode len. We've already verified that we're allowed to read
202 	 * `digits` bytes.
203 	 */
204 	len = 0;
205 	for (i = 0; i < digits; i++)
206 		len = (len << 8) | c[(*p)++];
207 
208 	if (len > UINT32_MAX - *p || *p + len >= l)
209 		return DER_BAD;
210 	return CAST(uint32_t, len);
211 }
212 
213 static const char *
214 der_tag(char *buf, size_t len, uint32_t tag)
215 {
216 	if (tag < DER_TAG_LONG)
217 		strlcpy(buf, der__tag[tag], len);
218 	else
219 		snprintf(buf, len, "%#x", tag);
220 	return buf;
221 }
222 
223 #ifndef TEST_DER
224 static int
225 der_data(char *buf, size_t blen, uint32_t tag, const void *q, uint32_t len)
226 {
227 	const uint8_t *d = CAST(const uint8_t *, q);
228 	switch (tag) {
229 	case DER_TAG_PRINTABLE_STRING:
230 	case DER_TAG_UTF8_STRING:
231 	case DER_TAG_IA5_STRING:
232 	case DER_TAG_UTCTIME:
233 		return snprintf(buf, blen, "%.*s", len, RCAST(const char *, q));
234 	default:
235 		break;
236 	}
237 
238 	for (uint32_t i = 0; i < len; i++) {
239 		uint32_t z = i << 1;
240 		if (z < blen - 2)
241 			snprintf(buf + z, blen - z, "%.2x", d[i]);
242 	}
243 	return len * 2;
244 }
245 
246 int32_t
247 der_offs(struct magic_set *ms, struct magic *m, size_t nbytes)
248 {
249 	const uint8_t *b = RCAST(const uint8_t *, ms->search.s);
250 	size_t offs = 0, len = ms->search.s_len ? ms->search.s_len : nbytes;
251 
252 	if (gettag(b, &offs, len) == DER_BAD)
253 		return -1;
254 	DPRINTF(("%s1: %d %" SIZE_T_FORMAT "u %u\n", __func__, ms->offset,
255 	    offs, m->offset));
256 
257 	uint32_t tlen = getlength(b, &offs, len);
258 	if (tlen == DER_BAD)
259 		return -1;
260 	DPRINTF(("%s2: %d %" SIZE_T_FORMAT "u %u\n", __func__, ms->offset,
261 	    offs, tlen));
262 
263 	offs += ms->offset + m->offset;
264 	DPRINTF(("cont_level = %d\n", m->cont_level));
265 #ifdef DEBUG_DER
266 	for (size_t i = 0; i < m->cont_level; i++)
267 		printf("cont_level[%" SIZE_T_FORMAT "u] = %u\n", i,
268 		    ms->c.li[i].off);
269 #endif
270 	if (m->cont_level != 0) {
271 		if (offs + tlen > nbytes)
272 			return -1;
273 		ms->c.li[m->cont_level - 1].off = CAST(int, offs + tlen);
274 		DPRINTF(("cont_level[%u] = %u\n", m->cont_level - 1,
275 		    ms->c.li[m->cont_level - 1].off));
276 	}
277 	return CAST(int32_t, offs);
278 }
279 
280 int
281 der_cmp(struct magic_set *ms, struct magic *m)
282 {
283 	const uint8_t *b = RCAST(const uint8_t *, ms->search.s);
284 	const char *s = m->value.s;
285 	size_t offs = 0, len = ms->search.s_len;
286 	uint32_t tag, tlen;
287 	char buf[128];
288 
289 	tag = gettag(b, &offs, len);
290 	if (tag == DER_BAD)
291 		return -1;
292 
293 	tlen = getlength(b, &offs, len);
294 	if (tlen == DER_BAD)
295 		return -1;
296 
297 	der_tag(buf, sizeof(buf), tag);
298 	if ((ms->flags & MAGIC_DEBUG) != 0)
299 		fprintf(stderr, "%s: tag %p got=%s exp=%s\n", __func__, b,
300 		    buf, s);
301 	size_t slen = strlen(buf);
302 
303 	if (strncmp(buf, s, slen) != 0)
304 		return 0;
305 
306 	s += slen;
307 
308 again:
309 	switch (*s) {
310 	case '\0':
311 		return 1;
312 	case '=':
313 		s++;
314 		goto val;
315 	default:
316 		if (!isdigit(CAST(unsigned char, *s)))
317 			return 0;
318 
319 		slen = 0;
320 		do
321 			slen = slen * 10 + *s - '0';
322 		while (isdigit(CAST(unsigned char, *++s)));
323 		if ((ms->flags & MAGIC_DEBUG) != 0)
324 			fprintf(stderr, "%s: len %" SIZE_T_FORMAT "u %u\n",
325 			    __func__, slen, tlen);
326 		if (tlen != slen)
327 			return 0;
328 		goto again;
329 	}
330 val:
331 	DPRINTF(("%s: before data %" SIZE_T_FORMAT "u %u\n", __func__, offs,
332 	    tlen));
333 	der_data(buf, sizeof(buf), tag, b + offs, tlen);
334 	if ((ms->flags & MAGIC_DEBUG) != 0)
335 		fprintf(stderr, "%s: data %s %s\n", __func__, buf, s);
336 	if (strcmp(buf, s) != 0 && strcmp("x", s) != 0)
337 		return 0;
338 	strlcpy(ms->ms_value.s, buf, sizeof(ms->ms_value.s));
339 	return 1;
340 }
341 #endif
342 
343 #ifdef TEST_DER
344 static void
345 printtag(uint32_t tag, const void *q, uint32_t len)
346 {
347 	const uint8_t *d = q;
348 	switch (tag) {
349 	case DER_TAG_PRINTABLE_STRING:
350 	case DER_TAG_UTF8_STRING:
351 		printf("%.*s\n", len, (const char *)q);
352 		return;
353 	default:
354 		break;
355 	}
356 
357 	for (uint32_t i = 0; i < len; i++)
358 		printf("%.2x", d[i]);
359 	printf("\n");
360 }
361 
362 static void
363 printdata(size_t level, const void *v, size_t x, size_t l)
364 {
365 	const uint8_t *p = v, *ep = p + l;
366 	size_t ox;
367 	char buf[128];
368 
369 	while (p + x < ep) {
370 		const uint8_t *q;
371 		uint8_t c = getclass(p[x]);
372 		uint8_t t = gettype(p[x]);
373 		ox = x;
374 		if (x != 0)
375 		printf("%.2x %.2x %.2x\n", p[x - 1], p[x], p[x + 1]);
376 		uint32_t tag = gettag(p, &x, ep - p + x);
377 		if (p + x >= ep)
378 			break;
379 		uint32_t len = getlength(p, &x, ep - p + x);
380 
381 		printf("%" SIZE_T_FORMAT "u %" SIZE_T_FORMAT "u-%"
382 		    SIZE_T_FORMAT "u %c,%c,%s,%u:", level, ox, x,
383 		    der_class[c], der_type[t],
384 		    der_tag(buf, sizeof(buf), tag), len);
385 		q = p + x;
386 		if (p + len > ep)
387 			errx(EXIT_FAILURE, "corrupt der");
388 		printtag(tag, q, len);
389 		if (t != DER_TYPE_PRIMITIVE)
390 			printdata(level + 1, p, x, len + x);
391 		x += len;
392 	}
393 }
394 
395 int
396 main(int argc, char *argv[])
397 {
398 	int fd;
399 	struct stat st;
400 	size_t l;
401 	void *p;
402 
403 	if ((fd = open(argv[1], O_RDONLY)) == -1)
404 		err(EXIT_FAILURE, "open `%s'", argv[1]);
405 	if (fstat(fd, &st) == -1)
406 		err(EXIT_FAILURE, "stat `%s'", argv[1]);
407 	l = (size_t)st.st_size;
408 	if ((p = mmap(NULL, l, PROT_READ, MAP_FILE, fd, 0)) == MAP_FAILED)
409 		err(EXIT_FAILURE, "mmap `%s'", argv[1]);
410 
411 	printdata(0, p, 0, l);
412 	munmap(p, l);
413 	return 0;
414 }
415 #endif
416