Fix buffer overrun in ASN1_parse().
[openssl.git] / crypto / asn1 / asn1_par.c
1 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young (eay@cryptsoft.com).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young (eay@cryptsoft.com)"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.]
56  */
57
58 #include <stdio.h>
59 #include "internal/cryptlib.h"
60 #include <openssl/buffer.h>
61 #include <openssl/objects.h>
62 #include <openssl/asn1.h>
63
64 #ifndef ASN1_PARSE_MAXDEPTH
65 #define ASN1_PARSE_MAXDEPTH 128
66 #endif
67
68 static int asn1_print_info(BIO *bp, int tag, int xclass, int constructed,
69                            int indent);
70 static int asn1_parse2(BIO *bp, const unsigned char **pp, long length,
71                        int offset, int depth, int indent, int dump);
72 static int asn1_print_info(BIO *bp, int tag, int xclass, int constructed,
73                            int indent)
74 {
75     static const char fmt[] = "%-18s";
76     char str[128];
77     const char *p;
78
79     if (constructed & V_ASN1_CONSTRUCTED)
80         p = "cons: ";
81     else
82         p = "prim: ";
83     if (BIO_write(bp, p, 6) < 6)
84         goto err;
85     BIO_indent(bp, indent, 128);
86
87     p = str;
88     if ((xclass & V_ASN1_PRIVATE) == V_ASN1_PRIVATE)
89         BIO_snprintf(str, sizeof str, "priv [ %d ] ", tag);
90     else if ((xclass & V_ASN1_CONTEXT_SPECIFIC) == V_ASN1_CONTEXT_SPECIFIC)
91         BIO_snprintf(str, sizeof str, "cont [ %d ]", tag);
92     else if ((xclass & V_ASN1_APPLICATION) == V_ASN1_APPLICATION)
93         BIO_snprintf(str, sizeof str, "appl [ %d ]", tag);
94     else if (tag > 30)
95         BIO_snprintf(str, sizeof str, "<ASN1 %d>", tag);
96     else
97         p = ASN1_tag2str(tag);
98
99     if (BIO_printf(bp, fmt, p) <= 0)
100         goto err;
101     return (1);
102  err:
103     return (0);
104 }
105
106 int ASN1_parse(BIO *bp, const unsigned char *pp, long len, int indent)
107 {
108     return (asn1_parse2(bp, &pp, len, 0, 0, indent, 0));
109 }
110
111 int ASN1_parse_dump(BIO *bp, const unsigned char *pp, long len, int indent,
112                     int dump)
113 {
114     return (asn1_parse2(bp, &pp, len, 0, 0, indent, dump));
115 }
116
117 static int asn1_parse2(BIO *bp, const unsigned char **pp, long length,
118                        int offset, int depth, int indent, int dump)
119 {
120     const unsigned char *p, *ep, *tot, *op, *opp;
121     long len;
122     int tag, xclass, ret = 0;
123     int nl, hl, j, r;
124     ASN1_OBJECT *o = NULL;
125     ASN1_OCTET_STRING *os = NULL;
126     /* ASN1_BMPSTRING *bmp=NULL; */
127     int dump_indent, dump_cont = 0;
128
129     if (depth > ASN1_PARSE_MAXDEPTH) {
130             BIO_puts(bp, "BAD RECURSION DEPTH\n");
131             return 0;
132     }
133
134     dump_indent = 6;            /* Because we know BIO_dump_indent() */
135     p = *pp;
136     tot = p + length;
137     op = p - 1;
138     while ((p < tot) && (op < p)) {
139         op = p;
140         j = ASN1_get_object(&p, &len, &tag, &xclass, length);
141         if (j & 0x80) {
142             if (BIO_write(bp, "Error in encoding\n", 18) <= 0)
143                 goto end;
144             ret = 0;
145             goto end;
146         }
147         hl = (p - op);
148         length -= hl;
149         /*
150          * if j == 0x21 it is a constructed indefinite length object
151          */
152         if (BIO_printf(bp, "%5ld:", (long)offset + (long)(op - *pp))
153             <= 0)
154             goto end;
155
156         if (j != (V_ASN1_CONSTRUCTED | 1)) {
157             if (BIO_printf(bp, "d=%-2d hl=%ld l=%4ld ",
158                            depth, (long)hl, len) <= 0)
159                 goto end;
160         } else {
161             if (BIO_printf(bp, "d=%-2d hl=%ld l=inf  ", depth, (long)hl) <= 0)
162                 goto end;
163         }
164         if (!asn1_print_info(bp, tag, xclass, j, (indent) ? depth : 0))
165             goto end;
166         if (j & V_ASN1_CONSTRUCTED) {
167             const unsigned char *sp = p;
168                 
169             ep = p + len;
170             if (BIO_write(bp, "\n", 1) <= 0)
171                 goto end;
172             if (len > length) {
173                 BIO_printf(bp, "length is greater than %ld\n", length);
174                 ret = 0;
175                 goto end;
176             }
177             if ((j == 0x21) && (len == 0)) {
178                 for (;;) {
179                     r = asn1_parse2(bp, &p, (long)(tot - p),
180                                     offset + (p - *pp), depth + 1,
181                                     indent, dump);
182                     if (r == 0) {
183                         ret = 0;
184                         goto end;
185                     }
186                     if ((r == 2) || (p >= tot)) {
187                         len = p - sp;
188                         break;
189                     }
190                 }
191             } else {
192                 while (p < ep) {
193                     sp = p;
194                     r = asn1_parse2(bp, &p, len,
195                                     offset + (p - *pp), depth + 1,
196                                     indent, dump);
197                     if (r == 0) {
198                         ret = 0;
199                         goto end;
200                     }
201                     len -= p - sp;
202                 }
203                 len = length;
204             }
205         } else if (xclass != 0) {
206             p += len;
207             if (BIO_write(bp, "\n", 1) <= 0)
208                 goto end;
209         } else {
210             nl = 0;
211             if ((tag == V_ASN1_PRINTABLESTRING) ||
212                 (tag == V_ASN1_T61STRING) ||
213                 (tag == V_ASN1_IA5STRING) ||
214                 (tag == V_ASN1_VISIBLESTRING) ||
215                 (tag == V_ASN1_NUMERICSTRING) ||
216                 (tag == V_ASN1_UTF8STRING) ||
217                 (tag == V_ASN1_UTCTIME) || (tag == V_ASN1_GENERALIZEDTIME)) {
218                 if (BIO_write(bp, ":", 1) <= 0)
219                     goto end;
220                 if ((len > 0) && BIO_write(bp, (const char *)p, (int)len)
221                     != (int)len)
222                     goto end;
223             } else if (tag == V_ASN1_OBJECT) {
224                 opp = op;
225                 if (d2i_ASN1_OBJECT(&o, &opp, len + hl) != NULL) {
226                     if (BIO_write(bp, ":", 1) <= 0)
227                         goto end;
228                     i2a_ASN1_OBJECT(bp, o);
229                 } else {
230                     if (BIO_puts(bp, ":BAD OBJECT") <= 0)
231                         goto end;
232                     dump_cont = 1;
233                 }
234             } else if (tag == V_ASN1_BOOLEAN) {
235                 if (len != 1) {
236                     if (BIO_puts(bp, ":BAD BOOLEAN") <= 0)
237                         goto end;
238                     dump_cont = 1;
239                 }
240                 if (len > 0)
241                     BIO_printf(bp, ":%u", p[0]);
242             } else if (tag == V_ASN1_BMPSTRING) {
243                 /* do the BMP thang */
244             } else if (tag == V_ASN1_OCTET_STRING) {
245                 int i, printable = 1;
246
247                 opp = op;
248                 os = d2i_ASN1_OCTET_STRING(NULL, &opp, len + hl);
249                 if (os != NULL && os->length > 0) {
250                     opp = os->data;
251                     /*
252                      * testing whether the octet string is printable
253                      */
254                     for (i = 0; i < os->length; i++) {
255                         if (((opp[i] < ' ') &&
256                              (opp[i] != '\n') &&
257                              (opp[i] != '\r') &&
258                              (opp[i] != '\t')) || (opp[i] > '~')) {
259                             printable = 0;
260                             break;
261                         }
262                     }
263                     if (printable)
264                         /* printable string */
265                     {
266                         if (BIO_write(bp, ":", 1) <= 0)
267                             goto end;
268                         if (BIO_write(bp, (const char *)opp, os->length) <= 0)
269                             goto end;
270                     } else if (!dump)
271                         /*
272                          * not printable => print octet string as hex dump
273                          */
274                     {
275                         if (BIO_write(bp, "[HEX DUMP]:", 11) <= 0)
276                             goto end;
277                         for (i = 0; i < os->length; i++) {
278                             if (BIO_printf(bp, "%02X", opp[i]) <= 0)
279                                 goto end;
280                         }
281                     } else
282                         /* print the normal dump */
283                     {
284                         if (!nl) {
285                             if (BIO_write(bp, "\n", 1) <= 0)
286                                 goto end;
287                         }
288                         if (BIO_dump_indent(bp,
289                                             (const char *)opp,
290                                             ((dump == -1 || dump >
291                                               os->
292                                               length) ? os->length : dump),
293                                             dump_indent) <= 0)
294                             goto end;
295                         nl = 1;
296                     }
297                 }
298                 ASN1_OCTET_STRING_free(os);
299                 os = NULL;
300             } else if (tag == V_ASN1_INTEGER) {
301                 ASN1_INTEGER *bs;
302                 int i;
303
304                 opp = op;
305                 bs = d2i_ASN1_INTEGER(NULL, &opp, len + hl);
306                 if (bs != NULL) {
307                     if (BIO_write(bp, ":", 1) <= 0)
308                         goto end;
309                     if (bs->type == V_ASN1_NEG_INTEGER)
310                         if (BIO_write(bp, "-", 1) <= 0)
311                             goto end;
312                     for (i = 0; i < bs->length; i++) {
313                         if (BIO_printf(bp, "%02X", bs->data[i]) <= 0)
314                             goto end;
315                     }
316                     if (bs->length == 0) {
317                         if (BIO_write(bp, "00", 2) <= 0)
318                             goto end;
319                     }
320                 } else {
321                     if (BIO_puts(bp, ":BAD INTEGER") <= 0)
322                         goto end;
323                     dump_cont = 1;
324                 }
325                 ASN1_INTEGER_free(bs);
326             } else if (tag == V_ASN1_ENUMERATED) {
327                 ASN1_ENUMERATED *bs;
328                 int i;
329
330                 opp = op;
331                 bs = d2i_ASN1_ENUMERATED(NULL, &opp, len + hl);
332                 if (bs != NULL) {
333                     if (BIO_write(bp, ":", 1) <= 0)
334                         goto end;
335                     if (bs->type == V_ASN1_NEG_ENUMERATED)
336                         if (BIO_write(bp, "-", 1) <= 0)
337                             goto end;
338                     for (i = 0; i < bs->length; i++) {
339                         if (BIO_printf(bp, "%02X", bs->data[i]) <= 0)
340                             goto end;
341                     }
342                     if (bs->length == 0) {
343                         if (BIO_write(bp, "00", 2) <= 0)
344                             goto end;
345                     }
346                 } else {
347                     if (BIO_puts(bp, ":BAD ENUMERATED") <= 0)
348                         goto end;
349                     dump_cont = 1;
350                 }
351                 ASN1_ENUMERATED_free(bs);
352             } else if (len > 0 && dump) {
353                 if (!nl) {
354                     if (BIO_write(bp, "\n", 1) <= 0)
355                         goto end;
356                 }
357                 if (BIO_dump_indent(bp, (const char *)p,
358                                     ((dump == -1 || dump > len) ? len : dump),
359                                     dump_indent) <= 0)
360                     goto end;
361                 nl = 1;
362             }
363             if (dump_cont) {
364                 int i;
365                 const unsigned char *tmp = op + hl;
366                 if (BIO_puts(bp, ":[") <= 0)
367                     goto end;
368                 for (i = 0; i < len; i++) {
369                     if (BIO_printf(bp, "%02X", tmp[i]) <= 0)
370                         goto end;
371                 }
372                 if (BIO_puts(bp, "]") <= 0)
373                     goto end;
374             }
375
376             if (!nl) {
377                 if (BIO_write(bp, "\n", 1) <= 0)
378                     goto end;
379             }
380             p += len;
381             if ((tag == V_ASN1_EOC) && (xclass == 0)) {
382                 ret = 2;        /* End of sequence */
383                 goto end;
384             }
385         }
386         length -= len;
387     }
388     ret = 1;
389  end:
390     ASN1_OBJECT_free(o);
391     ASN1_OCTET_STRING_free(os);
392     *pp = p;
393     return (ret);
394 }
395
396 const char *ASN1_tag2str(int tag)
397 {
398     static const char *const tag2str[] = {
399         /* 0-4 */
400         "EOC", "BOOLEAN", "INTEGER", "BIT STRING", "OCTET STRING",
401         /* 5-9 */
402         "NULL", "OBJECT", "OBJECT DESCRIPTOR", "EXTERNAL", "REAL",
403         /* 10-13 */
404         "ENUMERATED", "<ASN1 11>", "UTF8STRING", "<ASN1 13>",
405         /* 15-17 */
406         "<ASN1 14>", "<ASN1 15>", "SEQUENCE", "SET",
407         /* 18-20 */
408         "NUMERICSTRING", "PRINTABLESTRING", "T61STRING",
409         /* 21-24 */
410         "VIDEOTEXSTRING", "IA5STRING", "UTCTIME", "GENERALIZEDTIME",
411         /* 25-27 */
412         "GRAPHICSTRING", "VISIBLESTRING", "GENERALSTRING",
413         /* 28-30 */
414         "UNIVERSALSTRING", "<ASN1 29>", "BMPSTRING"
415     };
416
417     if ((tag == V_ASN1_NEG_INTEGER) || (tag == V_ASN1_NEG_ENUMERATED))
418         tag &= ~0x100;
419
420     if (tag < 0 || tag > 30)
421         return "(unknown)";
422     return tag2str[tag];
423 }