added missing curly brackets
[strongswan.git] / src / libstrongswan / asn1 / asn1.c
1 /*
2 * Copyright (C) 2006 Martin Will
3 * Copyright (C) 2000-2008 Andreas Steffen
4 *
5 * Hochschule fuer Technik Rapperswil
6 *
7 * This program is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License as published by the
9 * Free Software Foundation; either version 2 of the License, or (at your
10 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
11 *
12 * This program is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 * for more details.
16 *
17 * $Id$
18 */
19
20 #include <stdio.h>
21 #include <string.h>
22 #include <time.h>
23
24 #include <library.h>
25 #include <debug.h>
26
27 #include "oid.h"
28 #include "asn1.h"
29 #include "asn1_parser.h"
30
31 /**
32 * some common prefabricated ASN.1 constants
33 */
34 static u_char ASN1_INTEGER_0_str[] = { 0x02, 0x00 };
35 static u_char ASN1_INTEGER_1_str[] = { 0x02, 0x01, 0x01 };
36 static u_char ASN1_INTEGER_2_str[] = { 0x02, 0x01, 0x02 };
37
38 const chunk_t ASN1_INTEGER_0 = chunk_from_buf(ASN1_INTEGER_0_str);
39 const chunk_t ASN1_INTEGER_1 = chunk_from_buf(ASN1_INTEGER_1_str);
40 const chunk_t ASN1_INTEGER_2 = chunk_from_buf(ASN1_INTEGER_2_str);
41
42 /**
43 * some popular algorithmIdentifiers
44 */
45
46 static u_char ASN1_md2_id_str[] = {
47 0x30, 0x0c,
48 0x06, 0x08,
49 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x02,
50 0x05,0x00,
51 };
52
53 static u_char ASN1_md5_id_str[] = {
54 0x30, 0x0C,
55 0x06, 0x08,
56 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x02, 0x05,
57 0x05, 0x00
58 };
59
60 static u_char ASN1_sha1_id_str[] = {
61 0x30, 0x09,
62 0x06, 0x05,
63 0x2B, 0x0E,0x03, 0x02, 0x1A,
64 0x05, 0x00
65 };
66
67 static u_char ASN1_sha256_id_str[] = {
68 0x30, 0x0d,
69 0x06, 0x09,
70 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01,
71 0x05, 0x00
72 };
73
74 static u_char ASN1_sha384_id_str[] = {
75 0x30, 0x0d,
76 0x06, 0x09,
77 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02,
78 0x05, 0x00
79 };
80
81 static u_char ASN1_sha512_id_str[] = {
82 0x30, 0x0d,
83 0x06, 0x09,
84 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03,
85 0x05,0x00
86 };
87
88 static u_char ASN1_md2WithRSA_id_str[] = {
89 0x30, 0x0D,
90 0x06, 0x09,
91 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x02,
92 0x05, 0x00
93 };
94
95 static u_char ASN1_md5WithRSA_id_str[] = {
96 0x30, 0x0D,
97 0x06, 0x09,
98 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x04,
99 0x05, 0x00
100 };
101
102 static u_char ASN1_sha1WithRSA_id_str[] = {
103 0x30, 0x0D,
104 0x06, 0x09,
105 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x05,
106 0x05, 0x00
107 };
108
109 static u_char ASN1_sha256WithRSA_id_str[] = {
110 0x30, 0x0D,
111 0x06, 0x09,
112 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B,
113 0x05, 0x00
114 };
115
116 static u_char ASN1_sha384WithRSA_id_str[] = {
117 0x30, 0x0D,
118 0x06, 0x09,
119 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0C,
120 0x05, 0x00
121 };
122
123 static u_char ASN1_sha512WithRSA_id_str[] = {
124 0x30, 0x0D,
125 0x06, 0x09,
126 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0D,
127 0x05, 0x00
128 };
129
130 static u_char ASN1_rsaEncryption_id_str[] = {
131 0x30, 0x0D,
132 0x06, 0x09,
133 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01,
134 0x05, 0x00
135 };
136
137 static const chunk_t ASN1_md2_id = chunk_from_buf(ASN1_md2_id_str);
138 static const chunk_t ASN1_md5_id = chunk_from_buf(ASN1_md5_id_str);
139 static const chunk_t ASN1_sha1_id = chunk_from_buf(ASN1_sha1_id_str);
140 static const chunk_t ASN1_sha256_id = chunk_from_buf(ASN1_sha256_id_str);
141 static const chunk_t ASN1_sha384_id = chunk_from_buf(ASN1_sha384_id_str);
142 static const chunk_t ASN1_sha512_id = chunk_from_buf(ASN1_sha512_id_str);
143 static const chunk_t ASN1_rsaEncryption_id = chunk_from_buf(ASN1_rsaEncryption_id_str);
144 static const chunk_t ASN1_md2WithRSA_id = chunk_from_buf(ASN1_md2WithRSA_id_str);
145 static const chunk_t ASN1_md5WithRSA_id = chunk_from_buf(ASN1_md5WithRSA_id_str);
146 static const chunk_t ASN1_sha1WithRSA_id = chunk_from_buf(ASN1_sha1WithRSA_id_str);
147 static const chunk_t ASN1_sha256WithRSA_id = chunk_from_buf(ASN1_sha256WithRSA_id_str);
148 static const chunk_t ASN1_sha384WithRSA_id = chunk_from_buf(ASN1_sha384WithRSA_id_str);
149 static const chunk_t ASN1_sha512WithRSA_id = chunk_from_buf(ASN1_sha512WithRSA_id_str);
150
151 /*
152 * Defined in header.
153 */
154 chunk_t asn1_algorithmIdentifier(int oid)
155 {
156 switch (oid)
157 {
158 case OID_RSA_ENCRYPTION:
159 return ASN1_rsaEncryption_id;
160 case OID_MD2_WITH_RSA:
161 return ASN1_md2WithRSA_id;
162 case OID_MD5_WITH_RSA:
163 return ASN1_md5WithRSA_id;
164 case OID_SHA1_WITH_RSA:
165 return ASN1_sha1WithRSA_id;
166 case OID_SHA256_WITH_RSA:
167 return ASN1_sha256WithRSA_id;
168 case OID_SHA384_WITH_RSA:
169 return ASN1_sha384WithRSA_id;
170 case OID_SHA512_WITH_RSA:
171 return ASN1_sha512WithRSA_id;
172 case OID_MD2:
173 return ASN1_md2_id;
174 case OID_MD5:
175 return ASN1_md5_id;
176 case OID_SHA1:
177 return ASN1_sha1_id;
178 case OID_SHA256:
179 return ASN1_sha256_id;
180 case OID_SHA384:
181 return ASN1_sha384_id;
182 case OID_SHA512:
183 return ASN1_sha512_id;
184 default:
185 return chunk_empty;
186 }
187 }
188
189 /*
190 * Defined in header.
191 */
192 int asn1_known_oid(chunk_t object)
193 {
194 int oid = 0;
195
196 while (object.len)
197 {
198 if (oid_names[oid].octet == *object.ptr)
199 {
200 if (--object.len == 0 || oid_names[oid].down == 0)
201 {
202 return oid; /* found terminal symbol */
203 }
204 else
205 {
206 object.ptr++; oid++; /* advance to next hex octet */
207 }
208 }
209 else
210 {
211 if (oid_names[oid].next)
212 {
213 oid = oid_names[oid].next;
214 }
215 else
216 {
217 return OID_UNKNOWN;
218 }
219 }
220 }
221 return -1;
222 }
223
224 /*
225 * Defined in header.
226 */
227 chunk_t asn1_get_known_oid(int n)
228 {
229 chunk_t oid;
230 int i;
231
232 if (n < 0 || n >= OID_MAX)
233 {
234 return chunk_empty;
235 }
236
237 i = oid_names[n].level + 1;
238 oid = chunk_alloc(i);
239 do
240 {
241 if (oid_names[n].level >= i)
242 {
243 n--;
244 continue;
245 }
246 oid.ptr[--i] = oid_names[n--].octet;
247 }
248 while (i > 0);
249
250 return oid;
251 }
252
253 /*
254 * Defined in header.
255 */
256 u_int asn1_length(chunk_t *blob)
257 {
258 u_char n;
259 size_t len;
260
261 /* advance from tag field on to length field */
262 blob->ptr++;
263 blob->len--;
264
265 /* read first octet of length field */
266 n = *blob->ptr++;
267 blob->len--;
268
269 if ((n & 0x80) == 0)
270 {/* single length octet */
271 return n;
272 }
273
274 /* composite length, determine number of length octets */
275 n &= 0x7f;
276
277 if (n > blob->len)
278 {
279 DBG2("number of length octets is larger than ASN.1 object");
280 return ASN1_INVALID_LENGTH;
281 }
282
283 if (n > sizeof(len))
284 {
285 DBG2("number of length octets is larger than limit of %d octets",
286 (int)sizeof(len));
287 return ASN1_INVALID_LENGTH;
288 }
289
290 len = 0;
291
292 while (n-- > 0)
293 {
294 len = 256*len + *blob->ptr++;
295 blob->len--;
296 }
297 return len;
298 }
299
300 #define TIME_MAX 0x7fffffff
301
302 /**
303 * Converts ASN.1 UTCTIME or GENERALIZEDTIME into calender time
304 */
305 time_t asn1_to_time(const chunk_t *utctime, asn1_t type)
306 {
307 struct tm t;
308 time_t tc, tz_offset;
309 u_char *eot = NULL;
310
311 if ((eot = memchr(utctime->ptr, 'Z', utctime->len)) != NULL)
312 {
313 tz_offset = 0; /* Zulu time with a zero time zone offset */
314 }
315 else if ((eot = memchr(utctime->ptr, '+', utctime->len)) != NULL)
316 {
317 int tz_hour, tz_min;
318
319 sscanf(eot+1, "%2d%2d", &tz_hour, &tz_min);
320 tz_offset = 3600*tz_hour + 60*tz_min; /* positive time zone offset */
321 }
322 else if ((eot = memchr(utctime->ptr, '-', utctime->len)) != NULL)
323 {
324 int tz_hour, tz_min;
325
326 sscanf(eot+1, "%2d%2d", &tz_hour, &tz_min);
327 tz_offset = -3600*tz_hour - 60*tz_min; /* negative time zone offset */
328 }
329 else
330 {
331 return 0; /* error in time format */
332 }
333
334 /* parse ASN.1 time string */
335 {
336 const char* format = (type == ASN1_UTCTIME)? "%2d%2d%2d%2d%2d":
337 "%4d%2d%2d%2d%2d";
338
339 sscanf(utctime->ptr, format, &t.tm_year, &t.tm_mon, &t.tm_mday,
340 &t.tm_hour, &t.tm_min);
341 }
342
343 /* is there a seconds field? */
344 if ((eot - utctime->ptr) == ((type == ASN1_UTCTIME)?12:14))
345 {
346 sscanf(eot-2, "%2d", &t.tm_sec);
347 }
348 else
349 {
350 t.tm_sec = 0;
351 }
352
353 /* representation of year */
354 if (t.tm_year >= 1900)
355 {
356 t.tm_year -= 1900;
357 }
358 else if (t.tm_year >= 100)
359 {
360 return 0;
361 }
362 else if (t.tm_year < 50)
363 {
364 t.tm_year += 100;
365 }
366
367 /* representation of month 0..11*/
368 t.tm_mon--;
369
370 /* set daylight saving time to off */
371 t.tm_isdst = 0;
372
373 /* convert to time_t */
374 tc = mktime(&t);
375
376 /* if no conversion overflow occurred, compensate timezone */
377 return (tc == -1) ? TIME_MAX : (tc - timezone - tz_offset);
378 }
379
380 /**
381 * Convert a date into ASN.1 UTCTIME or GENERALIZEDTIME format
382 */
383 chunk_t asn1_from_time(const time_t *time, asn1_t type)
384 {
385 int offset;
386 const char *format;
387 char buf[BUF_LEN];
388 chunk_t formatted_time;
389 struct tm t;
390
391 gmtime_r(time, &t);
392 if (type == ASN1_GENERALIZEDTIME)
393 {
394 format = "%04d%02d%02d%02d%02d%02dZ";
395 offset = 1900;
396 }
397 else /* ASN1_UTCTIME */
398 {
399 format = "%02d%02d%02d%02d%02d%02dZ";
400 offset = (t.tm_year < 100)? 0 : -100;
401 }
402 snprintf(buf, BUF_LEN, format, t.tm_year + offset,
403 t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec);
404 formatted_time.ptr = buf;
405 formatted_time.len = strlen(buf);
406 return asn1_simple_object(type, formatted_time);
407 }
408
409 /*
410 * Defined in header.
411 */
412 void asn1_debug_simple_object(chunk_t object, asn1_t type, bool private)
413 {
414 int oid;
415
416 switch (type)
417 {
418 case ASN1_OID:
419 oid = asn1_known_oid(object);
420 if (oid != OID_UNKNOWN)
421 {
422 DBG2(" '%s'", oid_names[oid].name);
423 return;
424 }
425 break;
426 case ASN1_UTF8STRING:
427 case ASN1_IA5STRING:
428 case ASN1_PRINTABLESTRING:
429 case ASN1_T61STRING:
430 case ASN1_VISIBLESTRING:
431 DBG2(" '%.*s'", (int)object.len, object.ptr);
432 return;
433 case ASN1_UTCTIME:
434 case ASN1_GENERALIZEDTIME:
435 {
436 time_t time = asn1_to_time(&object, type);
437
438 DBG2(" '%T'", &time, TRUE);
439 }
440 return;
441 default:
442 break;
443 }
444 if (private)
445 {
446 DBG4("%B", &object);
447 }
448 else
449 {
450 DBG3("%B", &object);
451 }
452 }
453
454 /**
455 * parse an ASN.1 simple type
456 */
457 bool asn1_parse_simple_object(chunk_t *object, asn1_t type, u_int level, const char* name)
458 {
459 size_t len;
460
461 /* an ASN.1 object must possess at least a tag and length field */
462 if (object->len < 2)
463 {
464 DBG2("L%d - %s: ASN.1 object smaller than 2 octets", level, name);
465 return FALSE;
466 }
467
468 if (*object->ptr != type)
469 {
470 DBG2("L%d - %s: ASN1 tag 0x%02x expected, but is 0x%02x",
471 level, name, type, *object->ptr);
472 return FALSE;
473 }
474
475 len = asn1_length(object);
476
477 if (len == ASN1_INVALID_LENGTH || object->len < len)
478 {
479 DBG2("L%d - %s: length of ASN.1 object invalid or too large",
480 level, name);
481 return FALSE;
482 }
483
484 DBG2("L%d - %s:", level, name);
485 asn1_debug_simple_object(*object, type, FALSE);
486 return TRUE;
487 }
488
489 /**
490 * ASN.1 definition of an algorithmIdentifier
491 */
492 static const asn1Object_t algorithmIdentifierObjects[] = {
493 { 0, "algorithmIdentifier", ASN1_SEQUENCE, ASN1_NONE }, /* 0 */
494 { 1, "algorithm", ASN1_OID, ASN1_BODY }, /* 1 */
495 { 1, "parameters", ASN1_EOC, ASN1_RAW|ASN1_OPT }, /* 2 */
496 { 1, "end opt", ASN1_EOC, ASN1_END }, /* 3 */
497 { 0, "exit", ASN1_EOC, ASN1_EXIT }
498 };
499 #define ALGORITHM_ID_ALG 1
500 #define ALGORITHM_ID_PARAMETERS 2
501
502 /*
503 * Defined in header
504 */
505 int asn1_parse_algorithmIdentifier(chunk_t blob, int level0, chunk_t *parameters)
506 {
507 asn1_parser_t *parser;
508 chunk_t object;
509 int objectID;
510 int alg = OID_UNKNOWN;
511
512 parser = asn1_parser_create(algorithmIdentifierObjects, blob);
513 parser->set_top_level(parser, level0);
514
515 while (parser->iterate(parser, &objectID, &object))
516 {
517 switch (objectID)
518 {
519 case ALGORITHM_ID_ALG:
520 alg = asn1_known_oid(object);
521 break;
522 case ALGORITHM_ID_PARAMETERS:
523 if (parameters != NULL)
524 {
525 *parameters = object;
526 }
527 break;
528 default:
529 break;
530 }
531 }
532 parser->destroy(parser);
533 return alg;
534 }
535
536 /*
537 * tests if a blob contains a valid ASN.1 set or sequence
538 */
539 bool is_asn1(chunk_t blob)
540 {
541 u_int len;
542 u_char tag = *blob.ptr;
543
544 if (tag != ASN1_SEQUENCE && tag != ASN1_SET)
545 {
546 DBG2(" file content is not binary ASN.1");
547 return FALSE;
548 }
549
550 len = asn1_length(&blob);
551
552 /* exact match */
553 if (len == blob.len)
554 {
555 return TRUE;
556 }
557
558 /* some websites append a surplus newline character to the blob */
559 if (len + 1 == blob.len && *(blob.ptr + len) == '\n')
560 {
561 return TRUE;
562 }
563
564 DBG2(" file size does not match ASN.1 coded length");
565 return FALSE;
566 }
567
568 /*
569 * Defined in header.
570 */
571 bool asn1_is_printablestring(chunk_t str)
572 {
573 const char printablestring_charset[] =
574 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 '()+,-./:=?";
575 u_int i;
576
577 for (i = 0; i < str.len; i++)
578 {
579 if (strchr(printablestring_charset, str.ptr[i]) == NULL)
580 return FALSE;
581 }
582 return TRUE;
583 }
584
585 /**
586 * codes ASN.1 lengths up to a size of 16'777'215 bytes
587 */
588 static void asn1_code_length(size_t length, chunk_t *code)
589 {
590 if (length < 128)
591 {
592 code->ptr[0] = length;
593 code->len = 1;
594 }
595 else if (length < 256)
596 {
597 code->ptr[0] = 0x81;
598 code->ptr[1] = (u_char) length;
599 code->len = 2;
600 }
601 else if (length < 65536)
602 {
603 code->ptr[0] = 0x82;
604 code->ptr[1] = length >> 8;
605 code->ptr[2] = length & 0x00ff;
606 code->len = 3;
607 }
608 else
609 {
610 code->ptr[0] = 0x83;
611 code->ptr[1] = length >> 16;
612 code->ptr[2] = (length >> 8) & 0x00ff;
613 code->ptr[3] = length & 0x0000ff;
614 code->len = 4;
615 }
616 }
617
618 /**
619 * build an empty asn.1 object with tag and length fields already filled in
620 */
621 u_char* asn1_build_object(chunk_t *object, asn1_t type, size_t datalen)
622 {
623 u_char length_buf[4];
624 chunk_t length = { length_buf, 0 };
625 u_char *pos;
626
627 /* code the asn.1 length field */
628 asn1_code_length(datalen, &length);
629
630 /* allocate memory for the asn.1 TLV object */
631 object->len = 1 + length.len + datalen;
632 object->ptr = malloc(object->len);
633
634 /* set position pointer at the start of the object */
635 pos = object->ptr;
636
637 /* copy the asn.1 tag field and advance the pointer */
638 *pos++ = type;
639
640 /* copy the asn.1 length field and advance the pointer */
641 memcpy(pos, length.ptr, length.len);
642 pos += length.len;
643
644 return pos;
645 }
646
647 /**
648 * Build a simple ASN.1 object
649 */
650 chunk_t asn1_simple_object(asn1_t tag, chunk_t content)
651 {
652 chunk_t object;
653
654 u_char *pos = asn1_build_object(&object, tag, content.len);
655 memcpy(pos, content.ptr, content.len);
656 pos += content.len;
657
658 return object;
659 }
660
661 /**
662 * Build an ASN.1 BITSTRING object
663 */
664 chunk_t asn1_bitstring(const char *mode, chunk_t content)
665 {
666 chunk_t object;
667 u_char *pos = asn1_build_object(&object, ASN1_BIT_STRING, 1 + content.len);
668
669 *pos++ = 0x00;
670 memcpy(pos, content.ptr, content.len);
671 if (*mode == 'm')
672 {
673 free(content.ptr);
674 }
675 return object;
676 }
677
678 /**
679 * Build an ASN.1 object from a variable number of individual chunks.
680 * Depending on the mode, chunks either are moved ('m') or copied ('c').
681 */
682 chunk_t asn1_wrap(asn1_t type, const char *mode, ...)
683 {
684 chunk_t construct;
685 va_list chunks;
686 u_char *pos;
687 int i;
688 int count = strlen(mode);
689
690 /* sum up lengths of individual chunks */
691 va_start(chunks, mode);
692 construct.len = 0;
693 for (i = 0; i < count; i++)
694 {
695 chunk_t ch = va_arg(chunks, chunk_t);
696 construct.len += ch.len;
697 }
698 va_end(chunks);
699
700 /* allocate needed memory for construct */
701 pos = asn1_build_object(&construct, type, construct.len);
702
703 /* copy or move the chunks */
704 va_start(chunks, mode);
705 for (i = 0; i < count; i++)
706 {
707 chunk_t ch = va_arg(chunks, chunk_t);
708
709 memcpy(pos, ch.ptr, ch.len);
710 pos += ch.len;
711
712 if (*mode++ == 'm')
713 {
714 free(ch.ptr);
715 }
716 }
717 va_end(chunks);
718
719 return construct;
720 }
721
722 /**
723 * ASN.1 definition of time
724 */
725 static const asn1Object_t timeObjects[] = {
726 { 0, "utcTime", ASN1_UTCTIME, ASN1_OPT|ASN1_BODY }, /* 0 */
727 { 0, "end opt", ASN1_EOC, ASN1_END }, /* 1 */
728 { 0, "generalizeTime", ASN1_GENERALIZEDTIME, ASN1_OPT|ASN1_BODY }, /* 2 */
729 { 0, "end opt", ASN1_EOC, ASN1_END }, /* 3 */
730 { 0, "exit", ASN1_EOC, ASN1_EXIT }
731 };
732 #define TIME_UTC 0
733 #define TIME_GENERALIZED 2
734
735 /**
736 * extracts and converts a UTCTIME or GENERALIZEDTIME object
737 */
738 time_t asn1_parse_time(chunk_t blob, int level0)
739 {
740 asn1_parser_t *parser;
741 chunk_t object;
742 int objectID;
743 time_t utc_time = 0;
744
745 parser= asn1_parser_create(timeObjects, blob);
746 parser->set_top_level(parser, level0);
747
748 while (parser->iterate(parser, &objectID, &object))
749 {
750 if (objectID == TIME_UTC || objectID == TIME_GENERALIZED)
751 {
752 utc_time = asn1_to_time(&object, (objectID == TIME_UTC)
753 ? ASN1_UTCTIME : ASN1_GENERALIZEDTIME);
754 }
755 }
756 parser->destroy(parser);
757 return utc_time;
758 }