der.c 9.6 KB

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