Coverage Report

Created: 2026-02-26 06:38

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/freeradius-server/src/protocols/der/encode.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: 253d9b6c5269b51e3651a31836e7bd31debe900a $
19
 *
20
 * @file protocols/der/encode.c
21
 * @brief Functions to encode DER
22
 *
23
 * @copyright 2025 Network RADIUS SAS (legal@networkradius.com)
24
 */
25
RCSID("$Id: 253d9b6c5269b51e3651a31836e7bd31debe900a $")
26
27
#include <freeradius-devel/util/dbuff.h>
28
#include <freeradius-devel/util/encode.h>
29
#include <freeradius-devel/util/proto.h>
30
#include <freeradius-devel/util/sbuff.h>
31
#include <freeradius-devel/util/struct.h>
32
#include <freeradius-devel/util/time.h>
33
#include <freeradius-devel/util/dict_ext.h>
34
35
#include <freeradius-devel/io/test_point.h>
36
37
#include "der.h"
38
39
extern fr_dict_attr_t const *attr_oid_tree;
40
41
typedef struct {
42
  uint8_t *tmp_ctx;     //!< Temporary context for encoding.
43
} fr_der_encode_ctx_t;
44
45
/** Function signature for DER encode functions
46
 *
47
 * @param[in] dbuff   Where to encode the data.
48
 * @param[in] cursor    Where to encode the data from.
49
 * @param[in] encode_ctx  Any encode specific data.
50
 * @return
51
 *  - > 0 on success.  How many bytes were encoded.
52
 *  - 0 no bytes encoded.
53
 *  - < 0 on error.  May be the offset (as a negative value) where the error occurred.
54
 */
55
typedef ssize_t (*fr_der_encode_t)(fr_dbuff_t *dbuff, fr_dcursor_t *cursor, fr_der_encode_ctx_t *encode_ctx);
56
57
typedef struct {
58
  fr_der_tag_constructed_t constructed;
59
  fr_der_encode_t    encode;
60
} fr_der_tag_encode_t;
61
62
63
static ssize_t fr_der_encode_oid_and_value(fr_dbuff_t *dbuff, fr_dcursor_t *cursor, fr_der_encode_ctx_t *encode_ctx) CC_HINT(nonnull);
64
static ssize_t fr_der_encode_choice(fr_dbuff_t *dbuff, fr_dcursor_t *cursor, fr_der_encode_ctx_t *encode_ctx) CC_HINT(nonnull);
65
66
/*
67
 *  We have per-type function names to make it clear that different types have different encoders.
68
 *  However, the methods to encode them are the same.  So rather than having trampoline functions, we just
69
 *  use defines.
70
 */
71
#define fr_der_encode_enumerated fr_der_encode_integer
72
73
74
static ssize_t fr_der_encode_len(fr_dbuff_t *dbuff, fr_dbuff_marker_t *length_start) CC_HINT(nonnull);
75
static inline CC_HINT(always_inline) ssize_t
76
  fr_der_encode_tag(fr_dbuff_t *dbuff, fr_der_tag_t tag_num, fr_der_tag_class_t tag_class,
77
        fr_der_tag_constructed_t constructed) CC_HINT(nonnull);
78
static ssize_t encode_value(fr_dbuff_t *dbuff, fr_dcursor_t *cursor, void *encode_ctx);
79
80
/** Compare two pairs by their tag number.
81
 *
82
 * @param[in] a First pair.
83
 * @param[in] b Second pair.
84
 * @return    -1 if a < b, 0 if a == b, 1 if a > b.
85
 */
86
static inline CC_HINT(always_inline) int8_t fr_der_pair_cmp_by_da_tag(void const *a, void const *b)
87
0
{
88
0
  fr_pair_t const *my_a = a;
89
0
  fr_pair_t const *my_b = b;
90
91
0
  return CMP_PREFER_SMALLER(fr_der_flag_der_type(my_a->da), fr_der_flag_der_type(my_b->da));
92
0
}
93
94
static ssize_t encode_pair(fr_dbuff_t *dbuff, UNUSED fr_da_stack_t *da_stack, UNUSED unsigned int depth, fr_dcursor_t *cursor,
95
         void *encode_ctx)
96
0
{
97
0
  return encode_value(dbuff, cursor, encode_ctx);
98
0
}
99
100
static ssize_t fr_der_encode_boolean(fr_dbuff_t *dbuff, fr_dcursor_t *cursor, UNUSED fr_der_encode_ctx_t *encode_ctx)
101
0
{
102
0
  fr_dbuff_t   our_dbuff = FR_DBUFF(dbuff);
103
0
  fr_pair_t const *vp;
104
0
  uint8_t    value;
105
106
0
  vp = fr_dcursor_current(cursor);
107
0
  PAIR_VERIFY(vp);
108
0
  fr_assert(!vp->da->flags.is_raw);
109
110
  /*
111
   *  ISO/IEC 8825-1:2021
112
   *  8.2 Encoding of a boolean value
113
   *  8.2.1 The encoding of a boolean value shall be primitive.
114
   *        The contents octets shall consist of a single octet.
115
   *  8.2.2 If the boolean value is:
116
   *        FALSE the octet shall be zero [0x00].
117
   *        If the boolean value is TRUE the octet shall have any non-zero value, as a sender's option.
118
   *
119
   *  11.1 Boolean values
120
   *    If the encoding represents the boolean value TRUE, its single contents octet shall have all
121
   *    eight bits set to one [0xFF]. (Contrast with 8.2.2.)
122
   */
123
0
  value = vp->vp_bool;
124
125
0
  FR_DBUFF_IN_RETURN(&our_dbuff, (uint8_t)(value ? DER_BOOLEAN_TRUE : DER_BOOLEAN_FALSE));
126
127
0
  return fr_dbuff_set(dbuff, &our_dbuff);
128
0
}
129
130
static ssize_t fr_der_encode_integer(fr_dbuff_t *dbuff, fr_dcursor_t *cursor, UNUSED fr_der_encode_ctx_t *encode_ctx)
131
0
{
132
0
  fr_dbuff_t   our_dbuff = FR_DBUFF(dbuff);
133
0
  fr_pair_t const *vp;
134
0
  uint64_t         value;
135
0
  uint8_t    first_octet = 0;
136
0
  size_t     i, len;
137
138
0
  vp = fr_dcursor_current(cursor);
139
0
  PAIR_VERIFY(vp);
140
0
  fr_assert(!vp->da->flags.is_raw);
141
142
  /*
143
   *  ISO/IEC 8825-1:2021
144
   *  8.3 Encoding of an integer value
145
   *  8.3.1 The encoding of an integer value shall be primitive.
146
   *        The contents octets shall consist of one or more octets.
147
   *  8.3.2 If the contents octets of an integer value encoding consist of more than one octet,
148
   *        then the bits of the first octet and bit 8 of the second octet:
149
   *        a) shall not all be ones; and
150
   *        b) shall not all be zero.
151
   *        NOTE - These rules ensure that an integer value is always encoded in the smallest possible number
152
   *        of octets. 8.3.3 The contents octets shall be a two's complement binary number equal to the
153
   *        integer value, and consisting of bits 8 to 1 of the first octet, followed by bits 8 to 1 of the
154
   *        second octet, followed by bits 8 to 1 of each octet in turn up to and including the last octet of
155
   *        the contents octets.
156
   */
157
158
  /*
159
   *  Some 'integer' types such as serialNumber are too
160
   *  large for 64-bits.  So we just treat them as octet
161
   *  strings.
162
   */
163
0
  if (vp->da->type != FR_TYPE_INT64) {
164
0
    fr_assert(vp->da->type == FR_TYPE_OCTETS);
165
0
    FR_DBUFF_IN_MEMCPY_RETURN(&our_dbuff, vp->vp_octets, vp->vp_length);
166
0
    return fr_dbuff_set(dbuff, &our_dbuff);
167
0
  }
168
169
  /*
170
   *  Yes, the type is FR_TYPE_INT64.  But we encode the
171
   *  data as-is, without caring about things like signed
172
   *  math.
173
   */
174
0
  value = vp->vp_uint64;
175
176
0
  for (i = 0, len = 0; i < sizeof(value); i++) {
177
0
    uint8_t byte = (value >> 56) & 0xff;
178
179
0
    value <<= 8;
180
181
0
    if (len == 0) {
182
0
      first_octet = byte;
183
0
      len++;
184
0
      continue;
185
186
0
    } else if (len == 1) {
187
      /*
188
       *  8.3.2 If the contents octets of an integer value encoding consist of more than one
189
       *  octet, then the bits of the first octet and bit 8 of the second octet: a) shall not all
190
       *  be ones; and b) shall not all be zero.
191
       */
192
0
      if ((first_octet == 0xff && (byte & 0x80)) || ((first_octet == 0x00) && (byte >> 7 == 0))) {
193
0
        if (i == sizeof(value) - 1) {
194
          /*
195
           *  If this is the only byte, then we can encode it as a single byte.
196
           */
197
0
          FR_DBUFF_IN_RETURN(&our_dbuff, byte);
198
0
          continue;
199
0
        }
200
201
0
        first_octet = byte;
202
0
        continue;
203
204
0
      } else {
205
0
        FR_DBUFF_IN_RETURN(&our_dbuff, first_octet);
206
0
        FR_DBUFF_IN_RETURN(&our_dbuff, byte);
207
0
        len++;
208
0
        continue;
209
0
      }
210
0
    }
211
212
0
    FR_DBUFF_IN_RETURN(&our_dbuff, byte);
213
0
    len++;
214
0
  }
215
216
0
  return fr_dbuff_set(dbuff, &our_dbuff);
217
0
}
218
219
static ssize_t fr_der_encode_bitstring(fr_dbuff_t *dbuff, fr_dcursor_t *cursor, fr_der_encode_ctx_t *encode_ctx)
220
0
{
221
0
  fr_dbuff_t our_dbuff = FR_DBUFF(dbuff);
222
0
  fr_pair_t const *vp;
223
0
  ssize_t    slen;
224
0
  uint8_t    unused_bits = 0;
225
226
0
  vp = fr_dcursor_current(cursor);
227
0
  PAIR_VERIFY(vp);
228
0
  fr_assert(!vp->da->flags.is_raw);
229
230
  /*
231
   *  ISO/IEC 8825-1:2021
232
   *  8.6 Encoding of a bitstring value
233
   *    8.6.1 The encoding of a bitstring value shall be either primitive or constructed at the option
234
   *          of the sender.
235
   *      NOTE - Where it is necessary to transfer part of a bit string before the entire
236
   *             bitstring is available, the constructed encoding is used.
237
   *    8.6.2 The contents octets for the primitive encoding shall contain an initial octet followed
238
   *          by zero, one or more subsequent octets.
239
   *      8.6.2.1 The bits in the bitstring value, commencing with the leading bit and proceeding
240
   *        to the trailing bit, shall be placed in bits 8 to 1 of the first subsequent
241
   *        octet, followed by bits 8 to 1 of the second subsequent octet, followed by bits
242
   *        8 to 1 of each octet in turn, followed by as many bits as are needed of the
243
   *        final subsequent octet, commencing with bit 8.
244
   *        NOTE - The terms "leading bit" and "trailing bit" are defined in
245
   *               Rec. ITU-T X.680 | ISO/IEC 8824-1, 22.2.
246
   *      8.6.2.2 The initial octet shall encode, as an unsigned binary integer with bit 1 as the
247
   *        least significant bit, the number of unused bits in the final subsequent octet.
248
   *        The number shall be in the range zero to seven.
249
   *      8.6.2.3 If the bitstring is empty, there shall be no subsequent octets, and the initial
250
   *        octet shall be zero.
251
   *
252
   *  10.2 String encoding forms
253
   *    For bitstring, octetstring and restricted character string types, the constructed form of
254
   *    encoding shall not be used. (Contrast with 8.23.6.)
255
   *
256
   *  11.2 Unused bits 11.2.1 Each unused bit in the final octet of the encoding of a bit string value shall
257
   *       be set to zero.
258
   */
259
260
0
  if (fr_type_is_struct(vp->vp_type)) {
261
    /*
262
     *  For struct type, we need to encode the struct as a bitstring using the
263
     *  fr_struct_to_network function.
264
     */
265
0
    unsigned int    depth = vp->da->depth - 1;
266
0
    fr_da_stack_t   da_stack;
267
0
    fr_dbuff_t    work_dbuff = FR_DBUFF(&our_dbuff);
268
0
    fr_dbuff_marker_t unused_bits_marker;
269
0
    uint8_t     last_byte = 0;
270
271
0
    fr_dbuff_marker(&unused_bits_marker, &work_dbuff);
272
0
    FR_DBUFF_ADVANCE_RETURN(&work_dbuff, 1);
273
274
0
    fr_proto_da_stack_build(&da_stack, vp->da);
275
276
0
    FR_PROTO_STACK_PRINT(&da_stack, depth);
277
278
0
    slen = fr_struct_to_network(&work_dbuff, &da_stack, depth, cursor, encode_ctx, NULL, NULL);
279
0
    if (slen < 0) {
280
0
      fr_strerror_printf("Failed to encode struct: %s", fr_strerror());
281
0
      return slen;
282
0
    }
283
284
    /*
285
     *  We need to trim any empty trailing octets
286
     */
287
0
    while ((slen > 1) && (fr_dbuff_current(&work_dbuff) != fr_dbuff_start(&work_dbuff))) {
288
0
      uint8_t byte;
289
290
      /*
291
       *  Move the dbuff cursor back by one byte
292
       */
293
0
      fr_dbuff_set(&work_dbuff, fr_dbuff_current(&work_dbuff) - sizeof(byte));
294
295
0
      if (fr_dbuff_out(&byte, &work_dbuff) < 0) {
296
0
        fr_strerror_const("Failed to read byte");
297
0
        return -1;
298
0
      }
299
300
0
      if (byte != 0) break;
301
302
      /*
303
       *  Trim this byte from the buff
304
       */
305
0
      fr_dbuff_set_end(&work_dbuff, fr_dbuff_current(&work_dbuff) - sizeof(byte));
306
0
      fr_dbuff_set(&work_dbuff, fr_dbuff_current(&work_dbuff) - (sizeof(byte) * 2));
307
0
      slen--;
308
0
    }
309
310
    /*
311
     *  Grab the last octet written to the dbuff and count the number of trailing 0 bits
312
     */
313
0
    if (fr_dbuff_out(&last_byte, &work_dbuff) < 0) {
314
0
      fr_strerror_const("Failed to read last byte");
315
0
      return -1;
316
0
    }
317
318
0
    while ((last_byte != 0) && ((last_byte & 0x01) == 0)) {
319
0
      unused_bits++;
320
0
      last_byte >>= 1;
321
0
    }
322
323
    /*
324
     *  Write the unused bits
325
     */
326
0
    fr_dbuff_set(&our_dbuff, fr_dbuff_current(&unused_bits_marker));
327
0
    FR_DBUFF_IN_MEMCPY_RETURN(&our_dbuff, &unused_bits, 1);
328
329
    /*
330
     *  Copy the work dbuff to the output dbuff
331
     */
332
0
    fr_dbuff_set(&work_dbuff, &our_dbuff);
333
0
    FR_DBUFF_IN_MEMCPY_RETURN(&our_dbuff, &work_dbuff, (size_t)slen);
334
335
0
    return fr_dbuff_set(dbuff, &our_dbuff);
336
0
  }
337
338
  /*
339
   *  For octets type, we do not need to write the unused bits portion
340
   *  because this information should be retained when encoding/decoding.
341
   */
342
0
  if (vp->vp_length == 0) {
343
0
    FR_DBUFF_IN_RETURN(&our_dbuff, (uint8_t) 0x00);
344
345
0
  } else {
346
0
    FR_DBUFF_IN_MEMCPY_RETURN(&our_dbuff, vp->vp_octets, vp->vp_length);
347
0
  }
348
349
0
  return fr_dbuff_set(dbuff, &our_dbuff);
350
0
}
351
352
static ssize_t fr_der_encode_ipv4_addr(fr_dbuff_t *dbuff, fr_dcursor_t *cursor, UNUSED fr_der_encode_ctx_t *encode_ctx)
353
0
{
354
0
  fr_dbuff_t   our_dbuff = FR_DBUFF(dbuff);
355
0
  fr_pair_t const *vp;
356
357
0
  vp = fr_dcursor_current(cursor);
358
0
  PAIR_VERIFY(vp);
359
0
  fr_assert(!vp->da->flags.is_raw);
360
361
  /*
362
   *  RFC3779 Section 2.1.1.
363
   *
364
   *  An IP address or prefix is encoded in the IP address delegation
365
   *  extension as a DER-encoded ASN.1 BIT STRING containing the constant
366
   *  most-significant bits.  Recall [X.690] that the DER encoding of a BIT
367
   *  STRING consists of the BIT STRING type (0x03), followed by (an
368
   *  encoding of) the number of value octets, followed by the value.  The
369
   *  value consists of an "initial octet" that specifies the number of
370
   *  unused bits in the last value octet, followed by the "subsequent
371
   *  octets" that contain the octets of the bit string.  (For IP
372
   *  addresses, the encoding of the length will be just the length.)
373
   */
374
375
  /*
376
   *  The number of unused bits in the last byte is always zero.
377
   */
378
0
  FR_DBUFF_IN_RETURN(&our_dbuff, (uint8_t) 0x00);
379
0
  FR_DBUFF_IN_MEMCPY_RETURN(&our_dbuff, (uint8_t const *) &vp->vp_ipv4addr, sizeof(vp->vp_ipv4addr));
380
381
0
  return fr_dbuff_set(dbuff, &our_dbuff);
382
0
}
383
384
static ssize_t fr_der_encode_ipv4_prefix(fr_dbuff_t *dbuff, fr_dcursor_t *cursor, UNUSED fr_der_encode_ctx_t *encode_ctx)
385
0
{
386
0
  fr_dbuff_t   our_dbuff = FR_DBUFF(dbuff);
387
0
  fr_pair_t const *vp;
388
0
  size_t    len;
389
390
0
  vp = fr_dcursor_current(cursor);
391
0
  PAIR_VERIFY(vp);
392
0
  fr_assert(!vp->da->flags.is_raw);
393
394
0
  if (vp->vp_ip.prefix == 0) {
395
0
    FR_DBUFF_IN_RETURN(&our_dbuff, (uint8_t) 0x00);
396
0
    return fr_dbuff_set(dbuff, &our_dbuff);
397
0
  }
398
399
  /*
400
   *  RFC3779 Section 2.1.1.
401
   *
402
   *  An IP address or prefix is encoded in the IP address delegation
403
   *  extension as a DER-encoded ASN.1 BIT STRING containing the constant
404
   *  most-significant bits.  Recall [X.690] that the DER encoding of a BIT
405
   *  STRING consists of the BIT STRING type (0x03), followed by (an
406
   *  encoding of) the number of value octets, followed by the value.  The
407
   *  value consists of an "initial octet" that specifies the number of
408
   *  unused bits in the last value octet, followed by the "subsequent
409
   *  octets" that contain the octets of the bit string.  (For IP
410
   *  addresses, the encoding of the length will be just the length.)
411
   */
412
0
  if (vp->vp_ip.prefix == 32) {
413
0
    FR_DBUFF_IN_RETURN(&our_dbuff, (uint8_t) 0x00);
414
0
    FR_DBUFF_IN_MEMCPY_RETURN(&our_dbuff, (uint8_t const *) &vp->vp_ipv4addr, sizeof(vp->vp_ipv4addr));
415
0
    return fr_dbuff_set(dbuff, &our_dbuff);
416
0
  }
417
418
0
  FR_DBUFF_IN_RETURN(&our_dbuff, (uint8_t) (8 - (vp->vp_ip.prefix & 0x07)));
419
420
0
  len = (vp->vp_ip.prefix + 0x07) >> 3;
421
422
0
  if (len) FR_DBUFF_IN_MEMCPY_RETURN(&our_dbuff, (uint8_t const *) &vp->vp_ipv4addr, len);
423
424
0
  return fr_dbuff_set(dbuff, &our_dbuff);
425
0
}
426
427
static ssize_t fr_der_encode_ipv6_addr(fr_dbuff_t *dbuff, fr_dcursor_t *cursor, UNUSED fr_der_encode_ctx_t *encode_ctx)
428
0
{
429
0
  fr_dbuff_t   our_dbuff = FR_DBUFF(dbuff);
430
0
  fr_pair_t const *vp;
431
432
0
  vp = fr_dcursor_current(cursor);
433
0
  PAIR_VERIFY(vp);
434
0
  fr_assert(!vp->da->flags.is_raw);
435
436
  /*
437
   *  RFC3779 Section 2.1.1.
438
   *
439
   *  An IP address or prefix is encoded in the IP address delegation
440
   *  extension as a DER-encoded ASN.1 BIT STRING containing the constant
441
   *  most-significant bits.  Recall [X.690] that the DER encoding of a BIT
442
   *  STRING consists of the BIT STRING type (0x03), followed by (an
443
   *  encoding of) the number of value octets, followed by the value.  The
444
   *  value consists of an "initial octet" that specifies the number of
445
   *  unused bits in the last value octet, followed by the "subsequent
446
   *  octets" that contain the octets of the bit string.  (For IP
447
   *  addresses, the encoding of the length will be just the length.)
448
   */
449
450
  /*
451
   *  The number of unused bits in the last byte is always zero.
452
   */
453
0
  FR_DBUFF_IN_RETURN(&our_dbuff, (uint8_t) 0x00);
454
0
  FR_DBUFF_IN_MEMCPY_RETURN(&our_dbuff, (uint8_t const *) &vp->vp_ipv6addr, sizeof(vp->vp_ipv6addr));
455
456
0
  return fr_dbuff_set(dbuff, &our_dbuff);
457
0
}
458
459
static ssize_t fr_der_encode_ipv6_prefix(fr_dbuff_t *dbuff, fr_dcursor_t *cursor, UNUSED fr_der_encode_ctx_t *encode_ctx)
460
0
{
461
0
  fr_dbuff_t   our_dbuff = FR_DBUFF(dbuff);
462
0
  fr_pair_t const *vp;
463
0
  size_t    len;
464
465
0
  vp = fr_dcursor_current(cursor);
466
0
  PAIR_VERIFY(vp);
467
0
  fr_assert(!vp->da->flags.is_raw);
468
469
  /*
470
   *  RFC3779 Section 2.1.1.
471
   *
472
   *  An IP address or prefix is encoded in the IP address delegation
473
   *  extension as a DER-encoded ASN.1 BIT STRING containing the constant
474
   *  most-significant bits.  Recall [X.690] that the DER encoding of a BIT
475
   *  STRING consists of the BIT STRING type (0x03), followed by (an
476
   *  encoding of) the number of value octets, followed by the value.  The
477
   *  value consists of an "initial octet" that specifies the number of
478
   *  unused bits in the last value octet, followed by the "subsequent
479
   *  octets" that contain the octets of the bit string.  (For IP
480
   *  addresses, the encoding of the length will be just the length.)
481
   */
482
483
0
  if (vp->vp_ip.prefix == 128) {
484
0
    FR_DBUFF_IN_RETURN(&our_dbuff, (uint8_t) 0x00);
485
0
    FR_DBUFF_IN_MEMCPY_RETURN(&our_dbuff, (uint8_t const *) &vp->vp_ipv6addr, sizeof(vp->vp_ipv6addr));
486
0
    return fr_dbuff_set(dbuff, &our_dbuff);
487
0
  }
488
489
0
  FR_DBUFF_IN_RETURN(&our_dbuff, (uint8_t) (8 - (vp->vp_ip.prefix & 0x07)));
490
491
0
  len = (vp->vp_ip.prefix + 0x07) >> 3;
492
493
0
  if (len) FR_DBUFF_IN_MEMCPY_RETURN(&our_dbuff, (uint8_t const *) &vp->vp_ipv6addr, len);
494
495
0
  return fr_dbuff_set(dbuff, &our_dbuff);
496
0
}
497
498
499
static ssize_t fr_der_encode_combo_ip(fr_dbuff_t *dbuff, fr_dcursor_t *cursor, UNUSED fr_der_encode_ctx_t *encode_ctx)
500
0
{
501
0
  fr_dbuff_t   our_dbuff = FR_DBUFF(dbuff);
502
0
  fr_pair_t const *vp;
503
504
0
  vp = fr_dcursor_current(cursor);
505
0
  PAIR_VERIFY(vp);
506
0
  fr_assert(!vp->da->flags.is_raw);
507
508
  /*
509
   *  RFC5280 Section 4.2.1.6
510
   *
511
   *  When the subjectAltName extension contains an iPAddress, the address
512
   *  MUST be stored in the octet string in "network byte order", as
513
   *  specified in [RFC791].  The least significant bit (LSB) of each octet
514
   *  is the LSB of the corresponding byte in the network address.  For IP
515
   *  version 4, as specified in [RFC791], the octet string MUST contain
516
   *  exactly four octets.  For IP version 6, as specified in
517
   *  [RFC2460], the octet string MUST contain exactly sixteen octets.
518
   */
519
0
  if (vp->vp_ip.af == AF_INET) {
520
0
    FR_DBUFF_IN_MEMCPY_RETURN(&our_dbuff, (uint8_t const *) &vp->vp_ipv4addr, sizeof(vp->vp_ipv4addr));
521
0
  } else {
522
0
    FR_DBUFF_IN_MEMCPY_RETURN(&our_dbuff, (uint8_t const *) &vp->vp_ipv6addr, sizeof(vp->vp_ipv6addr));
523
0
  }
524
525
0
  return fr_dbuff_set(dbuff, &our_dbuff);
526
0
}
527
528
529
static ssize_t fr_der_encode_octetstring(fr_dbuff_t *dbuff, fr_dcursor_t *cursor,
530
           UNUSED fr_der_encode_ctx_t *encode_ctx)
531
0
{
532
0
  fr_dbuff_t  our_dbuff = FR_DBUFF(dbuff);
533
0
  fr_pair_t const *vp;
534
535
0
  vp = fr_dcursor_current(cursor);
536
0
  PAIR_VERIFY(vp);
537
  /* can be raw! */
538
539
  /*
540
   *  ISO/IEC 8825-1:2021
541
   *  8.7 Encoding of an octetstring value
542
   *    8.7.1 The encoding of an octetstring value shall be either primitive or constructed at the
543
   *          option of the sender.
544
   *      NOTE - Where it is necessary to transfer part of an octet string before the entire
545
   *             octetstring is available, the constructed encoding is used.
546
   *    8.7.2 The primitive encoding contains zero, one or more contents octets equal in value to the
547
   *          octets in the data value, in the order they appear in the data value, and with the most
548
   *          significant bit of an octet of the data value aligned with the most significant bit of an
549
   *          octet of the contents octets.
550
   *    8.7.3 The contents octets for the constructed encoding shall consist of zero, one, or more
551
   *          encodings.
552
   *      NOTE - Each such encoding includes identifier, length, and contents octets, and may
553
   *             include end-of-contents octets if it is constructed.
554
   *      8.7.3.1 To encode an octetstring value in this way, it is segmented. Each segment shall
555
   *             consist of a series of consecutive octets of the value. There shall be no
556
   *             significance placed on the segment boundaries.
557
   *        NOTE - A segment may be of size zero, i.e. contain no octets.
558
   *
559
   *  10.2 String encoding forms
560
   *    For bitstring, octetstring and restricted character string types, the constructed form of
561
   *    encoding shall not be used. (Contrast with 8.23.6.)
562
   */
563
0
  FR_DBUFF_IN_MEMCPY_RETURN(&our_dbuff, vp->vp_octets, vp->vp_length);
564
565
0
  return fr_dbuff_set(dbuff, &our_dbuff);
566
0
}
567
568
569
static ssize_t fr_der_encode_null(UNUSED fr_dbuff_t *dbuff, fr_dcursor_t *cursor,
570
          UNUSED fr_der_encode_ctx_t *encode_ctx)
571
0
{
572
0
  fr_pair_t const *vp;
573
574
0
  vp = fr_dcursor_current(cursor);
575
0
  PAIR_VERIFY(vp);
576
0
  fr_assert(!vp->da->flags.is_raw);
577
578
  /*
579
   *  ISO/IEC 8825-1:2021
580
   *  8.8 Encoding of a null value
581
   *  8.8.1 The encoding of a null value shall be primitive.
582
   *  8.8.2 The contents octets shall not contain any octets.
583
   *    NOTE - The length must be zero.
584
   */
585
0
  if (vp->vp_length != 0) {
586
0
    fr_strerror_printf("Null has non-zero length %zu", vp->vp_length);
587
0
    return -1;
588
0
  }
589
590
0
  return 0;
591
0
}
592
593
static ssize_t fr_der_encode_oid_from_value(fr_dbuff_t *dbuff, uint64_t value, uint64_t *component, int *count)
594
0
{
595
0
  fr_dbuff_t  our_dbuff;
596
0
  int   i;
597
0
  uint64_t  oid;
598
599
  /*
600
   *  The first subidentifier is the encoding of the first two object identifier components, encoded as:
601
   *    (X * 40) + Y
602
   *  where X is the first number and Y is the second number.
603
   *  The first number is 0, 1, or 2.
604
   */
605
0
  if (*count == 0) {
606
0
    if (!((value == 0) || (value == 1) || (value == 2))) {
607
0
      fr_strerror_printf("Invalid value %" PRIu64 " for initial component", value);
608
0
      return -1;
609
0
    }
610
611
0
    *component = value;
612
0
    (*count)++;
613
0
    return 0;
614
0
  }
615
616
0
  if (*count == 1) {
617
0
    if ((*component < 2) && (value > 40)) {
618
0
      fr_strerror_printf("Invalid value %" PRIu64 " for second component", value);
619
0
      return -1;
620
0
    }
621
622
0
    oid = *component * 40 + value;
623
0
  } else {
624
0
    oid = value;
625
0
  }
626
627
0
  our_dbuff = FR_DBUFF(dbuff);
628
629
  /*
630
   *  Encode the number as 7-bit chunks.  Just brute-force over all bits, as doing that ends
631
   *  up being fast enough.
632
   *
633
   *  i.e. if we did anything else to count bits, it would end up with pretty much the same
634
   *  code.
635
   */
636
0
  for (i = 63; i >= 0; i -= 7) {
637
0
    uint8_t more, part;
638
639
0
    part = (oid >> i) & 0x7f;
640
0
    if (!part) continue;
641
642
0
    more = ((uint8_t) (i > 0)) << 7;
643
644
0
    FR_DBUFF_IN_RETURN(&our_dbuff, (uint8_t) (more | part));
645
0
  }
646
647
0
  (*count)++;
648
649
0
  return fr_dbuff_set(dbuff, &our_dbuff);
650
0
}
651
652
static ssize_t fr_der_encode_oid(fr_dbuff_t *dbuff, fr_dcursor_t *cursor, UNUSED fr_der_encode_ctx_t *encode_ctx)
653
0
{
654
0
  fr_dbuff_t  our_dbuff = FR_DBUFF(dbuff);
655
0
  fr_pair_t const *vp;
656
0
  uint64_t  component;
657
0
  int   i, count = 0;
658
0
  fr_da_stack_t da_stack;
659
660
0
  vp = fr_dcursor_current(cursor);
661
0
  PAIR_VERIFY(vp);
662
0
  fr_assert(!vp->da->flags.is_raw);
663
0
  fr_assert(vp->vp_type == FR_TYPE_ATTR);
664
665
0
  fr_proto_da_stack_build(&da_stack, vp->vp_attr);
666
0
  FR_PROTO_STACK_PRINT(&da_stack, da_stack.depth);
667
668
  /*
669
   *  ISO/IEC 8825-1:2021
670
   *  8.19 Encoding of an object identifier value
671
   *  8.19.1 The encoding of an object identifier value shall be primitive.
672
   *  8.19.2 The contents octets shall be an (ordered) list of encodings of subidentifiers (see 8.19.3
673
   *         and 8.19.4) concatenated together. Each subidentifier is represented as a series of
674
   *         (one or more) octets. Bit 8 of each octet indicates whether it is the last in the series: bit 8
675
   *         of the last octet is zero; bit 8 of each preceding octet is one. Bits 7 to 1 of the octets in
676
   *         the series collectively encode the subidentifier. Conceptually, these groups of bits are
677
   *         concatenated to form an unsigned binary number whose most significant bit is bit 7 of the first
678
   *         octet and whose least significant bit is bit 1 of the last octet. The subidentifier shall be
679
   *         encoded in the fewest possible octets, that is, the leading octet of the subidentifier shall not
680
   *         have the value 8016.
681
   *  8.19.3 The number of subidentifiers (N) shall be one less than the number of object identifier
682
   *    components in the object identifier value being encoded. 8.19.4 The numerical value of the
683
   *    first subidentifier is derived from the values of the first two object identifier components in
684
   *    the object identifier value being encoded, using the formula: (X*40) + Y where X is the value
685
   *    of the first object identifier component and Y is the value of the second object identifier
686
   *    component. NOTE - This packing of the first two object identifier components recognizes that
687
   *    only three values are allocated from the root node, and at most 39 subsequent values from nodes
688
   *    reached by X = 0 and X = 1. 8.19.5 The numerical value of the ith subidentifier, (2 <= i <= N) is
689
   *    that of the (i + 1)th object identifier component.
690
   */
691
692
  /*
693
   *  Parse each OID component.
694
   */
695
0
  for (i = 0; i < da_stack.depth; i++) {
696
0
    ssize_t slen;
697
698
0
    if ((i == 0) && (da_stack.da[0] == attr_oid_tree)) continue; /* don't encode this */
699
700
0
    slen = fr_der_encode_oid_from_value(&our_dbuff, da_stack.da[i]->attr, &component, &count);
701
0
    if (slen < 0) return -1;
702
0
  }
703
704
0
  if (count <= 2) {
705
0
    fr_strerror_printf("Invalid OID '%s' - too short", vp->vp_strvalue);
706
0
    return -1;
707
0
  }
708
709
0
  return fr_dbuff_set(dbuff, &our_dbuff);
710
0
}
711
712
static ssize_t fr_der_encode_sequence(fr_dbuff_t *dbuff, fr_dcursor_t *cursor, fr_der_encode_ctx_t *encode_ctx)
713
0
{
714
0
  fr_pair_t       *vp;
715
716
0
  vp = fr_dcursor_current(cursor);
717
0
  PAIR_VERIFY(vp);
718
0
  fr_assert(!vp->da->flags.is_raw);
719
720
0
  fr_assert(fr_type_is_group(vp->vp_type) || fr_type_is_tlv(vp->vp_type));
721
722
  /*
723
   *  ISO/IEC 8825-1:2021
724
   *  8.9 Encoding of a sequence value
725
   *    8.9.1 The encoding of a sequence value shall be constructed.
726
   *    8.9.2 The contents octets shall consist of the complete encoding of one data value from each of
727
   *          the types listed in the ASN.1 definition of the sequence type, in the order of their
728
   *          appearance in the definition, unless the type was referenced with the keyword OPTIONAL
729
   *          or the keyword DEFAULT.
730
   *    8.9.3 The encoding of a data value may, but need not, be present for a type referenced with the
731
   *          keyword OPTIONAL or the keyword DEFAULT. If present, it shall appear in the order of
732
   *          appearance of the corresponding type in the ASN.1 definition.
733
   *
734
   *  11.5 Set and sequence components with default value
735
   *    The encoding of a set value or sequence value shall not include an encoding for any component
736
   *    value which is equal to its default value.
737
   */
738
0
  if (fr_type_is_group(vp->vp_type) && fr_der_flag_is_oid_and_value(vp->da)) {
739
0
    return fr_der_encode_oid_and_value(dbuff, cursor, encode_ctx);
740
0
  }
741
742
0
  return fr_der_encode_choice(dbuff, cursor, encode_ctx);
743
0
}
744
745
typedef struct {
746
  uint8_t *data;    //!< Pointer to the start of the encoded item (beginning of the tag)
747
  size_t   len;   //!< Length of the encoded item (tag + length + value)
748
} fr_der_encode_set_of_ptr_pairs_t;
749
750
/*
751
 *  Lexicographically sort the set of pairs
752
 */
753
static int CC_HINT(nonnull) fr_der_encode_set_of_cmp(void const *one, void const *two)
754
0
{
755
0
  fr_der_encode_set_of_ptr_pairs_t const *a = one;
756
0
  fr_der_encode_set_of_ptr_pairs_t const *b = two;
757
758
0
  if (a->len >= b->len) {
759
0
    return memcmp(a->data, b->data, a->len);
760
0
  }
761
762
0
  return memcmp(a->data, b->data, b->len);
763
0
}
764
765
static ssize_t fr_der_encode_set(fr_dbuff_t *dbuff, fr_dcursor_t *cursor, fr_der_encode_ctx_t *encode_ctx)
766
0
{
767
0
  fr_dbuff_t        our_dbuff = FR_DBUFF(dbuff);
768
0
  fr_pair_t      *vp;
769
0
  ssize_t         slen;
770
771
0
  vp = fr_dcursor_current(cursor);
772
0
  PAIR_VERIFY(vp);
773
0
  fr_assert(!vp->da->flags.is_raw);
774
775
0
  fr_assert(fr_type_is_tlv(vp->vp_type));
776
777
  /*
778
   *  ISO/IEC 8825-1:2021
779
   *  8.11 Encoding of a set value
780
   *    8.11.1 The encoding of a set value shall be constructed.
781
   *    8.11.2 The contents octets shall consist of the complete encoding of one data value from each
782
   *           of the types listed in the ASN.1 definition of the set type, in an order chosen by the
783
   *           sender, unless the type was referenced with the keyword OPTIONAL or the keyword DEFAULT.
784
   *    8.11.3 The encoding of a data value may, but need not, be present for a type referenced with the
785
   *           keyword OPTIONAL or the keyword DEFAULT.
786
   *
787
   *  11.5 Set and sequence components with default value
788
   *    The encoding of a set value or sequence value shall not include an encoding for any component
789
   *    value which is equal to its default value.
790
   *
791
   *  ISO/IEC 8825-1:2021
792
   *  8.12 Encoding of a set-of value
793
   *    8.12.1 The encoding of a set-of value shall be constructed.
794
   *    8.12.2 The text of 8.10.2 applies.
795
   *    8.12.3 The order of data values need not be preserved by the encoding and subsequent decoding.
796
   *
797
   *  11.6 Set-of components
798
   *    The encodings of the component values of a set-of value shall appear in ascending order, the
799
   *    encodings being compared as octet strings with the shorter components being padded at their
800
   *    trailing end with 0-octets.
801
   *      NOTE - The padding octets are for comparison purposes only and do not appear in the
802
   *      encodings.
803
   */
804
805
0
  if (fr_der_flag_is_set_of(vp->da)) {
806
    /*
807
     *  Set-of items will all have the same tag, so we need to sort them lexicographically
808
     */
809
0
    size_t          i, count;
810
0
    fr_dbuff_t        work_dbuff;
811
0
    fr_der_encode_set_of_ptr_pairs_t *ptr_pairs;
812
0
    uint8_t        *buff;
813
0
    fr_da_stack_t             da_stack;
814
0
    fr_dcursor_t              child_cursor;
815
816
    /*
817
     *  This can happen, but is possible.
818
     */
819
0
    count = fr_pair_list_num_elements(&vp->children);
820
0
    if (unlikely(!count)) return 0;
821
822
    /*
823
     *  Sets can be nested, so we have to use local buffers when sorting.
824
     */
825
0
    buff = talloc_array(encode_ctx->tmp_ctx, uint8_t, fr_dbuff_remaining(&our_dbuff));
826
0
    fr_assert(buff != NULL);
827
828
0
    ptr_pairs = talloc_array(buff, fr_der_encode_set_of_ptr_pairs_t, count);
829
0
    if (unlikely(ptr_pairs == NULL)) {
830
0
      fr_strerror_const("Failed to allocate memory for set of pointers");
831
0
      talloc_free(buff);
832
0
      return -1;
833
0
    }
834
835
    /*
836
     *  Now that we have our intermediate buffers, initialize the buffers and start encoding.
837
     */
838
0
    fr_dbuff_init(&work_dbuff, buff, fr_dbuff_remaining(&our_dbuff));
839
840
0
    fr_proto_da_stack_build(&da_stack, vp->da);
841
842
0
    FR_PROTO_STACK_PRINT(&da_stack, vp->da->depth - 1);
843
844
0
    fr_pair_dcursor_child_iter_init(&child_cursor, &vp->children, cursor);
845
846
0
    for (i = 0; fr_dcursor_current(&child_cursor) != NULL; i++) {
847
0
      ptr_pairs[i].data = fr_dbuff_current(&work_dbuff);
848
849
0
      slen = encode_value(&work_dbuff, &child_cursor, encode_ctx);
850
0
      if (unlikely(slen < 0)) {
851
0
        fr_strerror_printf("Failed to encode pair: %s", fr_strerror());
852
0
        talloc_free(buff);
853
0
        return slen;
854
0
      }
855
856
0
      ptr_pairs[i].len = slen;
857
0
    }
858
859
0
    fr_assert(i <= count);
860
0
    count = i;
861
862
    /*
863
     *  If there's a "min" for this set, then we can't do anything about it.
864
     */
865
0
    if (unlikely(!count)) goto done;
866
867
    /*
868
     *  If there's only one child, we don't need to sort it.
869
     */
870
0
    if (count > 1) qsort(ptr_pairs, count, sizeof(fr_der_encode_set_of_ptr_pairs_t), fr_der_encode_set_of_cmp);
871
872
    /*
873
     *  The data in work_dbuff is always less than the data in the our_dbuff, so we don't need
874
     *  to check the return value here.
875
     */
876
0
    for (i = 0; i < count; i++) {
877
0
      (void) fr_dbuff_in_memcpy(&our_dbuff, ptr_pairs[i].data, ptr_pairs[i].len);
878
0
    }
879
880
0
  done:
881
0
    talloc_free(buff);
882
883
0
    return fr_dbuff_set(dbuff, &our_dbuff);
884
0
  }
885
886
  /*
887
   *  Children of a set are ordered by tag.  However, as each tag can only be used once, this is a
888
   *  unique order.
889
   */
890
0
  fr_pair_list_sort(&vp->children, fr_der_pair_cmp_by_da_tag);
891
892
0
  return fr_der_encode_choice(dbuff, cursor, encode_ctx);
893
0
}
894
895
static ssize_t fr_der_encode_utc_time(fr_dbuff_t *dbuff, fr_dcursor_t *cursor, UNUSED fr_der_encode_ctx_t *encode_ctx)
896
0
{
897
0
  fr_dbuff_t   our_dbuff = FR_DBUFF(dbuff);
898
0
  fr_pair_t const *vp;
899
0
  fr_sbuff_t   time_sbuff;
900
0
  char     fmt_time[50] = { 0 };
901
0
  size_t     i;
902
903
0
  fmt_time[0] = '\0';
904
0
  time_sbuff  = FR_SBUFF_OUT(fmt_time, sizeof(fmt_time));
905
906
0
  vp = fr_dcursor_current(cursor);
907
0
  PAIR_VERIFY(vp);
908
0
  fr_assert(!vp->da->flags.is_raw);
909
910
  /*
911
   *  ISO/IEC 8825-1:2021
912
   *  8.25 Encoding for values of the useful types
913
   *    The following "useful types" shall be encoded as if they had been replaced by their definitions
914
   *    given in clauses 46-48 of Rec. ITU-T X.680 | ISO/IEC 8824-1:
915
   *      - generalized time;
916
   *      - universal time;
917
   *      - object descriptor.
918
   *
919
   *  8.26 Encoding for values of the TIME type and the useful time types
920
   *    8.26 Encoding for values of the TIME type and the useful time types 8.26.1 Encoding for values
921
   *    of the TIME type NOTE - The defined time types are subtypes of the TIME type, with the same
922
   *    tag, and have the same encoding as the TIME type. 8.26.1.1 The encoding of the TIME type shall
923
   *    be primitive. 8.26.1.2 The contents octets shall be the UTF-8 encoding of the value notation,
924
   *    after the removal of initial and final QUOTATION MARK (34) characters.
925
   *
926
   *  11.8 UTCTime
927
   *    11.8.1 The encoding shall terminate with "Z", as described in the ITU-T X.680 | ISO/IEC 8824-1
928
   *           clause on UTCTime.
929
   *    11.8.2 The seconds element shall always be present.
930
   *    11.8.3 Midnight (GMT) shall be represented as "YYMMDD000000Z", where "YYMMDD" represents the
931
   *           day following the midnight in question.
932
   */
933
934
  /*
935
   *  The format of a UTC time is "YYMMDDhhmmssZ"
936
   *  Where:
937
   *  1. YY is the year
938
   *  2. MM is the month
939
   *  3. DD is the day
940
   *  4. hh is the hour
941
   *  5. mm is the minute
942
   *  6. ss is the second (not optional in DER)
943
   *  7. Z is the timezone (UTC)
944
   */
945
0
  fr_unix_time_to_str(&time_sbuff, vp->vp_date, FR_TIME_RES_SEC, true);
946
947
  /*
948
   *  Remove the century from the year
949
   */
950
0
  fr_sbuff_shift(&time_sbuff, 2, false);
951
952
  /*
953
   *  Trim the time string of any unwanted characters
954
   */
955
0
  for (i = 0; i < sizeof(fmt_time); i++) {
956
0
    if (fmt_time[i] == '\0') {
957
0
      break;
958
0
    }
959
960
0
    if ((fmt_time[i] == '-') || (fmt_time[i] == 'T') || (fmt_time[i] == ':')) {
961
0
      size_t j = i;
962
963
0
      while (fmt_time[j] != '\0') {
964
0
        fmt_time[j] = fmt_time[j + 1];
965
0
        j++;
966
0
      }
967
968
0
      fmt_time[j] = '\0';
969
970
0
      continue;
971
0
    }
972
0
  }
973
974
0
  FR_DBUFF_IN_MEMCPY_RETURN(&our_dbuff, fmt_time, DER_UTC_TIME_LEN);
975
976
0
  return fr_dbuff_set(dbuff, &our_dbuff);
977
0
}
978
979
static ssize_t fr_der_encode_generalized_time(fr_dbuff_t *dbuff, fr_dcursor_t *cursor,
980
                UNUSED fr_der_encode_ctx_t *encode_ctx)
981
0
{
982
0
  fr_dbuff_t   our_dbuff = FR_DBUFF(dbuff);
983
0
  fr_pair_t const *vp;
984
0
  fr_sbuff_t   time_sbuff;
985
0
  char     fmt_time[50] = { 0 };
986
0
  size_t     i;
987
988
0
  fmt_time[0] = '\0';
989
0
  time_sbuff  = FR_SBUFF_OUT(fmt_time, sizeof(fmt_time));
990
991
0
  vp = fr_dcursor_current(cursor);
992
0
  PAIR_VERIFY(vp);
993
0
  fr_assert(!vp->da->flags.is_raw);
994
995
  /*
996
   *  ISO/IEC 8825-1:2021
997
   *  8.25 Encoding for values of the useful types
998
   *    The following "useful types" shall be encoded as if they had been replaced by their definitions
999
   *    given in clauses 46-48 of Rec. ITU-T X.680 | ISO/IEC 8824-1:
1000
   *      - generalized time;
1001
   *      - universal time;
1002
   *      - object descriptor.
1003
   *
1004
   *  8.26 Encoding for values of the TIME type and the useful time types
1005
   *    8.26 Encoding for values of the TIME type and the useful time types 8.26.1 Encoding for values
1006
   *    of the TIME type NOTE - The defined time types are subtypes of the TIME type, with the same
1007
   *    tag, and have the same encoding as the TIME type. 8.26.1.1 The encoding of the TIME type shall
1008
   *    be primitive. 8.26.1.2 The contents octets shall be the UTF-8 encoding of the value notation,
1009
   *    after the removal of initial and final QUOTATION MARK (34) characters.
1010
   *
1011
   *  11.7 GeneralizedTime
1012
   *    11.7.1 The encoding shall terminate with a "Z", as described in the Rec. ITU-T X.680 | ISO/IEC
1013
   *           8824-1 clause on GeneralizedTime.
1014
   *    11.7.2 The seconds element shall always be present.
1015
   *    11.7.3 The fractional-seconds elements, if present, shall omit all trailing zeros; if the
1016
   *           elements correspond to 0, they shall be wholly omitted, and the decimal point element
1017
   *           also shall be omitted.
1018
   */
1019
1020
  /*
1021
   *  The format of a generalized time is "YYYYMMDDHHMMSS[.fff]Z"
1022
   *  Where:
1023
   *  1. YYYY is the year
1024
   *  2. MM is the month
1025
   *  3. DD is the day
1026
   *  4. HH is the hour
1027
   *  5. MM is the minute
1028
   *  6. SS is the second
1029
   *  7. fff is the fraction of a second (optional)
1030
   *  8. Z is the timezone (UTC)
1031
   */
1032
1033
0
  fr_unix_time_to_str(&time_sbuff, vp->vp_date, FR_TIME_RES_USEC, true);
1034
1035
  /*
1036
   *  Trim the time string of any unwanted characters
1037
   */
1038
0
  for (i = 0; i < sizeof(fmt_time); i++) {
1039
0
    if (fmt_time[i] == '\0') {
1040
0
      break;
1041
0
    }
1042
1043
0
    if ((fmt_time[i] == '-') || (fmt_time[i] == 'T') || (fmt_time[i] == ':')) {
1044
0
      size_t j = i;
1045
1046
0
      while (fmt_time[j] != '\0') {
1047
0
        fmt_time[j] = fmt_time[j + 1];
1048
0
        j++;
1049
0
      }
1050
1051
0
      fmt_time[j] = '\0';
1052
1053
0
      continue;
1054
0
    }
1055
1056
0
    if (fmt_time[i] == '.') {
1057
      /*
1058
       *  Remove any trailing zeros
1059
       */
1060
0
      size_t j = strlen(fmt_time) - 2;
1061
1062
0
      while (fmt_time[j] == '0') {
1063
0
        fmt_time[j] = fmt_time[j + 1];
1064
0
        fmt_time[j + 1] = '\0';
1065
0
        j--;
1066
0
      }
1067
1068
      /*
1069
       *  Remove the decimal point if there are no fractional seconds
1070
       */
1071
0
      if (j == i) {
1072
0
        fmt_time[i] = fmt_time[i + 1];
1073
0
        fmt_time[i + 1] = '\0';
1074
0
      }
1075
0
    }
1076
0
  }
1077
1078
0
  FR_DBUFF_IN_MEMCPY_RETURN(&our_dbuff, fmt_time, i);
1079
1080
0
  return fr_dbuff_set(dbuff, &our_dbuff);
1081
0
}
1082
1083
/** Encode a CHOICE type
1084
 *
1085
 * @param[in] dbuff   Buffer to write the encoded data to
1086
 * @param[in] cursor    Cursor to the pair to encode
1087
 * @param[in] encode_ctx  Encoding context
1088
 *
1089
 * @return  Number of bytes written to the buffer, or -1 on error
1090
 */
1091
static ssize_t fr_der_encode_choice(fr_dbuff_t *dbuff, fr_dcursor_t *cursor, fr_der_encode_ctx_t *encode_ctx)
1092
0
{
1093
0
  fr_dbuff_t        our_dbuff = FR_DBUFF(dbuff);
1094
0
  fr_pair_t const *vp;
1095
0
  fr_da_stack_t       da_stack;
1096
0
  fr_dcursor_t        child_cursor;
1097
0
  ssize_t    slen = 0;
1098
1099
0
  vp = fr_dcursor_current(cursor);
1100
0
  PAIR_VERIFY(vp);
1101
0
  fr_assert(!vp->da->flags.is_raw);
1102
1103
0
  fr_proto_da_stack_build(&da_stack, vp->da);
1104
1105
0
  FR_PROTO_STACK_PRINT(&da_stack, vp->da->depth - 1);
1106
1107
0
  fr_pair_dcursor_child_iter_init(&child_cursor, &vp->children, cursor);
1108
1109
0
  slen = fr_pair_cursor_to_network(&our_dbuff, &da_stack, vp->da->depth - 1, &child_cursor, encode_ctx, encode_pair);
1110
0
  if (slen < 0) return -1;
1111
1112
0
  return fr_dbuff_set(dbuff, &our_dbuff);
1113
0
}
1114
1115
static ssize_t fr_der_encode_X509_extensions(fr_dbuff_t *dbuff, fr_dcursor_t *cursor, fr_der_encode_ctx_t *encode_ctx)
1116
0
{
1117
0
  fr_dbuff_t    our_dbuff = FR_DBUFF(dbuff);
1118
0
  fr_dbuff_marker_t outer_seq_len_start;
1119
0
  fr_dcursor_t    child_cursor, root_cursor, parent_cursor;
1120
0
  fr_pair_t const  *vp;
1121
0
  ssize_t     slen        = 0;
1122
0
  size_t      is_critical = 0;
1123
0
  uint64_t    max, num;
1124
1125
0
  vp = fr_dcursor_current(cursor);
1126
0
  PAIR_VERIFY(vp);
1127
0
  fr_assert(!vp->da->flags.is_raw);
1128
1129
0
  fr_assert(fr_type_is_group(vp->vp_type));
1130
1131
  /*
1132
   *  RFC 5280 Section 4.2
1133
   *  The extensions defined for X.509 v3 certificates provide methods for
1134
   *  associating additional attributes with users or public keys and for
1135
   *  managing relationships between CAs.  The X.509 v3 certificate format
1136
   *  also allows communities to define private extensions to carry
1137
   *  information unique to those communities.  Each extension in a
1138
   *  certificate is designated as either critical or non-critical.
1139
   *
1140
   *  Each extension includes an OID and an ASN.1 structure.  When an
1141
   *  extension appears in a certificate, the OID appears as the field
1142
   *  extnID and the corresponding ASN.1 DER encoded structure is the value
1143
   *  of the octet string extnValue.
1144
   *
1145
   *  RFC 5280 Section A.1 Explicitly Tagged Module, 1988 Syntax
1146
   *    Extensions  ::=  SEQUENCE SIZE (1..MAX) OF Extension
1147
   *
1148
   *    Extension  ::=  SEQUENCE  {
1149
   *      extnID      OBJECT IDENTIFIER,
1150
   *      critical    BOOLEAN DEFAULT FALSE,
1151
   *      extnValue   OCTET STRING
1152
   *          -- contains the DER encoding of an ASN.1 value
1153
   *          -- corresponding to the extension type identified
1154
   *          -- by extnID
1155
   *    }
1156
   *
1157
   *  So the extensions are a SEQUENCE of SEQUENCEs containing an OID, a boolean and an OCTET STRING.
1158
   *  Note: If the boolean value is false, it is not included in the encoding.
1159
   */
1160
1161
0
  max = fr_der_flag_max(vp->da); /* Maximum number of extensions specified in the dictionary */
1162
0
  num = 0;
1163
1164
0
  slen = fr_der_encode_tag(&our_dbuff, FR_DER_TAG_SEQUENCE, FR_DER_CLASS_UNIVERSAL, FR_DER_TAG_CONSTRUCTED);
1165
0
  if (slen < 0) return slen;
1166
1167
0
  fr_dbuff_marker(&outer_seq_len_start, &our_dbuff);
1168
0
  FR_DBUFF_ADVANCE_RETURN(&our_dbuff, 1);
1169
1170
0
  FR_PROTO_HEX_DUMP(fr_dbuff_start(&our_dbuff), fr_dbuff_used(&our_dbuff),"BEFORE encoded X509 extension");
1171
1172
0
  fr_pair_dcursor_child_iter_init(&root_cursor, &vp->children, cursor);
1173
0
  fr_dcursor_copy(&parent_cursor, &root_cursor);
1174
1175
0
  while (fr_dcursor_current(&parent_cursor)) {
1176
0
    uint64_t    component;
1177
0
    int     count;
1178
0
    fr_dbuff_marker_t length_start, inner_seq_len_start;
1179
0
    fr_pair_t   *child;
1180
1181
    /*
1182
     *  Extensions are sequences or sets containing 2 items:
1183
     *  1. The first item is the OID
1184
     *  2. The second item is the value
1185
     *
1186
     *  Note: The value may be a constructed or primitive type
1187
     */
1188
1189
0
    if (num >= max) {
1190
0
      fr_strerror_printf("Too many X509 extensions (%" PRIu64 ")", max);
1191
0
      break;
1192
0
    }
1193
1194
0
    slen = fr_der_encode_tag(&our_dbuff, FR_DER_TAG_SEQUENCE, FR_DER_CLASS_UNIVERSAL, FR_DER_TAG_CONSTRUCTED);
1195
0
    if (slen < 0) return slen;
1196
1197
0
    fr_dbuff_marker(&inner_seq_len_start, &our_dbuff);
1198
0
    FR_DBUFF_ADVANCE_RETURN(&our_dbuff, 1);
1199
1200
    /*
1201
     *  Encode the OID portion of the extension
1202
     */
1203
0
    slen = fr_der_encode_tag(&our_dbuff, FR_DER_TAG_OID, FR_DER_CLASS_UNIVERSAL, FR_DER_TAG_PRIMITIVE);
1204
0
    if (slen < 0) return slen;
1205
1206
0
    fr_dbuff_marker(&length_start, &our_dbuff);
1207
0
    FR_DBUFF_ADVANCE_RETURN(&our_dbuff, 1);
1208
1209
    /*
1210
     *  Walk through the children until we find either an attribute marked as an extension, or one with
1211
     *  no children (which is an unknown OID).
1212
     *
1213
     *  We will use this to construct the OID to encode, as well as to get the actual value of the
1214
     *  extension.
1215
     */
1216
0
    fr_dcursor_copy(&child_cursor, &parent_cursor);
1217
0
    count = 0;
1218
1219
0
    while ((child = fr_dcursor_current(&child_cursor)) != NULL) {
1220
0
      PAIR_VERIFY(child);
1221
1222
0
      FR_PROTO_TRACE("Child: %s", child->da->name);
1223
1224
0
      if (!is_critical && (strcmp(child->da->name, "Critical") == 0)) {
1225
        /*
1226
         *  We don't encode the critical flag
1227
         */
1228
0
        is_critical = fr_pair_list_num_elements(&child->children);
1229
0
        FR_PROTO_TRACE("Critical flag: %zu", is_critical);
1230
1231
0
        fr_pair_dcursor_child_iter_init(&parent_cursor, &child->children, &child_cursor);
1232
0
        goto next;
1233
0
      }
1234
1235
      /*
1236
       *  If we find a normal leaf data type, we don't encode it.  But we do encode leaf data
1237
       *  types which are marked up as needing OID leaf encoding.
1238
       */
1239
0
      if (!fr_type_is_structural(child->vp_type) && !fr_der_flag_leaf(child->da) && !child->da->flags.is_raw) {
1240
0
        FR_PROTO_TRACE("Found non-structural child %s", child->da->name);
1241
1242
0
        fr_dcursor_copy(&child_cursor, &parent_cursor);
1243
0
        break;
1244
0
      }
1245
1246
0
      slen = fr_der_encode_oid_from_value(&our_dbuff, child->da->attr, &component, &count);
1247
0
      if (unlikely(slen < 0)) return -1;
1248
1249
      /*
1250
       *  We've encoded a leaf data type, or a raw one.  Stop encoding it.
1251
       */
1252
0
      if (!fr_type_is_structural(child->vp_type)) break;
1253
1254
      /*
1255
       *  Unless this was the last child (marked as an extension), there should only be one child
1256
       *  - representing the next OID in the extension
1257
       */
1258
0
      if (fr_pair_list_num_elements(&child->children) > 1) break;
1259
1260
0
    next:
1261
0
      if (fr_der_flag_leaf(child->da)) break;
1262
1263
0
      fr_pair_dcursor_child_iter_init(&child_cursor, &child->children, &child_cursor);
1264
0
    }
1265
1266
    /*
1267
     *  Encode the length of the OID
1268
     */
1269
0
    slen = fr_der_encode_len(&our_dbuff, &length_start);
1270
0
    if (slen < 0) return slen;
1271
1272
    /*
1273
     *  Encode the critical flag
1274
     */
1275
0
    if (is_critical) {
1276
      /*
1277
       *  Universal+Boolean flag is always 0x01. Length of a boolean is always 0x01.
1278
       *  True is always 0xff.
1279
       */
1280
0
      FR_DBUFF_IN_BYTES_RETURN(&our_dbuff, (uint8_t) 0x01, (uint8_t) 0x01, (uint8_t)(0xff));
1281
0
      is_critical--;
1282
0
    }
1283
1284
    /*
1285
     *  Encode the value portion of the extension
1286
     */
1287
0
    slen = fr_der_encode_tag(&our_dbuff, FR_DER_TAG_OCTETSTRING, FR_DER_CLASS_UNIVERSAL, FR_DER_TAG_PRIMITIVE);
1288
0
    if (slen < 0) return slen;
1289
1290
0
    fr_dbuff_marker(&length_start, &our_dbuff);
1291
0
    FR_DBUFF_ADVANCE_RETURN(&our_dbuff, 1);
1292
1293
    /*
1294
     *  Encode the data
1295
     */
1296
0
    slen = encode_value(&our_dbuff, &child_cursor, encode_ctx);
1297
0
    if (slen < 0) return slen;
1298
1299
    /*
1300
     *  Encode the length of the value
1301
     */
1302
0
    slen = fr_der_encode_len(&our_dbuff, &length_start);
1303
0
    if (slen < 0) return slen;
1304
1305
    /*
1306
     *  Encode the length of the extension (OID + Value portions)
1307
     */
1308
0
    slen = fr_der_encode_len(&our_dbuff, &inner_seq_len_start);
1309
0
    if (slen < 0) return -1;
1310
1311
0
    if (is_critical) {
1312
0
      fr_dcursor_next(&parent_cursor);
1313
0
      num++;
1314
0
      continue;
1315
0
    }
1316
1317
0
    FR_PROTO_HEX_DUMP(fr_dbuff_start(&our_dbuff), fr_dbuff_behind(&outer_seq_len_start) + 2,
1318
0
          "Encoded X509 extension");
1319
1320
0
    fr_dcursor_next(&root_cursor);
1321
0
    fr_dcursor_copy(&parent_cursor, &root_cursor);
1322
0
    num++;
1323
0
  }
1324
1325
  /*
1326
   *  Encode the length of the extensions
1327
   */
1328
0
  slen = fr_der_encode_len(&our_dbuff, &outer_seq_len_start);
1329
0
  if (slen < 0) return slen;
1330
1331
0
  FR_PROTO_HEX_DUMP(fr_dbuff_start(&our_dbuff), slen, "Encoded X509 extensions");
1332
1333
0
  return fr_dbuff_set(dbuff, &our_dbuff);
1334
0
}
1335
1336
static ssize_t fr_der_encode_oid_and_value(fr_dbuff_t *dbuff, fr_dcursor_t *cursor, fr_der_encode_ctx_t *encode_ctx)
1337
0
{
1338
0
  fr_dbuff_t    our_dbuff = FR_DBUFF(dbuff);
1339
0
  fr_dbuff_marker_t length_start;
1340
0
  fr_dcursor_t    child_cursor, parent_cursor = *cursor;
1341
0
  fr_pair_t const   *vp, *child;
1342
0
  ssize_t     slen   = 0;
1343
0
  uint64_t    component;
1344
0
  int     count;
1345
1346
0
  vp = fr_dcursor_current(&parent_cursor);
1347
0
  PAIR_VERIFY(vp);
1348
0
  fr_assert(!vp->da->flags.is_raw);
1349
1350
0
  fr_assert(fr_type_is_group(vp->vp_type));
1351
1352
  /*
1353
   *  A very common pattern in DER encoding is ro have a sequence of set containing two things: an OID and a
1354
   *  value, where the OID is used to determine how to decode the value.
1355
   *  We will be decoding the OID first and then try to find the attribute associated with that OID to then
1356
   *  decode the value. If no attribute is found, one will be created and the value will be stored as raw
1357
   *  octets in the attribute.
1358
   *
1359
   *  Note: The value may be a constructed or primitive type
1360
   */
1361
1362
0
  slen = fr_der_encode_tag(&our_dbuff, FR_DER_TAG_OID, FR_DER_CLASS_UNIVERSAL, FR_DER_TAG_PRIMITIVE);
1363
0
  if (slen < 0) return slen;
1364
1365
0
  fr_dbuff_marker(&length_start, &our_dbuff);
1366
0
  FR_DBUFF_ADVANCE_RETURN(&our_dbuff, 1);
1367
1368
  /*
1369
   *  Walk through the children until we find either an attribute marked as an oid leaf, or one with
1370
   *  no children (which is an unknown OID).
1371
   *
1372
   *  We will use this to construct the OID to encode, as well as to get the actual value of the
1373
   *  pair.
1374
   */
1375
0
  fr_pair_dcursor_child_iter_init(&child_cursor, &vp->children, &parent_cursor);
1376
0
  count = 0;
1377
1378
0
  while ((child = fr_dcursor_current(&child_cursor)) != NULL) {
1379
0
    PAIR_VERIFY(child);
1380
1381
    /*
1382
     *  If we find a normal leaf data type, we don't encode it.  But we do encode leaf data
1383
     *  types which are marked up as needing OID leaf encoding.
1384
     */
1385
0
    if (!fr_type_is_structural(child->vp_type) && !fr_der_flag_leaf(child->da) && !child->da->flags.is_raw) {
1386
0
      FR_PROTO_TRACE("Found non-structural child %s", child->da->name);
1387
1388
0
      fr_dcursor_copy(&child_cursor, &parent_cursor);
1389
0
      break;
1390
0
    }
1391
1392
0
    slen = fr_der_encode_oid_from_value(&our_dbuff, child->da->attr, &component, &count);
1393
0
    if (unlikely(slen < 0)) return -1;
1394
1395
    /*
1396
     *  We've encoded a leaf data type, or a raw one.  Stop encoding it.
1397
     */
1398
0
    if (!fr_type_is_structural(child->vp_type)) break;
1399
1400
    /*
1401
     *  Some structural types can be marked as a leaf for the purposes of OID encoding.
1402
     */
1403
0
    if (fr_der_flag_leaf(child->da)) break;
1404
1405
    /*
1406
     *  Unless this was the last child (marked as an oid leaf), there should only be one child
1407
     *  - representing the next OID in the pair
1408
     */
1409
0
    if (fr_pair_list_num_elements(&child->children) > 1) break;
1410
1411
0
    fr_pair_dcursor_child_iter_init(&child_cursor, &child->children, &child_cursor);
1412
0
  }
1413
1414
  /*
1415
   *  Encode the length of the OID
1416
   */
1417
0
  slen = fr_der_encode_len(&our_dbuff, &length_start);
1418
0
  if (slen < 0) return slen;
1419
1420
  /*
1421
   *  And then encode the actual data.
1422
   */
1423
0
  slen = encode_value(&our_dbuff, &child_cursor, encode_ctx);
1424
0
  if (slen < 0) return slen;
1425
1426
0
  return fr_dbuff_set(dbuff, &our_dbuff);
1427
0
}
1428
1429
static ssize_t fr_der_encode_string(fr_dbuff_t *dbuff, fr_dcursor_t *cursor, UNUSED fr_der_encode_ctx_t *encode_ctx)
1430
0
{
1431
0
  fr_dbuff_t   our_dbuff = FR_DBUFF(dbuff);
1432
0
  fr_pair_t const *vp;
1433
1434
0
  vp = fr_dcursor_current(cursor);
1435
0
  PAIR_VERIFY(vp);
1436
0
  fr_assert(!vp->da->flags.is_raw);
1437
1438
  /*
1439
   *  ISO/IEC 8825-1:2021
1440
   *  8.23 Encoding for values of the restricted character string types
1441
   *    8.23.1 The data value consists of a string of characters from the character set specified in
1442
   *      the ASN.1 type definition.
1443
   *    8.23.2 Each data value shall be encoded independently of other data values of the same type.
1444
   *
1445
   *  10.2 String encoding forms
1446
   *    For bitstring, octetstring and restricted character string types, the constructed form of
1447
   *    encoding shall not be used. (Contrast with 8.23.6.)
1448
   *
1449
   *  NOTE:
1450
   *    We DO NOT check for restricted character sets here. This should be done as a separate validation
1451
   *    step. Here we simply trust that administrators have done their job and are providing us with
1452
   *    valid data.
1453
   */
1454
1455
0
  FR_DBUFF_IN_MEMCPY_RETURN(&our_dbuff, vp->vp_strvalue, vp->vp_length);
1456
1457
0
  return fr_dbuff_set(dbuff, &our_dbuff);
1458
0
}
1459
1460
static const fr_der_tag_encode_t tag_funcs[FR_DER_TAG_MAX] = {
1461
  [FR_DER_TAG_BOOLEAN]        = { .constructed = FR_DER_TAG_PRIMITIVE, .encode = fr_der_encode_boolean },
1462
  [FR_DER_TAG_INTEGER]        = { .constructed = FR_DER_TAG_PRIMITIVE, .encode = fr_der_encode_integer },
1463
  [FR_DER_TAG_BITSTRING]        = { .constructed = FR_DER_TAG_PRIMITIVE, .encode = fr_der_encode_bitstring },
1464
  [FR_DER_TAG_OCTETSTRING]      = { .constructed = FR_DER_TAG_PRIMITIVE, .encode = fr_der_encode_octetstring },
1465
  [FR_DER_TAG_NULL]       = { .constructed = FR_DER_TAG_PRIMITIVE, .encode = fr_der_encode_null },
1466
  [FR_DER_TAG_OID]        = { .constructed = FR_DER_TAG_PRIMITIVE, .encode = fr_der_encode_oid },
1467
  [FR_DER_TAG_ENUMERATED]       = { .constructed = FR_DER_TAG_PRIMITIVE, .encode = fr_der_encode_enumerated },
1468
  [FR_DER_TAG_UTF8_STRING]      = { .constructed = FR_DER_TAG_PRIMITIVE, .encode = fr_der_encode_string },
1469
  [FR_DER_TAG_SEQUENCE]       = { .constructed = FR_DER_TAG_CONSTRUCTED, .encode = fr_der_encode_sequence },
1470
  [FR_DER_TAG_SET]        = { .constructed = FR_DER_TAG_CONSTRUCTED, .encode = fr_der_encode_set },
1471
  [FR_DER_TAG_PRINTABLE_STRING] = { .constructed = FR_DER_TAG_PRIMITIVE,
1472
            .encode      = fr_der_encode_string },
1473
  [FR_DER_TAG_T61_STRING]       = { .constructed = FR_DER_TAG_PRIMITIVE, .encode = fr_der_encode_string },
1474
  [FR_DER_TAG_IA5_STRING]       = { .constructed = FR_DER_TAG_PRIMITIVE, .encode = fr_der_encode_string },
1475
  [FR_DER_TAG_UTC_TIME]       = { .constructed = FR_DER_TAG_PRIMITIVE, .encode = fr_der_encode_utc_time },
1476
  [FR_DER_TAG_GENERALIZED_TIME] = { .constructed = FR_DER_TAG_PRIMITIVE,
1477
            .encode      = fr_der_encode_generalized_time },
1478
  [FR_DER_TAG_VISIBLE_STRING]   = { .constructed = FR_DER_TAG_PRIMITIVE, .encode = fr_der_encode_string },
1479
  [FR_DER_TAG_GENERAL_STRING]   = { .constructed = FR_DER_TAG_PRIMITIVE, .encode = fr_der_encode_string },
1480
  [FR_DER_TAG_UNIVERSAL_STRING] = { .constructed = FR_DER_TAG_PRIMITIVE,
1481
            .encode      = fr_der_encode_string },
1482
};
1483
1484
static const fr_der_tag_encode_t type_funcs[FR_TYPE_MAX] = {
1485
  [FR_TYPE_IPV4_ADDR]       = { .constructed = FR_DER_TAG_PRIMITIVE, .encode = fr_der_encode_ipv4_addr },
1486
  [FR_TYPE_IPV4_PREFIX]     = { .constructed = FR_DER_TAG_PRIMITIVE, .encode = fr_der_encode_ipv4_prefix },
1487
  [FR_TYPE_IPV6_ADDR]       = { .constructed = FR_DER_TAG_PRIMITIVE, .encode = fr_der_encode_ipv6_addr },
1488
  [FR_TYPE_IPV6_PREFIX]   = { .constructed = FR_DER_TAG_PRIMITIVE, .encode = fr_der_encode_ipv6_prefix },
1489
1490
  [FR_TYPE_COMBO_IP_ADDR]   = { .constructed = FR_DER_TAG_PRIMITIVE, .encode = fr_der_encode_combo_ip },
1491
};
1492
1493
1494
/** Encode the length field of a DER structure
1495
 *
1496
 *  The input dbuff is composed of the following data:
1497
 *
1498
 *  1 byte of nothing (length_start).  Where the "length length" will be written to.
1499
 *  N bytes of data.  dbuff is pointing to the end of the encoded data.
1500
 *
1501
 *  We have to either write a length to length_start (if it's < 0x7f),
1502
 *
1503
 *  OR we figure out how many bytes we need to encode the length,
1504
 *  shift the data to the right to make room, and then encode the
1505
 *  length.
1506
 *
1507
 * @param dbuff   The buffer to update with the length field
1508
 * @param length_start  The start of the length field
1509
 * @return
1510
 *  - <0 for "cannot extend the input buffer by the needed "length length".
1511
 *  - 1 for "success".  Note that 'length_start' WILL be updated after this call,
1512
 *    and the caller should just release it immediately.
1513
 */
1514
static ssize_t fr_der_encode_len(fr_dbuff_t *dbuff, fr_dbuff_marker_t *length_start)
1515
0
{
1516
0
  size_t      i, len_len;
1517
0
  size_t      tmp, datalen;
1518
1519
0
  datalen = fr_dbuff_current(dbuff) - fr_dbuff_current(length_start) - 1;
1520
1521
  /*
1522
   *  If the length can fit in a single byte, we don't need to extend the size of the length field
1523
   */
1524
0
  if (datalen <= 0x7f) {
1525
0
    (void) fr_dbuff_in(length_start, (uint8_t) datalen);
1526
0
    return 1;
1527
0
  }
1528
1529
  /*
1530
   *  Calculate the number of bytes needed to encode the length.
1531
   */
1532
0
  for (tmp = datalen, len_len = 0; tmp != 0; tmp >>= 8) {
1533
0
    len_len++;
1534
0
  }
1535
1536
  /*
1537
   *  DER says that the length field cannot be more than
1538
   *  0x7f.  Since sizeof(datalen) == 8, we can always
1539
   *  encode the length field.
1540
   */
1541
0
  fr_assert(len_len > 0);
1542
0
  fr_assert(len_len < 0x7f);
1543
1544
0
  (void) fr_dbuff_in(length_start, (uint8_t) (0x80 | len_len));
1545
1546
  /*
1547
   *  This is the only operation which can fail.  The dbuff
1548
   *  is currently set to the end of the encoded data.  We
1549
   *  need to ensure that there is sufficient room in the
1550
   *  dbuff to encode the additional bytes.
1551
   *
1552
   *  fr_dbuff_set() checks if the length exceeds the input
1553
   *  buffer.  But it does NOT extend the buffer by reading
1554
   *  more data, if more data is needed.  So we need to
1555
   *  manually extend the dbuff here.
1556
   */
1557
0
  FR_DBUFF_EXTEND_LOWAT_OR_RETURN(dbuff, len_len);
1558
1559
  /*
1560
   *  Reset the dbuff to the new start, where the data
1561
   *  should be.
1562
   */
1563
0
  fr_dbuff_set(dbuff, fr_dbuff_current(length_start) + len_len);
1564
1565
  /*
1566
   *  Move the data over.  Note that the move updates BOTH
1567
   *  input and output dbuffs.  As a result, we have to wrap
1568
   *  'length_start' in a temporary dbuff, so that it
1569
   *  doesn't get updated by the move.
1570
   */
1571
0
  fr_dbuff_move(dbuff, &FR_DBUFF(length_start), datalen);
1572
1573
  /*
1574
   *  Encode high bits first, but only the non-zero ones.
1575
   */
1576
0
  for (i = len_len; i > 0; i--) {
1577
0
    (void) fr_dbuff_in(length_start, (uint8_t)((datalen) >> ((i - 1) * 8)));
1578
0
  }
1579
1580
0
  return 1;
1581
0
}
1582
1583
/** Encode a DER tag
1584
 *
1585
 * @param dbuff   The buffer to write the tag to
1586
 * @param tag_num The tag number
1587
 * @param tag_class The tag class
1588
 * @param constructed Whether the tag is constructed
1589
 *
1590
 * @return    The number of bytes written to the buffer
1591
 */
1592
static inline CC_HINT(always_inline) ssize_t
1593
  fr_der_encode_tag(fr_dbuff_t *dbuff, fr_der_tag_t tag_num, fr_der_tag_class_t tag_class,
1594
        fr_der_tag_constructed_t constructed)
1595
0
{
1596
0
  fr_dbuff_t  our_dbuff = FR_DBUFF(dbuff);
1597
0
  uint8_t   tag_byte;
1598
1599
0
  tag_byte = (tag_class & DER_TAG_CLASS_MASK) | (constructed & DER_TAG_CONSTRUCTED_MASK) |
1600
0
       (tag_num & DER_TAG_NUM_MASK);
1601
1602
0
  FR_DBUFF_IN_RETURN(&our_dbuff, tag_byte);
1603
1604
0
  return fr_dbuff_set(dbuff, &our_dbuff);
1605
0
}
1606
1607
/** Encode a DER structure
1608
 *
1609
 * @param[out] dbuff    The buffer to write the structure to
1610
 * @param[in] cursor  The cursor to the structure to encode
1611
 * @param[in] encode_ctx  The encoding context
1612
 *
1613
 * @return    The number of bytes written to the buffer
1614
 */
1615
static ssize_t encode_value(fr_dbuff_t *dbuff, fr_dcursor_t *cursor, void *encode_ctx)
1616
0
{
1617
0
  fr_pair_t const     *vp;
1618
0
  fr_dbuff_t       our_dbuff;
1619
0
  fr_dbuff_marker_t    marker;
1620
0
  fr_der_tag_encode_t const *func;
1621
0
  fr_der_tag_t         tag;
1622
0
  fr_der_tag_class_t   tag_class;
1623
0
  fr_der_encode_ctx_t *uctx = encode_ctx;
1624
0
  ssize_t        slen = 0;
1625
0
  fr_der_attr_flags_t const *flags;
1626
1627
0
  if (unlikely(cursor == NULL)) {
1628
0
    fr_strerror_const("No cursor to encode");
1629
0
    return -1;
1630
0
  }
1631
1632
0
  vp = fr_dcursor_current(cursor);
1633
0
  if (unlikely(!vp)) {
1634
0
    fr_strerror_const("No pair to encode");
1635
0
    return -1;
1636
0
  }
1637
1638
0
  PAIR_VERIFY(vp);
1639
1640
0
  FR_PROTO_TRACE("Encoding %s", vp->da->name);
1641
1642
0
  flags = fr_der_attr_flags(vp->da);
1643
0
  fr_assert(flags != NULL);
1644
1645
  /*
1646
   *  Raw things get encoded as-is, so that we can encode the correct tag and class.
1647
   */
1648
0
  if (unlikely(vp->da->flags.is_raw)) {
1649
0
    fr_assert(vp->vp_type == FR_TYPE_OCTETS);
1650
1651
0
    slen = fr_der_encode_octetstring(dbuff, cursor, encode_ctx);
1652
0
    if (slen < 0) return 0;
1653
1654
0
    fr_dcursor_next(cursor);
1655
0
    return slen;
1656
0
  }
1657
1658
0
  our_dbuff = FR_DBUFF(dbuff);
1659
1660
  /*
1661
   *  ISO/IEC 8825-1:2021
1662
   *  The structure of a DER encoding is as follows:
1663
   *
1664
   *    +------------+--------+-------+
1665
   *    | IDENTIFIER | LENGTH | VALUE |
1666
   *    +------------+--------+-------+
1667
   *
1668
   *  The IDENTIFIER is a tag that specifies the type of the value field and is encoded as follows:
1669
   *
1670
   *      8   7    6    5   4   3   2   1
1671
   *    +---+---+-----+---+---+---+---+---+
1672
   *    | Class | P/C |     Tag Number    |
1673
   *    +---+---+-----+---+---+---+---+---+
1674
   *         |
1675
   *         |- 0 = Primitive
1676
   *         |- 1 = Constructed
1677
   *
1678
   *  The CLASS field specifies the encoding class of the tag and may be one of the following values:
1679
   *
1680
   *    +------------------+-------+-------+
1681
   *    |      Class       | Bit 8 | Bit 7 |
1682
   *    +------------------+-------+-------+
1683
   *    | UNIVERSAL        |   0   |   0   |
1684
   *    | APPLICATION      |   0   |   1   |
1685
   *    | CONTEXT-SPECIFIC |   1   |   0   |
1686
   *    | PRIVATE          |   1   |   1   |
1687
   *    +------------------+-------+-------+
1688
   *
1689
   *  The P/C field specifies whether the value field is primitive or constructed.
1690
   *  The TAG NUMBER field specifies the tag number of the value field and is encoded as an unsigned binary
1691
   *  integer.
1692
   *
1693
   *  The LENGTH field specifies the length of the VALUE field and is encoded as an unsigned binary integer
1694
   *  and may be encoded as a single byte or multiple bytes.
1695
   *
1696
   *  The VALUE field contains LENGTH number of bytes and is encoded according to the tag.
1697
   *
1698
   */
1699
1700
0
  if (flags->has_default_value) {
1701
    /*
1702
     *  Skip encoding the default value, as per ISO/IEC 8825-1:2021 11.5
1703
     */
1704
0
    if (fr_value_box_cmp(&vp->data, flags->default_value) == 0) {
1705
0
      FR_PROTO_TRACE("Skipping default value");
1706
0
      fr_dcursor_next(cursor);
1707
0
      return 0;
1708
0
    }
1709
0
  }
1710
1711
0
  if (unlikely(flags->is_choice)) {
1712
0
    slen = fr_der_encode_choice(&our_dbuff, cursor, uctx);
1713
0
    if (slen < 0) return slen;
1714
1715
0
    fr_dcursor_next(cursor);
1716
0
    return fr_dbuff_set(dbuff, &our_dbuff);
1717
0
  }
1718
1719
0
  tag = flags->der_type;
1720
0
  if (!tag) tag = fr_type_to_der_tag_default(vp->vp_type);
1721
1722
0
  if (unlikely(tag == FR_DER_TAG_INVALID)) {
1723
0
    fr_strerror_printf("No tag defined for type %s", fr_type_to_str(vp->vp_type));
1724
0
    return -1;
1725
0
  }
1726
1727
0
  fr_assert(tag < FR_DER_TAG_MAX);
1728
1729
0
  func = &type_funcs[vp->vp_type];
1730
0
  if (!func->encode) func = &tag_funcs[tag];
1731
1732
0
  fr_assert(func != NULL);
1733
0
  fr_assert(func->encode != NULL);
1734
1735
  /*
1736
   *  Default flag class is 0, which is FR_DER_CLASS_UNIVERSAL.
1737
   */
1738
0
  tag_class = flags->class;
1739
1740
  /*
1741
   *  We call the DER type encoding function based on its
1742
   *  tag, but we might need to encode an option value
1743
   *  instead of a tag.
1744
   */
1745
0
  if (flags->is_option) tag = flags->option;
1746
1747
0
  slen = fr_der_encode_tag(&our_dbuff, tag, tag_class, func->constructed);
1748
0
  if (slen < 0) return slen;
1749
1750
  /*
1751
   *  Mark and reserve space in the buffer for the length field
1752
   */
1753
0
  fr_dbuff_marker(&marker, &our_dbuff);
1754
0
  FR_DBUFF_ADVANCE_RETURN(&our_dbuff, 1);
1755
1756
0
  if (flags->is_extensions) {
1757
0
    slen = fr_der_encode_X509_extensions(&our_dbuff, cursor, uctx);
1758
0
  } else {
1759
1760
0
    slen = func->encode(&our_dbuff, cursor, uctx);
1761
0
  }
1762
0
  if (slen < 0) return slen;
1763
1764
  /*
1765
  * Encode the length of the value
1766
  */
1767
0
  slen = fr_der_encode_len(&our_dbuff, &marker);
1768
0
  if (slen < 0) return slen;
1769
1770
0
  fr_dcursor_next(cursor);
1771
0
  return fr_dbuff_set(dbuff, &our_dbuff);
1772
0
}
1773
1774
static ssize_t fr_der_encode_proto(UNUSED TALLOC_CTX *ctx, fr_pair_list_t *vps, uint8_t *data, size_t data_len,
1775
           void *encode_ctx)
1776
0
{
1777
0
  fr_dbuff_t   dbuff;
1778
0
  fr_dcursor_t cursor;
1779
0
  ssize_t      slen;
1780
1781
0
  fr_dbuff_init(&dbuff, data, data_len);
1782
1783
0
  fr_pair_dcursor_init(&cursor, vps);
1784
1785
0
  slen = encode_value(&dbuff, &cursor, encode_ctx);
1786
1787
0
  if (slen < 0) {
1788
0
    fr_strerror_printf("Failed to encode data: %s", fr_strerror());
1789
0
    return -1;
1790
0
  }
1791
1792
0
  return slen;
1793
0
}
1794
1795
/*
1796
 *  Test points
1797
 */
1798
static int encode_test_ctx(void **out, TALLOC_CTX *ctx, UNUSED fr_dict_t const *dict,
1799
         UNUSED fr_dict_attr_t const *root_da)
1800
3.93k
{
1801
3.93k
  fr_der_encode_ctx_t *test_ctx;
1802
1803
3.93k
  test_ctx = talloc_zero(ctx, fr_der_encode_ctx_t);
1804
3.93k
  if (!test_ctx) return -1;
1805
1806
3.93k
  test_ctx->tmp_ctx      = talloc(test_ctx, uint8_t);
1807
1808
3.93k
  *out = test_ctx;
1809
1810
3.93k
  return 0;
1811
3.93k
}
1812
1813
extern fr_test_point_pair_encode_t der_tp_encode_pair;
1814
fr_test_point_pair_encode_t    der_tp_encode_pair = {
1815
         .test_ctx = encode_test_ctx,
1816
         .func   = encode_value,
1817
};
1818
1819
extern fr_test_point_proto_encode_t der_tp_encode_proto;
1820
fr_test_point_proto_encode_t      der_tp_encode_proto = {
1821
         .test_ctx = encode_test_ctx,
1822
         .func   = fr_der_encode_proto,
1823
};