xref: /PHP-7.2/ext/fileinfo/libmagic/der.c (revision 08d8623d)
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.12 2017/02/10 18:14:01 christos Exp $")
39 #endif
40 #endif
41 
42 #include <sys/types.h>
43 
44 #include <stdio.h>
45 #include <fcntl.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <ctype.h>
49 
50 #ifndef TEST_DER
51 #include "magic.h"
52 #include "der.h"
53 #else
54 #ifndef PHP_WIN32
55 #include <sys/mman.h>
56 #endif
57 #include <sys/stat.h>
58 #include <err.h>
59 #endif
60 
61 #define DER_BAD	((uint32_t)-1)
62 
63 #define DER_CLASS_UNIVERSAL	0
64 #define	DER_CLASS_APPLICATION	1
65 #define	DER_CLASS_CONTEXT	2
66 #define	DER_CLASS_PRIVATE	3
67 #ifdef DEBUG_DER
68 static const char der_class[] = "UACP";
69 #endif
70 
71 #define DER_TYPE_PRIMITIVE	0
72 #define DER_TYPE_CONSTRUCTED	1
73 #ifdef DEBUG_DER
74 static const char der_type[] = "PC";
75 #endif
76 
77 #define	DER_TAG_EOC			0x00
78 #define	DER_TAG_BOOLEAN			0x01
79 #define	DER_TAG_INTEGER			0x02
80 #define	DER_TAG_BIT STRING		0x03
81 #define	DER_TAG_OCTET_STRING		0x04
82 #define	DER_TAG_NULL			0x05
83 #define	DER_TAG_OBJECT_IDENTIFIER	0x06
84 #define	DER_TAG_OBJECT_DESCRIPTOR	0x07
85 #define	DER_TAG_EXTERNAL		0x08
86 #define	DER_TAG_REAL			0x09
87 #define	DER_TAG_ENUMERATED		0x0a
88 #define	DER_TAG_EMBEDDED_PDV		0x0b
89 #define	DER_TAG_UTF8_STRING		0x0c
90 #define	DER_TAG_RELATIVE_OID		0x0d
91 #define DER_TAG_RESERVED_1		0x0e
92 #define DER_TAG_RESERVED_2		0x0f
93 #define	DER_TAG_SEQUENCE		0x10
94 #define	DER_TAG_SET			0x11
95 #define	DER_TAG_NUMERIC_STRING		0x12
96 #define	DER_TAG_PRINTABLE_STRING	0x13
97 #define	DER_TAG_T61_STRING		0x14
98 #define	DER_TAG_VIDEOTEX_STRING		0x15
99 #define	DER_TAG_IA5_STRING		0x16
100 #define	DER_TAG_UTCTIME			0x17
101 #define	DER_TAG_GENERALIZED_TIME	0x18
102 #define	DER_TAG_GRAPHIC_STRING		0x19
103 #define	DER_TAG_VISIBLE_STRING		0x1a
104 #define	DER_TAG_GENERAL_STRING		0x1b
105 #define	DER_TAG_UNIVERSAL_STRING	0x1c
106 #define	DER_TAG_CHARACTER_STRING	0x1d
107 #define	DER_TAG_BMP_STRING		0x1e
108 #define	DER_TAG_LONG			0x1f
109 
110 static const char *der__tag[] = {
111 	"eoc", "bool", "int", "bit_str", "octet_str",
112 	"null", "obj_id", "obj_desc", "ext", "real",
113 	"enum", "embed", "utf8_str", "oid", "res1",
114 	"res2", "seq", "set", "num_str", "prt_str",
115 	"t61_str", "vid_str", "ia5_str", "utc_time",
116 	"gen_time", "gr_str", "vis_str", "gen_str",
117 	"char_str", "bmp_str", "long"
118 };
119 
120 #ifdef DEBUG_DER
121 #define DPRINTF(a) printf a
122 #else
123 #define DPRINTF(a)
124 #endif
125 
126 #ifdef TEST_DER
127 static uint8_t
getclass(uint8_t c)128 getclass(uint8_t c)
129 {
130 	return c >> 6;
131 }
132 
133 static uint8_t
gettype(uint8_t c)134 gettype(uint8_t c)
135 {
136 	return (c >> 5) & 1;
137 }
138 #endif
139 
140 static uint32_t
gettag(const uint8_t * c,size_t * p,size_t l)141 gettag(const uint8_t *c, size_t *p, size_t l)
142 {
143 	uint32_t tag;
144 
145 	if (*p >= l)
146 		return DER_BAD;
147 
148 	tag = c[(*p)++] & 0x1f;
149 
150 	if (tag != 0x1f)
151 		return tag;
152 
153 	if (*p >= l)
154 		return DER_BAD;
155 
156 	while (c[*p] >= 0x80) {
157 		tag = tag * 128 + c[(*p)++] - 0x80;
158 		if (*p >= l)
159 			return DER_BAD;
160 	}
161 	return tag;
162 }
163 
164 /*
165  * Read the length of a DER tag from the input.
166  *
167  * `c` is the input, `p` is an output parameter that specifies how much of the
168  * input we consumed, and `l` is the maximum input length.
169  *
170  * Returns the length, or DER_BAD if the end of the input is reached or the
171  * length exceeds the remaining input.
172  */
173 static uint32_t
getlength(const uint8_t * c,size_t * p,size_t l)174 getlength(const uint8_t *c, size_t *p, size_t l)
175 {
176 	uint8_t digits, i;
177 	size_t len;
178 	int is_onebyte_result;
179 
180 	if (*p >= l)
181 		return DER_BAD;
182 
183 	/*
184 	 * Digits can either be 0b0 followed by the result, or 0b1
185 	 * followed by the number of digits of the result. In either case,
186 	 * we verify that we can read so many bytes from the input.
187 	 */
188 	is_onebyte_result = (c[*p] & 0x80) == 0;
189 	digits = c[(*p)++] & 0x7f;
190 	if (*p + digits >= l)
191 		return DER_BAD;
192 
193 	if (is_onebyte_result)
194 		return digits;
195 
196 	/*
197 	 * Decode len. We've already verified that we're allowed to read
198 	 * `digits` bytes.
199 	 */
200 	len = 0;
201 	for (i = 0; i < digits; i++)
202 		len = (len << 8) | c[(*p)++];
203 
204 	if (*p + len >= l)
205 		return DER_BAD;
206 	return CAST(uint32_t, len);
207 }
208 
209 static const char *
der_tag(char * buf,size_t len,uint32_t tag)210 der_tag(char *buf, size_t len, uint32_t tag)
211 {
212 	if (tag < DER_TAG_LONG)
213 		strlcpy(buf, der__tag[tag], len);
214 	else
215 		snprintf(buf, len, "%#x", tag);
216 	return buf;
217 }
218 
219 #ifndef TEST_DER
220 static int
der_data(char * buf,size_t blen,uint32_t tag,const void * q,uint32_t len)221 der_data(char *buf, size_t blen, uint32_t tag, const void *q, uint32_t len)
222 {
223 	const uint8_t *d = CAST(const uint8_t *, q);
224 	uint32_t i;
225 	switch (tag) {
226 	case DER_TAG_PRINTABLE_STRING:
227 	case DER_TAG_UTF8_STRING:
228 	case DER_TAG_IA5_STRING:
229 	case DER_TAG_UTCTIME:
230 		return snprintf(buf, blen, "%.*s", len, (const char *)q);
231 	default:
232 		break;
233 	}
234 
235 	for (i = 0; i < len; i++) {
236 		uint32_t z = i << 1;
237 		if (z < blen - 2)
238 			snprintf(buf + z, blen - z, "%.2x", d[i]);
239 	}
240 	return len * 2;
241 }
242 
243 int32_t
der_offs(struct magic_set * ms,struct magic * m,size_t nbytes)244 der_offs(struct magic_set *ms, struct magic *m, size_t nbytes)
245 {
246 	const uint8_t *b = RCAST(const uint8_t *, ms->search.s);
247 	size_t offs = 0, len = ms->search.s_len ? ms->search.s_len : nbytes;
248 
249 	if (gettag(b, &offs, len) == DER_BAD)
250 		return -1;
251 	DPRINTF(("%s1: %d %zu %u\n", __func__, ms->offset, offs, m->offset));
252 
253 	uint32_t tlen = getlength(b, &offs, len);
254 	if (tlen == DER_BAD)
255 		return -1;
256 	DPRINTF(("%s2: %d %zu %u\n", __func__, ms->offset, offs, tlen));
257 
258 	offs += ms->offset + m->offset;
259 	DPRINTF(("cont_level = %d\n", m->cont_level));
260 #ifdef DEBUG_DER
261 	for (size_t i = 0; i < m->cont_level; i++)
262 		printf("cont_level[%zu] = %u\n", i, ms->c.li[i].off);
263 #endif
264 	if (m->cont_level != 0) {
265 		if (offs + tlen > nbytes)
266 			return -1;
267 		ms->c.li[m->cont_level - 1].off = CAST(int, offs + tlen);
268 		DPRINTF(("cont_level[%u] = %u\n", m->cont_level - 1,
269 		    ms->c.li[m->cont_level - 1].off));
270 	}
271 	return CAST(int32_t, offs);
272 }
273 
274 int
der_cmp(struct magic_set * ms,struct magic * m)275 der_cmp(struct magic_set *ms, struct magic *m)
276 {
277 	const uint8_t *b = RCAST(const uint8_t *, ms->search.s);
278 	const char *s = m->value.s;
279 	size_t offs = 0, len = ms->search.s_len;
280 	uint32_t tag, tlen;
281 	char buf[128];
282 
283 	tag = gettag(b, &offs, len);
284 	if (tag == DER_BAD)
285 		return -1;
286 
287 	tlen = getlength(b, &offs, len);
288 	if (tlen == DER_BAD)
289 		return -1;
290 
291 	der_tag(buf, sizeof(buf), tag);
292 	if ((ms->flags & MAGIC_DEBUG) != 0)
293 		fprintf(stderr, "%s: tag %p got=%s exp=%s\n", __func__, b,
294 		    buf, s);
295 	size_t slen = strlen(buf);
296 
297 	if (strncmp(buf, s, slen) != 0)
298 		return 0;
299 
300 	s += slen;
301 
302 again:
303 	switch (*s) {
304 	case '\0':
305 		return 1;
306 	case '=':
307 		s++;
308 		goto val;
309 	default:
310 		if (!isdigit((unsigned char)*s))
311 			return 0;
312 
313 		slen = 0;
314 		do
315 			slen = slen * 10 + *s - '0';
316 		while (isdigit((unsigned char)*++s));
317 		if ((ms->flags & MAGIC_DEBUG) != 0)
318 			fprintf(stderr, "%s: len %zu %u\n", __func__,
319 			    slen, tlen);
320 		if (tlen != slen)
321 			return 0;
322 		goto again;
323 	}
324 val:
325 	DPRINTF(("%s: before data %zu %u\n", __func__, offs, tlen));
326 	der_data(buf, sizeof(buf), tag, b + offs, tlen);
327 	if ((ms->flags & MAGIC_DEBUG) != 0)
328 		fprintf(stderr, "%s: data %s %s\n", __func__, buf, s);
329 	if (strcmp(buf, s) != 0 && strcmp("x", s) != 0)
330 		return 0;
331 	strlcpy(ms->ms_value.s, buf, sizeof(ms->ms_value.s));
332 	return 1;
333 }
334 #endif
335 
336 #ifdef TEST_DER
337 static void
printtag(uint32_t tag,const void * q,uint32_t len)338 printtag(uint32_t tag, const void *q, uint32_t len)
339 {
340 	const uint8_t *d = q;
341 	switch (tag) {
342 	case DER_TAG_PRINTABLE_STRING:
343 	case DER_TAG_UTF8_STRING:
344 		printf("%.*s\n", len, (const char *)q);
345 		return;
346 	default:
347 		break;
348 	}
349 
350 	for (uint32_t i = 0; i < len; i++)
351 		printf("%.2x", d[i]);
352 	printf("\n");
353 }
354 
355 static void
printdata(size_t level,const void * v,size_t x,size_t l)356 printdata(size_t level, const void *v, size_t x, size_t l)
357 {
358 	const uint8_t *p = v, *ep = p + l;
359 	size_t ox;
360 	char buf[128];
361 
362 	while (p + x < ep) {
363 		const uint8_t *q;
364 		uint8_t c = getclass(p[x]);
365 		uint8_t t = gettype(p[x]);
366 		ox = x;
367 		if (x != 0)
368 		printf("%.2x %.2x %.2x\n", p[x - 1], p[x], p[x + 1]);
369 		uint32_t tag = gettag(p, &x, ep - p + x);
370 		if (p + x >= ep)
371 			break;
372 		uint32_t len = getlength(p, &x, ep - p + x);
373 
374 		printf("%zu %zu-%zu %c,%c,%s,%u:", level, ox, x,
375 		    der_class[c], der_type[t],
376 		    der_tag(buf, sizeof(buf), tag), len);
377 		q = p + x;
378 		if (p + len > ep)
379 			errx(EXIT_FAILURE, "corrupt der");
380 		printtag(tag, q, len);
381 		if (t != DER_TYPE_PRIMITIVE)
382 			printdata(level + 1, p, x, len + x);
383 		x += len;
384 	}
385 }
386 
387 int
main(int argc,char * argv[])388 main(int argc, char *argv[])
389 {
390 	int fd;
391 	struct stat st;
392 	size_t l;
393 	void *p;
394 
395 	if ((fd = open(argv[1], O_RDONLY)) == -1)
396 		err(EXIT_FAILURE, "open `%s'", argv[1]);
397 	if (fstat(fd, &st) == -1)
398 		err(EXIT_FAILURE, "stat `%s'", argv[1]);
399 	l = (size_t)st.st_size;
400 	if ((p = mmap(NULL, l, PROT_READ, MAP_FILE, fd, 0)) == MAP_FAILED)
401 		err(EXIT_FAILURE, "mmap `%s'", argv[1]);
402 
403 	printdata(0, p, 0, l);
404 	munmap(p, l);
405 	return 0;
406 }
407 #endif
408