making the parsing of parameters of a subjectAlgorithmIdentifier optional
[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 oid = oid_names[oid].next;
213 else
214 return OID_UNKNOWN;
215 }
216 }
217 return -1;
218 }
219
220 /*
221 * Defined in header.
222 */
223 u_int asn1_length(chunk_t *blob)
224 {
225 u_char n;
226 size_t len;
227
228 /* advance from tag field on to length field */
229 blob->ptr++;
230 blob->len--;
231
232 /* read first octet of length field */
233 n = *blob->ptr++;
234 blob->len--;
235
236 if ((n & 0x80) == 0)
237 {/* single length octet */
238 return n;
239 }
240
241 /* composite length, determine number of length octets */
242 n &= 0x7f;
243
244 if (n > blob->len)
245 {
246 DBG2("number of length octets is larger than ASN.1 object");
247 return ASN1_INVALID_LENGTH;
248 }
249
250 if (n > sizeof(len))
251 {
252 DBG2("number of length octets is larger than limit of %d octets",
253 (int)sizeof(len));
254 return ASN1_INVALID_LENGTH;
255 }
256
257 len = 0;
258
259 while (n-- > 0)
260 {
261 len = 256*len + *blob->ptr++;
262 blob->len--;
263 }
264 return len;
265 }
266
267 /**
268 * Converts ASN.1 UTCTIME or GENERALIZEDTIME into calender time
269 */
270 time_t asn1_to_time(const chunk_t *utctime, asn1_t type)
271 {
272 struct tm t;
273 time_t tz_offset;
274 u_char *eot = NULL;
275
276 if ((eot = memchr(utctime->ptr, 'Z', utctime->len)) != NULL)
277 {
278 tz_offset = 0; /* Zulu time with a zero time zone offset */
279 }
280 else if ((eot = memchr(utctime->ptr, '+', utctime->len)) != NULL)
281 {
282 int tz_hour, tz_min;
283
284 sscanf(eot+1, "%2d%2d", &tz_hour, &tz_min);
285 tz_offset = 3600*tz_hour + 60*tz_min; /* positive time zone offset */
286 }
287 else if ((eot = memchr(utctime->ptr, '-', utctime->len)) != NULL)
288 {
289 int tz_hour, tz_min;
290
291 sscanf(eot+1, "%2d%2d", &tz_hour, &tz_min);
292 tz_offset = -3600*tz_hour - 60*tz_min; /* negative time zone offset */
293 }
294 else
295 {
296 return 0; /* error in time format */
297 }
298
299 {
300 const char* format = (type == ASN1_UTCTIME)? "%2d%2d%2d%2d%2d":
301 "%4d%2d%2d%2d%2d";
302
303 sscanf(utctime->ptr, format, &t.tm_year, &t.tm_mon, &t.tm_mday,
304 &t.tm_hour, &t.tm_min);
305 }
306
307 /* is there a seconds field? */
308 if ((eot - utctime->ptr) == ((type == ASN1_UTCTIME)?12:14))
309 {
310 sscanf(eot-2, "%2d", &t.tm_sec);
311 }
312 else
313 {
314 t.tm_sec = 0;
315 }
316
317 /* representation of year */
318 if (t.tm_year >= 1900)
319 {
320 t.tm_year -= 1900;
321 }
322 else if (t.tm_year >= 100)
323 {
324 return 0;
325 }
326 else if (t.tm_year < 50)
327 {
328 t.tm_year += 100;
329 }
330
331 /* representation of month 0..11*/
332 t.tm_mon--;
333
334 /* set daylight saving time to off */
335 t.tm_isdst = 0;
336
337 /* compensate timezone */
338
339 return mktime(&t) - timezone - tz_offset;
340 }
341
342 /**
343 * Convert a date into ASN.1 UTCTIME or GENERALIZEDTIME format
344 */
345 chunk_t asn1_from_time(const time_t *time, asn1_t type)
346 {
347 int offset;
348 const char *format;
349 char buf[BUF_LEN];
350 chunk_t formatted_time;
351 struct tm *t = gmtime(time);
352
353 if (type == ASN1_GENERALIZEDTIME)
354 {
355 format = "%04d%02d%02d%02d%02d%02dZ";
356 offset = 1900;
357 }
358 else /* ASN1_UTCTIME */
359 {
360 format = "%02d%02d%02d%02d%02d%02dZ";
361 offset = (t->tm_year < 100)? 0 : -100;
362 }
363 snprintf(buf, BUF_LEN, format, t->tm_year + offset,
364 t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec);
365 formatted_time.ptr = buf;
366 formatted_time.len = strlen(buf);
367 return asn1_simple_object(type, formatted_time);
368 }
369
370 /*
371 * Defined in header.
372 */
373 void asn1_debug_simple_object(chunk_t object, asn1_t type, bool private)
374 {
375 int oid;
376
377 switch (type)
378 {
379 case ASN1_OID:
380 oid = asn1_known_oid(object);
381 if (oid != OID_UNKNOWN)
382 {
383 DBG2(" '%s'", oid_names[oid].name);
384 return;
385 }
386 break;
387 case ASN1_UTF8STRING:
388 case ASN1_IA5STRING:
389 case ASN1_PRINTABLESTRING:
390 case ASN1_T61STRING:
391 case ASN1_VISIBLESTRING:
392 DBG2(" '%.*s'", (int)object.len, object.ptr);
393 return;
394 case ASN1_UTCTIME:
395 case ASN1_GENERALIZEDTIME:
396 {
397 time_t time = asn1_to_time(&object, type);
398
399 DBG2(" '%T'", &time);
400 }
401 return;
402 default:
403 break;
404 }
405 if (private)
406 {
407 DBG4("%B", &object);
408 }
409 else
410 {
411 DBG3("%B", &object);
412 }
413 }
414
415 /**
416 * parse an ASN.1 simple type
417 */
418 bool asn1_parse_simple_object(chunk_t *object, asn1_t type, u_int level, const char* name)
419 {
420 size_t len;
421
422 /* an ASN.1 object must possess at least a tag and length field */
423 if (object->len < 2)
424 {
425 DBG2("L%d - %s: ASN.1 object smaller than 2 octets", level, name);
426 return FALSE;
427 }
428
429 if (*object->ptr != type)
430 {
431 DBG2("L%d - %s: ASN1 tag 0x%02x expected, but is 0x%02x",
432 level, name, type, *object->ptr);
433 return FALSE;
434 }
435
436 len = asn1_length(object);
437
438 if (len == ASN1_INVALID_LENGTH || object->len < len)
439 {
440 DBG2("L%d - %s: length of ASN.1 object invalid or too large",
441 level, name);
442 return FALSE;
443 }
444
445 DBG2("L%d - %s:", level, name);
446 asn1_debug_simple_object(*object, type, FALSE);
447 return TRUE;
448 }
449
450 /**
451 * ASN.1 definition of an algorithmIdentifier
452 */
453 static const asn1Object_t algorithmIdentifierObjects[] = {
454 { 0, "algorithmIdentifier", ASN1_SEQUENCE, ASN1_NONE }, /* 0 */
455 { 1, "algorithm", ASN1_OID, ASN1_BODY }, /* 1 */
456 { 1, "parameters", ASN1_EOC, ASN1_RAW }, /* 2 */
457 { 0, "exit", ASN1_EOC, ASN1_EXIT }
458 };
459 /* parameters are optional in case of ecdsa-with-SHA1 as algorithm (RFC 3279) */
460 static const asn1Object_t algorithmIdentifierObjectsOptional[] = {
461 { 0, "algorithmIdentifier", ASN1_SEQUENCE, ASN1_NONE }, /* 0 */
462 { 1, "algorithm", ASN1_OID, ASN1_BODY }, /* 1 */
463 { 1, "parameters", ASN1_EOC, ASN1_RAW|ASN1_OPT }, /* 2 */
464 { 1, "end opt", ASN1_EOC, ASN1_END }, /* 3 */
465 { 0, "exit", ASN1_EOC, ASN1_EXIT }
466 };
467 #define ALGORITHM_ID_ALG 1
468 #define ALGORITHM_ID_PARAMETERS 2
469
470 /*
471 * Defined in header
472 */
473 int asn1_parse_algorithmIdentifier(chunk_t blob, int level0, chunk_t *parameters)
474 {
475 asn1_parser_t *parser;
476 chunk_t object;
477 int objectID;
478 int alg = OID_UNKNOWN;
479 const asn1Object_t *objects = algorithmIdentifierObjectsOptional;
480
481 if (parameters != NULL)
482 {
483 objects = algorithmIdentifierObjects;
484 }
485
486 parser = asn1_parser_create(objects, blob);
487 parser->set_top_level(parser, level0);
488
489 while (parser->iterate(parser, &objectID, &object))
490 {
491 switch (objectID)
492 {
493 case ALGORITHM_ID_ALG:
494 alg = asn1_known_oid(object);
495 break;
496 case ALGORITHM_ID_PARAMETERS:
497 if (parameters != NULL)
498 {
499 *parameters = object;
500 }
501 break;
502 default:
503 break;
504 }
505 }
506 parser->destroy(parser);
507 return alg;
508 }
509
510 /*
511 * tests if a blob contains a valid ASN.1 set or sequence
512 */
513 bool is_asn1(chunk_t blob)
514 {
515 u_int len;
516 u_char tag = *blob.ptr;
517
518 if (tag != ASN1_SEQUENCE && tag != ASN1_SET)
519 {
520 DBG2(" file content is not binary ASN.1");
521 return FALSE;
522 }
523
524 len = asn1_length(&blob);
525
526 /* exact match */
527 if (len == blob.len)
528 {
529 return TRUE;
530 }
531
532 /* some websites append a surplus newline character to the blob */
533 if (len + 1 == blob.len && *(blob.ptr + len) == '\n')
534 {
535 return TRUE;
536 }
537
538 DBG2(" file size does not match ASN.1 coded length");
539 return FALSE;
540 }
541
542 /*
543 * Defined in header.
544 */
545 bool asn1_is_printablestring(chunk_t str)
546 {
547 const char printablestring_charset[] =
548 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 '()+,-./:=?";
549 u_int i;
550
551 for (i = 0; i < str.len; i++)
552 {
553 if (strchr(printablestring_charset, str.ptr[i]) == NULL)
554 return FALSE;
555 }
556 return TRUE;
557 }
558
559 /**
560 * codes ASN.1 lengths up to a size of 16'777'215 bytes
561 */
562 static void asn1_code_length(size_t length, chunk_t *code)
563 {
564 if (length < 128)
565 {
566 code->ptr[0] = length;
567 code->len = 1;
568 }
569 else if (length < 256)
570 {
571 code->ptr[0] = 0x81;
572 code->ptr[1] = (u_char) length;
573 code->len = 2;
574 }
575 else if (length < 65536)
576 {
577 code->ptr[0] = 0x82;
578 code->ptr[1] = length >> 8;
579 code->ptr[2] = length & 0x00ff;
580 code->len = 3;
581 }
582 else
583 {
584 code->ptr[0] = 0x83;
585 code->ptr[1] = length >> 16;
586 code->ptr[2] = (length >> 8) & 0x00ff;
587 code->ptr[3] = length & 0x0000ff;
588 code->len = 4;
589 }
590 }
591
592 /**
593 * build an empty asn.1 object with tag and length fields already filled in
594 */
595 u_char* asn1_build_object(chunk_t *object, asn1_t type, size_t datalen)
596 {
597 u_char length_buf[4];
598 chunk_t length = { length_buf, 0 };
599 u_char *pos;
600
601 /* code the asn.1 length field */
602 asn1_code_length(datalen, &length);
603
604 /* allocate memory for the asn.1 TLV object */
605 object->len = 1 + length.len + datalen;
606 object->ptr = malloc(object->len);
607
608 /* set position pointer at the start of the object */
609 pos = object->ptr;
610
611 /* copy the asn.1 tag field and advance the pointer */
612 *pos++ = type;
613
614 /* copy the asn.1 length field and advance the pointer */
615 memcpy(pos, length.ptr, length.len);
616 pos += length.len;
617
618 return pos;
619 }
620
621 /**
622 * Build a simple ASN.1 object
623 */
624 chunk_t asn1_simple_object(asn1_t tag, chunk_t content)
625 {
626 chunk_t object;
627
628 u_char *pos = asn1_build_object(&object, tag, content.len);
629 memcpy(pos, content.ptr, content.len);
630 pos += content.len;
631
632 return object;
633 }
634
635 /**
636 * Build an ASN.1 BITSTRING object
637 */
638 chunk_t asn1_bitstring(const char *mode, chunk_t content)
639 {
640 chunk_t object;
641 u_char *pos = asn1_build_object(&object, ASN1_BIT_STRING, 1 + content.len);
642
643 *pos++ = 0x00;
644 memcpy(pos, content.ptr, content.len);
645 if (*mode == 'm')
646 {
647 free(content.ptr);
648 }
649 return object;
650 }
651
652 /**
653 * Build an ASN.1 object from a variable number of individual chunks.
654 * Depending on the mode, chunks either are moved ('m') or copied ('c').
655 */
656 chunk_t asn1_wrap(asn1_t type, const char *mode, ...)
657 {
658 chunk_t construct;
659 va_list chunks;
660 u_char *pos;
661 int i;
662 int count = strlen(mode);
663
664 /* sum up lengths of individual chunks */
665 va_start(chunks, mode);
666 construct.len = 0;
667 for (i = 0; i < count; i++)
668 {
669 chunk_t ch = va_arg(chunks, chunk_t);
670 construct.len += ch.len;
671 }
672 va_end(chunks);
673
674 /* allocate needed memory for construct */
675 pos = asn1_build_object(&construct, type, construct.len);
676
677 /* copy or move the chunks */
678 va_start(chunks, mode);
679 for (i = 0; i < count; i++)
680 {
681 chunk_t ch = va_arg(chunks, chunk_t);
682
683 memcpy(pos, ch.ptr, ch.len);
684 pos += ch.len;
685
686 if (*mode++ == 'm')
687 {
688 free(ch.ptr);
689 }
690 }
691 va_end(chunks);
692
693 return construct;
694 }
695
696 /**
697 * ASN.1 definition of time
698 */
699 static const asn1Object_t timeObjects[] = {
700 { 0, "utcTime", ASN1_UTCTIME, ASN1_OPT|ASN1_BODY }, /* 0 */
701 { 0, "end opt", ASN1_EOC, ASN1_END }, /* 1 */
702 { 0, "generalizeTime", ASN1_GENERALIZEDTIME, ASN1_OPT|ASN1_BODY }, /* 2 */
703 { 0, "end opt", ASN1_EOC, ASN1_END }, /* 3 */
704 { 0, "exit", ASN1_EOC, ASN1_EXIT }
705 };
706 #define TIME_UTC 0
707 #define TIME_GENERALIZED 2
708
709 /**
710 * extracts and converts a UTCTIME or GENERALIZEDTIME object
711 */
712 time_t asn1_parse_time(chunk_t blob, int level0)
713 {
714 asn1_parser_t *parser;
715 chunk_t object;
716 int objectID;
717 time_t utc_time = 0;
718
719 parser= asn1_parser_create(timeObjects, blob);
720 parser->set_top_level(parser, level0);
721
722 while (parser->iterate(parser, &objectID, &object))
723 {
724 if (objectID == TIME_UTC || objectID == TIME_GENERALIZED)
725 {
726 utc_time = asn1_to_time(&object, (objectID == TIME_UTC)
727 ? ASN1_UTCTIME : ASN1_GENERALIZEDTIME);
728 }
729 }
730 parser->destroy(parser);
731 return utc_time;
732 }