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