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