Coverage Report

Created: 2026-04-30 06:12

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/boringssl/crypto/asn1/tasn_dec.cc
Line
Count
Source
1
// Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved.
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//     https://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
15
#include <openssl/asn1.h>
16
#include <openssl/asn1t.h>
17
#include <openssl/bytestring.h>
18
#include <openssl/err.h>
19
#include <openssl/mem.h>
20
#include <openssl/pool.h>
21
22
#include <assert.h>
23
#include <limits.h>
24
#include <string.h>
25
26
#include "../bytestring/internal.h"
27
#include "../internal.h"
28
#include "internal.h"
29
30
31
using namespace bssl;
32
33
// Constructed types with a recursive definition (such as can be found in PKCS7)
34
// could eventually exceed the stack given malicious input with excessive
35
// recursion. Therefore we limit the stack depth. This is the maximum number of
36
// recursive invocations of asn1_item_embed_d2i().
37
4.04M
#define ASN1_MAX_CONSTRUCTED_NEST 30
38
39
static int asn1_check_tlen(long *olen, int *otag, unsigned char *oclass,
40
                           char *cst, const unsigned char **in, long len,
41
                           int exptag, int expclass, char opt);
42
43
static int asn1_template_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
44
                                long len, const ASN1_TEMPLATE *tt, char opt,
45
                                int depth);
46
static int asn1_template_noexp_d2i(ASN1_VALUE **val, const unsigned char **in,
47
                                   long len, const ASN1_TEMPLATE *tt, char opt,
48
                                   int depth);
49
static int asn1_d2i_ex_primitive(ASN1_VALUE **pval, const unsigned char **in,
50
                                 long len, const ASN1_ITEM *it, int tag,
51
                                 int aclass, char opt);
52
static int asn1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
53
                            long len, const ASN1_ITEM *it, int tag, int aclass,
54
                            char opt, int depth);
55
56
168k
unsigned long ASN1_tag2bit(int tag) {
57
168k
  switch (tag) {
58
3
    case V_ASN1_BIT_STRING:
59
3
      return B_ASN1_BIT_STRING;
60
0
    case V_ASN1_OCTET_STRING:
61
0
      return B_ASN1_OCTET_STRING;
62
1.44k
    case V_ASN1_UTF8STRING:
63
1.44k
      return B_ASN1_UTF8STRING;
64
5
    case V_ASN1_SEQUENCE:
65
5
      return B_ASN1_SEQUENCE;
66
0
    case V_ASN1_NUMERICSTRING:
67
0
      return B_ASN1_NUMERICSTRING;
68
1.35k
    case V_ASN1_PRINTABLESTRING:
69
1.35k
      return B_ASN1_PRINTABLESTRING;
70
4.43k
    case V_ASN1_T61STRING:
71
4.43k
      return B_ASN1_T61STRING;
72
4
    case V_ASN1_VIDEOTEXSTRING:
73
4
      return B_ASN1_VIDEOTEXSTRING;
74
4.23k
    case V_ASN1_IA5STRING:
75
4.23k
      return B_ASN1_IA5STRING;
76
3
    case V_ASN1_UTCTIME:
77
3
      return B_ASN1_UTCTIME;
78
3
    case V_ASN1_GENERALIZEDTIME:
79
3
      return B_ASN1_GENERALIZEDTIME;
80
1
    case V_ASN1_GRAPHICSTRING:
81
1
      return B_ASN1_GRAPHICSTRING;
82
38
    case V_ASN1_ISO64STRING:
83
38
      return B_ASN1_ISO64STRING;
84
6
    case V_ASN1_GENERALSTRING:
85
6
      return B_ASN1_GENERALSTRING;
86
150k
    case V_ASN1_UNIVERSALSTRING:
87
150k
      return B_ASN1_UNIVERSALSTRING;
88
5.96k
    case V_ASN1_BMPSTRING:
89
5.96k
      return B_ASN1_BMPSTRING;
90
17
    default:
91
17
      return 0;
92
168k
  }
93
168k
}
94
95
// Decode an ASN1 item, this currently behaves just like a standard 'd2i'
96
// function. 'in' points to a buffer to read the data from, in future we
97
// will have more advanced versions that can input data a piece at a time and
98
// this will simply be a special case.
99
100
ASN1_VALUE *ASN1_item_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,
101
254k
                          const ASN1_ITEM *it) {
102
254k
  ASN1_VALUE *ret = nullptr;
103
254k
  if (asn1_item_ex_d2i(&ret, in, len, it, /*tag=*/-1, /*aclass=*/0, /*opt=*/0,
104
254k
                       /*depth=*/0) <= 0) {
105
    // Clean up, in case the caller left a partial object.
106
    //
107
    // TODO(davidben): I don't think it can leave one, but the codepaths below
108
    // are a bit inconsistent. Revisit this when rewriting this function.
109
20.6k
    ASN1_item_ex_free(&ret, it);
110
20.6k
  }
111
112
  // If the caller supplied an output pointer, free the old one and replace it
113
  // with |ret|. This differs from OpenSSL slightly in that we don't support
114
  // object reuse. We run this on both success and failure. On failure, even
115
  // with object reuse, OpenSSL destroys the previous object.
116
254k
  if (pval != nullptr) {
117
0
    ASN1_item_ex_free(pval, it);
118
0
    *pval = ret;
119
0
  }
120
254k
  return ret;
121
254k
}
122
123
// Decode an item, taking care of IMPLICIT tagging, if any. If 'opt' set and
124
// tag mismatch return -1 to handle OPTIONAL
125
//
126
// TODO(davidben): Historically, all functions in this file had to account for
127
// |*pval| containing an arbitrary existing value. This is no longer the case
128
// because |ASN1_item_d2i| now always starts from NULL. As part of rewriting
129
// this function, take the simplified assumptions into account. Though we must
130
// still account for the internal calls to |ASN1_item_ex_new|.
131
132
static int asn1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
133
                            long len, const ASN1_ITEM *it, int tag, int aclass,
134
4.04M
                            char opt, int depth) {
135
4.04M
  const ASN1_TEMPLATE *tt, *errtt = nullptr;
136
4.04M
  const unsigned char *p = nullptr, *q;
137
4.04M
  unsigned char oclass;
138
4.04M
  char cst, isopt;
139
4.04M
  int i;
140
4.04M
  int otag;
141
4.04M
  int ret = 0;
142
4.04M
  ASN1_VALUE **pchptr;
143
4.04M
  if (!pval) {
144
0
    return 0;
145
0
  }
146
4.04M
  if (len < 0) {
147
0
    OPENSSL_PUT_ERROR(ASN1, ASN1_R_BUFFER_TOO_SMALL);
148
0
    goto err;
149
0
  }
150
151
  // Bound |len| to comfortably fit in an int. Lengths in this module often
152
  // switch between int and long without overflow checks.
153
4.04M
  if (len > INT_MAX / 2) {
154
0
    len = INT_MAX / 2;
155
0
  }
156
157
4.04M
  if (++depth > ASN1_MAX_CONSTRUCTED_NEST) {
158
0
    OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_TOO_DEEP);
159
0
    goto err;
160
0
  }
161
162
4.04M
  switch (it->itype) {
163
2.78M
    case ASN1_ITYPE_PRIMITIVE:
164
2.78M
      if (it->templates) {
165
        // tagging or OPTIONAL is currently illegal on an item template
166
        // because the flags can't get passed down. In practice this
167
        // isn't a problem: we include the relevant flags from the item
168
        // template in the template itself.
169
175k
        if ((tag != -1) || opt) {
170
0
          OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE);
171
0
          goto err;
172
0
        }
173
175k
        return asn1_template_ex_d2i(pval, in, len, it->templates, opt, depth);
174
175k
      }
175
2.60M
      return asn1_d2i_ex_primitive(pval, in, len, it, tag, aclass, opt);
176
177
468
    case ASN1_ITYPE_MSTRING:
178
      // It never makes sense for multi-strings to have implicit tagging, so
179
      // if tag != -1, then this looks like an error in the template.
180
468
      if (tag != -1) {
181
0
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE);
182
0
        goto err;
183
0
      }
184
185
468
      p = *in;
186
      // Just read in tag and class
187
468
      ret =
188
468
          asn1_check_tlen(nullptr, &otag, &oclass, nullptr, &p, len, -1, 0, 1);
189
468
      if (!ret) {
190
19
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
191
19
        goto err;
192
19
      }
193
194
      // Must be UNIVERSAL class
195
449
      if (oclass != V_ASN1_UNIVERSAL) {
196
        // If OPTIONAL, assume this is OK
197
17
        if (opt) {
198
0
          return -1;
199
0
        }
200
17
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_MSTRING_NOT_UNIVERSAL);
201
17
        goto err;
202
17
      }
203
      // Check tag matches bit map
204
432
      if (!(ASN1_tag2bit(otag) & it->utype)) {
205
        // If OPTIONAL, assume this is OK
206
42
        if (opt) {
207
0
          return -1;
208
0
        }
209
42
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_MSTRING_WRONG_TAG);
210
42
        goto err;
211
42
      }
212
390
      return asn1_d2i_ex_primitive(pval, in, len, it, otag, 0, 0);
213
214
4.87k
    case ASN1_ITYPE_EXTERN: {
215
      // We don't support implicit tagging with external types.
216
4.87k
      if (tag != -1) {
217
0
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE);
218
0
        goto err;
219
0
      }
220
4.87k
      const ASN1_EXTERN_FUNCS *ef =
221
4.87k
          reinterpret_cast<const ASN1_EXTERN_FUNCS *>(it->funcs);
222
4.87k
      CBS cbs;
223
4.87k
      CBS_init(&cbs, *in, len);
224
4.87k
      CBS copy = cbs;
225
4.87k
      if (!ef->asn1_ex_parse(pval, &cbs, it, opt)) {
226
503
        goto err;
227
503
      }
228
4.37k
      *in = CBS_data(&cbs);
229
      // Check whether the function skipped an optional element.
230
      //
231
      // TODO(crbug.com/42290418): Switch the rest of this function to
232
      // |asn1_ex_parse|'s calling convention.
233
4.37k
      return CBS_len(&cbs) == CBS_len(&copy) ? -1 : 1;
234
4.87k
    }
235
236
259k
    case ASN1_ITYPE_CHOICE: {
237
      // It never makes sense for CHOICE types to have implicit tagging, so if
238
      // tag != -1, then this looks like an error in the template.
239
259k
      if (tag != -1) {
240
0
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE);
241
0
        goto err;
242
0
      }
243
244
259k
      const ASN1_AUX *aux = reinterpret_cast<const ASN1_AUX *>(it->funcs);
245
259k
      ASN1_aux_cb *asn1_cb = aux != nullptr ? aux->asn1_cb : nullptr;
246
259k
      if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, nullptr)) {
247
0
        goto auxerr;
248
0
      }
249
250
259k
      if (*pval) {
251
        // Free up and zero CHOICE value if initialised
252
1.18k
        i = asn1_get_choice_selector(pval, it);
253
1.18k
        if ((i >= 0) && (i < it->tcount)) {
254
0
          tt = it->templates + i;
255
0
          pchptr = asn1_get_field_ptr(pval, tt);
256
0
          ASN1_template_free(pchptr, tt);
257
0
          asn1_set_choice_selector(pval, -1, it);
258
0
        }
259
258k
      } else if (!ASN1_item_ex_new(pval, it)) {
260
0
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
261
0
        goto err;
262
0
      }
263
      // CHOICE type, try each possibility in turn
264
259k
      p = *in;
265
1.59M
      for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
266
1.59M
        pchptr = asn1_get_field_ptr(pval, tt);
267
        // We mark field as OPTIONAL so its absence can be recognised.
268
1.59M
        ret = asn1_template_ex_d2i(pchptr, &p, len, tt, 1, depth);
269
        // If field not present, try the next one
270
1.59M
        if (ret == -1) {
271
1.33M
          continue;
272
1.33M
        }
273
        // If positive return, read OK, break loop
274
259k
        if (ret > 0) {
275
257k
          break;
276
257k
        }
277
        // Otherwise must be an ASN1 parsing error
278
2.25k
        errtt = tt;
279
2.25k
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
280
2.25k
        goto err;
281
259k
      }
282
283
      // Did we fall off the end without reading anything?
284
257k
      if (i == it->tcount) {
285
        // If OPTIONAL, this is OK
286
474
        if (opt) {
287
          // Free and zero it
288
0
          ASN1_item_ex_free(pval, it);
289
0
          return -1;
290
0
        }
291
474
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_NO_MATCHING_CHOICE_TYPE);
292
474
        goto err;
293
474
      }
294
295
257k
      asn1_set_choice_selector(pval, i, it);
296
257k
      if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, nullptr)) {
297
0
        goto auxerr;
298
0
      }
299
257k
      *in = p;
300
257k
      return 1;
301
257k
    }
302
303
1.00M
    case ASN1_ITYPE_SEQUENCE: {
304
1.00M
      p = *in;
305
306
      // If no IMPLICIT tagging set to SEQUENCE, UNIVERSAL
307
1.00M
      if (tag == -1) {
308
543k
        tag = V_ASN1_SEQUENCE;
309
543k
        aclass = V_ASN1_UNIVERSAL;
310
543k
      }
311
      // Get SEQUENCE length and update len, p
312
1.00M
      ret = asn1_check_tlen(&len, nullptr, nullptr, &cst, &p, len, tag, aclass,
313
1.00M
                            opt);
314
1.00M
      if (!ret) {
315
4.29k
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
316
4.29k
        goto err;
317
998k
      } else if (ret == -1) {
318
449k
        return -1;
319
449k
      }
320
548k
      if (!cst) {
321
159
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_SEQUENCE_NOT_CONSTRUCTED);
322
159
        goto err;
323
159
      }
324
325
548k
      if (!*pval && !ASN1_item_ex_new(pval, it)) {
326
0
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
327
0
        goto err;
328
0
      }
329
330
548k
      const ASN1_AUX *aux = reinterpret_cast<const ASN1_AUX *>(it->funcs);
331
548k
      ASN1_aux_cb *asn1_cb = aux != nullptr ? aux->asn1_cb : nullptr;
332
548k
      if (asn1_cb && !asn1_cb(ASN1_OP_D2I_PRE, pval, it, nullptr)) {
333
0
        goto auxerr;
334
0
      }
335
336
      // Free up and zero any ADB found
337
2.18M
      for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
338
1.63M
        if (tt->flags & ASN1_TFLG_ADB_MASK) {
339
2.47k
          const ASN1_TEMPLATE *seqtt;
340
2.47k
          ASN1_VALUE **pseqval;
341
2.47k
          seqtt = asn1_do_adb(pval, tt, 0);
342
2.47k
          if (seqtt == nullptr) {
343
2.47k
            continue;
344
2.47k
          }
345
0
          pseqval = asn1_get_field_ptr(pval, seqtt);
346
0
          ASN1_template_free(pseqval, seqtt);
347
0
        }
348
1.63M
      }
349
350
      // Get each field entry
351
2.16M
      for (i = 0, tt = it->templates; i < it->tcount; i++, tt++) {
352
1.62M
        const ASN1_TEMPLATE *seqtt;
353
1.62M
        ASN1_VALUE **pseqval;
354
1.62M
        seqtt = asn1_do_adb(pval, tt, 1);
355
1.62M
        if (seqtt == nullptr) {
356
0
          goto err;
357
0
        }
358
1.62M
        pseqval = asn1_get_field_ptr(pval, seqtt);
359
        // Have we ran out of data?
360
1.62M
        if (!len) {
361
4.26k
          break;
362
4.26k
        }
363
1.61M
        q = p;
364
        // This determines the OPTIONAL flag value. The field cannot be
365
        // omitted if it is the last of a SEQUENCE and there is still
366
        // data to be read. This isn't strictly necessary but it
367
        // increases efficiency in some cases.
368
1.61M
        if (i == (it->tcount - 1)) {
369
541k
          isopt = 0;
370
1.07M
        } else {
371
1.07M
          isopt = (seqtt->flags & ASN1_TFLG_OPTIONAL) != 0;
372
1.07M
        }
373
        // attempt to read in field, allowing each to be OPTIONAL
374
375
1.61M
        ret = asn1_template_ex_d2i(pseqval, &p, len, seqtt, isopt, depth);
376
1.61M
        if (!ret) {
377
4.77k
          errtt = seqtt;
378
4.77k
          goto err;
379
1.61M
        } else if (ret == -1) {
380
          // OPTIONAL component absent. Free and zero the field.
381
366k
          ASN1_template_free(pseqval, seqtt);
382
366k
          continue;
383
366k
        }
384
        // Update length
385
1.24M
        len -= p - q;
386
1.24M
      }
387
388
      // Check all data read
389
543k
      if (len) {
390
89
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_SEQUENCE_LENGTH_MISMATCH);
391
89
        goto err;
392
89
      }
393
394
      // If we get here we've got no more data in the SEQUENCE, however we
395
      // may not have read all fields so check all remaining are OPTIONAL
396
      // and clear any that are.
397
554k
      for (; i < it->tcount; tt++, i++) {
398
10.7k
        const ASN1_TEMPLATE *seqtt;
399
10.7k
        seqtt = asn1_do_adb(pval, tt, 1);
400
10.7k
        if (seqtt == nullptr) {
401
0
          goto err;
402
0
        }
403
10.7k
        if (seqtt->flags & ASN1_TFLG_OPTIONAL) {
404
10.5k
          ASN1_VALUE **pseqval;
405
10.5k
          pseqval = asn1_get_field_ptr(pval, seqtt);
406
10.5k
          ASN1_template_free(pseqval, seqtt);
407
10.5k
        } else {
408
285
          errtt = seqtt;
409
285
          OPENSSL_PUT_ERROR(ASN1, ASN1_R_FIELD_MISSING);
410
285
          goto err;
411
285
        }
412
10.7k
      }
413
      // Save encoding
414
543k
      if (!asn1_enc_save(pval, *in, p - *in, it)) {
415
0
        goto auxerr;
416
0
      }
417
543k
      if (asn1_cb && !asn1_cb(ASN1_OP_D2I_POST, pval, it, nullptr)) {
418
0
        goto auxerr;
419
0
      }
420
543k
      *in = p;
421
543k
      return 1;
422
543k
    }
423
424
0
    default:
425
0
      return 0;
426
4.04M
  }
427
0
auxerr:
428
0
  OPENSSL_PUT_ERROR(ASN1, ASN1_R_AUX_ERROR);
429
12.9k
err:
430
12.9k
  ASN1_item_ex_free(pval, it);
431
12.9k
  if (errtt) {
432
7.30k
    ERR_add_error_data(4, "Field=", errtt->field_name, ", Type=", it->sname);
433
7.30k
  } else {
434
5.59k
    ERR_add_error_data(2, "Type=", it->sname);
435
5.59k
  }
436
12.9k
  return 0;
437
0
}
438
439
int bssl::ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in,
440
                           long len, const ASN1_ITEM *it, int tag, int aclass,
441
0
                           char opt) {
442
0
  return asn1_item_ex_d2i(pval, in, len, it, tag, aclass, opt, /*depth=*/0);
443
0
}
444
445
// Templates are handled with two separate functions. One handles any
446
// EXPLICIT tag and the other handles the rest.
447
448
static int asn1_template_ex_d2i(ASN1_VALUE **val, const unsigned char **in,
449
                                long inlen, const ASN1_TEMPLATE *tt, char opt,
450
3.39M
                                int depth) {
451
3.39M
  int aclass;
452
3.39M
  int ret;
453
3.39M
  long len;
454
3.39M
  const unsigned char *p, *q;
455
3.39M
  if (!val) {
456
0
    return 0;
457
0
  }
458
3.39M
  uint32_t flags = tt->flags;
459
3.39M
  aclass = flags & ASN1_TFLG_TAG_CLASS;
460
461
3.39M
  p = *in;
462
463
  // Check if EXPLICIT tag expected
464
3.39M
  if (flags & ASN1_TFLG_EXPTAG) {
465
216k
    char cst;
466
    // Need to work out amount of data available to the inner content and
467
    // where it starts: so read in EXPLICIT header to get the info.
468
216k
    ret = asn1_check_tlen(&len, nullptr, nullptr, &cst, &p, inlen, tt->tag,
469
216k
                          aclass, opt);
470
216k
    q = p;
471
216k
    if (!ret) {
472
233
      OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
473
233
      return 0;
474
216k
    } else if (ret == -1) {
475
201k
      return -1;
476
201k
    }
477
14.6k
    if (!cst) {
478
161
      OPENSSL_PUT_ERROR(ASN1, ASN1_R_EXPLICIT_TAG_NOT_CONSTRUCTED);
479
161
      return 0;
480
161
    }
481
    // We've found the field so it can't be OPTIONAL now
482
14.5k
    ret = asn1_template_noexp_d2i(val, &p, len, tt, /*opt=*/0, depth);
483
14.5k
    if (!ret) {
484
986
      OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
485
986
      return 0;
486
986
    }
487
    // We read the field in OK so update length
488
13.5k
    len -= p - q;
489
    // Check for trailing data.
490
13.5k
    if (len) {
491
107
      OPENSSL_PUT_ERROR(ASN1, ASN1_R_EXPLICIT_LENGTH_MISMATCH);
492
107
      goto err;
493
107
    }
494
3.17M
  } else {
495
3.17M
    return asn1_template_noexp_d2i(val, in, inlen, tt, opt, depth);
496
3.17M
  }
497
498
13.4k
  *in = p;
499
13.4k
  return 1;
500
501
107
err:
502
107
  ASN1_template_free(val, tt);
503
107
  return 0;
504
3.39M
}
505
506
static int asn1_template_noexp_d2i(ASN1_VALUE **val, const unsigned char **in,
507
                                   long len, const ASN1_TEMPLATE *tt, char opt,
508
3.18M
                                   int depth) {
509
3.18M
  int aclass;
510
3.18M
  int ret;
511
3.18M
  const unsigned char *p;
512
3.18M
  if (!val) {
513
0
    return 0;
514
0
  }
515
3.18M
  uint32_t flags = tt->flags;
516
3.18M
  aclass = flags & ASN1_TFLG_TAG_CLASS;
517
518
3.18M
  p = *in;
519
520
3.18M
  if (flags & ASN1_TFLG_SK_MASK) {
521
    // SET OF, SEQUENCE OF
522
180k
    int sktag, skaclass;
523
    // First work out expected inner tag value
524
180k
    if (flags & ASN1_TFLG_IMPTAG) {
525
4.20k
      sktag = tt->tag;
526
4.20k
      skaclass = aclass;
527
176k
    } else {
528
176k
      skaclass = V_ASN1_UNIVERSAL;
529
176k
      if (flags & ASN1_TFLG_SET_OF) {
530
0
        sktag = V_ASN1_SET;
531
176k
      } else {
532
176k
        sktag = V_ASN1_SEQUENCE;
533
176k
      }
534
176k
    }
535
    // Get the tag
536
180k
    ret = asn1_check_tlen(&len, nullptr, nullptr, nullptr, &p, len, sktag,
537
180k
                          skaclass, opt);
538
180k
    if (!ret) {
539
4.03k
      OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
540
4.03k
      return 0;
541
176k
    } else if (ret == -1) {
542
1.17k
      return -1;
543
1.17k
    }
544
175k
    if (!*val) {
545
175k
      *val = (ASN1_VALUE *)sk_ASN1_VALUE_new_null();
546
175k
    } else {
547
      // We've got a valid STACK: free up any items present
548
17
      STACK_OF(ASN1_VALUE) *sktmp = (STACK_OF(ASN1_VALUE) *)*val;
549
17
      ASN1_VALUE *vtmp;
550
17
      while (sk_ASN1_VALUE_num(sktmp) > 0) {
551
0
        vtmp = sk_ASN1_VALUE_pop(sktmp);
552
0
        ASN1_item_ex_free(&vtmp, ASN1_ITEM_ptr(tt->item));
553
0
      }
554
17
    }
555
556
175k
    if (!*val) {
557
0
      goto err;
558
0
    }
559
560
    // Read as many items as we can
561
954k
    while (len > 0) {
562
785k
      ASN1_VALUE *skfield;
563
785k
      const unsigned char *q = p;
564
785k
      skfield = nullptr;
565
785k
      if (!asn1_item_ex_d2i(&skfield, &p, len, ASN1_ITEM_ptr(tt->item),
566
785k
                            /*tag=*/-1, /*aclass=*/0, /*opt=*/0, depth)) {
567
5.90k
        ASN1_item_ex_free(&skfield, ASN1_ITEM_ptr(tt->item));
568
5.90k
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
569
5.90k
        goto err;
570
5.90k
      }
571
779k
      len -= p - q;
572
779k
      if (!sk_ASN1_VALUE_push((STACK_OF(ASN1_VALUE) *)*val, skfield)) {
573
0
        ASN1_item_ex_free(&skfield, ASN1_ITEM_ptr(tt->item));
574
0
        goto err;
575
0
      }
576
779k
    }
577
3.00M
  } else if (flags & ASN1_TFLG_IMPTAG) {
578
    // IMPLICIT tagging
579
1.39M
    ret = asn1_item_ex_d2i(val, &p, len, ASN1_ITEM_ptr(tt->item), tt->tag,
580
1.39M
                           aclass, opt, depth);
581
1.39M
    if (!ret) {
582
2.01k
      OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
583
2.01k
      goto err;
584
1.39M
    } else if (ret == -1) {
585
1.13M
      return -1;
586
1.13M
    }
587
1.61M
  } else {
588
    // Nothing special
589
1.61M
    ret = asn1_item_ex_d2i(val, &p, len, ASN1_ITEM_ptr(tt->item), /*tag=*/-1,
590
1.61M
                           /*aclass=*/0, opt, depth);
591
1.61M
    if (!ret) {
592
2.50k
      OPENSSL_PUT_ERROR(ASN1, ASN1_R_NESTED_ASN1_ERROR);
593
2.50k
      goto err;
594
1.61M
    } else if (ret == -1) {
595
362k
      return -1;
596
362k
    }
597
1.61M
  }
598
599
1.67M
  *in = p;
600
1.67M
  return 1;
601
602
10.4k
err:
603
10.4k
  ASN1_template_free(val, tt);
604
10.4k
  return 0;
605
3.18M
}
606
607
// TODO(crbug.com/42290418): Switch the whole file to use a CBS-based calling
608
// convention.
609
static int asn1_d2i_ex_primitive_cbs(ASN1_VALUE **pval, CBS *cbs,
610
                                     const ASN1_ITEM *it, int tag, int aclass,
611
                                     char opt);
612
613
// asn1_d2i_ex_primitive returns one on success, zero on error, and -1 if an
614
// optional value was skipped.
615
static int asn1_d2i_ex_primitive(ASN1_VALUE **pval, const unsigned char **in,
616
                                 long inlen, const ASN1_ITEM *it, int tag,
617
2.60M
                                 int aclass, char opt) {
618
2.60M
  CBS cbs;
619
2.60M
  CBS_init(&cbs, *in, inlen);
620
2.60M
  int ret = asn1_d2i_ex_primitive_cbs(pval, &cbs, it, tag, aclass, opt);
621
2.60M
  if (ret <= 0) {
622
1.06M
    return ret;
623
1.06M
  }
624
1.54M
  *in = CBS_data(&cbs);
625
1.54M
  return 1;
626
2.60M
}
627
628
774k
static ASN1_STRING *ensure_string(ASN1_VALUE **pval) {
629
774k
  if (*pval) {
630
527k
    return (ASN1_STRING *)*pval;
631
527k
  }
632
246k
  ASN1_STRING *str = ASN1_STRING_new();
633
246k
  if (str == nullptr) {
634
0
    return nullptr;
635
0
  }
636
246k
  *pval = (ASN1_VALUE *)str;
637
246k
  return str;
638
246k
}
639
640
static int asn1_d2i_ex_primitive_cbs(ASN1_VALUE **pval, CBS *cbs,
641
                                     const ASN1_ITEM *it, int tag, int aclass,
642
2.60M
                                     char opt) {
643
  // Historically, |it->funcs| for primitive types contained an
644
  // |ASN1_PRIMITIVE_FUNCS| table of callbacks.
645
2.60M
  assert(it->funcs == nullptr);
646
647
2.60M
  int utype;
648
2.60M
  assert(it->itype == ASN1_ITYPE_PRIMITIVE || it->itype == ASN1_ITYPE_MSTRING);
649
2.60M
  if (it->itype == ASN1_ITYPE_MSTRING) {
650
    // MSTRING passes utype in |tag|, normally used for implicit tagging.
651
390
    utype = tag;
652
390
    tag = -1;
653
2.60M
  } else {
654
2.60M
    utype = it->utype;
655
2.60M
  }
656
657
  // Handle ANY types.
658
2.60M
  if (utype == V_ASN1_ANY) {
659
57.2k
    if (tag >= 0) {
660
0
      OPENSSL_PUT_ERROR(ASN1, ASN1_R_ILLEGAL_TAGGED_ANY);
661
0
      return 0;
662
0
    }
663
57.2k
    if (opt && CBS_len(cbs) == 0) {
664
0
      return -1;  // Omitted OPTIONAL value.
665
0
    }
666
57.2k
    ASN1_TYPE *typ;
667
57.2k
    if (!*pval) {
668
48.7k
      typ = ASN1_TYPE_new();
669
48.7k
      if (typ == nullptr) {
670
0
        return 0;
671
0
      }
672
48.7k
      *pval = (ASN1_VALUE *)typ;
673
48.7k
    } else {
674
8.49k
      typ = (ASN1_TYPE *)*pval;
675
8.49k
    }
676
57.2k
    return asn1_parse_any(cbs, typ);
677
57.2k
  }
678
679
  // Convert the crypto/asn1 tag into a CBS one.
680
2.54M
  if (tag == -1) {
681
1.61M
    tag = utype;
682
1.61M
    aclass = V_ASN1_UNIVERSAL;
683
1.61M
  }
684
685
  // All edge cases of |utype| should have been handled already. |utype| is now
686
  // either a primitive |ASN1_ITEM|, handled by |DECLARE_ASN1_ITEM|, or a
687
  // multistring option with a corresponding |B_ASN1_*| constant.
688
2.54M
  assert(utype >= 0 && utype <= V_ASN1_MAX_UNIVERSAL);
689
2.54M
  CBS_ASN1_TAG cbs_tag =
690
2.54M
      (static_cast<CBS_ASN1_TAG>(aclass) << CBS_ASN1_TAG_SHIFT) |
691
2.54M
      static_cast<CBS_ASN1_TAG>(tag);
692
2.54M
  if (utype == V_ASN1_SEQUENCE || utype == V_ASN1_SET) {
693
214k
    cbs_tag |= CBS_ASN1_CONSTRUCTED;
694
214k
  }
695
696
2.54M
  if (opt && !CBS_peek_asn1_tag(cbs, cbs_tag)) {
697
1.05M
    return -1;  // Omitted OPTIONAL value.
698
1.05M
  }
699
700
  // Handle non-|ASN1_STRING| types.
701
1.49M
  switch (utype) {
702
556k
    case V_ASN1_OBJECT: {
703
556k
      UniquePtr<ASN1_OBJECT> obj(asn1_parse_object(cbs, cbs_tag));
704
556k
      if (obj == nullptr) {
705
614
        return 0;
706
614
      }
707
555k
      ASN1_OBJECT_free((ASN1_OBJECT *)*pval);
708
555k
      *pval = (ASN1_VALUE *)obj.release();
709
555k
      return 1;
710
556k
    }
711
53
    case V_ASN1_NULL: {
712
53
      CBS null;
713
53
      if (!CBS_get_asn1(cbs, &null, cbs_tag)) {
714
35
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR);
715
35
        return 0;
716
35
      }
717
18
      if (CBS_len(&null) != 0) {
718
9
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_NULL_IS_WRONG_LENGTH);
719
9
        return 0;
720
9
      }
721
9
      *pval = (ASN1_VALUE *)1;
722
9
      return 1;
723
18
    }
724
166k
    case V_ASN1_BOOLEAN: {
725
166k
      CBS child;
726
166k
      if (!CBS_get_asn1(cbs, &child, cbs_tag)) {
727
182
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR);
728
182
        return 0;
729
182
      }
730
      // TODO(crbug.com/42290221): Reject invalid BOOLEAN encodings and just
731
      // call |CBS_get_asn1_bool|.
732
165k
      if (CBS_len(&child) != 1) {
733
157
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_BOOLEAN_IS_WRONG_LENGTH);
734
157
        return 0;
735
157
      }
736
165k
      ASN1_BOOLEAN *tbool;
737
165k
      tbool = (ASN1_BOOLEAN *)pval;
738
165k
      *tbool = CBS_data(&child)[0];
739
165k
      return 1;
740
165k
    }
741
1.49M
  }
742
743
  // All other types as an |ASN1_STRING| representation.
744
774k
  ASN1_STRING *str = ensure_string(pval);
745
774k
  if (str == nullptr) {
746
0
    return 0;
747
0
  }
748
749
774k
  switch (utype) {
750
4.29k
    case V_ASN1_BIT_STRING:
751
4.29k
      return asn1_parse_bit_string(cbs, str, cbs_tag);
752
3.30k
    case V_ASN1_INTEGER:
753
3.30k
      return asn1_parse_integer(cbs, str, cbs_tag);
754
3.14k
    case V_ASN1_ENUMERATED:
755
3.14k
      return asn1_parse_enumerated(cbs, str, cbs_tag);
756
67
    case V_ASN1_UNIVERSALSTRING:
757
67
      return asn1_parse_universal_string(cbs, str, cbs_tag);
758
57
    case V_ASN1_BMPSTRING:
759
57
      return asn1_parse_bmp_string(cbs, str, cbs_tag);
760
110
    case V_ASN1_UTF8STRING:
761
110
      return asn1_parse_utf8_string(cbs, str, cbs_tag);
762
0
    case V_ASN1_UTCTIME:
763
      // TODO(crbug.com/42290221): Reject timezone offsets. We need to parse
764
      // invalid timestamps in |X509| objects, but that parser no longer uses
765
      // this code.
766
0
      return asn1_parse_utc_time(cbs, str, cbs_tag,
767
0
                                 /*allow_timezone_offset=*/1);
768
2.37k
    case V_ASN1_GENERALIZEDTIME:
769
2.37k
      return asn1_parse_generalized_time(cbs, str, cbs_tag);
770
544k
    case V_ASN1_OCTET_STRING:
771
544k
    case V_ASN1_NUMERICSTRING:
772
544k
    case V_ASN1_PRINTABLESTRING:
773
544k
    case V_ASN1_T61STRING:
774
544k
    case V_ASN1_VIDEOTEXSTRING:
775
752k
    case V_ASN1_IA5STRING:
776
752k
    case V_ASN1_GRAPHICSTRING:
777
752k
    case V_ASN1_VISIBLESTRING:
778
752k
    case V_ASN1_GENERALSTRING:
779
      // T61String is parsed as Latin-1, so all byte strings are valid. The
780
      // others we currently do not enforce.
781
      //
782
      // TODO(crbug.com/42290290): Enforce the encoding of the other string
783
      // types.
784
752k
      if (!asn1_parse_octet_string(cbs, str, cbs_tag)) {
785
1.35k
        return 0;
786
1.35k
      }
787
751k
      str->type = utype;
788
751k
      return 1;
789
8.54k
    case V_ASN1_SEQUENCE: {
790
      // Save the entire element in the string.
791
8.54k
      CBS elem;
792
8.54k
      if (!CBS_get_asn1_element(cbs, &elem, cbs_tag)) {
793
0
        OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR);
794
0
        return 0;
795
0
      }
796
8.54k
      str->type = V_ASN1_SEQUENCE;
797
8.54k
      return ASN1_STRING_set(str, CBS_data(&elem), CBS_len(&elem));
798
8.54k
    }
799
0
    default:
800
0
      OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_TEMPLATE);
801
0
      return 0;
802
774k
    }
803
774k
}
804
805
// Check an ASN1 tag and length: a bit like ASN1_get_object but it
806
// checks the expected tag.
807
808
static int asn1_check_tlen(long *olen, int *otag, unsigned char *oclass,
809
                           char *cst, const unsigned char **in, long len,
810
1.40M
                           int exptag, int expclass, char opt) {
811
1.40M
  int i;
812
1.40M
  int ptag, pclass;
813
1.40M
  long plen;
814
1.40M
  const unsigned char *p;
815
1.40M
  p = *in;
816
817
1.40M
  i = ASN1_get_object(&p, &plen, &ptag, &pclass, len);
818
1.40M
  if (i & 0x80) {
819
5.42k
    OPENSSL_PUT_ERROR(ASN1, ASN1_R_BAD_OBJECT_HEADER);
820
5.42k
    return 0;
821
5.42k
  }
822
1.39M
  if (exptag >= 0) {
823
1.39M
    if ((exptag != ptag) || (expclass != pclass)) {
824
      // If type is OPTIONAL, not an error: indicate missing type.
825
655k
      if (opt) {
826
652k
        return -1;
827
652k
      }
828
3.14k
      OPENSSL_PUT_ERROR(ASN1, ASN1_R_WRONG_TAG);
829
3.14k
      return 0;
830
655k
    }
831
1.39M
  }
832
833
738k
  if (cst) {
834
563k
    *cst = i & V_ASN1_CONSTRUCTED;
835
563k
  }
836
837
738k
  if (olen) {
838
738k
    *olen = plen;
839
738k
  }
840
841
738k
  if (oclass) {
842
449
    *oclass = pclass;
843
449
  }
844
845
738k
  if (otag) {
846
449
    *otag = ptag;
847
449
  }
848
849
738k
  *in = p;
850
738k
  return 1;
851
1.39M
}