1 /* Copyright (c) 2014, Google Inc.
2  *
3  * Permission to use, copy, modify, and/or distribute this software for any
4  * purpose with or without fee is hereby granted, provided that the above
5  * copyright notice and this permission notice appear in all copies.
6  *
7  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10  * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14 
15 #include <openssl/bytestring.h>
16 
17 #include <assert.h>
18 #include <limits.h>
19 #include <string.h>
20 
21 #include <openssl/mem.h>
22 
23 #include "../internal.h"
24 
25 
CBB_zero(CBB * cbb)26 void CBB_zero(CBB *cbb) {
27   OPENSSL_memset(cbb, 0, sizeof(CBB));
28 }
29 
cbb_init(CBB * cbb,uint8_t * buf,size_t cap)30 static int cbb_init(CBB *cbb, uint8_t *buf, size_t cap) {
31   // This assumes that |cbb| has already been zeroed.
32   struct cbb_buffer_st *base;
33 
34   base = OPENSSL_malloc(sizeof(struct cbb_buffer_st));
35   if (base == NULL) {
36     return 0;
37   }
38 
39   base->buf = buf;
40   base->len = 0;
41   base->cap = cap;
42   base->can_resize = 1;
43   base->error = 0;
44 
45   cbb->base = base;
46   cbb->is_child = 0;
47   return 1;
48 }
49 
CBB_init(CBB * cbb,size_t initial_capacity)50 int CBB_init(CBB *cbb, size_t initial_capacity) {
51   CBB_zero(cbb);
52 
53   uint8_t *buf = OPENSSL_malloc(initial_capacity);
54   if (initial_capacity > 0 && buf == NULL) {
55     return 0;
56   }
57 
58   if (!cbb_init(cbb, buf, initial_capacity)) {
59     OPENSSL_free(buf);
60     return 0;
61   }
62 
63   return 1;
64 }
65 
CBB_init_fixed(CBB * cbb,uint8_t * buf,size_t len)66 int CBB_init_fixed(CBB *cbb, uint8_t *buf, size_t len) {
67   CBB_zero(cbb);
68 
69   if (!cbb_init(cbb, buf, len)) {
70     return 0;
71   }
72 
73   cbb->base->can_resize = 0;
74   return 1;
75 }
76 
CBB_cleanup(CBB * cbb)77 void CBB_cleanup(CBB *cbb) {
78   // Child |CBB|s are non-owning. They are implicitly discarded and should not
79   // be used with |CBB_cleanup| or |ScopedCBB|.
80   assert(!cbb->is_child);
81   if (cbb->is_child) {
82     return;
83   }
84 
85   if (cbb->base) {
86     if (cbb->base->can_resize) {
87       OPENSSL_free(cbb->base->buf);
88     }
89     OPENSSL_free(cbb->base);
90   }
91   cbb->base = NULL;
92 }
93 
cbb_buffer_reserve(struct cbb_buffer_st * base,uint8_t ** out,size_t len)94 static int cbb_buffer_reserve(struct cbb_buffer_st *base, uint8_t **out,
95                               size_t len) {
96   size_t newlen;
97 
98   if (base == NULL) {
99     return 0;
100   }
101 
102   newlen = base->len + len;
103   if (newlen < base->len) {
104     // Overflow
105     goto err;
106   }
107 
108   if (newlen > base->cap) {
109     size_t newcap = base->cap * 2;
110     uint8_t *newbuf;
111 
112     if (!base->can_resize) {
113       goto err;
114     }
115 
116     if (newcap < base->cap || newcap < newlen) {
117       newcap = newlen;
118     }
119     newbuf = OPENSSL_realloc(base->buf, newcap);
120     if (newbuf == NULL) {
121       goto err;
122     }
123 
124     base->buf = newbuf;
125     base->cap = newcap;
126   }
127 
128   if (out) {
129     *out = base->buf + base->len;
130   }
131 
132   return 1;
133 
134 err:
135   base->error = 1;
136   return 0;
137 }
138 
cbb_buffer_add(struct cbb_buffer_st * base,uint8_t ** out,size_t len)139 static int cbb_buffer_add(struct cbb_buffer_st *base, uint8_t **out,
140                           size_t len) {
141   if (!cbb_buffer_reserve(base, out, len)) {
142     return 0;
143   }
144   // This will not overflow or |cbb_buffer_reserve| would have failed.
145   base->len += len;
146   return 1;
147 }
148 
cbb_buffer_add_u(struct cbb_buffer_st * base,uint64_t v,size_t len_len)149 static int cbb_buffer_add_u(struct cbb_buffer_st *base, uint64_t v,
150                             size_t len_len) {
151   if (len_len == 0) {
152     return 1;
153   }
154 
155   uint8_t *buf;
156   if (!cbb_buffer_add(base, &buf, len_len)) {
157     return 0;
158   }
159 
160   for (size_t i = len_len - 1; i < len_len; i--) {
161     buf[i] = v;
162     v >>= 8;
163   }
164 
165   if (v != 0) {
166     base->error = 1;
167     return 0;
168   }
169 
170   return 1;
171 }
172 
CBB_finish(CBB * cbb,uint8_t ** out_data,size_t * out_len)173 int CBB_finish(CBB *cbb, uint8_t **out_data, size_t *out_len) {
174   if (cbb->is_child) {
175     return 0;
176   }
177 
178   if (!CBB_flush(cbb)) {
179     return 0;
180   }
181 
182   if (cbb->base->can_resize && (out_data == NULL || out_len == NULL)) {
183     // |out_data| and |out_len| can only be NULL if the CBB is fixed.
184     return 0;
185   }
186 
187   if (out_data != NULL) {
188     *out_data = cbb->base->buf;
189   }
190   if (out_len != NULL) {
191     *out_len = cbb->base->len;
192   }
193   cbb->base->buf = NULL;
194   CBB_cleanup(cbb);
195   return 1;
196 }
197 
198 // CBB_flush recurses and then writes out any pending length prefix. The
199 // current length of the underlying base is taken to be the length of the
200 // length-prefixed data.
CBB_flush(CBB * cbb)201 int CBB_flush(CBB *cbb) {
202   size_t child_start, i, len;
203 
204   // If |cbb->base| has hit an error, the buffer is in an undefined state, so
205   // fail all following calls. In particular, |cbb->child| may point to invalid
206   // memory.
207   if (cbb->base == NULL || cbb->base->error) {
208     return 0;
209   }
210 
211   if (cbb->child == NULL || cbb->child->pending_len_len == 0) {
212     return 1;
213   }
214 
215   child_start = cbb->child->offset + cbb->child->pending_len_len;
216 
217   if (!CBB_flush(cbb->child) ||
218       child_start < cbb->child->offset ||
219       cbb->base->len < child_start) {
220     goto err;
221   }
222 
223   len = cbb->base->len - child_start;
224 
225   if (cbb->child->pending_is_asn1) {
226     // For ASN.1 we assume that we'll only need a single byte for the length.
227     // If that turned out to be incorrect, we have to move the contents along
228     // in order to make space.
229     uint8_t len_len;
230     uint8_t initial_length_byte;
231 
232     assert (cbb->child->pending_len_len == 1);
233 
234     if (len > 0xfffffffe) {
235       // Too large.
236       goto err;
237     } else if (len > 0xffffff) {
238       len_len = 5;
239       initial_length_byte = 0x80 | 4;
240     } else if (len > 0xffff) {
241       len_len = 4;
242       initial_length_byte = 0x80 | 3;
243     } else if (len > 0xff) {
244       len_len = 3;
245       initial_length_byte = 0x80 | 2;
246     } else if (len > 0x7f) {
247       len_len = 2;
248       initial_length_byte = 0x80 | 1;
249     } else {
250       len_len = 1;
251       initial_length_byte = (uint8_t)len;
252       len = 0;
253     }
254 
255     if (len_len != 1) {
256       // We need to move the contents along in order to make space.
257       size_t extra_bytes = len_len - 1;
258       if (!cbb_buffer_add(cbb->base, NULL, extra_bytes)) {
259         goto err;
260       }
261       OPENSSL_memmove(cbb->base->buf + child_start + extra_bytes,
262                       cbb->base->buf + child_start, len);
263     }
264     cbb->base->buf[cbb->child->offset++] = initial_length_byte;
265     cbb->child->pending_len_len = len_len - 1;
266   }
267 
268   for (i = cbb->child->pending_len_len - 1; i < cbb->child->pending_len_len;
269        i--) {
270     cbb->base->buf[cbb->child->offset + i] = (uint8_t)len;
271     len >>= 8;
272   }
273   if (len != 0) {
274     goto err;
275   }
276 
277   cbb->child->base = NULL;
278   cbb->child = NULL;
279 
280   return 1;
281 
282 err:
283   cbb->base->error = 1;
284   return 0;
285 }
286 
CBB_data(const CBB * cbb)287 const uint8_t *CBB_data(const CBB *cbb) {
288   assert(cbb->child == NULL);
289   return cbb->base->buf + cbb->offset + cbb->pending_len_len;
290 }
291 
CBB_len(const CBB * cbb)292 size_t CBB_len(const CBB *cbb) {
293   assert(cbb->child == NULL);
294   assert(cbb->offset + cbb->pending_len_len <= cbb->base->len);
295 
296   return cbb->base->len - cbb->offset - cbb->pending_len_len;
297 }
298 
cbb_add_length_prefixed(CBB * cbb,CBB * out_contents,uint8_t len_len)299 static int cbb_add_length_prefixed(CBB *cbb, CBB *out_contents,
300                                    uint8_t len_len) {
301   uint8_t *prefix_bytes;
302 
303   if (!CBB_flush(cbb)) {
304     return 0;
305   }
306 
307   size_t offset = cbb->base->len;
308   if (!cbb_buffer_add(cbb->base, &prefix_bytes, len_len)) {
309     return 0;
310   }
311 
312   OPENSSL_memset(prefix_bytes, 0, len_len);
313   OPENSSL_memset(out_contents, 0, sizeof(CBB));
314   out_contents->base = cbb->base;
315   out_contents->is_child = 1;
316   cbb->child = out_contents;
317   cbb->child->offset = offset;
318   cbb->child->pending_len_len = len_len;
319   cbb->child->pending_is_asn1 = 0;
320 
321   return 1;
322 }
323 
CBB_add_u8_length_prefixed(CBB * cbb,CBB * out_contents)324 int CBB_add_u8_length_prefixed(CBB *cbb, CBB *out_contents) {
325   return cbb_add_length_prefixed(cbb, out_contents, 1);
326 }
327 
CBB_add_u16_length_prefixed(CBB * cbb,CBB * out_contents)328 int CBB_add_u16_length_prefixed(CBB *cbb, CBB *out_contents) {
329   return cbb_add_length_prefixed(cbb, out_contents, 2);
330 }
331 
CBB_add_u24_length_prefixed(CBB * cbb,CBB * out_contents)332 int CBB_add_u24_length_prefixed(CBB *cbb, CBB *out_contents) {
333   return cbb_add_length_prefixed(cbb, out_contents, 3);
334 }
335 
336 // add_base128_integer encodes |v| as a big-endian base-128 integer where the
337 // high bit of each byte indicates where there is more data. This is the
338 // encoding used in DER for both high tag number form and OID components.
add_base128_integer(CBB * cbb,uint64_t v)339 static int add_base128_integer(CBB *cbb, uint64_t v) {
340   unsigned len_len = 0;
341   uint64_t copy = v;
342   while (copy > 0) {
343     len_len++;
344     copy >>= 7;
345   }
346   if (len_len == 0) {
347     len_len = 1;  // Zero is encoded with one byte.
348   }
349   for (unsigned i = len_len - 1; i < len_len; i--) {
350     uint8_t byte = (v >> (7 * i)) & 0x7f;
351     if (i != 0) {
352       // The high bit denotes whether there is more data.
353       byte |= 0x80;
354     }
355     if (!CBB_add_u8(cbb, byte)) {
356       return 0;
357     }
358   }
359   return 1;
360 }
361 
CBB_add_asn1(CBB * cbb,CBB * out_contents,unsigned tag)362 int CBB_add_asn1(CBB *cbb, CBB *out_contents, unsigned tag) {
363   if (!CBB_flush(cbb)) {
364     return 0;
365   }
366 
367   // Split the tag into leading bits and tag number.
368   uint8_t tag_bits = (tag >> CBS_ASN1_TAG_SHIFT) & 0xe0;
369   unsigned tag_number = tag & CBS_ASN1_TAG_NUMBER_MASK;
370   if (tag_number >= 0x1f) {
371     // Set all the bits in the tag number to signal high tag number form.
372     if (!CBB_add_u8(cbb, tag_bits | 0x1f) ||
373         !add_base128_integer(cbb, tag_number)) {
374       return 0;
375     }
376   } else if (!CBB_add_u8(cbb, tag_bits | tag_number)) {
377     return 0;
378   }
379 
380   size_t offset = cbb->base->len;
381   if (!CBB_add_u8(cbb, 0)) {
382     return 0;
383   }
384 
385   OPENSSL_memset(out_contents, 0, sizeof(CBB));
386   out_contents->base = cbb->base;
387   out_contents->is_child = 1;
388   cbb->child = out_contents;
389   cbb->child->offset = offset;
390   cbb->child->pending_len_len = 1;
391   cbb->child->pending_is_asn1 = 1;
392 
393   return 1;
394 }
395 
CBB_add_bytes(CBB * cbb,const uint8_t * data,size_t len)396 int CBB_add_bytes(CBB *cbb, const uint8_t *data, size_t len) {
397   uint8_t *dest;
398 
399   if (!CBB_flush(cbb) ||
400       !cbb_buffer_add(cbb->base, &dest, len)) {
401     return 0;
402   }
403   OPENSSL_memcpy(dest, data, len);
404   return 1;
405 }
406 
CBB_add_zeros(CBB * cbb,size_t len)407 int CBB_add_zeros(CBB *cbb, size_t len) {
408   uint8_t *out;
409   if (!CBB_add_space(cbb, &out, len)) {
410     return 0;
411   }
412   OPENSSL_memset(out, 0, len);
413   return 1;
414 }
415 
CBB_add_space(CBB * cbb,uint8_t ** out_data,size_t len)416 int CBB_add_space(CBB *cbb, uint8_t **out_data, size_t len) {
417   if (!CBB_flush(cbb) ||
418       !cbb_buffer_add(cbb->base, out_data, len)) {
419     return 0;
420   }
421   return 1;
422 }
423 
CBB_reserve(CBB * cbb,uint8_t ** out_data,size_t len)424 int CBB_reserve(CBB *cbb, uint8_t **out_data, size_t len) {
425   if (!CBB_flush(cbb) ||
426       !cbb_buffer_reserve(cbb->base, out_data, len)) {
427     return 0;
428   }
429   return 1;
430 }
431 
CBB_did_write(CBB * cbb,size_t len)432 int CBB_did_write(CBB *cbb, size_t len) {
433   size_t newlen = cbb->base->len + len;
434   if (cbb->child != NULL ||
435       newlen < cbb->base->len ||
436       newlen > cbb->base->cap) {
437     return 0;
438   }
439   cbb->base->len = newlen;
440   return 1;
441 }
442 
CBB_add_u8(CBB * cbb,uint8_t value)443 int CBB_add_u8(CBB *cbb, uint8_t value) {
444   if (!CBB_flush(cbb)) {
445     return 0;
446   }
447 
448   return cbb_buffer_add_u(cbb->base, value, 1);
449 }
450 
CBB_add_u16(CBB * cbb,uint16_t value)451 int CBB_add_u16(CBB *cbb, uint16_t value) {
452   if (!CBB_flush(cbb)) {
453     return 0;
454   }
455 
456   return cbb_buffer_add_u(cbb->base, value, 2);
457 }
458 
CBB_add_u16le(CBB * cbb,uint16_t value)459 int CBB_add_u16le(CBB *cbb, uint16_t value) {
460   return CBB_add_u16(cbb, CRYPTO_bswap2(value));
461 }
462 
CBB_add_u24(CBB * cbb,uint32_t value)463 int CBB_add_u24(CBB *cbb, uint32_t value) {
464   if (!CBB_flush(cbb)) {
465     return 0;
466   }
467 
468   return cbb_buffer_add_u(cbb->base, value, 3);
469 }
470 
CBB_add_u32(CBB * cbb,uint32_t value)471 int CBB_add_u32(CBB *cbb, uint32_t value) {
472   if (!CBB_flush(cbb)) {
473     return 0;
474   }
475 
476   return cbb_buffer_add_u(cbb->base, value, 4);
477 }
478 
CBB_add_u32le(CBB * cbb,uint32_t value)479 int CBB_add_u32le(CBB *cbb, uint32_t value) {
480   return CBB_add_u32(cbb, CRYPTO_bswap4(value));
481 }
482 
CBB_add_u64(CBB * cbb,uint64_t value)483 int CBB_add_u64(CBB *cbb, uint64_t value) {
484   if (!CBB_flush(cbb)) {
485     return 0;
486   }
487   return cbb_buffer_add_u(cbb->base, value, 8);
488 }
489 
CBB_add_u64le(CBB * cbb,uint64_t value)490 int CBB_add_u64le(CBB *cbb, uint64_t value) {
491   return CBB_add_u64(cbb, CRYPTO_bswap8(value));
492 }
493 
CBB_discard_child(CBB * cbb)494 void CBB_discard_child(CBB *cbb) {
495   if (cbb->child == NULL) {
496     return;
497   }
498 
499   cbb->base->len = cbb->child->offset;
500 
501   cbb->child->base = NULL;
502   cbb->child = NULL;
503 }
504 
CBB_add_asn1_uint64(CBB * cbb,uint64_t value)505 int CBB_add_asn1_uint64(CBB *cbb, uint64_t value) {
506   CBB child;
507   int started = 0;
508 
509   if (!CBB_add_asn1(cbb, &child, CBS_ASN1_INTEGER)) {
510     return 0;
511   }
512 
513   for (size_t i = 0; i < 8; i++) {
514     uint8_t byte = (value >> 8*(7-i)) & 0xff;
515     if (!started) {
516       if (byte == 0) {
517         // Don't encode leading zeros.
518         continue;
519       }
520       // If the high bit is set, add a padding byte to make it
521       // unsigned.
522       if ((byte & 0x80) && !CBB_add_u8(&child, 0)) {
523         return 0;
524       }
525       started = 1;
526     }
527     if (!CBB_add_u8(&child, byte)) {
528       return 0;
529     }
530   }
531 
532   // 0 is encoded as a single 0, not the empty string.
533   if (!started && !CBB_add_u8(&child, 0)) {
534     return 0;
535   }
536 
537   return CBB_flush(cbb);
538 }
539 
CBB_add_asn1_int64(CBB * cbb,int64_t value)540 int CBB_add_asn1_int64(CBB *cbb, int64_t value) {
541   if (value >= 0) {
542     return CBB_add_asn1_uint64(cbb, value);
543   }
544 
545   union {
546     int64_t i;
547     uint8_t bytes[sizeof(int64_t)];
548   } u;
549   u.i = value;
550   int start = 7;
551   // Skip leading sign-extension bytes unless they are necessary.
552   while (start > 0 && (u.bytes[start] == 0xff && (u.bytes[start - 1] & 0x80))) {
553     start--;
554   }
555 
556   CBB child;
557   if (!CBB_add_asn1(cbb, &child, CBS_ASN1_INTEGER)) {
558     return 0;
559   }
560   for (int i = start; i >= 0; i--) {
561     if (!CBB_add_u8(&child, u.bytes[i])) {
562       return 0;
563     }
564   }
565   return CBB_flush(cbb);
566 }
567 
CBB_add_asn1_octet_string(CBB * cbb,const uint8_t * data,size_t data_len)568 int CBB_add_asn1_octet_string(CBB *cbb, const uint8_t *data, size_t data_len) {
569   CBB child;
570   if (!CBB_add_asn1(cbb, &child, CBS_ASN1_OCTETSTRING) ||
571       !CBB_add_bytes(&child, data, data_len) ||
572       !CBB_flush(cbb)) {
573     return 0;
574   }
575 
576   return 1;
577 }
578 
CBB_add_asn1_bool(CBB * cbb,int value)579 int CBB_add_asn1_bool(CBB *cbb, int value) {
580   CBB child;
581   if (!CBB_add_asn1(cbb, &child, CBS_ASN1_BOOLEAN) ||
582       !CBB_add_u8(&child, value != 0 ? 0xff : 0) ||
583       !CBB_flush(cbb)) {
584     return 0;
585   }
586 
587   return 1;
588 }
589 
590 // parse_dotted_decimal parses one decimal component from |cbs|, where |cbs| is
591 // an OID literal, e.g., "1.2.840.113554.4.1.72585". It consumes both the
592 // component and the dot, so |cbs| may be passed into the function again for the
593 // next value.
parse_dotted_decimal(CBS * cbs,uint64_t * out)594 static int parse_dotted_decimal(CBS *cbs, uint64_t *out) {
595   *out = 0;
596   int seen_digit = 0;
597   for (;;) {
598     // Valid terminators for a component are the end of the string or a
599     // non-terminal dot. If the string ends with a dot, this is not a valid OID
600     // string.
601     uint8_t u;
602     if (!CBS_get_u8(cbs, &u) ||
603         (u == '.' && CBS_len(cbs) > 0)) {
604       break;
605     }
606     if (u < '0' || u > '9' ||
607         // Forbid stray leading zeros.
608         (seen_digit && *out == 0) ||
609         // Check for overflow.
610         *out > UINT64_MAX / 10 ||
611         *out * 10 > UINT64_MAX - (u - '0')) {
612       return 0;
613     }
614     *out = *out * 10 + (u - '0');
615     seen_digit = 1;
616   }
617   // The empty string is not a legal OID component.
618   return seen_digit;
619 }
620 
CBB_add_asn1_oid_from_text(CBB * cbb,const char * text,size_t len)621 int CBB_add_asn1_oid_from_text(CBB *cbb, const char *text, size_t len) {
622   if (!CBB_flush(cbb)) {
623     return 0;
624   }
625 
626   CBS cbs;
627   CBS_init(&cbs, (const uint8_t *)text, len);
628 
629   // OIDs must have at least two components.
630   uint64_t a, b;
631   if (!parse_dotted_decimal(&cbs, &a) ||
632       !parse_dotted_decimal(&cbs, &b)) {
633     return 0;
634   }
635 
636   // The first component is encoded as 40 * |a| + |b|. This assumes that |a| is
637   // 0, 1, or 2 and that, when it is 0 or 1, |b| is at most 39.
638   if (a > 2 ||
639       (a < 2 && b > 39) ||
640       b > UINT64_MAX - 80 ||
641       !add_base128_integer(cbb, 40u * a + b)) {
642     return 0;
643   }
644 
645   // The remaining components are encoded unmodified.
646   while (CBS_len(&cbs) > 0) {
647     if (!parse_dotted_decimal(&cbs, &a) ||
648         !add_base128_integer(cbb, a)) {
649       return 0;
650     }
651   }
652 
653   return 1;
654 }
655 
compare_set_of_element(const void * a_ptr,const void * b_ptr)656 static int compare_set_of_element(const void *a_ptr, const void *b_ptr) {
657   // See X.690, section 11.6 for the ordering. They are sorted in ascending
658   // order by their DER encoding.
659   const CBS *a = a_ptr, *b = b_ptr;
660   size_t a_len = CBS_len(a), b_len = CBS_len(b);
661   size_t min_len = a_len < b_len ? a_len : b_len;
662   int ret = OPENSSL_memcmp(CBS_data(a), CBS_data(b), min_len);
663   if (ret != 0) {
664     return ret;
665   }
666   if (a_len == b_len) {
667     return 0;
668   }
669   // If one is a prefix of the other, the shorter one sorts first. (This is not
670   // actually reachable. No DER encoding is a prefix of another DER encoding.)
671   return a_len < b_len ? -1 : 1;
672 }
673 
CBB_flush_asn1_set_of(CBB * cbb)674 int CBB_flush_asn1_set_of(CBB *cbb) {
675   if (!CBB_flush(cbb)) {
676     return 0;
677   }
678 
679   CBS cbs;
680   size_t num_children = 0;
681   CBS_init(&cbs, CBB_data(cbb), CBB_len(cbb));
682   while (CBS_len(&cbs) != 0) {
683     if (!CBS_get_any_asn1_element(&cbs, NULL, NULL, NULL)) {
684       return 0;
685     }
686     num_children++;
687   }
688 
689   if (num_children < 2) {
690     return 1;  // Nothing to do. This is the common case for X.509.
691   }
692   if (num_children > ((size_t)-1) / sizeof(CBS)) {
693     return 0;  // Overflow.
694   }
695 
696   // Parse out the children and sort. We alias them into a copy of so they
697   // remain valid as we rewrite |cbb|.
698   int ret = 0;
699   size_t buf_len = CBB_len(cbb);
700   uint8_t *buf = OPENSSL_memdup(CBB_data(cbb), buf_len);
701   CBS *children = OPENSSL_malloc(num_children * sizeof(CBS));
702   if (buf == NULL || children == NULL) {
703     goto err;
704   }
705   CBS_init(&cbs, buf, buf_len);
706   for (size_t i = 0; i < num_children; i++) {
707     if (!CBS_get_any_asn1_element(&cbs, &children[i], NULL, NULL)) {
708       goto err;
709     }
710   }
711   qsort(children, num_children, sizeof(CBS), compare_set_of_element);
712 
713   // Rewind |cbb| and write the contents back in the new order.
714   cbb->base->len = cbb->offset + cbb->pending_len_len;
715   for (size_t i = 0; i < num_children; i++) {
716     if (!CBB_add_bytes(cbb, CBS_data(&children[i]), CBS_len(&children[i]))) {
717       goto err;
718     }
719   }
720   assert(CBB_len(cbb) == buf_len);
721 
722   ret = 1;
723 
724 err:
725   OPENSSL_free(buf);
726   OPENSSL_free(children);
727   return ret;
728 }
729