Coverage Report

Created: 2024-11-21 07:03

/src/boringssl/crypto/asn1/tasn_dec.c
Line
Count
Source (jump to first uncovered line)
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
#include <openssl/asn1.h>
58
#include <openssl/asn1t.h>
59
#include <openssl/bytestring.h>
60
#include <openssl/err.h>
61
#include <openssl/mem.h>
62
#include <openssl/pool.h>
63
64
#include <assert.h>
65
#include <limits.h>
66
#include <string.h>
67
68
#include "../bytestring/internal.h"
69
#include "../internal.h"
70
#include "internal.h"
71
72
// Constructed types with a recursive definition (such as can be found in PKCS7)
73
// could eventually exceed the stack given malicious input with excessive
74
// recursion. Therefore we limit the stack depth. This is the maximum number of
75
// recursive invocations of asn1_item_embed_d2i().
76
0
#define ASN1_MAX_CONSTRUCTED_NEST 30
77
78
static int asn1_check_tlen(long *olen, int *otag, unsigned char *oclass,
79
                           char *cst, const unsigned char **in, long len,
80
                           int exptag, int expclass, char opt);
81
82
static int asn1_template_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
83
                                long len, const ASN1_TEMPLATE *tt, char opt,
84
                                CRYPTO_BUFFER *buf, int depth);
85
static int asn1_template_noexp_d2i(ASN1_VALUE **val, const unsigned char **in,
86
                                   long len, const ASN1_TEMPLATE *tt, char opt,
87
                                   CRYPTO_BUFFER *buf, int depth);
88
static int asn1_ex_c2i(ASN1_VALUE **pval, const unsigned char *cont, long len,
89
                       int utype, const ASN1_ITEM *it);
90
static int asn1_d2i_ex_primitive(ASN1_VALUE **pval, const unsigned char **in,
91
                                 long len, const ASN1_ITEM *it, int tag,
92
                                 int aclass, char opt);
93
static int asn1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
94
                            long len, const ASN1_ITEM *it, int tag, int aclass,
95
                            char opt, CRYPTO_BUFFER *buf, int depth);
96
97
// Table to convert tags to bit values, used for MSTRING type
98
static const unsigned long tag2bit[31] = {
99
    0,  // (reserved)
100
    0,  // BOOLEAN
101
    0,  // INTEGER
102
    B_ASN1_BIT_STRING,
103
    B_ASN1_OCTET_STRING,
104
    0,               // NULL
105
    0,               // OBJECT IDENTIFIER
106
    B_ASN1_UNKNOWN,  // ObjectDescriptor
107
    B_ASN1_UNKNOWN,  // EXTERNAL
108
    B_ASN1_UNKNOWN,  // REAL
109
    B_ASN1_UNKNOWN,  // ENUMERATED
110
    B_ASN1_UNKNOWN,  // EMBEDDED PDV
111
    B_ASN1_UTF8STRING,
112
    B_ASN1_UNKNOWN,  // RELATIVE-OID
113
    B_ASN1_UNKNOWN,  // TIME
114
    B_ASN1_UNKNOWN,  // (reserved)
115
    B_ASN1_SEQUENCE,
116
    0,  // SET
117
    B_ASN1_NUMERICSTRING,
118
    B_ASN1_PRINTABLESTRING,
119
    B_ASN1_T61STRING,
120
    B_ASN1_VIDEOTEXSTRING,
121
    B_ASN1_IA5STRING,
122
    B_ASN1_UTCTIME,
123
    B_ASN1_GENERALIZEDTIME,
124
    B_ASN1_GRAPHICSTRING,
125
    B_ASN1_ISO64STRING,
126
    B_ASN1_GENERALSTRING,
127
    B_ASN1_UNIVERSALSTRING,
128
    B_ASN1_UNKNOWN,  // CHARACTER STRING
129
    B_ASN1_BMPSTRING,
130
};
131
132
0
unsigned long ASN1_tag2bit(int tag) {
133
0
  if (tag < 0 || tag > 30) {
134
0
    return 0;
135
0
  }
136
0
  return tag2bit[tag];
137
0
}
138
139
0
static int is_supported_universal_type(int tag, int aclass) {
140
0
  if (aclass != V_ASN1_UNIVERSAL) {
141
0
    return 0;
142
0
  }
143
0
  return tag == V_ASN1_OBJECT || tag == V_ASN1_NULL || tag == V_ASN1_BOOLEAN ||
144
0
         tag == V_ASN1_BIT_STRING || tag == V_ASN1_INTEGER ||
145
0
         tag == V_ASN1_ENUMERATED || tag == V_ASN1_OCTET_STRING ||
146
0
         tag == V_ASN1_NUMERICSTRING || tag == V_ASN1_PRINTABLESTRING ||
147
0
         tag == V_ASN1_T61STRING || tag == V_ASN1_VIDEOTEXSTRING ||
148
0
         tag == V_ASN1_IA5STRING || tag == V_ASN1_UTCTIME ||
149
0
         tag == V_ASN1_GENERALIZEDTIME || tag == V_ASN1_GRAPHICSTRING ||
150
0
         tag == V_ASN1_VISIBLESTRING || tag == V_ASN1_GENERALSTRING ||
151
0
         tag == V_ASN1_UNIVERSALSTRING || tag == V_ASN1_BMPSTRING ||
152
0
         tag == V_ASN1_UTF8STRING || tag == V_ASN1_SET ||
153
0
         tag == V_ASN1_SEQUENCE;
154
0
}
155
156
// Macro to initialize and invalidate the cache
157
158
// Decode an ASN1 item, this currently behaves just like a standard 'd2i'
159
// function. 'in' points to a buffer to read the data from, in future we
160
// will have more advanced versions that can input data a piece at a time and
161
// this will simply be a special case.
162
163
ASN1_VALUE *ASN1_item_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,
164
0
                          const ASN1_ITEM *it) {
165
0
  ASN1_VALUE *ret = NULL;
166
0
  if (asn1_item_ex_d2i(&ret, in, len, it, /*tag=*/-1, /*aclass=*/0, /*opt=*/0,
167
0
                       /*buf=*/NULL, /*depth=*/0) <= 0) {
168
    // Clean up, in case the caller left a partial object.
169
    //
170
    // TODO(davidben): I don't think it can leave one, but the codepaths below
171
    // are a bit inconsistent. Revisit this when rewriting this function.
172
0
    ASN1_item_ex_free(&ret, it);
173
0
  }
174
175
  // If the caller supplied an output pointer, free the old one and replace it
176
  // with |ret|. This differs from OpenSSL slightly in that we don't support
177
  // object reuse. We run this on both success and failure. On failure, even
178
  // with object reuse, OpenSSL destroys the previous object.
179
0
  if (pval != NULL) {
180
0
    ASN1_item_ex_free(pval, it);
181
0
    *pval = ret;
182
0
  }
183
0
  return ret;
184
0
}
185
186
// Decode an item, taking care of IMPLICIT tagging, if any. If 'opt' set and
187
// tag mismatch return -1 to handle OPTIONAL
188
//
189
// TODO(davidben): Historically, all functions in this file had to account for
190
// |*pval| containing an arbitrary existing value. This is no longer the case
191
// because |ASN1_item_d2i| now always starts from NULL. As part of rewriting
192
// this function, take the simplified assumptions into account. Though we must
193
// still account for the internal calls to |ASN1_item_ex_new|.
194
195
static int asn1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
196
                            long len, const ASN1_ITEM *it, int tag, int aclass,
197
0
                            char opt, CRYPTO_BUFFER *buf, int depth) {
198
0
  const ASN1_TEMPLATE *tt, *errtt = NULL;
199
0
  const unsigned char *p = NULL, *q;
200
0
  unsigned char oclass;
201
0
  char cst, isopt;
202
0
  int i;
203
0
  int otag;
204
0
  int ret = 0;
205
0
  ASN1_VALUE **pchptr;
206
0
  if (!pval) {
207
0
    return 0;
208
0
  }
209
210
0
  if (buf != NULL) {
211
0
    assert(CRYPTO_BUFFER_data(buf) <= *in &&
212
0
           *in + len <= CRYPTO_BUFFER_data(buf) + CRYPTO_BUFFER_len(buf));
213
0
  }
214
215
  // Bound |len| to comfortably fit in an int. Lengths in this module often
216
  // switch between int and long without overflow checks.
217
0
  if (len > INT_MAX / 2) {
218
0
    len = INT_MAX / 2;
219
0
  }
220
221
0
  if (++depth > ASN1_MAX_CONSTRUCTED_NEST) {
222
0
    OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_TOO_DEEP);
223
0
    goto err;
224
0
  }
225
226
0
  switch (it->itype) {
227
0
    case ASN1_ITYPE_PRIMITIVE:
228
0
      if (it->templates) {
229
        // tagging or OPTIONAL is currently illegal on an item template
230
        // because the flags can't get passed down. In practice this
231
        // isn't a problem: we include the relevant flags from the item
232
        // template in the template itself.
233
0
        if ((tag != -1) || opt) {
234
0
          OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE);
235
0
          goto err;
236
0
        }
237
0
        return asn1_template_ex_d2i(pval, in, len, it->templates, opt, buf,
238
0
                                    depth);
239
0
      }
240
0
      return asn1_d2i_ex_primitive(pval, in, len, it, tag, aclass, opt);
241
0
      break;
242
243
0
    case ASN1_ITYPE_MSTRING:
244
      // It never makes sense for multi-strings to have implicit tagging, so
245
      // if tag != -1, then this looks like an error in the template.
246
0
      if (tag != -1) {
247
0
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE);
248
0
        goto err;
249
0
      }
250
251
0
      p = *in;
252
      // Just read in tag and class
253
0
      ret = asn1_check_tlen(NULL, &otag, &oclass, NULL, &p, len, -1, 0, 1);
254
0
      if (!ret) {
255
0
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
256
0
        goto err;
257
0
      }
258
259
      // Must be UNIVERSAL class
260
0
      if (oclass != V_ASN1_UNIVERSAL) {
261
        // If OPTIONAL, assume this is OK
262
0
        if (opt) {
263
0
          return -1;
264
0
        }
265
0
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_MSTRING_NOT_UNIVERSAL);
266
0
        goto err;
267
0
      }
268
      // Check tag matches bit map
269
0
      if (!(ASN1_tag2bit(otag) & it->utype)) {
270
        // If OPTIONAL, assume this is OK
271
0
        if (opt) {
272
0
          return -1;
273
0
        }
274
0
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_MSTRING_WRONG_TAG);
275
0
        goto err;
276
0
      }
277
0
      return asn1_d2i_ex_primitive(pval, in, len, it, otag, 0, 0);
278
279
0
    case ASN1_ITYPE_EXTERN: {
280
      // We don't support implicit tagging with external types.
281
0
      if (tag != -1) {
282
0
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE);
283
0
        goto err;
284
0
      }
285
0
      const ASN1_EXTERN_FUNCS *ef = it->funcs;
286
0
      return ef->asn1_ex_d2i(pval, in, len, it, opt, NULL);
287
0
    }
288
289
0
    case ASN1_ITYPE_CHOICE: {
290
      // It never makes sense for CHOICE types to have implicit tagging, so if
291
      // tag != -1, then this looks like an error in the template.
292
0
      if (tag != -1) {
293
0
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE);
294
0
        goto err;
295
0
      }
296
297
0
      const ASN1_AUX *aux = it->funcs;
298
0
      ASN1_aux_cb *asn1_cb = aux != NULL ? aux->asn1_cb : NULL;
299
0
      if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL)) {
300
0
        goto auxerr;
301
0
      }
302
303
0
      if (*pval) {
304
        // Free up and zero CHOICE value if initialised
305
0
        i = asn1_get_choice_selector(pval, it);
306
0
        if ((i >= 0) && (i < it->tcount)) {
307
0
          tt = it->templates + i;
308
0
          pchptr = asn1_get_field_ptr(pval, tt);
309
0
          ASN1_template_free(pchptr, tt);
310
0
          asn1_set_choice_selector(pval, -1, it);
311
0
        }
312
0
      } else if (!ASN1_item_ex_new(pval, it)) {
313
0
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
314
0
        goto err;
315
0
      }
316
      // CHOICE type, try each possibility in turn
317
0
      p = *in;
318
0
      for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
319
0
        pchptr = asn1_get_field_ptr(pval, tt);
320
        // We mark field as OPTIONAL so its absence can be recognised.
321
0
        ret = asn1_template_ex_d2i(pchptr, &p, len, tt, 1, buf, depth);
322
        // If field not present, try the next one
323
0
        if (ret == -1) {
324
0
          continue;
325
0
        }
326
        // If positive return, read OK, break loop
327
0
        if (ret > 0) {
328
0
          break;
329
0
        }
330
        // Otherwise must be an ASN1 parsing error
331
0
        errtt = tt;
332
0
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
333
0
        goto err;
334
0
      }
335
336
      // Did we fall off the end without reading anything?
337
0
      if (i == it->tcount) {
338
        // If OPTIONAL, this is OK
339
0
        if (opt) {
340
          // Free and zero it
341
0
          ASN1_item_ex_free(pval, it);
342
0
          return -1;
343
0
        }
344
0
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_NO_MATCHING_CHOICE_TYPE);
345
0
        goto err;
346
0
      }
347
348
0
      asn1_set_choice_selector(pval, i, it);
349
0
      if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL)) {
350
0
        goto auxerr;
351
0
      }
352
0
      *in = p;
353
0
      return 1;
354
0
    }
355
356
0
    case ASN1_ITYPE_SEQUENCE: {
357
0
      p = *in;
358
359
      // If no IMPLICIT tagging set to SEQUENCE, UNIVERSAL
360
0
      if (tag == -1) {
361
0
        tag = V_ASN1_SEQUENCE;
362
0
        aclass = V_ASN1_UNIVERSAL;
363
0
      }
364
      // Get SEQUENCE length and update len, p
365
0
      ret = asn1_check_tlen(&len, NULL, NULL, &cst, &p, len, tag, aclass, opt);
366
0
      if (!ret) {
367
0
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
368
0
        goto err;
369
0
      } else if (ret == -1) {
370
0
        return -1;
371
0
      }
372
0
      if (!cst) {
373
0
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_SEQUENCE_NOT_CONSTRUCTED);
374
0
        goto err;
375
0
      }
376
377
0
      if (!*pval && !ASN1_item_ex_new(pval, it)) {
378
0
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
379
0
        goto err;
380
0
      }
381
382
0
      const ASN1_AUX *aux = it->funcs;
383
0
      ASN1_aux_cb *asn1_cb = aux != NULL ? aux->asn1_cb : NULL;
384
0
      if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, NULL)) {
385
0
        goto auxerr;
386
0
      }
387
388
      // Free up and zero any ADB found
389
0
      for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
390
0
        if (tt->flags & ASN1_TFLG_ADB_MASK) {
391
0
          const ASN1_TEMPLATE *seqtt;
392
0
          ASN1_VALUE **pseqval;
393
0
          seqtt = asn1_do_adb(pval, tt, 0);
394
0
          if (seqtt == NULL) {
395
0
            continue;
396
0
          }
397
0
          pseqval = asn1_get_field_ptr(pval, seqtt);
398
0
          ASN1_template_free(pseqval, seqtt);
399
0
        }
400
0
      }
401
402
      // Get each field entry
403
0
      for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
404
0
        const ASN1_TEMPLATE *seqtt;
405
0
        ASN1_VALUE **pseqval;
406
0
        seqtt = asn1_do_adb(pval, tt, 1);
407
0
        if (seqtt == NULL) {
408
0
          goto err;
409
0
        }
410
0
        pseqval = asn1_get_field_ptr(pval, seqtt);
411
        // Have we ran out of data?
412
0
        if (!len) {
413
0
          break;
414
0
        }
415
0
        q = p;
416
        // This determines the OPTIONAL flag value. The field cannot be
417
        // omitted if it is the last of a SEQUENCE and there is still
418
        // data to be read. This isn't strictly necessary but it
419
        // increases efficiency in some cases.
420
0
        if (i == (it->tcount - 1)) {
421
0
          isopt = 0;
422
0
        } else {
423
0
          isopt = (seqtt->flags & ASN1_TFLG_OPTIONAL) != 0;
424
0
        }
425
        // attempt to read in field, allowing each to be OPTIONAL
426
427
0
        ret = asn1_template_ex_d2i(pseqval, &p, len, seqtt, isopt, buf, depth);
428
0
        if (!ret) {
429
0
          errtt = seqtt;
430
0
          goto err;
431
0
        } else if (ret == -1) {
432
          // OPTIONAL component absent. Free and zero the field.
433
0
          ASN1_template_free(pseqval, seqtt);
434
0
          continue;
435
0
        }
436
        // Update length
437
0
        len -= p - q;
438
0
      }
439
440
      // Check all data read
441
0
      if (len) {
442
0
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_SEQUENCE_LENGTH_MISMATCH);
443
0
        goto err;
444
0
      }
445
446
      // If we get here we've got no more data in the SEQUENCE, however we
447
      // may not have read all fields so check all remaining are OPTIONAL
448
      // and clear any that are.
449
0
      for (; i < it->tcount; tt++, i++) {
450
0
        const ASN1_TEMPLATE *seqtt;
451
0
        seqtt = asn1_do_adb(pval, tt, 1);
452
0
        if (seqtt == NULL) {
453
0
          goto err;
454
0
        }
455
0
        if (seqtt->flags & ASN1_TFLG_OPTIONAL) {
456
0
          ASN1_VALUE **pseqval;
457
0
          pseqval = asn1_get_field_ptr(pval, seqtt);
458
0
          ASN1_template_free(pseqval, seqtt);
459
0
        } else {
460
0
          errtt = seqtt;
461
0
          OPENSSL_PUT_ERROR(ASN1, ASN1_R_FIELD_MISSING);
462
0
          goto err;
463
0
        }
464
0
      }
465
      // Save encoding
466
0
      if (!asn1_enc_save(pval, *in, p - *in, it, buf)) {
467
0
        goto auxerr;
468
0
      }
469
0
      if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, NULL)) {
470
0
        goto auxerr;
471
0
      }
472
0
      *in = p;
473
0
      return 1;
474
0
    }
475
476
0
    default:
477
0
      return 0;
478
0
  }
479
0
auxerr:
480
0
  OPENSSL_PUT_ERROR(ASN1, ASN1_R_AUX_ERROR);
481
0
err:
482
0
  ASN1_item_ex_free(pval, it);
483
0
  if (errtt) {
484
0
    ERR_add_error_data(4, "Field=", errtt->field_name, ", Type=", it->sname);
485
0
  } else {
486
0
    ERR_add_error_data(2, "Type=", it->sname);
487
0
  }
488
0
  return 0;
489
0
}
490
491
int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,
492
                     const ASN1_ITEM *it, int tag, int aclass, char opt,
493
0
                     CRYPTO_BUFFER *buf) {
494
0
  return asn1_item_ex_d2i(pval, in, len, it, tag, aclass, opt, buf,
495
0
                          /*depth=*/0);
496
0
}
497
498
// Templates are handled with two separate functions. One handles any
499
// EXPLICIT tag and the other handles the rest.
500
501
static int asn1_template_ex_d2i(ASN1_VALUE **val, const unsigned char **in,
502
                                long inlen, const ASN1_TEMPLATE *tt, char opt,
503
0
                                CRYPTO_BUFFER *buf, int depth) {
504
0
  int aclass;
505
0
  int ret;
506
0
  long len;
507
0
  const unsigned char *p, *q;
508
0
  if (!val) {
509
0
    return 0;
510
0
  }
511
0
  uint32_t flags = tt->flags;
512
0
  aclass = flags & ASN1_TFLG_TAG_CLASS;
513
514
0
  p = *in;
515
516
  // Check if EXPLICIT tag expected
517
0
  if (flags & ASN1_TFLG_EXPTAG) {
518
0
    char cst;
519
    // Need to work out amount of data available to the inner content and
520
    // where it starts: so read in EXPLICIT header to get the info.
521
0
    ret = asn1_check_tlen(&len, NULL, NULL, &cst, &p, inlen, tt->tag, aclass,
522
0
                          opt);
523
0
    q = p;
524
0
    if (!ret) {
525
0
      OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
526
0
      return 0;
527
0
    } else if (ret == -1) {
528
0
      return -1;
529
0
    }
530
0
    if (!cst) {
531
0
      OPENSSL_PUT_ERROR(ASN1, ASN1_R_EXPLICIT_TAG_NOT_CONSTRUCTED);
532
0
      return 0;
533
0
    }
534
    // We've found the field so it can't be OPTIONAL now
535
0
    ret = asn1_template_noexp_d2i(val, &p, len, tt, /*opt=*/0, buf, depth);
536
0
    if (!ret) {
537
0
      OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
538
0
      return 0;
539
0
    }
540
    // We read the field in OK so update length
541
0
    len -= p - q;
542
    // Check for trailing data.
543
0
    if (len) {
544
0
      OPENSSL_PUT_ERROR(ASN1, ASN1_R_EXPLICIT_LENGTH_MISMATCH);
545
0
      goto err;
546
0
    }
547
0
  } else {
548
0
    return asn1_template_noexp_d2i(val, in, inlen, tt, opt, buf, depth);
549
0
  }
550
551
0
  *in = p;
552
0
  return 1;
553
554
0
err:
555
0
  ASN1_template_free(val, tt);
556
0
  return 0;
557
0
}
558
559
static int asn1_template_noexp_d2i(ASN1_VALUE **val, const unsigned char **in,
560
                                   long len, const ASN1_TEMPLATE *tt, char opt,
561
0
                                   CRYPTO_BUFFER *buf, int depth) {
562
0
  int aclass;
563
0
  int ret;
564
0
  const unsigned char *p;
565
0
  if (!val) {
566
0
    return 0;
567
0
  }
568
0
  uint32_t flags = tt->flags;
569
0
  aclass = flags & ASN1_TFLG_TAG_CLASS;
570
571
0
  p = *in;
572
573
0
  if (flags & ASN1_TFLG_SK_MASK) {
574
    // SET OF, SEQUENCE OF
575
0
    int sktag, skaclass;
576
    // First work out expected inner tag value
577
0
    if (flags & ASN1_TFLG_IMPTAG) {
578
0
      sktag = tt->tag;
579
0
      skaclass = aclass;
580
0
    } else {
581
0
      skaclass = V_ASN1_UNIVERSAL;
582
0
      if (flags & ASN1_TFLG_SET_OF) {
583
0
        sktag = V_ASN1_SET;
584
0
      } else {
585
0
        sktag = V_ASN1_SEQUENCE;
586
0
      }
587
0
    }
588
    // Get the tag
589
0
    ret =
590
0
        asn1_check_tlen(&len, NULL, NULL, NULL, &p, len, sktag, skaclass, opt);
591
0
    if (!ret) {
592
0
      OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
593
0
      return 0;
594
0
    } else if (ret == -1) {
595
0
      return -1;
596
0
    }
597
0
    if (!*val) {
598
0
      *val = (ASN1_VALUE *)sk_ASN1_VALUE_new_null();
599
0
    } else {
600
      // We've got a valid STACK: free up any items present
601
0
      STACK_OF(ASN1_VALUE) *sktmp = (STACK_OF(ASN1_VALUE) *)*val;
602
0
      ASN1_VALUE *vtmp;
603
0
      while (sk_ASN1_VALUE_num(sktmp) > 0) {
604
0
        vtmp = sk_ASN1_VALUE_pop(sktmp);
605
0
        ASN1_item_ex_free(&vtmp, ASN1_ITEM_ptr(tt->item));
606
0
      }
607
0
    }
608
609
0
    if (!*val) {
610
0
      goto err;
611
0
    }
612
613
    // Read as many items as we can
614
0
    while (len > 0) {
615
0
      ASN1_VALUE *skfield;
616
0
      const unsigned char *q = p;
617
0
      skfield = NULL;
618
0
      if (!asn1_item_ex_d2i(&skfield, &p, len, ASN1_ITEM_ptr(tt->item),
619
0
                            /*tag=*/-1, /*aclass=*/0, /*opt=*/0, buf, depth)) {
620
0
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
621
0
        goto err;
622
0
      }
623
0
      len -= p - q;
624
0
      if (!sk_ASN1_VALUE_push((STACK_OF(ASN1_VALUE) *)*val, skfield)) {
625
0
        ASN1_item_ex_free(&skfield, ASN1_ITEM_ptr(tt->item));
626
0
        goto err;
627
0
      }
628
0
    }
629
0
  } else if (flags & ASN1_TFLG_IMPTAG) {
630
    // IMPLICIT tagging
631
0
    ret = asn1_item_ex_d2i(val, &p, len, ASN1_ITEM_ptr(tt->item), tt->tag,
632
0
                           aclass, opt, buf, depth);
633
0
    if (!ret) {
634
0
      OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
635
0
      goto err;
636
0
    } else if (ret == -1) {
637
0
      return -1;
638
0
    }
639
0
  } else {
640
    // Nothing special
641
0
    ret = asn1_item_ex_d2i(val, &p, len, ASN1_ITEM_ptr(tt->item), /*tag=*/-1,
642
0
                           /*aclass=*/0, opt, buf, depth);
643
0
    if (!ret) {
644
0
      OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
645
0
      goto err;
646
0
    } else if (ret == -1) {
647
0
      return -1;
648
0
    }
649
0
  }
650
651
0
  *in = p;
652
0
  return 1;
653
654
0
err:
655
0
  ASN1_template_free(val, tt);
656
0
  return 0;
657
0
}
658
659
static int asn1_d2i_ex_primitive(ASN1_VALUE **pval, const unsigned char **in,
660
                                 long inlen, const ASN1_ITEM *it, int tag,
661
0
                                 int aclass, char opt) {
662
0
  int ret = 0, utype;
663
0
  long plen;
664
0
  char cst;
665
0
  const unsigned char *p;
666
0
  const unsigned char *cont = NULL;
667
0
  long len;
668
0
  if (!pval) {
669
0
    OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_NULL);
670
0
    return 0;  // Should never happen
671
0
  }
672
673
0
  if (it->itype == ASN1_ITYPE_MSTRING) {
674
0
    utype = tag;
675
0
    tag = -1;
676
0
  } else {
677
0
    utype = it->utype;
678
0
  }
679
680
0
  if (utype == V_ASN1_ANY) {
681
    // If type is ANY need to figure out type from tag
682
0
    unsigned char oclass;
683
0
    if (tag >= 0) {
684
0
      OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_TAGGED_ANY);
685
0
      return 0;
686
0
    }
687
0
    if (opt) {
688
0
      OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_OPTIONAL_ANY);
689
0
      return 0;
690
0
    }
691
0
    p = *in;
692
0
    ret = asn1_check_tlen(NULL, &utype, &oclass, NULL, &p, inlen, -1, 0, 0);
693
0
    if (!ret) {
694
0
      OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
695
0
      return 0;
696
0
    }
697
0
    if (!is_supported_universal_type(utype, oclass)) {
698
0
      utype = V_ASN1_OTHER;
699
0
    }
700
0
  }
701
0
  if (tag == -1) {
702
0
    tag = utype;
703
0
    aclass = V_ASN1_UNIVERSAL;
704
0
  }
705
0
  p = *in;
706
  // Check header
707
0
  ret = asn1_check_tlen(&plen, NULL, NULL, &cst, &p, inlen, tag, aclass, opt);
708
0
  if (!ret) {
709
0
    OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
710
0
    return 0;
711
0
  } else if (ret == -1) {
712
0
    return -1;
713
0
  }
714
0
  ret = 0;
715
  // SEQUENCE, SET and "OTHER" are left in encoded form
716
0
  if ((utype == V_ASN1_SEQUENCE) || (utype == V_ASN1_SET) ||
717
0
      (utype == V_ASN1_OTHER)) {
718
    // SEQUENCE and SET must be constructed
719
0
    if (utype != V_ASN1_OTHER && !cst) {
720
0
      OPENSSL_PUT_ERROR(ASN1, ASN1_R_TYPE_NOT_CONSTRUCTED);
721
0
      return 0;
722
0
    }
723
724
0
    cont = *in;
725
0
    len = p - cont + plen;
726
0
    p += plen;
727
0
  } else if (cst) {
728
    // This parser historically supported BER constructed strings. We no
729
    // longer do and will gradually tighten this parser into a DER
730
    // parser. BER types should use |CBS_asn1_ber_to_der|.
731
0
    OPENSSL_PUT_ERROR(ASN1, ASN1_R_TYPE_NOT_PRIMITIVE);
732
0
    return 0;
733
0
  } else {
734
0
    cont = p;
735
0
    len = plen;
736
0
    p += plen;
737
0
  }
738
739
  // We now have content length and type: translate into a structure
740
0
  if (!asn1_ex_c2i(pval, cont, len, utype, it)) {
741
0
    goto err;
742
0
  }
743
744
0
  *in = p;
745
0
  ret = 1;
746
0
err:
747
0
  return ret;
748
0
}
749
750
// Translate ASN1 content octets into a structure
751
752
static int asn1_ex_c2i(ASN1_VALUE **pval, const unsigned char *cont, long len,
753
0
                       int utype, const ASN1_ITEM *it) {
754
0
  ASN1_VALUE **opval = NULL;
755
0
  ASN1_STRING *stmp;
756
0
  ASN1_TYPE *typ = NULL;
757
0
  int ret = 0;
758
0
  ASN1_INTEGER **tint;
759
760
  // Historically, |it->funcs| for primitive types contained an
761
  // |ASN1_PRIMITIVE_FUNCS| table of callbacks.
762
0
  assert(it->funcs == NULL);
763
764
  // If ANY type clear type and set pointer to internal value
765
0
  if (it->utype == V_ASN1_ANY) {
766
0
    if (!*pval) {
767
0
      typ = ASN1_TYPE_new();
768
0
      if (typ == NULL) {
769
0
        goto err;
770
0
      }
771
0
      *pval = (ASN1_VALUE *)typ;
772
0
    } else {
773
0
      typ = (ASN1_TYPE *)*pval;
774
0
    }
775
776
0
    if (utype != typ->type) {
777
0
      ASN1_TYPE_set(typ, utype, NULL);
778
0
    }
779
0
    opval = pval;
780
0
    pval = &typ->value.asn1_value;
781
0
  }
782
0
  switch (utype) {
783
0
    case V_ASN1_OBJECT:
784
0
      if (!c2i_ASN1_OBJECT((ASN1_OBJECT **)pval, &cont, len)) {
785
0
        goto err;
786
0
      }
787
0
      break;
788
789
0
    case V_ASN1_NULL:
790
0
      if (len) {
791
0
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_NULL_IS_WRONG_LENGTH);
792
0
        goto err;
793
0
      }
794
0
      *pval = (ASN1_VALUE *)1;
795
0
      break;
796
797
0
    case V_ASN1_BOOLEAN:
798
0
      if (len != 1) {
799
0
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_BOOLEAN_IS_WRONG_LENGTH);
800
0
        goto err;
801
0
      } else {
802
0
        ASN1_BOOLEAN *tbool;
803
0
        tbool = (ASN1_BOOLEAN *)pval;
804
0
        *tbool = *cont;
805
0
      }
806
0
      break;
807
808
0
    case V_ASN1_BIT_STRING:
809
0
      if (!c2i_ASN1_BIT_STRING((ASN1_BIT_STRING **)pval, &cont, len)) {
810
0
        goto err;
811
0
      }
812
0
      break;
813
814
0
    case V_ASN1_INTEGER:
815
0
    case V_ASN1_ENUMERATED:
816
0
      tint = (ASN1_INTEGER **)pval;
817
0
      if (!c2i_ASN1_INTEGER(tint, &cont, len)) {
818
0
        goto err;
819
0
      }
820
      // Fixup type to match the expected form
821
0
      (*tint)->type = utype | ((*tint)->type & V_ASN1_NEG);
822
0
      break;
823
824
0
    case V_ASN1_OCTET_STRING:
825
0
    case V_ASN1_NUMERICSTRING:
826
0
    case V_ASN1_PRINTABLESTRING:
827
0
    case V_ASN1_T61STRING:
828
0
    case V_ASN1_VIDEOTEXSTRING:
829
0
    case V_ASN1_IA5STRING:
830
0
    case V_ASN1_UTCTIME:
831
0
    case V_ASN1_GENERALIZEDTIME:
832
0
    case V_ASN1_GRAPHICSTRING:
833
0
    case V_ASN1_VISIBLESTRING:
834
0
    case V_ASN1_GENERALSTRING:
835
0
    case V_ASN1_UNIVERSALSTRING:
836
0
    case V_ASN1_BMPSTRING:
837
0
    case V_ASN1_UTF8STRING:
838
0
    case V_ASN1_OTHER:
839
0
    case V_ASN1_SET:
840
0
    case V_ASN1_SEQUENCE:
841
    // TODO(crbug.com/boringssl/412): This default case should be removed, now
842
    // that we've resolved https://crbug.com/boringssl/561. However, it is still
843
    // needed to support some edge cases in |ASN1_PRINTABLE|. |ASN1_PRINTABLE|
844
    // broadly doesn't tolerate unrecognized universal tags, but except for
845
    // eight values that map to |B_ASN1_UNKNOWN| instead of zero. See the
846
    // X509Test.NameAttributeValues test.
847
0
    default: {
848
0
      CBS cbs;
849
0
      CBS_init(&cbs, cont, (size_t)len);
850
0
      if (utype == V_ASN1_BMPSTRING) {
851
0
        while (CBS_len(&cbs) != 0) {
852
0
          uint32_t c;
853
0
          if (!CBS_get_ucs2_be(&cbs, &c)) {
854
0
            OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_BMPSTRING);
855
0
            goto err;
856
0
          }
857
0
        }
858
0
      }
859
0
      if (utype == V_ASN1_UNIVERSALSTRING) {
860
0
        while (CBS_len(&cbs) != 0) {
861
0
          uint32_t c;
862
0
          if (!CBS_get_utf32_be(&cbs, &c)) {
863
0
            OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_UNIVERSALSTRING);
864
0
            goto err;
865
0
          }
866
0
        }
867
0
      }
868
0
      if (utype == V_ASN1_UTF8STRING) {
869
0
        while (CBS_len(&cbs) != 0) {
870
0
          uint32_t c;
871
0
          if (!CBS_get_utf8(&cbs, &c)) {
872
0
            OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_UTF8STRING);
873
0
            goto err;
874
0
          }
875
0
        }
876
0
      }
877
0
      if (utype == V_ASN1_UTCTIME) {
878
0
        if (!CBS_parse_utc_time(&cbs, NULL, /*allow_timezone_offset=*/1)) {
879
0
          OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_TIME_FORMAT);
880
0
          goto err;
881
0
        }
882
0
      }
883
0
      if (utype == V_ASN1_GENERALIZEDTIME) {
884
0
        if (!CBS_parse_generalized_time(&cbs, NULL,
885
0
                                        /*allow_timezone_offset=*/0)) {
886
0
          OPENSSL_PUT_ERROR(ASN1, ASN1_R_INVALID_TIME_FORMAT);
887
0
          goto err;
888
0
        }
889
0
      }
890
      // TODO(https://crbug.com/boringssl/427): Check other string types.
891
892
      // All based on ASN1_STRING and handled the same
893
0
      if (!*pval) {
894
0
        stmp = ASN1_STRING_type_new(utype);
895
0
        if (!stmp) {
896
0
          goto err;
897
0
        }
898
0
        *pval = (ASN1_VALUE *)stmp;
899
0
      } else {
900
0
        stmp = (ASN1_STRING *)*pval;
901
0
        stmp->type = utype;
902
0
      }
903
0
      if (!ASN1_STRING_set(stmp, cont, len)) {
904
0
        ASN1_STRING_free(stmp);
905
0
        *pval = NULL;
906
0
        goto err;
907
0
      }
908
0
      break;
909
0
    }
910
0
  }
911
  // If ASN1_ANY and NULL type fix up value
912
0
  if (typ && (utype == V_ASN1_NULL)) {
913
0
    typ->value.ptr = NULL;
914
0
  }
915
916
0
  ret = 1;
917
0
err:
918
0
  if (!ret) {
919
0
    ASN1_TYPE_free(typ);
920
0
    if (opval) {
921
0
      *opval = NULL;
922
0
    }
923
0
  }
924
0
  return ret;
925
0
}
926
927
// Check an ASN1 tag and length: a bit like ASN1_get_object but it
928
// checks the expected tag.
929
930
static int asn1_check_tlen(long *olen, int *otag, unsigned char *oclass,
931
                           char *cst, const unsigned char **in, long len,
932
0
                           int exptag, int expclass, char opt) {
933
0
  int i;
934
0
  int ptag, pclass;
935
0
  long plen;
936
0
  const unsigned char *p;
937
0
  p = *in;
938
939
0
  i = ASN1_get_object(&p, &plen, &ptag, &pclass, len);
940
0
  if (i & 0x80) {
941
0
    OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_OBJECT_HEADER);
942
0
    return 0;
943
0
  }
944
0
  if (exptag >= 0) {
945
0
    if ((exptag != ptag) || (expclass != pclass)) {
946
      // If type is OPTIONAL, not an error: indicate missing type.
947
0
      if (opt) {
948
0
        return -1;
949
0
      }
950
0
      OPENSSL_PUT_ERROR(ASN1, ASN1_R_WRONG_TAG);
951
0
      return 0;
952
0
    }
953
0
  }
954
955
0
  if (cst) {
956
0
    *cst = i & V_ASN1_CONSTRUCTED;
957
0
  }
958
959
0
  if (olen) {
960
0
    *olen = plen;
961
0
  }
962
963
0
  if (oclass) {
964
0
    *oclass = pclass;
965
0
  }
966
967
0
  if (otag) {
968
0
    *otag = ptag;
969
0
  }
970
971
0
  *in = p;
972
0
  return 1;
973
0
}