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