Coverage Report

Created: 2026-06-30 07:16

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/freeradius-server/src/protocols/der/decode.c
Line
Count
Source
1
/*
2
 *   This library is free software; you can redistribute it and/or
3
 *   modify it under the terms of the GNU Lesser General Public
4
 *   License as published by the Free Software Foundation; either
5
 *   version 2.1 of the License, or (at your option) any later version.
6
 *
7
 *   This library is distributed in the hope that it will be useful,
8
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
9
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10
 *   Lesser General Public License for more details.
11
 *
12
 *   You should have received a copy of the GNU Lesser General Public
13
 *   License along with this library; if not, write to the Free Software
14
 *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
15
 */
16
17
/**
18
 * $Id: a53c8f71f710d79f8487191e82b12df3923f5e12 $
19
 *
20
 * @file protocols/der/decode.c
21
 * @brief Functions to decode DER encoded data.
22
 *
23
 * @author Arran Cudbard-Bell (a.cudbardb@freeradius.org)
24
 * @author Ethan Thompson (ethan.thompson@inkbridge.io)
25
 *
26
 * @copyright 2025 Arran Cudbard-Bell (a.cudbardb@freeradius.org)
27
 * @copyright 2025 Network RADIUS SAS (legal@networkradius.com)
28
 */
29
30
#include <freeradius-devel/io/test_point.h>
31
#include <freeradius-devel/util/dbuff.h>
32
#include <freeradius-devel/util/decode.h>
33
#include <freeradius-devel/util/dict.h>
34
#include <freeradius-devel/util/proto.h>
35
#include <freeradius-devel/util/struct.h>
36
37
#include "attrs.h"
38
#include "der.h"
39
40
4.00k
#define IS_DER_TAG_CONTINUATION(_tag) (((_tag) & DER_TAG_CONTINUATION) == DER_TAG_CONTINUATION)
41
7.88k
#define IS_DER_TAG_CONSTRUCTED(_tag) (((_tag) & 0x20) == 0x20)
42
3.87k
#define IS_DER_LEN_MULTI_BYTE(_len) (((_len) & DER_LEN_MULTI_BYTE) == DER_LEN_MULTI_BYTE)
43
44
typedef ssize_t (*fr_der_decode_oid_t)(uint64_t subidentifier, void *uctx, bool is_last);
45
46
static ssize_t fr_der_decode_oid(fr_dbuff_t *in, fr_der_decode_oid_t func, void *uctx) CC_HINT(nonnull);
47
48
static ssize_t fr_der_decode_hdr(fr_dict_attr_t const *parent, fr_dbuff_t *in, uint8_t *tag, size_t *len,
49
         fr_der_tag_t expected) CC_HINT(nonnull(2,3,4));
50
51
typedef ssize_t (*fr_der_decode_t)(TALLOC_CTX *ctx, fr_pair_list_t *out, fr_dict_attr_t const *parent, fr_dbuff_t *in,
52
           fr_der_decode_ctx_t *decode_ctx);
53
54
typedef struct {
55
  fr_der_tag_constructed_t constructed;
56
  fr_der_decode_t    decode;
57
} fr_der_tag_decode_t;
58
59
/** Function signature for DER decode functions
60
 *
61
 * @param[in] ctx   Allocation context
62
 * @param[in] out   Where to store the decoded pairs.
63
 * @param[in] parent    Parent attribute.  This should be the root of the dictionary
64
 *        we're using to decode DER data initially, and then nested children.
65
 * @param[in] in    The DER encoded data.
66
 * @param[in] allowed_chars Optional array indicating which ASCII characters are allowed.
67
 * @param[in] decode_ctx  Any decode specific data.
68
 * @return
69
 *  - > 0 on success.  How many bytes were decoded.
70
 *  - 0 no bytes decoded.
71
 *  - < 0 on error.  May be the offset (as a negative value) where the error occurred.
72
 */
73
static ssize_t fr_der_decode_string(TALLOC_CTX *ctx, fr_pair_list_t *out, fr_dict_attr_t const *parent, fr_dbuff_t *in,
74
            bool const allowed_chars[], fr_der_decode_ctx_t *decode_ctx) CC_HINT(nonnull(1,2,3,4,6));
75
76
static ssize_t fr_der_decode_boolean(TALLOC_CTX *ctx, fr_pair_list_t *out, fr_dict_attr_t const *parent, fr_dbuff_t *in,
77
             UNUSED fr_der_decode_ctx_t *decode_ctx)
78
15
{
79
15
  fr_pair_t *vp;
80
15
  fr_dbuff_t our_in = FR_DBUFF(in);
81
15
  uint8_t    value = 0;
82
83
15
  size_t len = fr_dbuff_remaining(&our_in);
84
85
15
  fr_assert(fr_type_is_bool(parent->type));
86
87
  /*
88
   *  ISO/IEC 8825-1:2021
89
   *  8.2 Encoding of a boolean value
90
   *  8.2.1 The encoding of a boolean value shall be primitive.
91
   *        The contents octets shall consist of a single octet.
92
   *  8.2.2 If the boolean value is:
93
   *        FALSE the octet shall be zero [0x00].
94
   *        If the boolean value is TRUE the octet shall have any non-zero value, as a sender's option.
95
   *
96
   *  11.1 Boolean values
97
   *    If the encoding represents the boolean value TRUE, its single contents octet shall have all
98
   *    eight bits set to one [0xff]. (Contrast with 8.2.2.)
99
   */
100
15
  if (len != 1) {
101
2
    fr_strerror_printf_push("Boolean has incorrect length (%zu). Must be 1.", len);
102
2
    return -1;
103
2
  }
104
105
13
  FR_DBUFF_OUT_RETURN(&value, &our_in);
106
107
13
  if (unlikely((value != DER_BOOLEAN_FALSE) && (value != DER_BOOLEAN_TRUE))) {
108
11
    fr_strerror_printf_push("Boolean is not correctly DER encoded (0x%02" PRIx32 " or 0x%02" PRIx32 ").", DER_BOOLEAN_FALSE,
109
11
           DER_BOOLEAN_TRUE);
110
11
    return -1;
111
11
  }
112
113
2
  vp = fr_pair_afrom_da(ctx, parent);
114
2
  if (unlikely(vp == NULL)) {
115
0
    fr_strerror_const_push("Out of memory");
116
0
    return -1;
117
0
  }
118
119
2
  vp->vp_bool = value > 0;
120
121
2
  fr_pair_append(out, vp);
122
123
2
  return fr_dbuff_set(in, &our_in);
124
2
}
125
126
static ssize_t fr_der_decode_integer(TALLOC_CTX *ctx, fr_pair_list_t *out, fr_dict_attr_t const *parent, fr_dbuff_t *in,
127
             UNUSED fr_der_decode_ctx_t *decode_ctx)
128
87
{
129
87
  fr_pair_t *vp;
130
87
  fr_dbuff_t our_in = FR_DBUFF(in);
131
87
  uint64_t   value  = 0;
132
87
  uint8_t    sign   = 0;
133
87
  size_t     i;
134
135
87
  size_t len = fr_dbuff_remaining(&our_in);
136
137
87
  if (parent->type != FR_TYPE_INT64) {
138
0
    fr_strerror_printf_push("Expected parent type 'int64', got attribute %s of type %s", parent->name,
139
0
           fr_type_to_str(parent->type));
140
0
    return -1;
141
0
  }
142
143
87
  if (len > sizeof(value)) {
144
2
    fr_strerror_printf_push("Integer too large (%zu)", len);
145
2
    return -1;
146
2
  }
147
148
  /*
149
   *  ISO/IEC 8825-1:2021
150
   *  8.3 Encoding of an integer value
151
   *  8.3.1 The encoding of an integer value shall be primitive.
152
   *        The contents octets shall consist of one or more octets.
153
   *  8.3.2 If the contents octets of an integer value encoding consist of more than one octet,
154
   *        then the bits of the first octet and bit 8 of the second octet:
155
   *        a) shall not all be ones; and
156
   *        b) shall not all be zero.
157
   *        NOTE - These rules ensure that an integer value is always encoded in the smallest possible number
158
   *        of octets. 8.3.3 The contents octets shall be a two's complement binary number equal to the
159
   *        integer value, and consisting of bits 8 to 1 of the first octet, followed by bits 8 to 1 of the
160
   *        second octet, followed by bits 8 to 1 of each octet in turn up to and including the last octet of
161
   *        the contents octets.
162
   */
163
85
  FR_DBUFF_OUT_RETURN(&sign, &our_in);
164
165
83
  if (sign & 0x80) {
166
    /*
167
     *  If the sign bit is set, this fill the upper bits with all zeros,
168
     *  and set the lower bits to "sign".
169
     *  This is important for the case where the length of the integer is less than the length of the
170
     *  integer type.
171
     */
172
39
    value = ~(uint64_t) 0xff;
173
39
  }
174
175
83
  value |= sign;
176
177
83
  if (len > 1) {
178
    /*
179
     *  If the length of the integer is greater than 1, we need to check that the first 9 bits:
180
     *  1. are not all 0s; and
181
     *  2. are not all 1s
182
     *  These two conditions are necessary to ensure that the integer conforms to DER.
183
     */
184
78
    uint8_t byte;
185
186
78
    FR_DBUFF_OUT_RETURN(&byte, &our_in);
187
188
78
    if ((((value & 0xff) == 0xff) && (byte & 0x80)) || (((~value & 0xff) == 0xff) && !(byte & 0x80))) {
189
11
      fr_strerror_const_push("Integer is not correctly DER encoded. First two bytes are all 0s or all 1s.");
190
11
      return -1;
191
11
    }
192
193
67
    value = (value << 8) | byte;
194
67
  }
195
196
104
  for (i = 2; i < len; i++) {
197
32
    uint8_t byte;
198
199
32
    FR_DBUFF_OUT_RETURN(&byte, &our_in);
200
32
    value = (value << 8) | byte;
201
32
  }
202
203
72
  vp = fr_pair_afrom_da(ctx, parent);
204
72
  if (unlikely(vp == NULL)) {
205
0
    fr_strerror_const_push("Out of memory");
206
0
    return -1;
207
0
  }
208
209
72
  vp->vp_int64 = value;
210
211
72
  fr_pair_append(out, vp);
212
213
72
  return fr_dbuff_set(in, &our_in);
214
72
}
215
216
static ssize_t fr_der_decode_bitstring(TALLOC_CTX *ctx, fr_pair_list_t *out, fr_dict_attr_t const *parent,
217
               fr_dbuff_t *in, fr_der_decode_ctx_t *decode_ctx)
218
35
{
219
35
  fr_pair_t *vp;
220
35
  fr_dbuff_t our_in      = FR_DBUFF(in);
221
35
  uint8_t    unused_bits = 0;
222
35
  uint8_t   *data;
223
224
35
  ssize_t data_len = 0, index = 0;
225
35
  size_t  len = fr_dbuff_remaining(&our_in);
226
227
35
  fr_assert(fr_type_is_octets(parent->type) || fr_type_is_struct(parent->type));
228
229
  /*
230
   *  Now we know that the parent is an octets attribute, we can decode the bitstring
231
   */
232
233
  /*
234
   *  ISO/IEC 8825-1:2021
235
   *  8.6 Encoding of a bitstring value
236
   *    8.6.1 The encoding of a bitstring value shall be either primitive or constructed at the option
237
   *          of the sender.
238
   *      NOTE - Where it is necessary to transfer part of a bit string before the entire
239
   *             bitstring is available, the constructed encoding is used.
240
   *    8.6.2 The contents octets for the primitive encoding shall contain an initial octet followed
241
   *          by zero, one or more subsequent octets.
242
   *      8.6.2.1 The bits in the bitstring value, commencing with the leading bit and proceeding
243
   *        to the trailing bit, shall be placed in bits 8 to 1 of the first subsequent
244
   *        octet, followed by bits 8 to 1 of the second subsequent octet, followed by bits
245
   *        8 to 1 of each octet in turn, followed by as many bits as are needed of the
246
   *        final subsequent octet, commencing with bit 8.
247
   *        NOTE - The terms "leading bit" and "trailing bit" are defined in
248
   *               Rec. ITU-T X.680 | ISO/IEC 8824-1, 22.2.
249
   *      8.6.2.2 The initial octet shall encode, as an unsigned binary integer with bit 1 as the
250
   *        least significant bit, the number of unused bits in the final subsequent octet.
251
   *        The number shall be in the range zero to seven.
252
   *      8.6.2.3 If the bitstring is empty, there shall be no subsequent octets, and the initial
253
   *        octet shall be zero.
254
   *
255
   *  10.2 String encoding forms
256
   *    For bitstring, octetstring and restricted character string types, the constructed form of
257
   *    encoding shall not be used. (Contrast with 8.23.6.)
258
   *
259
   *  11.2 Unused bits 11.2.1 Each unused bit in the final octet of the encoding of a bit string value shall
260
   *       be set to zero.
261
   */
262
263
35
  FR_DBUFF_OUT_RETURN(&unused_bits, &our_in);
264
265
31
  if (unlikely(unused_bits > 7)) {
266
    /*
267
     *  This means an entire byte is unused bits. Which is not allowed.
268
     */
269
6
    fr_strerror_const_push("Invalid number of unused bits in 'bitstring'");
270
6
    return -1;
271
6
  }
272
273
25
  if ((len == 1) && unused_bits) {
274
2
    fr_strerror_const_push("Insufficient data for 'bitstring'. Missing data bytes");
275
2
    return -1;
276
2
  }
277
278
23
  if (fr_type_is_struct(parent->type)) {
279
2
    if (!len) {
280
0
      fr_strerror_const_push("Insufficient data for 'struct'. Missing data bytes");
281
0
      return -1;
282
0
    }
283
284
    /*
285
     *  If the parent is a struct attribute, we will not be adding the unused bits count to the first
286
     *  byte
287
     */
288
2
    data_len = len - 1;
289
21
  } else {
290
21
    data_len = len;
291
21
  }
292
293
23
  data = talloc_array(decode_ctx->tmp_ctx, uint8_t, data_len);
294
23
  if (unlikely(!data)) {
295
0
    fr_strerror_const_push("Out of memory");
296
0
    return -1;
297
0
  }
298
299
23
  if (fr_type_is_octets(parent->type)) {
300
    /*
301
     *  If the parent is an octets attribute, we need to add the unused bits count to the first byte
302
     */
303
21
    index = 1;
304
21
    data[0] = unused_bits;
305
21
  }
306
307
326
  for (; index < data_len; index++) {
308
303
    uint8_t byte;
309
310
303
    FR_DBUFF_OUT_RETURN(&byte, &our_in);
311
312
303
    data[index] = byte;
313
303
  }
314
315
  /*
316
   *  Remove the unused bits from the last byte
317
   */
318
23
  if (unused_bits) {
319
11
    uint8_t mask = 0xff << unused_bits;
320
321
11
    data[data_len - 1] &= mask;
322
11
  }
323
324
23
  if (fr_type_is_struct(parent->type)) {
325
2
    ssize_t slen;
326
327
2
    slen = fr_struct_from_network(ctx, out, parent, data, data_len, decode_ctx, NULL, NULL);
328
329
    /*
330
     *  If the structure decoder didn't consume all the data, we need to free the data and bail out
331
     */
332
2
    if (unlikely(slen < data_len - 1)) {
333
0
      fr_strerror_printf_push("Bitstring structure decoder didn't consume all data. Consumed %zd of %zu bytes",
334
0
             slen, data_len);
335
0
    error:
336
0
      talloc_free(data);
337
0
      return -1;
338
0
    }
339
340
2
    talloc_free(data);
341
2
    return fr_dbuff_set(in, &our_in);
342
2
  }
343
344
21
  vp = fr_pair_afrom_da(ctx, parent);
345
21
  if (unlikely(!vp)) {
346
0
    fr_strerror_const_push("Out of memory");
347
0
    goto error;
348
0
  }
349
350
  /*
351
   *  Add the bitstring to the pair value as octets
352
   */
353
21
  fr_pair_value_memdup(vp, data, len, false);
354
355
21
  fr_pair_append(out, vp);
356
357
21
  return fr_dbuff_set(in, &our_in);
358
21
}
359
360
static ssize_t fr_der_decode_octetstring(TALLOC_CTX *ctx, fr_pair_list_t *out, fr_dict_attr_t const *parent,
361
           fr_dbuff_t *in, UNUSED fr_der_decode_ctx_t *decode_ctx)
362
368
{
363
368
  fr_pair_t *vp;
364
368
  fr_dbuff_t our_in = FR_DBUFF(in);
365
368
  uint8_t   *data   = NULL;
366
367
368
  size_t len = fr_dbuff_remaining(&our_in);
368
369
368
  fr_assert(fr_type_is_octets(parent->type));
370
371
  /*
372
   *  ISO/IEC 8825-1:2021
373
   *  8.7 Encoding of an octetstring value
374
   *    8.7.1 The encoding of an octetstring value shall be either primitive or constructed at the
375
   *          option of the sender.
376
   *      NOTE - Where it is necessary to transfer part of an octet string before the entire
377
   *             octetstring is available, the constructed encoding is used.
378
   *    8.7.2 The primitive encoding contains zero, one or more contents octets equal in value to the
379
   *          octets in the data value, in the order they appear in the data value, and with the most
380
   *          significant bit of an octet of the data value aligned with the most significant bit of an
381
   *          octet of the contents octets.
382
   *    8.7.3 The contents octets for the constructed encoding shall consist of zero, one, or more
383
   *          encodings.
384
   *      NOTE - Each such encoding includes identifier, length, and contents octets, and may
385
   *             include end-of-contents octets if it is constructed.
386
   *      8.7.3.1 To encode an octetstring value in this way, it is segmented. Each segment shall
387
   *             consist of a series of consecutive octets of the value. There shall be no
388
   *             significance placed on the segment boundaries.
389
   *        NOTE - A segment may be of size zero, i.e. contain no octets.
390
   *
391
   *  10.2 String encoding forms
392
   *    For bitstring, octetstring and restricted character string types, the constructed form of
393
   *    encoding shall not be used. (Contrast with 8.23.6.)
394
   */
395
396
368
  vp = fr_pair_afrom_da(ctx, parent);
397
368
  if (unlikely(!vp)) {
398
0
  oom:
399
0
    fr_strerror_const_push("Out of memory");
400
0
    return -1;
401
0
  }
402
403
368
  if (unlikely(fr_pair_value_mem_alloc(vp, &data, len, false) < 0)) {
404
0
    talloc_free(vp);
405
0
    goto oom;
406
0
  }
407
408
368
  (void) fr_dbuff_out_memcpy(data, &our_in, len); /* this can never fail */
409
410
368
  fr_pair_append(out, vp);
411
412
368
  return fr_dbuff_set(in, &our_in);
413
368
}
414
415
static ssize_t fr_der_decode_null(TALLOC_CTX *ctx, fr_pair_list_t *out, fr_dict_attr_t const *parent, fr_dbuff_t *in,
416
          UNUSED fr_der_decode_ctx_t *decode_ctx)
417
276
{
418
276
  fr_pair_t *vp;
419
276
  fr_dbuff_t our_in = FR_DBUFF(in);
420
421
276
  if (fr_dbuff_remaining(&our_in) != 0) {
422
0
    fr_strerror_const_push("Null has non-zero length");
423
0
    return -1;
424
0
  }
425
426
  /*
427
   *  ISO/IEC 8825-1:2021
428
   *  8.8 Encoding of a null value 8.8.1 The encoding of a null value shall be primitive. 8.8.2 The contents
429
   *      octets shall not contain any octets. NOTE - The length octet is zero.
430
   */
431
432
276
  vp = fr_pair_afrom_da(ctx, parent);
433
276
  if (unlikely(!vp)) {
434
0
    fr_strerror_const_push("Out of memory");
435
0
    return -1;
436
0
  }
437
438
276
  fr_pair_append(out, vp);
439
440
276
  return fr_dbuff_set(in, &our_in);
441
276
}
442
443
typedef struct {
444
  int   depth;
445
  unsigned int  oid[FR_DICT_MAX_TLV_STACK];
446
} fr_der_decode_oid_to_stack_ctx_t;     //!< Context for decoding an OID to a DA
447
448
/** Decode an OID to an exploded list
449
 *
450
 * @param[in] subidentifier The subidentifier to decode
451
 * @param[in] uctx    User context
452
 * @param[in] is_last   Is this the last subidentifier in the OID
453
 * @return
454
 *  - 1 on success
455
 *  - < 0 on error
456
 */
457
static ssize_t fr_der_decode_oid_to_stack(uint64_t subidentifier, void *uctx, UNUSED bool is_last)
458
518
{
459
518
  fr_der_decode_oid_to_stack_ctx_t *decode_ctx = uctx;
460
461
518
  if (decode_ctx->depth > 20) {
462
3
    fr_strerror_printf("OID has too many elements (%d > 20)", decode_ctx->depth);
463
3
    return -1;
464
3
  }
465
466
467
515
  decode_ctx->oid[decode_ctx->depth++] = subidentifier;
468
469
515
  return 1;
470
518
}
471
472
typedef struct {
473
  TALLOC_CTX       *ctx;    //!< Allocation context
474
  fr_dict_attr_t const *parent_da;  //!< Parent dictionary attribute
475
  fr_pair_list_t       *parent_list;  //!< Parent pair list
476
} fr_der_decode_oid_to_da_ctx_t;    //!< Context for decoding an OID to a dictionary attribute
477
478
/** Decode an OID to a dictionary attribute
479
 *
480
 * @param[in] subidentifier The subidentifier to decode
481
 * @param[in] uctx    User context
482
 * @param[in] is_last   Is this the last subidentifier in the OID
483
 * @return
484
 *  - 1 on success
485
 *  - < 0 on error
486
 */
487
static ssize_t fr_der_decode_oid_to_da(uint64_t subidentifier, void *uctx, bool is_last)
488
2.15k
{
489
2.15k
  fr_der_decode_oid_to_da_ctx_t *decode_ctx = uctx;
490
2.15k
  fr_pair_t         *vp;
491
2.15k
  fr_dict_attr_t const        *da;
492
493
2.15k
  fr_dict_attr_t const *parent_da = fr_type_is_group(decode_ctx->parent_da->type) ?
494
65
              fr_dict_attr_ref(decode_ctx->parent_da) :
495
2.15k
              decode_ctx->parent_da;
496
497
2.15k
  FR_PROTO_TRACE("Decoding OID to dictionary attribute");
498
2.15k
  FR_PROTO_TRACE("decode context - Parent Name: %s Sub-Identifier %" PRIu64, parent_da->name, subidentifier);
499
2.15k
  FR_PROTO_TRACE("decode context - Parent Address: %p", parent_da);
500
501
2.15k
  da = fr_dict_attr_child_by_num(parent_da, subidentifier);
502
503
2.15k
  if (is_last) {
504
381
    if (unlikely(da == NULL)) {
505
192
      decode_ctx->parent_da = fr_dict_attr_unknown_typed_afrom_num(decode_ctx->ctx, parent_da,
506
192
                         subidentifier, FR_TYPE_OCTETS);
507
508
192
      if (unlikely(decode_ctx->parent_da == NULL)) {
509
5
        return -1;
510
5
      }
511
512
187
      FR_PROTO_TRACE("Created DA: %s", decode_ctx->parent_da->name);
513
187
      return 1;
514
192
    }
515
516
189
    decode_ctx->parent_da = da;
517
518
189
    FR_PROTO_TRACE("Created DA: %s", decode_ctx->parent_da->name);
519
189
    return 1;
520
381
  }
521
522
1.77k
  if (unlikely(da == NULL)) {
523
    /*
524
     *  We need to create an unknown attribute for this subidentifier so we can store the raw data
525
     */
526
1.16k
    fr_dict_attr_t *unknown_da =
527
1.16k
      fr_dict_attr_unknown_typed_afrom_num(decode_ctx->ctx, parent_da, subidentifier, FR_TYPE_TLV);
528
529
1.16k
    if (unlikely(unknown_da == NULL)) {
530
4
    oom:
531
4
      fr_strerror_const_push("Out of memory");
532
4
      return -1;
533
4
    }
534
535
1.15k
    vp = fr_pair_afrom_da(decode_ctx->ctx, unknown_da);
536
537
1.15k
    talloc_free(unknown_da);
538
1.15k
  } else {
539
616
    vp = fr_pair_afrom_da(decode_ctx->ctx, da);
540
616
  }
541
542
1.77k
  if (unlikely(!vp)) goto oom;
543
544
1.77k
  fr_pair_append(decode_ctx->parent_list, vp);
545
546
1.77k
  decode_ctx->ctx   = vp;
547
1.77k
  decode_ctx->parent_da = vp->da;
548
1.77k
  decode_ctx->parent_list = &vp->vp_group;
549
550
1.77k
  FR_PROTO_TRACE("Created DA: %s", decode_ctx->parent_da->name);
551
1.77k
  return 1;
552
1.77k
}
553
554
/** Decode an OID from a DER encoded buffer using a callback
555
 *
556
 * @param[in] in    The DER encoded data.
557
 * @param[in] func    The callback function to call for each subidentifier.
558
 * @param[in] uctx    User context for the callback function.
559
 * @return
560
 *  - 0 on success
561
 *  - < 0 on error
562
 */
563
static ssize_t fr_der_decode_oid(fr_dbuff_t *in, fr_der_decode_oid_t func, void *uctx)
564
498
{
565
498
  fr_dbuff_t  our_in  = FR_DBUFF(in);
566
498
  bool    first;
567
498
  uint64_t  oid;
568
498
  int   magnitude, depth;
569
498
  size_t    len = fr_dbuff_remaining(&our_in); /* we decode the entire dbuff */
570
571
  /*
572
   *  ISO/IEC 8825-1:2021
573
   *  8.19 Encoding of an object identifier value
574
   *  8.19.1 The encoding of an object identifier value shall be primitive.
575
   *  8.19.2 The contents octets shall be an (ordered) list of encodings of subidentifiers (see 8.19.3
576
   *         and 8.19.4) concatenated together. Each subidentifier is represented as a series of
577
   *         (one or more) octets. Bit 8 of each octet indicates whether it is the last in the series: bit 8
578
   *         of the last octet is zero; bit 8 of each preceding octet is one. Bits 7 to 1 of the octets in
579
   *         the series collectively encode the subidentifier. Conceptually, these groups of bits are
580
   *         concatenated to form an unsigned binary number whose most significant bit is bit 7 of the first
581
   *         octet and whose least significant bit is bit 1 of the last octet. The subidentifier shall be
582
   *         encoded in the fewest possible octets, that is, the leading octet of the subidentifier shall not
583
   *         have the value 8016.
584
   *  8.19.3 The number of subidentifiers (N) shall be one less than the number of object identifier
585
   *    components in the object identifier value being encoded. 8.19.4 The numerical value of the
586
   *    first subidentifier is derived from the values of the first two object identifier components in
587
   *    the object identifier value being encoded, using the formula: (X*40) + Y where X is the value
588
   *    of the first object identifier component and Y is the value of the second object identifier
589
   *    component. NOTE - This packing of the first two object identifier components recognizes that
590
   *    only three values are allocated from the root node, and at most 39 subsequent values from nodes
591
   *    reached by X = 0 and X = 1. 8.19.5 The numerical value of the ith subidentifier, (2 <= i <= N) is
592
   *    that of the (i + 1)th object identifier component.
593
   */
594
595
  /*
596
   *  RFC 5280 says:
597
   *
598
   *  ...
599
   *  This specification mandates support for OIDs that have arc elements
600
   *  with values that are less than 2^28, that is, they MUST be between 0
601
   *  and 268,435,455, inclusive.  This allows each arc element to be
602
   *  represented within a single 32-bit word.  Implementations MUST also
603
   *  support OIDs where the length of the dotted decimal (see Section 1.4
604
   *  of [RFC4512]) string representation can be up to 100 bytes
605
   *  (inclusive).  Implementations MUST be able to handle OIDs with up to
606
   *  20 elements (inclusive).
607
   *  ...
608
   *
609
   *  We support up to 2^32 for attribute numbers (unsigned int), and 24 for
610
   *  nesting (FR_DICT_TLV_NEST_MAX), so we're OK here.
611
   *
612
   */
613
498
  FR_PROTO_TRACE("Decoding OID");
614
498
  FR_PROTO_HEX_DUMP(fr_dbuff_current(&our_in), len, "buff in OID");
615
616
498
  first = true;
617
498
  oid = 0;
618
498
  magnitude = 0;
619
498
  depth = 0;
620
621
  /*
622
   *  Loop until done.
623
   */
624
3.27k
  while (len) {
625
2.82k
    uint8_t byte;
626
627
2.82k
    FR_DBUFF_OUT_RETURN(&byte, &our_in);
628
629
2.82k
    magnitude++;
630
2.82k
    if (magnitude > 4) {
631
5
      fr_strerror_const_push("OID subidentifier too large (>32 bits)");
632
5
      return -1;
633
5
    }
634
635
    /*
636
     *  Shift in the new data.
637
     */
638
2.81k
    oid <<= 7;
639
2.81k
    oid |= byte & 0x7f;
640
2.81k
    len--;
641
642
    /*
643
     *  There's more?  The MUST be more if the high bit is set.
644
     */
645
2.81k
    if ((byte & 0x80) != 0) {
646
558
      if (len == 0) {
647
21
        fr_strerror_const_push("OID subidentifier is truncated");
648
21
        return -1;
649
21
      }
650
537
      continue;
651
558
    }
652
653
2.26k
    depth++;
654
2.26k
    if (depth >= FR_DICT_TLV_NEST_MAX) {
655
7
      fr_strerror_printf_push("OID has too many elements (%d >= %d)",
656
7
            depth, FR_DICT_TLV_NEST_MAX);
657
7
      return -1;
658
7
    }
659
660
    /*
661
     *  The initial packed field has the first two compenents included, as (x * 40) + y.
662
     */
663
2.25k
    if (first) {
664
423
      uint64_t first_component;
665
666
423
      if (oid < 40) {
667
82
        first_component = 0;
668
669
341
      } else if (oid < 80) {
670
79
        first_component = 1;
671
79
        oid -= 40;
672
673
262
      } else {
674
262
        first_component = 2;
675
262
        oid -= 80;
676
262
      }
677
423
      first = false;
678
423
      depth++; /* 2 OIDs packed into the first byte */
679
680
      /*
681
       *  Note that we allow OID=1 here.  It doesn't make sense, but whatever.
682
       */
683
423
      FR_PROTO_TRACE("decode context - first OID: %" PRIu64, first_component);
684
423
      if (unlikely(func(first_component, uctx, (len == 0)) <= 0)) return -1;
685
423
    }
686
687
    /*
688
     *  32 bits is still larger than 28, so we do another check here.
689
     */
690
2.25k
    if (oid >= ((uint64_t) 1 << 28)) {
691
0
      fr_strerror_printf("OID subidentifier '%" PRIu64 " is invalid - it must be no more than 28 bits in side",
692
0
             oid);
693
0
      return -1;
694
0
    }
695
696
2.25k
    FR_PROTO_TRACE("decode context - OID: %" PRIu64, oid);
697
2.25k
    if (unlikely(func(oid, uctx, (len == 0)) <= 0)) return -1;
698
699
    /*
700
     *  Reset fields.
701
     */
702
2.24k
    oid = 0;
703
2.24k
    magnitude = 0;
704
2.24k
  }
705
706
453
  return fr_dbuff_set(in, &our_in);
707
498
}
708
709
710
static ssize_t fr_der_decode_utf8_string(TALLOC_CTX *ctx, fr_pair_list_t *out, fr_dict_attr_t const *parent,
711
           fr_dbuff_t *in, fr_der_decode_ctx_t *decode_ctx)
712
2
{
713
  /*
714
   *  @todo - check for valid UTF8 string.
715
   */
716
717
2
  return fr_der_decode_string(ctx, out, parent, in, NULL, decode_ctx);
718
2
}
719
720
static ssize_t fr_der_decode_sequence(TALLOC_CTX *ctx, fr_pair_list_t *out, fr_dict_attr_t const *parent,
721
              fr_dbuff_t *in, fr_der_decode_ctx_t *decode_ctx)
722
1.85k
{
723
1.85k
  fr_pair_t      *vp;
724
1.85k
  fr_dict_attr_t const *child  = NULL;
725
1.85k
  fr_dbuff_t        our_in = FR_DBUFF(in);
726
1.85k
  fr_der_attr_flags_t const *flags = fr_der_attr_flags(parent);
727
728
1.85k
  fr_assert(fr_type_is_tlv(parent->type) || fr_type_is_group(parent->type));
729
730
  /*
731
   *  ISO/IEC 8825-1:2021
732
   *  8.9 Encoding of a sequence value
733
   *    8.9.1 The encoding of a sequence value shall be constructed.
734
   *    8.9.2 The contents octets shall consist of the complete encoding of one data value from each of
735
   *          the types listed in the ASN.1 definition of the sequence type, in the order of their
736
   *          appearance in the definition, unless the type was referenced with the keyword OPTIONAL
737
   *          or the keyword DEFAULT.
738
   *    8.9.3 The encoding of a data value may, but need not, be present for a type referenced with the
739
   *          keyword OPTIONAL or the keyword DEFAULT. If present, it shall appear in the order of
740
   *          appearance of the corresponding type in the ASN.1 definition.
741
   *
742
   *  11.5 Set and sequence components with default value
743
   *    The encoding of a set value or sequence value shall not include an encoding for any component
744
   *    value which is equal to its default value.
745
   */
746
747
1.85k
  if (flags->min && !fr_dbuff_remaining(&our_in)) {
748
1
    fr_strerror_printf_push("Expected at last %d elements in %s, got 0", flags->min, parent->name);
749
1
    return -1;
750
1
  }
751
752
1.84k
  vp = fr_pair_afrom_da(ctx, parent);
753
1.84k
  if (unlikely(!vp)) {
754
0
    fr_strerror_const_push("Out of memory");
755
0
    return -1;
756
0
  }
757
758
  /*
759
   *  This is a sequence-of, which means it either has only one child, or it's a sequence_of=choice,
760
   *  and all of the children are numbered options.
761
   */
762
1.84k
  if (unlikely(flags->is_sequence_of)) {
763
159
    if (flags->sequence_of != FR_DER_TAG_CHOICE) {
764
145
      child = fr_dict_attr_iterate_children(parent, &child);
765
145
      if (!child) {
766
1
        fr_strerror_printf_push("Sequence %s has no children", parent->name);
767
53
      error:
768
53
        talloc_free(vp);
769
53
        return -1;
770
1
      }
771
145
    }
772
773
    /*
774
     *  Decode all of the data.
775
     */
776
211
    while (fr_dbuff_remaining(&our_in) > 0) {
777
105
      ssize_t  slen;
778
105
      uint8_t  current_tag;
779
105
      uint8_t  tag_byte;
780
105
      uint8_t *current_marker = fr_dbuff_current(&our_in);
781
782
105
      FR_DBUFF_OUT_RETURN(&tag_byte, &our_in);
783
784
105
      current_tag = (tag_byte & DER_TAG_CONTINUATION); /* always <= FR_DER_TAG_MAX */
785
786
      /*
787
       *  If we have a choice, the children must be numbered.  The class can be CONTEXT,
788
       *  PRIVATE, or ENTERPRISE.
789
       *
790
       *  Otherwise the children are standard DER tags.  The class must be UNIVERSAL.
791
       */
792
105
      if (unlikely(flags->sequence_of == FR_DER_TAG_CHOICE)) {
793
14
        if ((tag_byte & DER_TAG_CLASS_MASK) == FR_DER_CLASS_UNIVERSAL) {
794
15
        unexpected_class:
795
15
          fr_strerror_printf_push("Tag has unexpected class %02x", tag_byte & DER_TAG_CLASS_MASK);
796
15
          goto error;
797
8
        }
798
799
6
        child = fr_dict_attr_child_by_num(parent, current_tag);
800
6
        if (!child) {
801
3
          fr_der_attr_flags_t *child_flags;
802
803
3
          child = fr_dict_attr_unknown_raw_afrom_num(decode_ctx->tmp_ctx, parent, current_tag);
804
3
          if (!child) goto error;
805
806
          /*
807
           *  Save the option and class, so that we can encode it later.
808
           */
809
3
          child_flags = fr_dict_attr_ext(child, FR_DICT_ATTR_EXT_PROTOCOL_SPECIFIC);
810
3
          child_flags->is_option = true;
811
3
          child_flags->option = current_tag;
812
3
          child_flags->class = tag_byte & DER_TAG_CLASS_MASK;
813
3
        }
814
815
91
      } else if (unlikely(current_tag != flags->sequence_of)) {
816
18
        if ((tag_byte & DER_TAG_CLASS_MASK) != FR_DER_CLASS_UNIVERSAL) {
817
7
          goto unexpected_class;
818
7
        }
819
820
11
        fr_strerror_printf_push("Attribute %s is a sequence_of=%s which does not allow DER type '%s'",
821
11
              parent->name,
822
11
              fr_der_tag_to_str(flags->sequence_of),
823
11
              fr_der_tag_to_str(current_tag));
824
11
        goto error;
825
18
      }
826
827
79
      FR_PROTO_TRACE("decode context %s -> %s", parent->name, child->name);
828
829
79
      fr_dbuff_set(&our_in, current_marker);
830
831
      /*
832
       *  A child could have been encoded with zero bytes if it has a default value.
833
       */
834
79
      slen = fr_der_decode_pair_dbuff(vp, &vp->vp_group, child, &our_in, decode_ctx);
835
79
      if (unlikely(slen < 0)) {
836
26
        fr_strerror_printf_push("Failed decoding %s", vp->da->name);
837
26
        goto error;
838
26
      }
839
79
    }
840
841
106
    fr_pair_append(out, vp);
842
843
106
    return fr_dbuff_set(in, &our_in);
844
158
  }
845
846
  /*
847
   *  Decode the children.  Since it's not a sequence_of=..., we must have a random bunch of
848
   *  children.  The children are packed in order.  Some may be optional.
849
   *
850
   *  We loop over all of the children, because some might have default values.
851
   */
852
7.79k
  while ((child = fr_dict_attr_iterate_children(parent, &child))) {
853
6.68k
    ssize_t ret;
854
855
6.68k
    FR_PROTO_TRACE("decode context %s -> %s", parent->name, child->name);
856
857
6.68k
    ret = fr_der_decode_pair_dbuff(vp, &vp->vp_group, child, &our_in, decode_ctx);
858
6.68k
    if (unlikely(ret < 0)) {
859
586
      fr_strerror_printf_push("Failed decoding %s", vp->da->name);
860
586
      talloc_free(vp);
861
586
      return ret;
862
586
    }
863
6.68k
  }
864
865
  /*
866
   *  Ensure that we grab all of the data.
867
   *
868
   *  @todo - if there is data left over, decode it as raw octets.  We then also have to keep track
869
   *  of the maximum child number, and create unknown attributes starting from the last one.
870
   */
871
1.10k
  if (fr_dbuff_remaining(&our_in)) {
872
88
    FR_PROTO_TRACE("Ignoring extra data in sequence");
873
88
    FR_PROTO_HEX_DUMP(fr_dbuff_current(&our_in), fr_dbuff_remaining(&our_in), " ");
874
875
88
    (void) fr_dbuff_advance(&our_in, fr_dbuff_remaining(&our_in));
876
88
  }
877
878
1.10k
  fr_pair_append(out, vp);
879
880
1.10k
  return fr_dbuff_set(in, &our_in);
881
1.69k
}
882
883
static ssize_t fr_der_decode_set(TALLOC_CTX *ctx, fr_pair_list_t *out, fr_dict_attr_t const *parent, fr_dbuff_t *in,
884
         fr_der_decode_ctx_t *decode_ctx)
885
70
{
886
70
  fr_pair_t      *vp;
887
70
  fr_dict_attr_t const *child  = NULL;
888
70
  fr_dbuff_t        our_in = FR_DBUFF(in);
889
70
  fr_dbuff_marker_t     previous_marker;
890
70
  uint8_t         previous_tag = 0x00;
891
70
  size_t          previous_len = 0;
892
70
  fr_der_attr_flags_t const *flags = fr_der_attr_flags(parent);
893
894
70
  fr_assert(fr_type_is_tlv(parent->type) || fr_type_is_group(parent->type));
895
896
  /*
897
   *  ISO/IEC 8825-1:2021
898
   *  8.11 Encoding of a set value
899
   *    8.11.1 The encoding of a set value shall be constructed.
900
   *    8.11.2 The contents octets shall consist of the complete encoding of one data value from each
901
   *           of the types listed in the ASN.1 definition of the set type, in an order chosen by the
902
   *           sender, unless the type was referenced with the keyword OPTIONAL or the keyword DEFAULT.
903
   *    8.11.3 The encoding of a data value may, but need not, be present for a type referenced with the
904
   *           keyword OPTIONAL or the keyword DEFAULT.
905
   *
906
   *  11.5 Set and sequence components with default value
907
   *    The encoding of a set value or sequence value shall not include an encoding for any component
908
   *    value which is equal to its default value.
909
   */
910
911
70
  if (flags->min && !fr_dbuff_remaining(&our_in)) {
912
0
    fr_strerror_printf_push("Expected at last %d elements in %s, got 0", flags->min, parent->name);
913
0
    return -1;
914
0
  }
915
916
70
  vp = fr_pair_afrom_da(ctx, parent);
917
70
  if (unlikely(!vp)) {
918
0
    fr_strerror_const_push("Out of memory");
919
0
    return -1;
920
0
  }
921
922
70
  if (flags->is_set_of) {
923
0
    fr_dbuff_marker_t current_value_marker;
924
925
    /*
926
     *  There should only be one child in a "set_of".  We can't check this when we load
927
     *  the dictionaries, because there is no "finalize" callback.
928
     *
929
     *  @todo - we would need to walk through all of the dictionary attributes, and
930
     *  call a new function which would check whether or not the parent had any
931
     *  children. And if not, return a load-time error.
932
     */
933
0
    child = NULL;
934
0
    child = fr_dict_attr_iterate_children(parent, &child);
935
0
    if (!child) {
936
0
      fr_strerror_printf_push("Missing child for %s", parent->name);
937
0
      return -1;
938
0
    }
939
940
0
    fr_dbuff_marker(&current_value_marker, &our_in);
941
942
0
    while (fr_dbuff_remaining(&our_in) > 0) {
943
0
      ssize_t     ret;
944
0
      uint8_t     current_tag;
945
0
      uint8_t    *current_marker = fr_dbuff_current(&our_in);
946
0
      size_t      len;
947
948
0
      FR_PROTO_TRACE("decode context %s -> %s", parent->name, child->name);
949
950
0
      if (unlikely(fr_der_decode_hdr(NULL, &our_in, &current_tag, &len, flags->set_of) <= 0)) {
951
0
        ret = -1;
952
0
      error:
953
0
        talloc_free(vp);
954
0
        fr_strerror_printf_push("Failed decoding %s", parent->name);
955
0
        return ret;
956
0
      }
957
958
0
      fr_dbuff_set(&current_value_marker, &our_in);
959
960
      /*
961
       *  Ensure that the contents of the tags are sorted.
962
       */
963
0
      if (previous_tag) {
964
0
        uint8_t    prev_byte = 0, curr_byte = 0;
965
0
        fr_dbuff_t previous_item = FR_DBUFF(&previous_marker);
966
967
0
        fr_dbuff_set_end(&previous_item, fr_dbuff_current(&previous_marker) + previous_len);
968
969
0
        do {
970
0
          FR_DBUFF_OUT_RETURN(&prev_byte, &previous_item);
971
0
          FR_DBUFF_OUT_RETURN(&curr_byte, &our_in);
972
973
0
          if (prev_byte > curr_byte) {
974
0
            fr_strerror_const_push("Set tags are not in ascending order");
975
0
            ret = -1;
976
0
            goto error;
977
0
          }
978
979
0
          if (prev_byte < curr_byte) {
980
0
            break;
981
0
          }
982
983
0
        } while (fr_dbuff_remaining(&our_in) > 0 && fr_dbuff_remaining(&previous_item) > 0);
984
985
0
        if (prev_byte > curr_byte && fr_dbuff_remaining(&previous_item) > 0) {
986
0
          fr_strerror_const_push(
987
0
            "Set tags are not in ascending order. Previous item has more data");
988
0
          ret = -1;
989
0
          goto error;
990
0
        }
991
0
      }
992
993
0
      previous_tag = current_tag;
994
0
      previous_len = len;
995
996
0
      previous_marker = current_value_marker;
997
998
0
      fr_dbuff_set(&our_in, current_marker);
999
1000
0
      ret = fr_der_decode_pair_dbuff(vp, &vp->vp_group, child, &our_in, decode_ctx);
1001
0
      if (unlikely(ret <= 0)) {
1002
0
        fr_strerror_printf_push("Failed decoding %s", vp->da->name);
1003
0
        goto error;
1004
0
      }
1005
0
    }
1006
1007
0
    fr_pair_append(out, vp);
1008
1009
0
    return fr_dbuff_set(in, &our_in);
1010
0
  }
1011
1012
  /*
1013
   *  Decode the children.  Since it's not a sequence_of=..., we must have a set of children.  The
1014
   *  children are packed in order.  Some may be optional.
1015
   */
1016
123
  while ((child = fr_dict_attr_iterate_children(parent, &child))) {
1017
70
    ssize_t  ret;
1018
70
    uint8_t  current_tag;
1019
1020
70
    FR_PROTO_TRACE("decode context %s -> %s", parent->name, child->name);
1021
1022
70
    if (fr_dbuff_remaining(&our_in)) {
1023
41
      uint8_t *current_ptr = fr_dbuff_current(&our_in);
1024
1025
      /*
1026
       *  Check that the tag is in ascending order
1027
       */
1028
41
      FR_DBUFF_OUT_RETURN(&current_tag, &our_in);
1029
1030
41
      if (unlikely(current_tag < previous_tag)) {
1031
0
        fr_strerror_const_push("Set tags are not in ascending order");
1032
0
        talloc_free(vp);
1033
0
        return -1;
1034
0
      }
1035
1036
41
      previous_tag = current_tag;
1037
1038
      /*
1039
       *      Reset the buffer to the start of the tag
1040
       */
1041
41
      fr_dbuff_set(&our_in, current_ptr);
1042
41
    }
1043
1044
    /*
1045
     *  A child could have been encoded with zero bytes if it has a default value.
1046
     */
1047
70
    ret = fr_der_decode_pair_dbuff(vp, &vp->vp_group, child, &our_in, decode_ctx);
1048
70
    if (unlikely(ret < 0)) {
1049
17
      fr_strerror_printf_push("Failed decoding %s", vp->da->name);
1050
17
      talloc_free(vp);
1051
17
      return ret;
1052
17
    }
1053
70
  }
1054
1055
  /*
1056
   *  Ensure that we grab all of the data.
1057
   *
1058
   *  @todo - if there is data left over, decode it as raw octets.  We then also have to keep track
1059
   *  of the maximum child number, and create unknown attributes starting from the last one.
1060
   */
1061
53
  if (fr_dbuff_remaining(&our_in)) {
1062
24
    FR_PROTO_TRACE("Ignoring extra data in set");
1063
24
    FR_PROTO_HEX_DUMP(fr_dbuff_current(&our_in), fr_dbuff_remaining(&our_in), " ");
1064
1065
24
    (void) fr_dbuff_advance(&our_in, fr_dbuff_remaining(&our_in));
1066
24
  }
1067
1068
53
  fr_pair_append(out, vp);
1069
1070
53
  return fr_dbuff_set(in, &our_in);
1071
70
}
1072
1073
#ifdef __clang__
1074
#pragma clang diagnostic ignored "-Wgnu-designator"
1075
#endif
1076
1077
static ssize_t fr_der_decode_printable_string(TALLOC_CTX *ctx, fr_pair_list_t *out, fr_dict_attr_t const *parent,
1078
                fr_dbuff_t *in, UNUSED fr_der_decode_ctx_t *decode_ctx)
1079
6
{
1080
6
  static bool const allowed_chars[SBUFF_CHAR_CLASS] = {
1081
6
    [' '] = true, ['\''] = true, ['('] = true, [')'] = true,
1082
6
    ['+'] = true, [','] = true, ['-'] = true, ['.'] = true,
1083
6
    ['/'] = true, [':'] = true, ['='] = true, ['?'] = true,
1084
6
    ['A' ... 'Z'] = true, ['a' ... 'z'] = true,
1085
6
    ['0' ... '9'] = true,
1086
6
  };
1087
1088
6
  return fr_der_decode_string(ctx, out, parent, in, allowed_chars, decode_ctx);
1089
6
}
1090
1091
static ssize_t fr_der_decode_t61_string(TALLOC_CTX *ctx, fr_pair_list_t *out, fr_dict_attr_t const *parent,
1092
          fr_dbuff_t *in, UNUSED fr_der_decode_ctx_t *decode_ctx)
1093
1
{
1094
1
  static bool const allowed_chars[SBUFF_CHAR_CLASS] = {
1095
1
    [0x08] = true, [0x0A] = true, [0x0C] = true, [0x0D] = true,
1096
1
    [0x0E] = true, [0x0F] = true, [0x19] = true, [0x1A] = true,
1097
1
    [0x1B] = true, [0x1D] = true, [' '] = true, ['!'] = true,
1098
1
    ['"'] = true, ['%'] = true, ['&'] = true, ['\''] = true,
1099
1
    ['('] = true, [')'] = true, ['*'] = true, ['+'] = true,
1100
1
    [','] = true, ['-'] = true, ['.'] = true, ['/'] = true,
1101
1
    [':'] = true, [';'] = true, ['<'] = true, ['='] = true,
1102
1
    ['>'] = true, ['?'] = true, ['@'] = true, ['['] = true,
1103
1
    [']'] = true, ['_'] = true, ['|'] = true, [0x7F] = true,
1104
1
    [0x8B] = true, [0x8C] = true, [0x9B] = true, [0xA0] = true,
1105
1
    [0xA1] = true, [0xA2] = true, [0xA3] = true, [0xA4] = true,
1106
1
    [0xA5] = true, [0xA6] = true, [0xA7] = true, [0xA8] = true,
1107
1
    [0xAB] = true, [0xB0] = true, [0xB1] = true, [0xB2] = true,
1108
1
    [0xB3] = true, [0xB4] = true, [0xB5] = true, [0xB6] = true,
1109
1
    [0xB7] = true, [0xB8] = true, [0xBB] = true, [0xBC] = true,
1110
1
    [0xBD] = true, [0xBE] = true, [0xBF] = true, [0xC1] = true,
1111
1
    [0xC2] = true, [0xC3] = true, [0xC4] = true, [0xC5] = true,
1112
1
    [0xC6] = true, [0xC7] = true, [0xC8] = true, [0xC9] = true,
1113
1
    [0xCA] = true, [0xCB] = true, [0xCC] = true, [0xCD] = true,
1114
1
    [0xCE] = true, [0xCF] = true, [0xE0] = true, [0xE1] = true,
1115
1
    [0xE2] = true, [0xE3] = true, [0xE4] = true, [0xE5] = true,
1116
1
    [0xE7] = true, [0xE8] = true, [0xE9] = true, [0xEA] = true,
1117
1
    [0xEB] = true, [0xEC] = true, [0xED] = true, [0xEE] = true,
1118
1
    [0xEF] = true, [0xF0] = true, [0xF1] = true, [0xF2] = true,
1119
1
    [0xF3] = true, [0xF4] = true, [0xF5] = true, [0xF6] = true,
1120
1
    [0xF7] = true, [0xF8] = true, [0xF9] = true, [0xFA] = true,
1121
1
    [0xFB] = true, [0xFC] = true, [0xFD] = true, [0xFE] = true,
1122
1
    ['A' ... 'Z'] = true, ['a' ... 'z'] = true,
1123
1
    ['0' ... '9'] = true,
1124
1
  };
1125
1126
1
  return fr_der_decode_string(ctx, out, parent, in, allowed_chars, decode_ctx);
1127
1
}
1128
1129
/*
1130
 *  128 characters exactly.  Identical to the first 128 characters of the ASCII alphabet.
1131
 */
1132
static ssize_t fr_der_decode_ia5_string(TALLOC_CTX *ctx, fr_pair_list_t *out, fr_dict_attr_t const *parent,
1133
          fr_dbuff_t *in, UNUSED fr_der_decode_ctx_t *decode_ctx)
1134
2
{
1135
#if 0
1136
  static bool const allowed_chars[SBUFF_CHAR_CLASS] = {
1137
    [0x00 ... 0x7f] = true,
1138
  };
1139
#endif
1140
1141
2
  return fr_der_decode_string(ctx, out, parent, in, NULL, decode_ctx);
1142
2
}
1143
1144
static ssize_t fr_der_decode_utc_time(TALLOC_CTX *ctx, fr_pair_list_t *out, fr_dict_attr_t const *parent,
1145
              fr_dbuff_t *in, UNUSED fr_der_decode_ctx_t *decode_ctx)
1146
12
{
1147
12
  fr_pair_t *vp;
1148
12
  fr_dbuff_t our_in = FR_DBUFF(in);
1149
12
  char     timestr[DER_UTC_TIME_LEN + 1] = {};
1150
12
  char    *p;
1151
12
  struct tm  tm = {};
1152
1153
12
  fr_assert(fr_type_is_date(parent->type));
1154
1155
  /*
1156
   *  ISO/IEC 8825-1:2021
1157
   *  8.25 Encoding for values of the useful types
1158
   *    The following "useful types" shall be encoded as if they had been replaced by their definitions
1159
   *    given in clauses 46-48 of Rec. ITU-T X.680 | ISO/IEC 8824-1:
1160
   *      - generalized time;
1161
   *      - universal time;
1162
   *      - object descriptor.
1163
   *
1164
   *  8.26 Encoding for values of the TIME type and the useful time types
1165
   *    8.26 Encoding for values of the TIME type and the useful time types 8.26.1 Encoding for values
1166
   *    of the TIME type NOTE - The defined time types are subtypes of the TIME type, with the same
1167
   *    tag, and have the same encoding as the TIME type. 8.26.1.1 The encoding of the TIME type shall
1168
   *    be primitive. 8.26.1.2 The contents octets shall be the UTF-8 encoding of the value notation,
1169
   *    after the removal of initial and final QUOTATION MARK (34) characters.
1170
   *
1171
   *  11.8 UTCTime
1172
   *    11.8.1 The encoding shall terminate with "Z", as described in the ITU-T X.680 | ISO/IEC 8824-1
1173
   *           clause on UTCTime.
1174
   *    11.8.2 The seconds element shall always be present.
1175
   *    11.8.3 Midnight (GMT) shall be represented as "YYMMDD000000Z", where "YYMMDD" represents the
1176
   *           day following the midnight in question.
1177
   */
1178
1179
  /*
1180
   *  The format of a UTC time is "YYMMDDhhmmssZ"
1181
   *  Where:
1182
   *  1. YY is the year
1183
   *  2. MM is the month
1184
   *  3. DD is the day
1185
   *  4. hh is the hour
1186
   *  5. mm is the minute
1187
   *  6. ss is the second (not optional in DER)
1188
   *  7. Z is the timezone (UTC)
1189
   */
1190
1191
12
  FR_DBUFF_OUT_MEMCPY_RETURN((uint8_t *)timestr, &our_in, DER_UTC_TIME_LEN);
1192
1193
4
  if (memchr(timestr, '\0', DER_UTC_TIME_LEN) != NULL) {
1194
2
    fr_strerror_const_push("UTC time contains null byte");
1195
2
    return -1;
1196
2
  }
1197
1198
2
  timestr[DER_UTC_TIME_LEN] = '\0';
1199
1200
2
  p = strptime(timestr, "%y%m%d%H%M%SZ", &tm);
1201
1202
2
  if (unlikely(p == NULL) || *p != '\0') {
1203
2
    fr_strerror_const_push("Invalid UTC time format");
1204
2
    return -1;
1205
2
  }
1206
1207
0
  vp = fr_pair_afrom_da(ctx, parent);
1208
0
  if (unlikely(!vp)) {
1209
0
    fr_strerror_const_push("Out of memory");
1210
0
    return -1;
1211
0
  }
1212
1213
0
  vp->vp_date = fr_unix_time_from_tm(&tm);
1214
1215
0
  fr_pair_append(out, vp);
1216
1217
0
  return fr_dbuff_set(in, &our_in);
1218
0
}
1219
1220
static bool const sbuff_char_class_num[SBUFF_CHAR_CLASS] = {
1221
  SBUFF_CHAR_CLASS_NUM,
1222
};
1223
1224
static ssize_t fr_der_decode_generalized_time(TALLOC_CTX *ctx, fr_pair_list_t *out, fr_dict_attr_t const *parent,
1225
                fr_dbuff_t *in, UNUSED fr_der_decode_ctx_t *decode_ctx)
1226
24
{
1227
24
  fr_pair_t    *vp;
1228
24
  fr_dbuff_t    our_in = FR_DBUFF(in);
1229
24
  char        timestr[DER_GENERALIZED_TIME_LEN_MIN + 1] = {};
1230
24
  char       *p;
1231
24
  unsigned long subseconds = 0;
1232
24
  struct tm     tm   = {};
1233
1234
24
  size_t len = fr_dbuff_remaining(&our_in);
1235
1236
24
  fr_assert(fr_type_is_date(parent->type));
1237
1238
24
  if (len < DER_GENERALIZED_TIME_LEN_MIN) {
1239
3
    fr_strerror_const_push("Insufficient data for generalized time or incorrect length");
1240
3
    return -1;
1241
3
  }
1242
1243
  /*
1244
   *  ISO/IEC 8825-1:2021
1245
   *  8.25 Encoding for values of the useful types
1246
   *    The following "useful types" shall be encoded as if they had been replaced by their definitions
1247
   *    given in clauses 46-48 of Rec. ITU-T X.680 | ISO/IEC 8824-1:
1248
   *      - generalized time;
1249
   *      - universal time;
1250
   *      - object descriptor.
1251
   *
1252
   *  8.26 Encoding for values of the TIME type and the useful time types
1253
   *    8.26 Encoding for values of the TIME type and the useful time types 8.26.1 Encoding for values
1254
   *    of the TIME type NOTE - The defined time types are subtypes of the TIME type, with the same
1255
   *    tag, and have the same encoding as the TIME type. 8.26.1.1 The encoding of the TIME type shall
1256
   *    be primitive. 8.26.1.2 The contents octets shall be the UTF-8 encoding of the value notation,
1257
   *    after the removal of initial and final QUOTATION MARK (34) characters.
1258
   *
1259
   *  11.7 GeneralizedTime
1260
   *    11.7.1 The encoding shall terminate with a "Z", as described in the Rec. ITU-T X.680 | ISO/IEC
1261
   *           8824-1 clause on GeneralizedTime.
1262
   *    11.7.2 The seconds element shall always be present.
1263
   *    11.7.3 The fractional-seconds elements, if present, shall omit all trailing zeros; if the
1264
   *           elements correspond to 0, they shall be wholly omitted, and the decimal point element
1265
   *           also shall be omitted.
1266
   */
1267
1268
  /*
1269
   *  The format of a generalized time is "YYYYMMDDHHMMSS[.fff]Z"
1270
   *  Where:
1271
   *  1. YYYY is the year
1272
   *  2. MM is the month
1273
   *  3. DD is the day
1274
   *  4. HH is the hour
1275
   *  5. MM is the minute
1276
   *  6. SS is the second
1277
   *  7. fff is the fraction of a second (optional)
1278
   *  8. Z is the timezone (UTC)
1279
   */
1280
1281
21
  FR_DBUFF_OUT_MEMCPY_RETURN((uint8_t *)timestr, &our_in, DER_GENERALIZED_TIME_LEN_MIN);
1282
1283
21
  if (memchr(timestr, '\0', DER_GENERALIZED_TIME_LEN_MIN) != NULL) {
1284
1
    fr_strerror_const_push("Generalized time contains null byte");
1285
1
    return -1;
1286
1
  }
1287
1288
20
  if (timestr[DER_GENERALIZED_TIME_LEN_MIN - 1] != 'Z' && timestr[DER_GENERALIZED_TIME_LEN_MIN - 1] != '.') {
1289
18
    fr_strerror_const_push("Incorrect format for generalized time. Missing timezone");
1290
18
    return -1;
1291
18
  }
1292
1293
  /*
1294
   *  Check if the fractional seconds are present.
1295
   */
1296
2
  if (timestr[DER_GENERALIZED_TIME_LEN_MIN - 1] == '.') {
1297
1
    size_t sublen;
1298
1299
    /*
1300
     *  We only support subseconds up to 9 decimal places (nanoseconds).
1301
     */
1302
1
    char subsecstring[DER_GENERALIZED_TIME_PRECISION_MAX + 1];
1303
1304
1
    uint8_t precision = DER_GENERALIZED_TIME_PRECISION_MAX;
1305
1306
    /*
1307
     *  "." is invalid, as is ".Z", or even ".0"
1308
     */
1309
1
    sublen = fr_dbuff_remaining(&our_in);
1310
1
    if (sublen <= 1) {
1311
1
    insufficient_data:
1312
1
      fr_strerror_const_push("Insufficient data for subseconds");
1313
1
      return -1;
1314
1
    }
1315
1316
    /*
1317
     *  Ensure that the remaining characters are all decimal numbers.
1318
     */
1319
0
    sublen = fr_sbuff_adv_past_allowed(&FR_SBUFF_IN((char const *) fr_dbuff_current(&our_in), sublen),
1320
0
               SIZE_MAX, sbuff_char_class_num, NULL);
1321
0
    if (sublen == 0) goto insufficient_data;
1322
1323
    /*
1324
     *  Limit precision to either what's there, or the maximum that we care about.
1325
     */
1326
0
    precision = (sublen <= DER_GENERALIZED_TIME_PRECISION_MAX ?
1327
0
           sublen : DER_GENERALIZED_TIME_PRECISION_MAX);
1328
1329
0
    FR_DBUFF_OUT_MEMCPY_RETURN((uint8_t *)subsecstring, &our_in, precision);
1330
1331
0
    subsecstring[precision] = '\0';
1332
1333
    /*
1334
     *  Skip the numbers, and see if we have a trailing 'Z'.
1335
     */
1336
0
    if (precision < sublen) (void) fr_dbuff_advance(&our_in, sublen - precision);
1337
1338
0
    sublen = fr_dbuff_remaining(&our_in);
1339
1340
    /*
1341
     *  Time zone can be missing.
1342
     */
1343
0
    if (sublen > 0) {
1344
0
      FR_DBUFF_OUT_MEMCPY_RETURN((uint8_t *)subsecstring, &our_in, 1);
1345
1346
      /*
1347
       *  This is a special case for error messages.
1348
       */
1349
0
      if (!subsecstring[0]) {
1350
0
        fr_strerror_const_push("Generalized time contains null byte in subseconds");
1351
0
        return -1;
1352
0
      }
1353
1354
0
      if ((sublen > 1) || (subsecstring[0] != 'Z')) {
1355
0
        fr_strerror_const_push("Generalized time contains invalid time zone");
1356
0
        return -1;
1357
0
      }
1358
0
    }
1359
1360
    /*
1361
     *  Convert the subseconds to an unsigned long
1362
     */
1363
0
    subseconds = strtoul(subsecstring, NULL, 10);
1364
1365
    /*
1366
     *  Scale to nanoseconds based on actual precision.
1367
     */
1368
0
    {
1369
0
      static const unsigned long nsec_multiplier[] = {
1370
0
        [1] = 100000000,
1371
0
        [2] = 10000000,
1372
0
        [3] = 1000000,
1373
0
        [4] = 100000,
1374
0
        [5] = 10000,
1375
0
        [6] = 1000,
1376
0
        [7] = 100,
1377
0
        [8] = 10,
1378
0
        [9] = 1,
1379
0
      };
1380
0
      subseconds *= nsec_multiplier[precision];
1381
0
    }
1382
0
  } /* else the trailing character is 'Z' */
1383
1384
  /*
1385
   *  Make sure the timezone is UTC (Z)
1386
   */
1387
1
  timestr[DER_GENERALIZED_TIME_LEN_MIN - 1] = 'Z';
1388
1389
1
  timestr[DER_GENERALIZED_TIME_LEN_MIN] = '\0';
1390
1391
1
  p = strptime(timestr, "%Y%m%d%H%M%SZ", &tm);
1392
1393
1
  if (unlikely(p == NULL)) {
1394
1
    fr_strerror_const_push("Invalid generalized time format (strptime)");
1395
1
    return -1;
1396
1
  }
1397
1398
0
  vp = fr_pair_afrom_da(ctx, parent);
1399
0
  if (unlikely(!vp)) {
1400
0
    fr_strerror_const_push("Out of memory");
1401
0
    return -1;
1402
0
  }
1403
1404
0
  vp->vp_date = fr_unix_time_add(fr_unix_time_from_tm(&tm), fr_time_delta_wrap(subseconds));
1405
1406
0
  fr_pair_append(out, vp);
1407
1408
0
  return fr_dbuff_set(in, &our_in);
1409
0
}
1410
1411
static ssize_t fr_der_decode_visible_string(TALLOC_CTX *ctx, fr_pair_list_t *out, fr_dict_attr_t const *parent,
1412
              fr_dbuff_t *in, UNUSED fr_der_decode_ctx_t *decode_ctx)
1413
23
{
1414
23
  static bool const allowed_chars[SBUFF_CHAR_CLASS] = {
1415
23
    [' '] = true,  ['!'] = true,  ['"'] = true, ['#'] = true,
1416
23
    ['$'] = true,  ['%'] = true,  ['&'] = true, ['\''] = true,
1417
23
    ['('] = true,  [')'] = true,  ['*'] = true, ['+'] = true,
1418
23
    [','] = true,  ['-'] = true,  ['.'] = true, ['/'] = true,
1419
23
    [':'] = true,  [';'] = true,  ['<'] = true, ['='] = true,
1420
23
    ['>'] = true,  ['?'] = true,  ['@'] = true, ['['] = true,
1421
23
    ['\\'] = true, [']'] = true,  ['^'] = true, ['_'] = true,
1422
23
    ['`'] = true,  ['{'] = true,  ['|'] = true, ['}'] = true,
1423
23
    ['A' ... 'Z'] = true, ['a' ... 'z'] = true,
1424
23
    ['0' ... '9'] = true,
1425
23
  };
1426
1427
23
  return fr_der_decode_string(ctx, out, parent, in, allowed_chars, decode_ctx);
1428
23
}
1429
1430
/*
1431
 *  We have per-type function names to make it clear that different types have different decoders.
1432
 *  However, the methods to decode them are the same.  So rather than having trampoline functions, we just
1433
 *  use defines.
1434
 */
1435
#define fr_der_decode_enumerated fr_der_decode_integer
1436
1437
static ssize_t fr_der_decode_general_string(TALLOC_CTX *ctx, fr_pair_list_t *out, fr_dict_attr_t const *parent,
1438
              fr_dbuff_t *in, UNUSED fr_der_decode_ctx_t *decode_ctx)
1439
4
{
1440
4
  return fr_der_decode_string(ctx, out, parent, in, NULL, decode_ctx);
1441
4
}
1442
1443
static ssize_t fr_der_decode_universal_string(TALLOC_CTX *ctx, fr_pair_list_t *out, fr_dict_attr_t const *parent,
1444
                fr_dbuff_t *in, UNUSED fr_der_decode_ctx_t *decode_ctx)
1445
0
{
1446
0
  return fr_der_decode_string(ctx, out, parent, in, NULL, decode_ctx);
1447
0
}
1448
1449
static ssize_t fr_der_decode_ipv4_addr(TALLOC_CTX *ctx, fr_pair_list_t *out, fr_dict_attr_t const *parent,
1450
               fr_dbuff_t *in, UNUSED fr_der_decode_ctx_t *decode_ctx)
1451
0
{
1452
0
  uint8_t byte;
1453
0
  fr_pair_t *vp;
1454
0
  fr_dbuff_t our_in = FR_DBUFF(in);
1455
1456
  /*
1457
   *  RFC3779 Section 2.1.1.
1458
   *
1459
   *  An IP address or prefix is encoded in the IP address delegation
1460
   *  extension as a DER-encoded ASN.1 BIT STRING containing the constant
1461
   *  most-significant bits.  Recall [X.690] that the DER encoding of a BIT
1462
   *  STRING consists of the BIT STRING type (0x03), followed by (an
1463
   *  encoding of) the number of value octets, followed by the value.  The
1464
   *  value consists of an "initial octet" that specifies the number of
1465
   *  unused bits in the last value octet, followed by the "subsequent
1466
   *  octets" that contain the octets of the bit string.  (For IP
1467
   *  addresses, the encoding of the length will be just the length.)
1468
   */
1469
1470
0
  if (fr_dbuff_remaining(&our_in) != 1 + sizeof(vp->vp_ipv4addr)) {
1471
0
    fr_strerror_printf_push("Invalid ipv4addr size.  Expected %zu, got %zu",
1472
0
           1 + sizeof(vp->vp_ipv4addr), fr_dbuff_remaining(&our_in));
1473
0
    return -1;
1474
0
  }
1475
1476
0
  FR_DBUFF_OUT_RETURN(&byte, &our_in);
1477
0
  if (byte != 0) {
1478
0
    fr_strerror_printf_push("Invalid ipv4addr prefix is non-zero (%02x)", byte);
1479
0
    return -1;
1480
0
  }
1481
1482
0
  vp = fr_pair_afrom_da(ctx, parent);
1483
0
  if (unlikely(!vp)) {
1484
0
    fr_strerror_const_push("Out of memory");
1485
0
    return -1;
1486
0
  }
1487
1488
0
  vp->vp_ip.af = AF_INET;
1489
0
  vp->vp_ip.prefix = 32;
1490
0
  FR_DBUFF_OUT_MEMCPY_RETURN((uint8_t *) &vp->vp_ipv4addr, &our_in, sizeof(vp->vp_ipv4addr));
1491
1492
0
  fr_pair_append(out, vp);
1493
1494
0
  return fr_dbuff_set(in, &our_in);
1495
0
}
1496
1497
static ssize_t fr_der_decode_ipv4_prefix(TALLOC_CTX *ctx, fr_pair_list_t *out, fr_dict_attr_t const *parent,
1498
               fr_dbuff_t *in, UNUSED fr_der_decode_ctx_t *decode_ctx)
1499
0
{
1500
0
  uint8_t byte;
1501
0
  fr_pair_t *vp;
1502
0
  fr_dbuff_t our_in = FR_DBUFF(in);
1503
0
  size_t len = fr_dbuff_remaining(&our_in);
1504
1505
  /*
1506
   *  RFC3779 Section 2.1.1.
1507
   *
1508
   *  An IP address or prefix is encoded in the IP address delegation
1509
   *  extension as a DER-encoded ASN.1 BIT STRING containing the constant
1510
   *  most-significant bits.  Recall [X.690] that the DER encoding of a BIT
1511
   *  STRING consists of the BIT STRING type (0x03), followed by (an
1512
   *  encoding of) the number of value octets, followed by the value.  The
1513
   *  value consists of an "initial octet" that specifies the number of
1514
   *  unused bits in the last value octet, followed by the "subsequent
1515
   *  octets" that contain the octets of the bit string.  (For IP
1516
   *  addresses, the encoding of the length will be just the length.)
1517
   */
1518
1519
0
  if (!len || (len > 1 + sizeof(vp->vp_ipv4addr))) {
1520
0
    fr_strerror_printf_push("Invalid ipv4prefix size.  Expected 1..%zu, got %zu",
1521
0
           1 + sizeof(vp->vp_ipv4addr), len);
1522
0
    return -1;
1523
0
  }
1524
0
  len--;
1525
1526
0
  FR_DBUFF_OUT_RETURN(&byte, &our_in);
1527
0
  if (byte > 7) {
1528
0
    fr_strerror_printf_push("Invalid ipv4prefix is too large (%02x)", byte);
1529
0
    return -1;
1530
0
  }
1531
1532
0
  vp = fr_pair_afrom_da(ctx, parent);
1533
0
  if (unlikely(!vp)) {
1534
0
    fr_strerror_const_push("Out of memory");
1535
0
    return -1;
1536
0
  }
1537
1538
0
  vp->vp_ip.af = AF_INET;
1539
0
  vp->vp_ip.prefix = len * 8 - byte;
1540
1541
0
  if (len) FR_DBUFF_OUT_MEMCPY_RETURN((uint8_t *) &vp->vp_ipv4addr, &our_in, len);
1542
1543
0
  fr_pair_append(out, vp);
1544
1545
0
  return fr_dbuff_set(in, &our_in);
1546
0
}
1547
1548
static ssize_t fr_der_decode_ipv6_addr(TALLOC_CTX *ctx, fr_pair_list_t *out, fr_dict_attr_t const *parent,
1549
               fr_dbuff_t *in, UNUSED fr_der_decode_ctx_t *decode_ctx)
1550
0
{
1551
0
  uint8_t byte;
1552
0
  fr_pair_t *vp;
1553
0
  fr_dbuff_t our_in = FR_DBUFF(in);
1554
1555
  /*
1556
   *  RFC3779 Section 2.1.1.
1557
   *
1558
   *  An IP address or prefix is encoded in the IP address delegation
1559
   *  extension as a DER-encoded ASN.1 BIT STRING containing the constant
1560
   *  most-significant bits.  Recall [X.690] that the DER encoding of a BIT
1561
   *  STRING consists of the BIT STRING type (0x03), followed by (an
1562
   *  encoding of) the number of value octets, followed by the value.  The
1563
   *  value consists of an "initial octet" that specifies the number of
1564
   *  unused bits in the last value octet, followed by the "subsequent
1565
   *  octets" that contain the octets of the bit string.  (For IP
1566
   *  addresses, the encoding of the length will be just the length.)
1567
   */
1568
1569
0
  if (fr_dbuff_remaining(&our_in) != 1 + sizeof(vp->vp_ipv6addr)) {
1570
0
    fr_strerror_printf_push("Invalid ipv6addr size.  Expected %zu, got %zu",
1571
0
           1 + sizeof(vp->vp_ipv6addr), fr_dbuff_remaining(&our_in));
1572
0
    return -1;
1573
0
  }
1574
1575
0
  FR_DBUFF_OUT_RETURN(&byte, &our_in);
1576
0
  if (byte != 0) {
1577
0
    fr_strerror_printf_push("Invalid ipv6addr prefix is non-zero (%02x)", byte);
1578
0
    return -1;
1579
0
  }
1580
1581
0
  vp = fr_pair_afrom_da(ctx, parent);
1582
0
  if (unlikely(!vp)) {
1583
0
    fr_strerror_const_push("Out of memory");
1584
0
    return -1;
1585
0
  }
1586
1587
0
  vp->vp_ip.af = AF_INET6;
1588
0
  vp->vp_ip.prefix = 128;
1589
0
  FR_DBUFF_OUT_MEMCPY_RETURN((uint8_t *) &vp->vp_ipv6addr, &our_in, sizeof(vp->vp_ipv6addr));
1590
1591
0
  fr_pair_append(out, vp);
1592
1593
0
  return fr_dbuff_set(in, &our_in);
1594
0
}
1595
1596
static ssize_t fr_der_decode_ipv6_prefix(TALLOC_CTX *ctx, fr_pair_list_t *out, fr_dict_attr_t const *parent,
1597
               fr_dbuff_t *in, UNUSED fr_der_decode_ctx_t *decode_ctx)
1598
0
{
1599
0
  uint8_t byte;
1600
0
  fr_pair_t *vp;
1601
0
  fr_dbuff_t our_in = FR_DBUFF(in);
1602
0
  size_t len = fr_dbuff_remaining(&our_in);
1603
1604
  /*
1605
   *  RFC3779 Section 2.1.1.
1606
   *
1607
   *  An IP address or prefix is encoded in the IP address delegation
1608
   *  extension as a DER-encoded ASN.1 BIT STRING containing the constant
1609
   *  most-significant bits.  Recall [X.690] that the DER encoding of a BIT
1610
   *  STRING consists of the BIT STRING type (0x03), followed by (an
1611
   *  encoding of) the number of value octets, followed by the value.  The
1612
   *  value consists of an "initial octet" that specifies the number of
1613
   *  unused bits in the last value octet, followed by the "subsequent
1614
   *  octets" that contain the octets of the bit string.  (For IP
1615
   *  addresses, the encoding of the length will be just the length.)
1616
   */
1617
1618
0
  if (!len || (len > 1 + sizeof(vp->vp_ipv6addr))) {
1619
0
    fr_strerror_printf_push("Invalid ipv6prefix size.  Expected 1..%zu, got %zu",
1620
0
           1 + sizeof(vp->vp_ipv6addr), len);
1621
0
    return -1;
1622
0
  }
1623
0
  len--;
1624
1625
0
  FR_DBUFF_OUT_RETURN(&byte, &our_in);
1626
0
  if (byte > 7) {
1627
0
    fr_strerror_printf_push("Invalid ipv6prefix is too large (%02x)", byte);
1628
0
    return -1;
1629
0
  }
1630
1631
0
  vp = fr_pair_afrom_da(ctx, parent);
1632
0
  if (unlikely(!vp)) {
1633
0
    fr_strerror_const_push("Out of memory");
1634
0
    return -1;
1635
0
  }
1636
1637
0
  vp->vp_ip.af = AF_INET6;
1638
0
  vp->vp_ip.prefix = len * 8 - byte;
1639
1640
0
  if (len) FR_DBUFF_OUT_MEMCPY_RETURN((uint8_t *) &vp->vp_ipv6addr, &our_in, len);
1641
1642
0
  fr_pair_append(out, vp);
1643
1644
0
  return fr_dbuff_set(in, &our_in);
1645
0
}
1646
1647
static ssize_t fr_der_decode_combo_ip_addr(TALLOC_CTX *ctx, fr_pair_list_t *out, fr_dict_attr_t const *parent,
1648
             fr_dbuff_t *in, UNUSED fr_der_decode_ctx_t *decode_ctx)
1649
6
{
1650
6
  fr_pair_t *vp;
1651
6
  fr_dbuff_t our_in = FR_DBUFF(in);
1652
6
  size_t len = fr_dbuff_remaining(&our_in);
1653
1654
  /*
1655
   *  RFC5280 Section 4.2.1.6
1656
   *
1657
   *  When the subjectAltName extension contains an iPAddress, the address
1658
   *  MUST be stored in the octet string in "network byte order", as
1659
   *  specified in [RFC791].  The least significant bit (LSB) of each octet
1660
   *  is the LSB of the corresponding byte in the network address.  For IP
1661
   *  version 4, as specified in [RFC791], the octet string MUST contain
1662
   *  exactly four octets.  For IP version 6, as specified in
1663
   *  [RFC2460], the octet string MUST contain exactly sixteen octets.
1664
   */
1665
6
  if ((len != 4) && (len != 16)) {
1666
5
    fr_strerror_printf_push("Invalid combo_ip_addr size.  Expected 4 or 16, got %zu",
1667
5
           len);
1668
5
    return -1;
1669
5
  }
1670
1671
1
  vp = fr_pair_afrom_da(ctx, parent);
1672
1
  if (unlikely(!vp)) {
1673
0
    fr_strerror_const_push("Out of memory");
1674
0
    return -1;
1675
0
  }
1676
1677
1
  if (len == 4) {
1678
1
    vp->vp_ip.af = AF_INET;
1679
1
    vp->vp_ip.prefix = 32;
1680
1
    FR_DBUFF_OUT_MEMCPY_RETURN((uint8_t *) &vp->vp_ipv4addr, &our_in, sizeof(vp->vp_ipv4addr));
1681
1682
1
  } else {
1683
0
    vp->vp_ip.af = AF_INET6;
1684
0
    vp->vp_ip.prefix = 128;
1685
0
    FR_DBUFF_OUT_MEMCPY_RETURN((uint8_t *) &vp->vp_ipv6addr, &our_in, sizeof(vp->vp_ipv6addr));
1686
0
  }
1687
1688
1
  fr_pair_append(out, vp);
1689
1690
1
  return fr_dbuff_set(in, &our_in);
1691
1
}
1692
1693
static ssize_t fr_der_decode_oid_wrapper(TALLOC_CTX *ctx, fr_pair_list_t *out, fr_dict_attr_t const *parent,
1694
           fr_dbuff_t *in, UNUSED fr_der_decode_ctx_t *decode_ctx)
1695
76
{
1696
76
  ssize_t   slen;
1697
76
  int   i;
1698
76
  fr_dict_attr_t const *da;
1699
76
  fr_pair_t *vp;
1700
1701
76
  fr_der_decode_oid_to_stack_ctx_t stack = {
1702
76
    .depth = 0,
1703
76
  };
1704
1705
76
  fr_assert(parent->type == FR_TYPE_ATTR);
1706
1707
  /*
1708
   *  We don't use an intermediate dbuff here.  We're not
1709
   *  doing anything with the dbuff, so an extra buffer
1710
   *  isn't necessary.
1711
   */
1712
76
  slen = fr_der_decode_oid(in, fr_der_decode_oid_to_stack, &stack);
1713
76
  if (unlikely(slen <= 0)) return -1; /* OIDs of zero length are invalid */
1714
1715
67
  vp = fr_pair_afrom_da(ctx, parent);
1716
67
  if (unlikely(!vp)) {
1717
3
  oom:
1718
3
    fr_strerror_const_push("Out of memory");
1719
3
    return -1;
1720
0
  }
1721
1722
67
  da = attr_oid_tree;
1723
170
  for (i = 0; i < stack.depth; i++) {
1724
165
    fr_dict_attr_t const *next;
1725
1726
165
    next = fr_dict_attr_child_by_num(da, stack.oid[i]);
1727
165
    if (!next) break;
1728
103
    da = next;
1729
103
  }
1730
1731
371
  for (/* left over i */; i < stack.depth; i++) {
1732
307
    fr_type_t type;
1733
1734
307
    type = (i < (stack.depth - 1)) ? FR_TYPE_TLV : FR_TYPE_BOOL;
1735
1736
307
    da = fr_dict_attr_unknown_typed_afrom_num(vp, da, stack.oid[i], type);
1737
307
    if (!da) {
1738
3
      talloc_free(vp);
1739
3
      goto oom;
1740
3
    }
1741
307
  }
1742
1743
64
  vp->vp_attr = da;
1744
64
  vp->data.enumv = attr_oid_tree;
1745
64
  fr_pair_append(out, vp);
1746
64
  return slen;
1747
67
}
1748
1749
/** Decode an OID value pair
1750
 *
1751
 * @param[in] ctx   Talloc context
1752
 * @param[out] out    Output list
1753
 * @param[in] parent    Parent attribute
1754
 * @param[in] in    Input buffer
1755
 * @param[in] decode_ctx  Decode context
1756
 *
1757
 * @return    0 on success, -1 on failure
1758
 */
1759
static ssize_t fr_der_decode_oid_and_value(TALLOC_CTX *ctx, fr_pair_list_t *out, fr_dict_attr_t const *parent,
1760
             fr_dbuff_t *in, fr_der_decode_ctx_t *decode_ctx)
1761
435
{
1762
435
  fr_dbuff_t          our_in = FR_DBUFF(in);
1763
435
  fr_dbuff_t          oid_in;
1764
435
  fr_der_decode_oid_to_da_ctx_t uctx;
1765
435
  fr_pair_t         *vp = NULL;
1766
1767
435
  uint8_t  tag;
1768
435
  size_t   oid_len;
1769
435
  ssize_t  slen;
1770
1771
435
  FR_PROTO_TRACE("Decoding OID value pair");
1772
1773
435
  fr_assert(fr_type_is_group(parent->type));
1774
1775
  /*
1776
   *  A very common pattern in DER encoding is to have a sequence of set containing two things: an OID and a
1777
   *  value, where the OID is used to determine how to decode the value.
1778
   *  We will be decoding the OID first and then try to find the attribute associated with that OID to then
1779
   *  decode the value. If no attribute is found, one will be created and the value will be stored as raw
1780
   *  octets in the attribute.
1781
   */
1782
1783
435
  if (unlikely((slen = fr_der_decode_hdr(parent, &our_in, &tag, &oid_len, FR_DER_TAG_OID)) <= 0)) {
1784
123
  error:
1785
123
    talloc_free(vp);
1786
123
    fr_strerror_printf_push("Failed decoding %s OID header", parent->name);
1787
123
    return slen;
1788
13
  }
1789
1790
422
  FR_PROTO_TRACE("Attribute %s, tag %u", parent->name, tag);
1791
1792
422
  vp = fr_pair_afrom_da(ctx, parent);
1793
422
  if (unlikely(vp == NULL)) {
1794
0
    fr_strerror_const_push("Out of memory");
1795
0
    return -1;
1796
0
  }
1797
1798
422
  uctx.ctx   = vp;
1799
422
  uctx.parent_da   = fr_dict_attr_ref(parent);
1800
422
  uctx.parent_list = &vp->vp_group;
1801
1802
422
  fr_assert(uctx.parent_da != NULL);
1803
1804
  /*
1805
   *  Limit the OID decoding to the length as given by the OID header.
1806
   */
1807
422
  oid_in = FR_DBUFF(&our_in);
1808
422
  fr_dbuff_set_end(&oid_in, fr_dbuff_current(&oid_in) + oid_len);
1809
1810
422
  slen = fr_der_decode_oid(&oid_in, fr_der_decode_oid_to_da, &uctx);
1811
422
  if (unlikely(slen <= 0)) goto error;
1812
1813
  /*
1814
   *  Skip the OID data.
1815
   */
1816
312
  FR_DBUFF_ADVANCE_RETURN(&our_in, oid_len);
1817
1818
312
  if (unlikely(uctx.parent_da->flags.is_unknown)) {
1819
    /*
1820
     *  This pair is not in the dictionary.
1821
     *  We will store the value as raw octets.
1822
     */
1823
185
    if (unlikely((slen = fr_der_decode_octetstring(uctx.ctx, uctx.parent_list, uctx.parent_da, &our_in,
1824
185
                     decode_ctx)) < 0)) {
1825
0
      talloc_free(vp);
1826
0
      fr_strerror_printf_push("Failed decoding %s OID value", parent->name);
1827
0
      return -1;
1828
0
    }
1829
185
  } else if (unlikely((slen = fr_der_decode_pair_dbuff(uctx.ctx, uctx.parent_list, uctx.parent_da, &our_in,
1830
127
                  decode_ctx)) < 0)) {
1831
71
    talloc_free(vp);
1832
71
    fr_strerror_printf_push("Failed decoding %s OID value", parent->name);
1833
71
    return -1;
1834
71
  }
1835
1836
241
  fr_pair_append(out, vp);
1837
1838
241
  return fr_dbuff_set(in, &our_in);
1839
312
}
1840
1841
static const fr_der_tag_decode_t tag_funcs[FR_DER_TAG_VALUE_MAX] = {
1842
  [FR_DER_TAG_BOOLEAN]        = { .constructed = FR_DER_TAG_PRIMITIVE, .decode = fr_der_decode_boolean },
1843
  [FR_DER_TAG_INTEGER]        = { .constructed = FR_DER_TAG_PRIMITIVE, .decode = fr_der_decode_integer },
1844
  [FR_DER_TAG_OID]        = { .constructed = FR_DER_TAG_PRIMITIVE, .decode = fr_der_decode_oid_wrapper },
1845
  [FR_DER_TAG_BITSTRING]        = { .constructed = FR_DER_TAG_PRIMITIVE, .decode = fr_der_decode_bitstring },
1846
  [FR_DER_TAG_OCTETSTRING]      = { .constructed = FR_DER_TAG_PRIMITIVE, .decode = fr_der_decode_octetstring },
1847
  [FR_DER_TAG_NULL]       = { .constructed = FR_DER_TAG_PRIMITIVE, .decode = fr_der_decode_null },
1848
  [FR_DER_TAG_ENUMERATED]       = { .constructed = FR_DER_TAG_PRIMITIVE, .decode = fr_der_decode_enumerated },
1849
  [FR_DER_TAG_UTF8_STRING]      = { .constructed = FR_DER_TAG_PRIMITIVE, .decode = fr_der_decode_utf8_string },
1850
  [FR_DER_TAG_SEQUENCE]       = { .constructed = FR_DER_TAG_CONSTRUCTED, .decode = fr_der_decode_sequence },
1851
  [FR_DER_TAG_SET]        = { .constructed = FR_DER_TAG_CONSTRUCTED, .decode = fr_der_decode_set },
1852
  [FR_DER_TAG_PRINTABLE_STRING] = { .constructed = FR_DER_TAG_PRIMITIVE,
1853
            .decode      = fr_der_decode_printable_string },
1854
  [FR_DER_TAG_T61_STRING]       = { .constructed = FR_DER_TAG_PRIMITIVE, .decode = fr_der_decode_t61_string },
1855
  [FR_DER_TAG_IA5_STRING]       = { .constructed = FR_DER_TAG_PRIMITIVE, .decode = fr_der_decode_ia5_string },
1856
  [FR_DER_TAG_UTC_TIME]       = { .constructed = FR_DER_TAG_PRIMITIVE, .decode = fr_der_decode_utc_time },
1857
  [FR_DER_TAG_GENERALIZED_TIME] = { .constructed = FR_DER_TAG_PRIMITIVE,
1858
            .decode      = fr_der_decode_generalized_time },
1859
  [FR_DER_TAG_VISIBLE_STRING]   = { .constructed = FR_DER_TAG_PRIMITIVE, .decode = fr_der_decode_visible_string },
1860
  [FR_DER_TAG_GENERAL_STRING]   = { .constructed = FR_DER_TAG_PRIMITIVE, .decode = fr_der_decode_general_string },
1861
  [FR_DER_TAG_UNIVERSAL_STRING] = { .constructed = FR_DER_TAG_PRIMITIVE,
1862
            .decode      = fr_der_decode_universal_string },
1863
};
1864
1865
static const fr_der_tag_decode_t type_funcs[FR_TYPE_MAX] = {
1866
  [FR_TYPE_IPV4_ADDR] = { .constructed = FR_DER_TAG_PRIMITIVE, .decode = fr_der_decode_ipv4_addr },
1867
  [FR_TYPE_IPV4_PREFIX] = { .constructed = FR_DER_TAG_PRIMITIVE, .decode = fr_der_decode_ipv4_prefix },
1868
  [FR_TYPE_IPV6_ADDR] = { .constructed = FR_DER_TAG_PRIMITIVE, .decode = fr_der_decode_ipv6_addr },
1869
  [FR_TYPE_IPV6_PREFIX] = { .constructed = FR_DER_TAG_PRIMITIVE, .decode = fr_der_decode_ipv6_prefix },
1870
1871
  [FR_TYPE_COMBO_IP_ADDR] = { .constructed = FR_DER_TAG_PRIMITIVE, .decode = fr_der_decode_combo_ip_addr },
1872
};
1873
1874
static const fr_der_tag_decode_t oid_and_value_func = {
1875
  .constructed = FR_DER_TAG_PRIMITIVE, .decode = fr_der_decode_oid_and_value,
1876
};
1877
1878
/** Decode the tag and length fields of a DER encoded structure
1879
 *
1880
 * @param[in] parent  Parent attribute
1881
 * @param[in] in  Input buffer
1882
 * @param[out] tag  Tag value
1883
 * @param[out] len  Length of the value field
1884
 * @param[in] expected  the expected / required tag
1885
 *
1886
 * @return    0 on success, -1 on failure
1887
 */
1888
static ssize_t fr_der_decode_hdr(fr_dict_attr_t const *parent, fr_dbuff_t *in, uint8_t *tag, size_t *len,
1889
         fr_der_tag_t expected)
1890
4.01k
{
1891
4.01k
  fr_dbuff_t     our_in = FR_DBUFF(in);
1892
4.01k
  uint8_t      tag_byte;
1893
4.01k
  uint8_t      len_byte;
1894
4.01k
  fr_der_tag_decode_t const *func;
1895
4.01k
  fr_der_tag_class_t   tag_class;
1896
4.01k
  fr_der_tag_constructed_t constructed;
1897
4.01k
  fr_der_attr_flags_t const *flags;
1898
1899
4.01k
  if (fr_dbuff_out(&tag_byte, &our_in) < 0) {
1900
22
  error:
1901
22
    fr_strerror_const_push("Failed decoding DER header - insufficient data");
1902
22
    return -1;
1903
7
  }
1904
1905
  /*
1906
   *  Decode the tag flags
1907
   */
1908
4.00k
  tag_class   = (tag_byte & DER_TAG_CLASS_MASK);
1909
4.00k
  constructed = IS_DER_TAG_CONSTRUCTED(tag_byte);
1910
1911
  /*
1912
   *  Decode the tag
1913
   */
1914
4.00k
  if (IS_DER_TAG_CONTINUATION(tag_byte)) {
1915
    /*
1916
     *  We have a multi-byte tag
1917
     *
1918
     *  Note: Multi-byte tags would mean having a tag number that is greater than 30 (0x1E) (since tag
1919
     *  31 would indicate a multi-byte tag). For most use-cases, this should not be needed, since all
1920
     *  of the basic ASN.1 types have values under 30, and if a CHOICE type were to have over 30 options
1921
     *  (meaning a multi-byte tag would be needed), that would be a very complex CHOICE type that
1922
     *  should probably be simplified.
1923
     */
1924
16
    fr_strerror_const_push("Multi-byte tags are not supported");
1925
16
    return -1;
1926
16
  }
1927
1928
3.98k
  *tag = tag_byte & DER_TAG_CONTINUATION;
1929
1930
  /*
1931
   *  Check if the tag is not universal
1932
   */
1933
3.98k
  switch (tag_class) {
1934
3.89k
  case FR_DER_CLASS_UNIVERSAL:
1935
3.89k
    if ((*tag == FR_DER_TAG_INVALID) || (*tag >= FR_DER_TAG_VALUE_MAX)) {
1936
13
      fr_strerror_printf_push("Invalid tag %u", *tag);
1937
13
      return -1;
1938
13
    }
1939
1940
3.88k
    if ((expected != FR_DER_TAG_INVALID) && (*tag != expected)) {
1941
10
      fr_strerror_printf_push("Invalid tag %s. Expected tag %s",
1942
10
             fr_der_tag_to_str(*tag), fr_der_tag_to_str(expected));
1943
10
      return -1;
1944
10
    }
1945
3.87k
    break;
1946
1947
3.87k
  default:
1948
    /*
1949
     *  The data type will need to be resolved using the dictionary and the tag value
1950
     */
1951
90
    if (!parent) {
1952
1
      fr_strerror_const_push("No parent attribute to resolve tag to class");
1953
1
      return -1;
1954
1
    }
1955
89
    flags = fr_der_attr_flags(parent);
1956
1957
89
    if (tag_class != flags->class) {
1958
32
      fr_strerror_printf_push("Invalid DER class %02x for attribute %s. Expected DER class %02x",
1959
32
            tag_class, parent->name, flags->class);
1960
32
      return -1;
1961
32
    }
1962
1963
    /*
1964
     *  Doesn't match, check if it's optional.
1965
     */
1966
57
    if (flags->is_option) {
1967
57
      if (*tag != flags->option) {
1968
34
        if (flags->optional) return 0;
1969
1970
8
        fr_strerror_printf_push("Invalid option %u for attribute %s. Expected option %u",
1971
8
               *tag, parent->name, flags->option);
1972
8
        return -1;
1973
34
      }
1974
1975
23
      *tag = flags->der_type;
1976
1977
23
    } else {
1978
0
      if (*tag != flags->der_type) {
1979
0
        if (flags->optional) return 0;
1980
1981
0
        fr_strerror_printf_push("Invalid tag %s for attribute %s. Expected tag %s",
1982
0
               fr_der_tag_to_str(*tag), parent->name, fr_der_tag_to_str(flags->der_type));
1983
0
        return -1;
1984
0
      }
1985
0
    }
1986
23
    fr_assert(flags->der_type != FR_DER_TAG_INVALID);
1987
23
    fr_assert(flags->der_type < NUM_ELEMENTS(tag_funcs));
1988
23
    break;
1989
3.98k
  }
1990
1991
3.89k
  func = &tag_funcs[*tag];
1992
3.89k
  fr_assert(func != NULL);
1993
1994
3.89k
  if (unlikely(func->decode == NULL)) {
1995
15
    fr_strerror_printf_push("No decode function for tag %u", *tag);
1996
15
    return -1;
1997
15
  }
1998
1999
3.88k
  if (IS_DER_TAG_CONSTRUCTED(func->constructed) != constructed) {
2000
7
    fr_strerror_printf_push("Constructed flag mismatch for tag %u", *tag);
2001
7
    return -1;
2002
7
  }
2003
2004
3.87k
  if (fr_dbuff_out(&len_byte, &our_in) < 0) goto error;
2005
2006
  /*
2007
   *  Check if the length is a multi-byte length field
2008
   */
2009
3.87k
  if (IS_DER_LEN_MULTI_BYTE(len_byte)) {
2010
187
    uint8_t len_len = len_byte & 0x7f;
2011
187
    *len    = 0;
2012
2013
    /*
2014
     *  Length-of-length of zero is the BER indefinite-length form.  DER (X.690 Section 10.1)
2015
     *  forbids it for both primitive and constructed encodings.  If we accept it, then an
2016
     *  attacker can hide a zero-length value with trailing bytes, which then gets reparsed as
2017
     *  a sibling TLV.
2018
     */
2019
187
    if (unlikely(len_len == 0)) {
2020
1
      fr_strerror_const_push("Indefinite-length form is forbidden in DER");
2021
1
      return -1;
2022
1
    }
2023
2024
186
    if (unlikely(len_len > sizeof(*len))) {
2025
20
      fr_strerror_printf_push("Length field too large (%" PRIu32 ")", len_len);
2026
20
      return -1;
2027
20
    }
2028
2029
    /*
2030
     *  DER (X.690 Section 10.1) mandates minimal length encoding.  In the long form, the
2031
     *  leading length octet must not be zero, otherwise the length could be expressed in
2032
     *  fewer octets.
2033
     */
2034
166
    if (fr_dbuff_out(&len_byte, &our_in) < 0) goto error;
2035
161
    if (unlikely(len_byte == 0)) {
2036
1
      fr_strerror_const_push("Non-minimal DER length encoding (leading zero in long form)");
2037
1
      return -1;
2038
1
    }
2039
160
    *len = len_byte;
2040
160
    len_len--;
2041
2042
909
    while (len_len--) {
2043
757
      if (fr_dbuff_out(&len_byte, &our_in) < 0) goto error;
2044
749
      *len = (*len << 8) | len_byte;
2045
749
    }
2046
2047
    /*
2048
     *  DER also mandates the short form whenever the
2049
     *  length fits in 7 bits.  Reject the long form when
2050
     *  the value is < 128.
2051
     */
2052
152
    if (unlikely(*len < 128)) {
2053
9
      fr_strerror_printf_push("Non-minimal DER length encoding (long form used for length %zu)", *len);
2054
9
      return -1;
2055
9
    }
2056
2057
3.68k
  } else {
2058
3.68k
    *len = len_byte;
2059
3.68k
  }
2060
2061
  /*
2062
   *  Ensure that there is the correct amount of data available to read.
2063
   */
2064
3.83k
  if (*len && unlikely((fr_dbuff_extend_lowat(NULL, &our_in, *len) < *len))) {
2065
168
    fr_strerror_printf_push("Insufficient data for length field (%zu)", *len);
2066
168
    return -1;
2067
168
  }
2068
2069
3.66k
  return fr_dbuff_set(in, &our_in);
2070
3.83k
}
2071
2072
/** Decode a CHOICE type
2073
 * This is where the actual decoding of the CHOICE type happens. The CHOICE type is a type that can have multiple
2074
 * types, but only one of them can be present at a time. The type that is present is determined by the tag of the
2075
 * data
2076
 *
2077
 * @param[in] ctx   Talloc context
2078
 * @param[in] out   Output list
2079
 * @param[in] parent    Parent attribute
2080
 * @param[in] in    Input buffer
2081
 * @param[in] decode_ctx  Decode context
2082
 */
2083
static ssize_t fr_der_decode_choice(TALLOC_CTX *ctx, fr_pair_list_t *out, fr_dict_attr_t const *parent,
2084
            fr_dbuff_t *in, fr_der_decode_ctx_t *decode_ctx)
2085
0
{
2086
0
  fr_pair_t      *vp;
2087
0
  fr_dict_attr_t const *child  = NULL;
2088
0
  fr_dbuff_t        our_in = FR_DBUFF(in);
2089
0
  uint8_t        tag;
2090
0
  uint8_t      tag_byte;
2091
0
  uint8_t     *current_marker = fr_dbuff_current(&our_in);
2092
2093
0
  fr_assert(fr_type_is_struct(parent->type) || fr_type_is_tlv(parent->type) || fr_type_is_group(parent->type));
2094
2095
0
  FR_DBUFF_OUT_RETURN(&tag_byte, &our_in);
2096
2097
0
  if (unlikely(IS_DER_TAG_CONTINUATION(tag_byte))) {
2098
0
    fr_strerror_printf_push("Attribute %s is a choice, but received tag with continuation bit set",
2099
0
          parent->name);
2100
0
    return -1;
2101
0
  }
2102
2103
0
  tag = (tag_byte & DER_TAG_CONTINUATION);
2104
2105
0
  child = fr_dict_attr_child_by_num(parent, tag);
2106
0
  if (unlikely(!child)) {
2107
0
    fr_strerror_printf_push("Attribute %s is a choice, but received unknown option %u",
2108
0
           parent->name, tag);
2109
0
    return -1;
2110
0
  }
2111
2112
0
  fr_dbuff_set(&our_in, current_marker);
2113
2114
0
  vp = fr_pair_afrom_da(ctx, parent);
2115
0
  if (unlikely(!vp)) {
2116
0
    fr_strerror_const_push("Out of memory");
2117
0
    return -1;
2118
0
  }
2119
0
  PAIR_ALLOCED(vp);
2120
2121
0
  if (unlikely(fr_der_decode_pair_dbuff(vp, &vp->vp_group, child, &our_in, decode_ctx) < 0)) {
2122
0
    fr_strerror_printf_push("Failed decoding %s", vp->da->name);
2123
0
    talloc_free(vp);
2124
0
    return -1;
2125
0
  }
2126
2127
0
  fr_pair_append(out, vp);
2128
2129
0
  return fr_dbuff_set(in, &our_in);
2130
0
}
2131
2132
/** Decode an X509 Extentions Field
2133
 *
2134
 * @param[in] ctx   Talloc context
2135
 * @param[in] out   Output list
2136
 * @param[in] in    Input buffer
2137
 * @param[in] parent    Parent attribute
2138
 * @param[in] decode_ctx  Decode context
2139
 *
2140
 * @return    0 on success, -1 on failure
2141
 */
2142
static ssize_t fr_der_decode_x509_extensions(TALLOC_CTX *ctx, fr_pair_list_t *out, fr_dbuff_t *in,
2143
               fr_dict_attr_t const *parent, fr_der_decode_ctx_t *decode_ctx)
2144
14
{
2145
14
  fr_dbuff_t our_in = FR_DBUFF(in);
2146
14
  fr_pair_t *vp, *vp2;
2147
14
  fr_dict_attr_t const *ref;
2148
2149
14
  uint8_t tag;
2150
14
  uint64_t max;
2151
14
  size_t   len;
2152
14
  ssize_t  slen;
2153
2154
14
  FR_PROTO_TRACE("Decoding extensions");
2155
14
  FR_PROTO_TRACE("Attribute %s", parent->name);
2156
14
  FR_PROTO_HEX_DUMP(fr_dbuff_current(in), fr_dbuff_remaining(in), "Top of extension decoding");
2157
2158
14
  fr_assert(fr_type_is_group(parent->type));
2159
2160
  /*
2161
   *  RFC 5280 Section 4.2
2162
   *  The extensions defined for X.509 v3 certificates provide methods for
2163
   *  associating additional attributes with users or public keys and for
2164
   *  managing relationships between CAs.  The X.509 v3 certificate format
2165
   *  also allows communities to define private extensions to carry
2166
   *  information unique to those communities.  Each extension in a
2167
   *  certificate is designated as either critical or non-critical.
2168
   *
2169
   *  Each extension includes an OID and an ASN.1 structure.  When an
2170
   *  extension appears in a certificate, the OID appears as the field
2171
   *  extnID and the corresponding ASN.1 DER encoded structure is the value
2172
   *  of the octet string extnValue.
2173
   *
2174
   *  RFC 5280 Section A.1 Explicitly Tagged Module, 1988 Syntax
2175
   *    Extensions  ::=  SEQUENCE SIZE (1..MAX) OF Extension
2176
   *
2177
   *    Extension  ::=  SEQUENCE  {
2178
   *      extnID      OBJECT IDENTIFIER,
2179
   *      critical    BOOLEAN DEFAULT FALSE,
2180
   *      extnValue   OCTET STRING
2181
   *          -- contains the DER encoding of an ASN.1 value
2182
   *          -- corresponding to the extension type identified
2183
   *          -- by extnID
2184
   *    }
2185
   *
2186
   *  So the extensions are a SEQUENCE of SEQUENCEs containing an OID, a boolean and an OCTET STRING.
2187
   *  Note: If the boolean value is false, it should not be included in the encoding.
2188
   */
2189
2190
  /*
2191
   *  Get the overall length of the first inner sequence.
2192
   *  Ideally this should fill the entire outer sequence.
2193
   */
2194
14
  if (unlikely((slen = fr_der_decode_hdr(parent, &our_in, &tag, &len, FR_DER_TAG_SEQUENCE)) <= 0)) {
2195
5
    fr_strerror_printf_push("Failed decoding %s sequence header", parent->name);
2196
5
    return slen;
2197
5
  }
2198
2199
9
  if (len != fr_dbuff_remaining(&our_in)) {
2200
1
    fr_strerror_printf_push("Inner %s x509extension sequence does not exactly fill the outer sequence",
2201
1
          parent->name);
2202
1
    return -1;
2203
1
  }
2204
2205
  /*
2206
   *  Normal extensions are decoded into the normal parent.
2207
   */
2208
8
  vp = fr_pair_afrom_da(ctx, parent);
2209
8
  if (unlikely(!vp)) {
2210
0
  oom:
2211
0
    fr_strerror_const_push("Out of memory");
2212
0
    return -1;
2213
0
  }
2214
8
  PAIR_ALLOCED(vp);
2215
2216
  /*
2217
   *  Critical extensions are decoded into the Critical parent.
2218
   */
2219
8
  ref = fr_dict_attr_ref(parent);
2220
8
  fr_assert(ref != NULL);
2221
8
  ref = fr_dict_attr_by_name(NULL, ref, "Critical");
2222
8
  fr_assert(ref != NULL);
2223
2224
8
  vp2 = fr_pair_afrom_da(vp, ref);
2225
8
  if (unlikely(vp2 == NULL)) {
2226
0
    talloc_free(vp);
2227
0
    goto oom;
2228
0
  }
2229
8
  PAIR_ALLOCED(vp2);
2230
2231
8
  max = fr_der_flag_max(parent); /* Maximum number of extensions which can be used here */
2232
2233
  /*
2234
   *  Each extension is composed of a sequence containing the following objects:
2235
   *
2236
   *    extnID      OID - a printable string "1.2.3.4"
2237
   *    critical    BOOLEAN OPTIONAL DEFAULT FALSE
2238
   *    extnValue   OCTETSTRING - the DER encoding of the referenced ASN.1 extension
2239
   */
2240
8
  while (fr_dbuff_remaining(&our_in) > 0) {
2241
7
    fr_dbuff_t          seq_in = FR_DBUFF(&our_in);
2242
7
    fr_dbuff_t          oid_in;
2243
7
    fr_der_decode_oid_to_da_ctx_t uctx;
2244
7
    size_t  seq_len, oid_len, ext_len;
2245
2246
7
    FR_PROTO_HEX_DUMP(fr_dbuff_current(&our_in), fr_dbuff_remaining(&our_in), "inner x509 sequence");
2247
2248
7
    if (!max) {
2249
0
      fr_strerror_printf_push("Too many extensions - reached the limit of %" PRIu64, max);
2250
0
      return -1;
2251
0
    }
2252
2253
7
    if (unlikely((slen = fr_der_decode_hdr(parent, &seq_in, &tag, &seq_len, FR_DER_TAG_SEQUENCE)) <= 0)) {
2254
3
      fr_strerror_printf_push("Failed decoding %s extension inner sequence header",
2255
3
            parent->name);
2256
7
    error:
2257
7
      talloc_free(vp);
2258
7
      return slen;
2259
3
    }
2260
2261
    /*
2262
     *  Limit decoding for the inner sequence.
2263
     */
2264
4
    fr_dbuff_set_end(&seq_in, fr_dbuff_current(&seq_in) + seq_len);
2265
2266
    /*
2267
     *  Start decoding the OID.
2268
     */
2269
4
    if (unlikely((slen = fr_der_decode_hdr(NULL, &seq_in, &tag, &oid_len, FR_DER_TAG_OID)) <= 0)) {
2270
3
      fr_strerror_printf_push("Failed decoding %s OID header", parent->name);
2271
3
      goto error;
2272
3
    }
2273
2274
    /*
2275
     *  Create a buffer where we can decode the OID.  This lets us avoid any back and forth
2276
     *  with markers.
2277
     *
2278
     *  The OID and extnValue will get decoded into a "critical" or "non-critical" vp,
2279
     *  depending on the value of the boolean Critical field.  So we don't know where to
2280
     *  decode the OID until we see the Critical field.  As a result, we have to save a
2281
     *  temporary OID buffer.
2282
     */
2283
1
    oid_in = FR_DBUFF(&seq_in);
2284
1
    fr_dbuff_set_end(&oid_in, fr_dbuff_current(&oid_in) + oid_len);
2285
2286
1
    FR_PROTO_TRACE("inner x509 OID length %zu", oid_len);
2287
1
    FR_PROTO_HEX_DUMP(fr_dbuff_current(&oid_in), fr_dbuff_remaining(&oid_in), "inner x509 OID");
2288
2289
    /*
2290
     *  Skip the OID data.  We'll decode that later.
2291
     */
2292
1
    FR_DBUFF_ADVANCE_RETURN(&seq_in, oid_len);
2293
2294
    /*
2295
     *  The next thing is either Critical, or is the extValue.
2296
     */
2297
1
    if (unlikely(fr_der_decode_hdr(NULL, &seq_in, &tag, &ext_len, FR_DER_TAG_INVALID) <= 0)) {
2298
1
      fr_strerror_printf_push("Failed decoding %s extnValue", parent->name);
2299
1
      slen = -1;
2300
1
      goto error;
2301
1
    }
2302
2303
0
    uctx.ctx   = vp;
2304
0
    uctx.parent_da   = vp->da;
2305
0
    uctx.parent_list = &vp->vp_group;
2306
2307
    /*
2308
     *  The optional boolean Critical field.  This tells us where the extensions will be
2309
     *  decoded to.
2310
     */
2311
0
    if (tag == FR_DER_TAG_BOOLEAN) {
2312
0
      uint8_t is_critical = false;
2313
2314
      /*
2315
       *  This Extension has the Critical field.
2316
       *  If this value is true, we will be storing the pair in the critical list
2317
       */
2318
0
      if (unlikely(fr_dbuff_out(&is_critical, &seq_in) <= 0)) {
2319
0
        fr_strerror_const_push("Insufficient data for isCritical field");
2320
0
        slen = -1;
2321
0
        goto error;
2322
0
      }
2323
2324
      /*
2325
       *  0x00 is false.  0xff is true.  But we don't care about invalid boolean values.
2326
       */
2327
0
      if (is_critical) {
2328
0
        uctx.ctx   = vp2;
2329
0
        uctx.parent_da   = vp2->da;
2330
0
        uctx.parent_list = &vp2->vp_group;
2331
0
      }
2332
2333
      /*
2334
       *  The next header should be the extnValue
2335
       */
2336
0
      if (unlikely(fr_der_decode_hdr(NULL, &seq_in, &tag, &ext_len, FR_DER_TAG_OCTETSTRING) <= 0)) {
2337
0
        fr_strerror_printf_push("Failed decoding %s extnValue", parent->name);
2338
0
        slen = -1;
2339
0
        goto error;
2340
0
      }
2341
0
    } else {
2342
      /*
2343
       *  The extnValue is DER tag OCTETSTRING.
2344
       */
2345
0
      if (unlikely(tag != FR_DER_TAG_OCTETSTRING)) {
2346
0
        fr_strerror_printf_push("Expected tag OCTETSTRING for the %s extnValue. Got tag %s",
2347
0
              parent->name, fr_der_tag_to_str(tag));
2348
0
        slen = -1;
2349
0
        goto error;
2350
0
      }
2351
0
    }
2352
2353
    /*
2354
     *  We leave the seq_in buffer at the extnValue field, which lets us decode it later.
2355
     */
2356
0
    FR_PROTO_HEX_DUMP(fr_dbuff_current(&seq_in), fr_dbuff_remaining(&seq_in),
2357
0
          "extnValue");
2358
2359
    /*
2360
     *  Decode the OID, which gets us the DA which lets us know how to decode the extnValue.
2361
     */
2362
0
    if (unlikely((slen = fr_der_decode_oid(&oid_in, fr_der_decode_oid_to_da, &uctx)) <= 0)) {
2363
0
      fr_strerror_const_push("Failed decoding OID in extension");
2364
0
      goto error;
2365
0
    }
2366
2367
    /*
2368
     *  This has been updated with the OID reference.
2369
     */
2370
0
    fr_assert(uctx.parent_da != NULL);
2371
2372
0
    FR_PROTO_HEX_DUMP(fr_dbuff_current(&seq_in), fr_dbuff_remaining(&seq_in), "inner x509 extnValue");
2373
2374
    /*
2375
     *  The extension was not found in the dictionary. We will store the value as raw octets.
2376
     */
2377
0
    if (uctx.parent_da->flags.is_unknown) {
2378
0
      slen = fr_der_decode_octetstring(uctx.ctx, uctx.parent_list, uctx.parent_da,
2379
0
               &seq_in, decode_ctx);
2380
0
    } else {
2381
0
      slen = fr_der_decode_pair_dbuff(uctx.ctx, uctx.parent_list, uctx.parent_da, &seq_in,
2382
0
              decode_ctx);
2383
0
    }
2384
0
    if (unlikely(slen < 0)) {
2385
0
      fr_strerror_printf_push("Failed decoding %s extValue", parent->name);
2386
0
      goto error;
2387
0
    }
2388
2389
0
    if (fr_dbuff_remaining(&seq_in)) {
2390
0
      fr_strerror_printf_push("Failed to decode all of the data in the %s x509_extensions inner sequence",
2391
0
            parent->name);
2392
0
      return -1;
2393
0
    }
2394
2395
0
    FR_PROTO_HEX_DUMP(fr_dbuff_current(&seq_in), fr_dbuff_remaining(&seq_in),
2396
0
          "Remaining data after decoding all of the extension");
2397
0
    max--;
2398
2399
0
    (void) fr_dbuff_set(&our_in, &seq_in);
2400
0
  }
2401
2402
1
  if (fr_pair_list_num_elements(&vp2->children) > 0) {
2403
0
    fr_pair_prepend(&vp->vp_group, vp2);
2404
1
  } else {
2405
1
    talloc_free(vp2);
2406
1
  }
2407
2408
1
  fr_pair_append(out, vp);
2409
2410
1
  return fr_dbuff_set(in, fr_dbuff_end(&our_in));
2411
8
}
2412
2413
static ssize_t fr_der_decode_string(TALLOC_CTX *ctx, fr_pair_list_t *out, fr_dict_attr_t const *parent, fr_dbuff_t *in,
2414
            bool const allowed_chars[], UNUSED fr_der_decode_ctx_t *decode_ctx)
2415
38
{
2416
38
  fr_pair_t *vp;
2417
38
  fr_dbuff_t our_in = FR_DBUFF(in);
2418
38
  char    *str    = NULL;
2419
2420
38
  size_t    pos, len = fr_dbuff_remaining(&our_in);
2421
2422
38
  fr_assert(fr_type_is_string(parent->type));
2423
2424
  /*
2425
   *  ISO/IEC 8825-1:2021
2426
   *  8.23 Encoding for values of the restricted character string types
2427
   *  8.23.1 The data value consists of a string of characters from the character set specified in the ASN.1
2428
   *    type definition. 8.23.2 Each data value shall be encoded independently of other data values of
2429
   *    the same type.
2430
   *  8.23.3 Each character string type shall be encoded as if it had been declared:
2431
   *      [UNIVERSAL x] IMPLICIT OCTET STRING
2432
   *    where x is the number of the universal class tag assigned to the character string type in
2433
   *    Rec. ITU-T X.680 | ISO/IEC 8824-1. The value of the octet string is specified in 8.23.4 and
2434
   *    8.23.5.
2435
   */
2436
2437
38
  vp = fr_pair_afrom_da(ctx, parent);
2438
38
  if (unlikely(!vp)) {
2439
0
  oom:
2440
0
    fr_strerror_const_push("Out of memory");
2441
0
    return -1;
2442
0
  }
2443
38
  PAIR_ALLOCED(vp);
2444
2445
38
  if (unlikely(fr_pair_value_bstr_alloc(vp, &str, len, false) < 0)) {
2446
0
    talloc_free(vp);
2447
0
    goto oom;
2448
0
  }
2449
2450
38
  (void) fr_dbuff_out_memcpy((uint8_t *)str, &our_in, len); /* this can never fail */
2451
2452
38
  if (allowed_chars && len) {
2453
27
    fr_sbuff_t sbuff;
2454
27
    sbuff = FR_SBUFF_OUT(str, len);
2455
2456
27
    if ((pos = fr_sbuff_adv_past_allowed(&sbuff, SIZE_MAX, allowed_chars, NULL)) < len - 1) {
2457
16
    invalid:
2458
16
      fr_strerror_printf_push("Invalid character in a string (%" PRId32 ")", str[pos]);
2459
16
      return -1;
2460
13
    }
2461
2462
    // Check the final character
2463
14
    if (!allowed_chars[(uint8_t)str[pos]]) goto invalid;
2464
14
  }
2465
2466
22
  str[len] = '\0';
2467
2468
22
  fr_pair_append(out, vp);
2469
2470
22
  return fr_dbuff_set(in, &our_in);
2471
38
}
2472
2473
ssize_t fr_der_decode_pair_dbuff(TALLOC_CTX *ctx, fr_pair_list_t *out, fr_dict_attr_t const *parent,
2474
         fr_dbuff_t *in, fr_der_decode_ctx_t *decode_ctx)
2475
7.84k
{
2476
7.84k
  fr_dbuff_t       our_in = FR_DBUFF(in);
2477
7.84k
  fr_der_tag_decode_t const *func;
2478
7.84k
  ssize_t        slen;
2479
7.84k
  uint8_t            tag;
2480
7.84k
  size_t         len;
2481
7.84k
  fr_der_attr_flags_t const *flags = fr_der_attr_flags(parent);
2482
2483
  /*
2484
   *  ISO/IEC 8825-1:2021
2485
   *  The structure of a DER encoding is as follows:
2486
   *
2487
   *    +------------+--------+-------+
2488
   *    | IDENTIFIER | LENGTH | VALUE |
2489
   *    +------------+--------+-------+
2490
   *
2491
   *  The IDENTIFIER is a tag that specifies the type of the value field and is encoded as follows:
2492
   *
2493
   *      8   7    6    5   4   3   2   1
2494
   *    +---+---+-----+---+---+---+---+---+
2495
   *    | Class | P/C |     Tag Number    |
2496
   *    +---+---+-----+---+---+---+---+---+
2497
   *         |
2498
   *         |- 0 = Primitive
2499
   *         |- 1 = Constructed
2500
   *
2501
   *  The CLASS field specifies the encoding class of the tag and may be one of the following values:
2502
   *
2503
   *    +------------------+-------+-------+
2504
   *    |      Class       | Bit 8 | Bit 7 |
2505
   *    +------------------+-------+-------+
2506
   *    | UNIVERSAL        |   0   |   0   |
2507
   *    | APPLICATION      |   0   |   1   |
2508
   *    | CONTEXT-SPECIFIC |   1   |   0   |
2509
   *    | PRIVATE          |   1   |   1   |
2510
   *    +------------------+-------+-------+
2511
   *
2512
   *  The P/C field specifies whether the value field is primitive or constructed.
2513
   *  The TAG NUMBER field specifies the tag number of the value field and is encoded as an unsigned binary
2514
   *  integer.
2515
   *
2516
   *  The LENGTH field specifies the length of the VALUE field and is encoded as an unsigned binary integer
2517
   *  and may be encoded as a single byte or multiple bytes.
2518
   *
2519
   *  The VALUE field contains LENGTH number of bytes and is encoded according to the tag.
2520
   *
2521
   */
2522
2523
  /*
2524
   *  Ensure that we have at least 2 bytes for the header.
2525
   */
2526
7.84k
  slen = fr_dbuff_extend_lowat(NULL, &our_in, 2);
2527
7.84k
  if (unlikely(slen < 0)) {
2528
0
    fr_strerror_const("Failed trying to read more data");
2529
0
    return -1;
2530
0
  }
2531
2532
  /*
2533
   *  One byte is not enough.
2534
   */
2535
7.84k
  if (unlikely(slen == 1)) {
2536
49
    fr_strerror_printf_push("Truncated header while trying to decode %s", parent->name);
2537
49
    return -1;
2538
49
  }
2539
2540
  /*
2541
   *  No header, we may need to create a default value.
2542
   */
2543
7.79k
  if (unlikely(slen == 0)) {
2544
4.24k
    fr_pair_t      *vp;
2545
2546
4.24k
    if (likely(!flags->has_default_value)) return 0;
2547
2548
4
  create_default:
2549
4
    vp = fr_pair_afrom_da(ctx, parent);
2550
4
    if (unlikely(!vp)) {
2551
0
      fr_strerror_const_push("Out of memory");
2552
0
      return -1;
2553
0
    }
2554
4
    PAIR_ALLOCED(vp);
2555
2556
4
    if (unlikely(fr_value_box_copy(vp, &vp->data, flags->default_value) < 0)) {
2557
0
      talloc_free(vp);
2558
0
      return -1;
2559
0
    }
2560
2561
4
    vp->data.enumv = vp->da;
2562
2563
4
    fr_pair_append(out, vp);
2564
2565
4
    return 0;
2566
4
  }
2567
2568
3.55k
  if (unlikely(flags->is_choice)) {
2569
0
    slen = fr_der_decode_choice(ctx, out, parent, &our_in, decode_ctx);
2570
2571
0
    if (unlikely(slen <= 0)) return slen;
2572
2573
0
    return fr_dbuff_set(in, &our_in);
2574
0
  }
2575
2576
3.55k
  slen = fr_der_decode_hdr(parent, &our_in, &tag, &len, FR_DER_TAG_INVALID);
2577
3.55k
  if ((slen == 0) && flags->optional) return 0;
2578
3.52k
  if (slen <= 0) {
2579
301
    fr_strerror_printf_push("Failed decoding %s header", parent->name);
2580
301
    return -1;
2581
301
  }
2582
2583
3.22k
  FR_PROTO_TRACE("Attribute %s, tag %u", parent->name, tag);
2584
2585
  /*
2586
   *  Limit the length of the data to be decoded.
2587
   */
2588
3.22k
  fr_dbuff_set_end(&our_in, fr_dbuff_current(&our_in) + len);
2589
2590
  /*
2591
   *  Unknown attributes have no defaults, and can be zero
2592
   *  length.  We also ignore whatever tag and class is
2593
   *  being used.
2594
   *
2595
   *  @todo - we need to store the tag and class somewhere,
2596
   *  so that re-encoding the "raw" data type will result in
2597
   *  the same data.
2598
   */
2599
3.22k
  if (unlikely(parent->flags.is_unknown)) {
2600
0
    func = &tag_funcs[FR_DER_TAG_OCTETSTRING];
2601
0
    goto decode_it;
2602
0
  }
2603
2604
  /*
2605
   *  No data?  Try to set a default value, OR decode it as
2606
   *  NULL.
2607
   */
2608
3.22k
  if (unlikely(fr_dbuff_remaining(&our_in) == 0)) {
2609
1.20k
    if (flags->has_default_value) goto create_default;
2610
2611
1.20k
    if (tag == FR_DER_TAG_NULL) {
2612
276
      func = &tag_funcs[FR_DER_TAG_NULL];
2613
276
      goto decode_it;
2614
276
    }
2615
2616
1.20k
  }
2617
2618
  /*
2619
   *  Hacks for serialNumber
2620
   */
2621
2.95k
  if (unlikely((tag == FR_DER_TAG_INTEGER) && (parent->type == FR_TYPE_OCTETS))) {
2622
179
    func = &tag_funcs[FR_DER_TAG_OCTETSTRING];
2623
179
    goto decode_it;
2624
179
  }
2625
2626
  /*
2627
   *  We didn't get the expected tag.  If it's not allowed for this parent, OR it's not an
2628
   *  equivalent tag, then that is likely an error.
2629
   *
2630
   *  The "compatible" check is to really to hack around Time and DirectoryString.  It's technically
2631
   *  wrong, and should perhaps be fixed.
2632
   *
2633
   *  @todo - parse 'string' and 'date', and then set flags->restrictions to allow any compatible
2634
   *  DER tags, as a hack.  Doing that makes this a little more generic?  Or, add support for data
2635
   *  types "Time" and "DirectoryString", and do the right thing.  Or, define them as separate
2636
   *  attributes in dictionarty.common, and remove the "tags compatible" checks.
2637
   */
2638
2.77k
  if (unlikely((tag != flags->der_type) &&
2639
2.77k
         (!fr_type_to_der_tag_valid(parent->type, tag) || !fr_der_tags_compatible(tag, flags->der_type)))) {
2640
    /*
2641
     *  Optional or not, if we can create a default value, then do so.
2642
     */
2643
100
    if (flags->has_default_value) goto create_default;
2644
2645
    /*
2646
     *  Optional means "decoded nothing".  Otherwise it's a hard failure.
2647
     */
2648
99
    if (!flags->optional) {
2649
41
      fr_strerror_printf_push("Failed decoding %s - got tag '%s', expected '%s'", parent->name,
2650
41
            fr_der_tag_to_str(tag), fr_der_tag_to_str(flags->der_type));
2651
41
      return -1;
2652
41
    }
2653
2654
58
    return 0;
2655
99
  }
2656
2657
2.67k
  if (flags->is_extensions) {
2658
14
    slen = fr_der_decode_x509_extensions(ctx, out, &our_in, parent, decode_ctx);
2659
14
    if (slen <= 0) return slen;
2660
2661
1
    return fr_dbuff_set(in, &our_in);
2662
14
  }
2663
2664
2.65k
  func = &type_funcs[parent->type];
2665
2.65k
  if (!func->decode) func = &tag_funcs[tag];
2666
2.65k
  fr_assert(func != NULL);
2667
2.65k
  fr_assert(func->decode != NULL);
2668
2669
  /*
2670
   *  Enforce limits on min/max.
2671
   */
2672
2.65k
  switch (tag) {
2673
2.28k
  case FR_DER_TAG_SEQUENCE:
2674
2.35k
  case FR_DER_TAG_SET:
2675
    /*
2676
     *  min/max is the number of elements, NOT the number of bytes.  The set / sequence
2677
     *  decoder has to validate its input.
2678
     */
2679
2680
    /*
2681
     *  If the sequence or set is an OID Value pair, then we decode it with the special OID
2682
     *  Value decoder.
2683
     */
2684
2.35k
    if (flags->is_oid_and_value) func = &oid_and_value_func;
2685
2.35k
    break;
2686
2687
    /*
2688
     *  min/max applies to the decoded values.
2689
     */
2690
87
  case FR_DER_TAG_INTEGER:
2691
87
  case FR_DER_TAG_ENUMERATED:
2692
87
    break;
2693
2694
215
  default:
2695
215
    if (parent->flags.is_raw) break;
2696
2697
    /*
2698
     *  min/max can be fixed width, but we only care for 'octets' and 'string'.
2699
     *
2700
     *  @todo - when we support IP addresses (which DER usually encodes as strings), this
2701
     *  check will have to be updated.
2702
     */
2703
215
    if (parent->flags.is_known_width) {
2704
57
      if (!fr_type_is_variable_size(parent->type)) break;
2705
2706
6
      if (len != parent->flags.length) {
2707
5
        fr_strerror_printf_push("Data length (%zu) is different from expected fixed size (%u)", len, parent->flags.length);
2708
5
        return -1;
2709
5
      }
2710
2711
1
      break;
2712
6
    }
2713
2714
158
    if (flags->min && (len < flags->min)) {
2715
0
      fr_strerror_printf_push("Data length (%zu) is smaller than expected minimum size (%u)", len, flags->min);
2716
0
      return -1;
2717
0
    }
2718
2719
158
    fr_assert(flags->max <= DER_MAX_STR); /* 'max' is always set in the attr_valid() function */
2720
2721
158
    if (unlikely(len > flags->max)) {
2722
0
      fr_strerror_printf_push("Data length (%zu) exceeds max size (%" PRIu64 ")", len, flags->max);
2723
0
      return -1;
2724
0
    }
2725
158
    break;
2726
2.65k
  }
2727
2728
  /*
2729
   *  The decode function can return 0 if len==0.  This is true for 'null' data types, and
2730
   *  for variable-sized types such as strings.
2731
   */
2732
3.10k
decode_it:
2733
3.10k
  slen = func->decode(ctx, out, parent, &our_in, decode_ctx);
2734
3.10k
  if (unlikely(slen < 0)) return slen;
2735
2736
  /*
2737
   *  There may be extra data, in which case we ignore it.
2738
   *
2739
   *  @todo - if the data type is fixed size, then return an error.
2740
   */
2741
2.22k
  if ((size_t) slen < len) {
2742
115
    FR_PROTO_TRACE("Ignoring extra data");
2743
115
    FR_PROTO_HEX_DUMP(fr_dbuff_current(&our_in), fr_dbuff_remaining(&our_in), " ");
2744
2745
115
    fr_dbuff_advance(&our_in, len - (size_t) slen);
2746
115
  }
2747
2748
2.22k
  return fr_dbuff_set(in, &our_in);
2749
3.10k
}
2750
2751
static ssize_t fr_der_decode_proto(TALLOC_CTX *ctx, fr_pair_list_t *out, uint8_t const *data, size_t data_len,
2752
           void *proto_ctx)
2753
877
{
2754
877
  fr_dbuff_t our_in = FR_DBUFF_TMP(data, data_len);
2755
877
  fr_der_decode_ctx_t *der_ctx = proto_ctx;
2756
877
  fr_dict_attr_t const *parent = der_ctx->root;
2757
2758
877
  if (!parent || (parent == fr_dict_root(dict_der))) {
2759
0
    fr_strerror_printf_push("Invalid dictionary. DER decoding requires a specific dictionary.");
2760
0
    return -1;
2761
0
  }
2762
2763
877
  return fr_der_decode_pair_dbuff(ctx, out, parent, &our_in, proto_ctx);
2764
877
}
2765
2766
/** Decode a DER structure using the specific dictionary
2767
 *
2768
 * @param[in] ctx   to allocate new pairs in.
2769
 * @param[in] out   where new VPs will be added
2770
 * @param[in] parent    Parent attribute.  This should be the root of the dictionary
2771
 *        we're using to decode DER data.  This only specifies structures
2772
 *        like SEQUENCES.  OID based pairs are resolved using the global
2773
 *        dictionary tree.
2774
 * @param[in] data    to decode.
2775
 * @param[in] data_len    Length of data.
2776
 * @param[in] decode_ctx  to pass to decode function.
2777
 *
2778
 */
2779
static ssize_t decode_pair(TALLOC_CTX *ctx, fr_pair_list_t *out, fr_dict_attr_t const *parent, uint8_t const *data,
2780
         size_t data_len, void *decode_ctx)
2781
0
{
2782
0
  if (unlikely(parent == fr_dict_root(dict_der))) {
2783
0
    fr_strerror_printf_push("Invalid dictionary. DER decoding requires a specific dictionary.");
2784
0
    return -1;
2785
0
  }
2786
2787
0
  return fr_der_decode_pair_dbuff(ctx, out, parent, &FR_DBUFF_TMP(data, data_len), decode_ctx);
2788
0
}
2789
2790
/*
2791
 *  Test points
2792
 */
2793
static int decode_test_ctx(void **out, TALLOC_CTX *ctx, UNUSED fr_dict_t const *dict,
2794
         fr_dict_attr_t const *root_da)
2795
6.55k
{
2796
6.55k
  fr_der_decode_ctx_t *test_ctx;
2797
2798
6.55k
  test_ctx = talloc_zero(ctx, fr_der_decode_ctx_t);
2799
6.55k
  if (!test_ctx) return -1;
2800
2801
6.55k
  test_ctx->tmp_ctx = talloc_new(test_ctx);
2802
6.55k
  test_ctx->root = root_da;  
2803
2804
6.55k
  *out = test_ctx;
2805
2806
6.55k
  return 0;
2807
6.55k
}
2808
2809
extern fr_test_point_pair_decode_t der_tp_decode_pair;
2810
fr_test_point_pair_decode_t    der_tp_decode_pair = {
2811
         .test_ctx = decode_test_ctx,
2812
         .func   = decode_pair,
2813
};
2814
2815
extern fr_test_point_proto_decode_t der_tp_decode_proto;
2816
fr_test_point_proto_decode_t      der_tp_decode_proto = {
2817
         .test_ctx = decode_test_ctx,
2818
         .func   = fr_der_decode_proto,
2819
};