1 /* $NetBSD: der.c,v 1.3 2017/05/25 00:11:26 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.12 2017/02/10 18:14:01 christos Exp $") 42 #else 43 __RCSID("$NetBSD: der.c,v 1.3 2017/05/25 00:11:26 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 ((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 (*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, (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 %zu %u\n", __func__, ms->offset, offs, m->offset)); 255 256 uint32_t tlen = getlength(b, &offs, len); 257 if (tlen == DER_BAD) 258 return -1; 259 DPRINTF(("%s2: %d %zu %u\n", __func__, ms->offset, offs, tlen)); 260 261 offs += ms->offset + m->offset; 262 DPRINTF(("cont_level = %d\n", m->cont_level)); 263 #ifdef DEBUG_DER 264 for (size_t i = 0; i < m->cont_level; i++) 265 printf("cont_level[%zu] = %u\n", i, ms->c.li[i].off); 266 #endif 267 if (m->cont_level != 0) { 268 if (offs + tlen > nbytes) 269 return -1; 270 ms->c.li[m->cont_level - 1].off = CAST(int, offs + tlen); 271 DPRINTF(("cont_level[%u] = %u\n", m->cont_level - 1, 272 ms->c.li[m->cont_level - 1].off)); 273 } 274 return CAST(int32_t, offs); 275 } 276 277 int 278 der_cmp(struct magic_set *ms, struct magic *m) 279 { 280 const uint8_t *b = RCAST(const uint8_t *, ms->search.s); 281 const char *s = m->value.s; 282 size_t offs = 0, len = ms->search.s_len; 283 uint32_t tag, tlen; 284 char buf[128]; 285 286 tag = gettag(b, &offs, len); 287 if (tag == DER_BAD) 288 return -1; 289 290 tlen = getlength(b, &offs, len); 291 if (tlen == DER_BAD) 292 return -1; 293 294 der_tag(buf, sizeof(buf), tag); 295 if ((ms->flags & MAGIC_DEBUG) != 0) 296 fprintf(stderr, "%s: tag %p got=%s exp=%s\n", __func__, b, 297 buf, s); 298 size_t slen = strlen(buf); 299 300 if (strncmp(buf, s, slen) != 0) 301 return 0; 302 303 s += slen; 304 305 again: 306 switch (*s) { 307 case '\0': 308 return 1; 309 case '=': 310 s++; 311 goto val; 312 default: 313 if (!isdigit((unsigned char)*s)) 314 return 0; 315 316 slen = 0; 317 do 318 slen = slen * 10 + *s - '0'; 319 while (isdigit((unsigned char)*++s)); 320 if ((ms->flags & MAGIC_DEBUG) != 0) 321 fprintf(stderr, "%s: len %zu %u\n", __func__, 322 slen, tlen); 323 if (tlen != slen) 324 return 0; 325 goto again; 326 } 327 val: 328 DPRINTF(("%s: before data %zu %u\n", __func__, offs, tlen)); 329 der_data(buf, sizeof(buf), tag, b + offs, tlen); 330 if ((ms->flags & MAGIC_DEBUG) != 0) 331 fprintf(stderr, "%s: data %s %s\n", __func__, buf, s); 332 if (strcmp(buf, s) != 0 && strcmp("x", s) != 0) 333 return 0; 334 strlcpy(ms->ms_value.s, buf, sizeof(ms->ms_value.s)); 335 return 1; 336 } 337 #endif 338 339 #ifdef TEST_DER 340 static void 341 printtag(uint32_t tag, const void *q, uint32_t len) 342 { 343 const uint8_t *d = q; 344 switch (tag) { 345 case DER_TAG_PRINTABLE_STRING: 346 case DER_TAG_UTF8_STRING: 347 printf("%.*s\n", len, (const char *)q); 348 return; 349 default: 350 break; 351 } 352 353 for (uint32_t i = 0; i < len; i++) 354 printf("%.2x", d[i]); 355 printf("\n"); 356 } 357 358 static void 359 printdata(size_t level, const void *v, size_t x, size_t l) 360 { 361 const uint8_t *p = v, *ep = p + l; 362 size_t ox; 363 char buf[128]; 364 365 while (p + x < ep) { 366 const uint8_t *q; 367 uint8_t c = getclass(p[x]); 368 uint8_t t = gettype(p[x]); 369 ox = x; 370 if (x != 0) 371 printf("%.2x %.2x %.2x\n", p[x - 1], p[x], p[x + 1]); 372 uint32_t tag = gettag(p, &x, ep - p + x); 373 if (p + x >= ep) 374 break; 375 uint32_t len = getlength(p, &x, ep - p + x); 376 377 printf("%zu %zu-%zu %c,%c,%s,%u:", level, ox, x, 378 der_class[c], der_type[t], 379 der_tag(buf, sizeof(buf), tag), len); 380 q = p + x; 381 if (p + len > ep) 382 errx(EXIT_FAILURE, "corrupt der"); 383 printtag(tag, q, len); 384 if (t != DER_TYPE_PRIMITIVE) 385 printdata(level + 1, p, x, len + x); 386 x += len; 387 } 388 } 389 390 int 391 main(int argc, char *argv[]) 392 { 393 int fd; 394 struct stat st; 395 size_t l; 396 void *p; 397 398 if ((fd = open(argv[1], O_RDONLY)) == -1) 399 err(EXIT_FAILURE, "open `%s'", argv[1]); 400 if (fstat(fd, &st) == -1) 401 err(EXIT_FAILURE, "stat `%s'", argv[1]); 402 l = (size_t)st.st_size; 403 if ((p = mmap(NULL, l, PROT_READ, MAP_FILE, fd, 0)) == MAP_FAILED) 404 err(EXIT_FAILURE, "mmap `%s'", argv[1]); 405 406 printdata(0, p, 0, l); 407 munmap(p, l); 408 return 0; 409 } 410 #endif 411