1 /*
2  *  X.509 base functions for creating certificates / CSRs
3  *
4  *  Copyright The Mbed TLS Contributors
5  *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
6  */
7 
8 #include "x509_internal.h"
9 
10 #if defined(MBEDTLS_X509_CREATE_C)
11 
12 #include "mbedtls/asn1write.h"
13 #include "mbedtls/error.h"
14 #include "mbedtls/oid.h"
15 #include "x509_oid.h"
16 
17 #include <limits.h>
18 #include <string.h>
19 
20 #include "mbedtls/platform.h"
21 
22 #include "mbedtls/asn1.h"
23 
24 /* Structure linking OIDs for X.509 DN AttributeTypes to their
25  * string representations and default string encodings used by Mbed TLS. */
26 typedef struct {
27     const char *name; /* String representation of AttributeType, e.g.
28                        * "CN" or "emailAddress". */
29     size_t name_len; /* Length of 'name', without trailing 0 byte. */
30     const char *oid; /* String representation of OID of AttributeType,
31                       * as per RFC 5280, Appendix A.1. encoded as per
32                       * X.690 */
33     int default_tag; /* The default character encoding used for the
34                       * given attribute type, e.g.
35                       * MBEDTLS_ASN1_UTF8_STRING for UTF-8. */
36 } x509_attr_descriptor_t;
37 
38 #define ADD_STRLEN(s)     s, sizeof(s) - 1
39 
40 /* X.509 DN attributes from RFC 5280, Appendix A.1. */
41 static const x509_attr_descriptor_t x509_attrs[] =
42 {
43     { ADD_STRLEN("CN"),
44       MBEDTLS_OID_AT_CN, MBEDTLS_ASN1_UTF8_STRING },
45     { ADD_STRLEN("commonName"),
46       MBEDTLS_OID_AT_CN, MBEDTLS_ASN1_UTF8_STRING },
47     { ADD_STRLEN("C"),
48       MBEDTLS_OID_AT_COUNTRY, MBEDTLS_ASN1_PRINTABLE_STRING },
49     { ADD_STRLEN("countryName"),
50       MBEDTLS_OID_AT_COUNTRY, MBEDTLS_ASN1_PRINTABLE_STRING },
51     { ADD_STRLEN("O"),
52       MBEDTLS_OID_AT_ORGANIZATION, MBEDTLS_ASN1_UTF8_STRING },
53     { ADD_STRLEN("organizationName"),
54       MBEDTLS_OID_AT_ORGANIZATION, MBEDTLS_ASN1_UTF8_STRING },
55     { ADD_STRLEN("L"),
56       MBEDTLS_OID_AT_LOCALITY, MBEDTLS_ASN1_UTF8_STRING },
57     { ADD_STRLEN("locality"),
58       MBEDTLS_OID_AT_LOCALITY, MBEDTLS_ASN1_UTF8_STRING },
59     { ADD_STRLEN("R"),
60       MBEDTLS_OID_PKCS9_EMAIL, MBEDTLS_ASN1_IA5_STRING },
61     { ADD_STRLEN("OU"),
62       MBEDTLS_OID_AT_ORG_UNIT, MBEDTLS_ASN1_UTF8_STRING },
63     { ADD_STRLEN("organizationalUnitName"),
64       MBEDTLS_OID_AT_ORG_UNIT, MBEDTLS_ASN1_UTF8_STRING },
65     { ADD_STRLEN("ST"),
66       MBEDTLS_OID_AT_STATE, MBEDTLS_ASN1_UTF8_STRING },
67     { ADD_STRLEN("stateOrProvinceName"),
68       MBEDTLS_OID_AT_STATE, MBEDTLS_ASN1_UTF8_STRING },
69     { ADD_STRLEN("emailAddress"),
70       MBEDTLS_OID_PKCS9_EMAIL, MBEDTLS_ASN1_IA5_STRING },
71     { ADD_STRLEN("serialNumber"),
72       MBEDTLS_OID_AT_SERIAL_NUMBER, MBEDTLS_ASN1_PRINTABLE_STRING },
73     { ADD_STRLEN("postalAddress"),
74       MBEDTLS_OID_AT_POSTAL_ADDRESS, MBEDTLS_ASN1_PRINTABLE_STRING },
75     { ADD_STRLEN("postalCode"),
76       MBEDTLS_OID_AT_POSTAL_CODE, MBEDTLS_ASN1_PRINTABLE_STRING },
77     { ADD_STRLEN("dnQualifier"),
78       MBEDTLS_OID_AT_DN_QUALIFIER, MBEDTLS_ASN1_PRINTABLE_STRING },
79     { ADD_STRLEN("title"),
80       MBEDTLS_OID_AT_TITLE, MBEDTLS_ASN1_UTF8_STRING },
81     { ADD_STRLEN("surName"),
82       MBEDTLS_OID_AT_SUR_NAME, MBEDTLS_ASN1_UTF8_STRING },
83     { ADD_STRLEN("SN"),
84       MBEDTLS_OID_AT_SUR_NAME, MBEDTLS_ASN1_UTF8_STRING },
85     { ADD_STRLEN("givenName"),
86       MBEDTLS_OID_AT_GIVEN_NAME, MBEDTLS_ASN1_UTF8_STRING },
87     { ADD_STRLEN("GN"),
88       MBEDTLS_OID_AT_GIVEN_NAME, MBEDTLS_ASN1_UTF8_STRING },
89     { ADD_STRLEN("initials"),
90       MBEDTLS_OID_AT_INITIALS, MBEDTLS_ASN1_UTF8_STRING },
91     { ADD_STRLEN("pseudonym"),
92       MBEDTLS_OID_AT_PSEUDONYM, MBEDTLS_ASN1_UTF8_STRING },
93     { ADD_STRLEN("generationQualifier"),
94       MBEDTLS_OID_AT_GENERATION_QUALIFIER, MBEDTLS_ASN1_UTF8_STRING },
95     { ADD_STRLEN("domainComponent"),
96       MBEDTLS_OID_DOMAIN_COMPONENT, MBEDTLS_ASN1_IA5_STRING },
97     { ADD_STRLEN("DC"),
98       MBEDTLS_OID_DOMAIN_COMPONENT,   MBEDTLS_ASN1_IA5_STRING },
99     { NULL, 0, NULL, MBEDTLS_ASN1_NULL }
100 };
101 
x509_attr_descr_from_name(const char * name,size_t name_len)102 static const x509_attr_descriptor_t *x509_attr_descr_from_name(const char *name, size_t name_len)
103 {
104     const x509_attr_descriptor_t *cur;
105 
106     for (cur = x509_attrs; cur->name != NULL; cur++) {
107         if (cur->name_len == name_len &&
108             strncmp(cur->name, name, name_len) == 0) {
109             break;
110         }
111     }
112 
113     if (cur->name == NULL) {
114         return NULL;
115     }
116 
117     return cur;
118 }
119 
hex_to_int(char c)120 static int hex_to_int(char c)
121 {
122     return ('0' <= c && c <= '9') ? (c - '0') :
123            ('a' <= c && c <= 'f') ? (c - 'a' + 10) :
124            ('A' <= c && c <= 'F') ? (c - 'A' + 10) : -1;
125 }
126 
hexpair_to_int(const char * hexpair)127 static int hexpair_to_int(const char *hexpair)
128 {
129     int n1 = hex_to_int(*hexpair);
130     int n2 = hex_to_int(*(hexpair + 1));
131 
132     if (n1 != -1 && n2 != -1) {
133         return (n1 << 4) | n2;
134     } else {
135         return -1;
136     }
137 }
138 
parse_attribute_value_string(const char * s,int len,unsigned char * data,size_t * data_len)139 static int parse_attribute_value_string(const char *s,
140                                         int len,
141                                         unsigned char *data,
142                                         size_t *data_len)
143 {
144     const char *c;
145     const char *end = s + len;
146     unsigned char *d = data;
147     int n;
148 
149     for (c = s; c < end; c++) {
150         if (*c == '\\') {
151             c++;
152 
153             /* Check for valid escaped characters as per RFC 4514 Section 3 */
154             if (c + 1 < end && (n = hexpair_to_int(c)) != -1) {
155                 if (n == 0) {
156                     return MBEDTLS_ERR_X509_INVALID_NAME;
157                 }
158                 *(d++) = n;
159                 c++;
160             } else if (c < end && strchr(" ,=+<>#;\"\\", *c)) {
161                 *(d++) = *c;
162             } else {
163                 return MBEDTLS_ERR_X509_INVALID_NAME;
164             }
165         } else {
166             *(d++) = *c;
167         }
168 
169         if (d - data == MBEDTLS_X509_MAX_DN_NAME_SIZE) {
170             return MBEDTLS_ERR_X509_INVALID_NAME;
171         }
172     }
173     *data_len = (size_t) (d - data);
174     return 0;
175 }
176 
177 /** Parse a hexstring containing a DER-encoded string.
178  *
179  * \param s         A string of \p len bytes hexadecimal digits.
180  * \param len       Number of bytes to read from \p s.
181  * \param data      Output buffer of size \p data_size.
182  *                  On success, it contains the payload that's DER-encoded
183  *                  in the input (content without the tag and length).
184  *                  If the DER tag is a string tag, the payload is guaranteed
185  *                  not to contain null bytes.
186  * \param data_size Length of the \p data buffer.
187  * \param data_len  On success, the length of the parsed string.
188  *                  It is guaranteed to be less than
189  *                  #MBEDTLS_X509_MAX_DN_NAME_SIZE.
190  * \param tag       The ASN.1 tag that the payload in \p data is encoded in.
191  *
192  * \retval          0 on success.
193  * \retval          #MBEDTLS_ERR_X509_INVALID_NAME if \p s does not contain
194  *                  a valid hexstring,
195  *                  or if the decoded hexstring is not valid DER,
196  *                  or if the payload does not fit in \p data,
197  *                  or if the payload is more than
198  *                  #MBEDTLS_X509_MAX_DN_NAME_SIZE bytes,
199  *                  of if \p *tag is an ASN.1 string tag and the payload
200  *                  contains a null byte.
201  * \retval          #MBEDTLS_ERR_X509_ALLOC_FAILED on low memory.
202  */
parse_attribute_value_hex_der_encoded(const char * s,size_t len,unsigned char * data,size_t data_size,size_t * data_len,int * tag)203 static int parse_attribute_value_hex_der_encoded(const char *s,
204                                                  size_t len,
205                                                  unsigned char *data,
206                                                  size_t data_size,
207                                                  size_t *data_len,
208                                                  int *tag)
209 {
210     /* Step 1: preliminary length checks. */
211     /* Each byte is encoded by exactly two hexadecimal digits. */
212     if (len % 2 != 0) {
213         /* Odd number of hex digits */
214         return MBEDTLS_ERR_X509_INVALID_NAME;
215     }
216     size_t const der_length = len / 2;
217     if (der_length > MBEDTLS_X509_MAX_DN_NAME_SIZE + 4) {
218         /* The payload would be more than MBEDTLS_X509_MAX_DN_NAME_SIZE
219          * (after subtracting the ASN.1 tag and length). Reject this early
220          * to avoid allocating a large intermediate buffer. */
221         return MBEDTLS_ERR_X509_INVALID_NAME;
222     }
223     if (der_length < 1) {
224         /* Avoid empty-buffer shenanigans. A valid DER encoding is never
225          * empty. */
226         return MBEDTLS_ERR_X509_INVALID_NAME;
227     }
228 
229     /* Step 2: Decode the hex string into an intermediate buffer. */
230     unsigned char *der = mbedtls_calloc(1, der_length);
231     if (der == NULL) {
232         return MBEDTLS_ERR_X509_ALLOC_FAILED;
233     }
234     /* Beyond this point, der needs to be freed on exit. */
235     for (size_t i = 0; i < der_length; i++) {
236         int c = hexpair_to_int(s + 2 * i);
237         if (c < 0) {
238             goto error;
239         }
240         der[i] = c;
241     }
242 
243     /* Step 3: decode the DER. */
244     /* We've checked that der_length >= 1 above. */
245     *tag = der[0];
246     {
247         unsigned char *p = der + 1;
248         if (mbedtls_asn1_get_len(&p, der + der_length, data_len) != 0) {
249             goto error;
250         }
251         /* Now p points to the first byte of the payload inside der,
252          * and *data_len is the length of the payload. */
253 
254         /* Step 4: payload validation */
255         if (*data_len > MBEDTLS_X509_MAX_DN_NAME_SIZE) {
256             goto error;
257         }
258         /* Strings must not contain null bytes. */
259         if (MBEDTLS_ASN1_IS_STRING_TAG(*tag)) {
260             for (size_t i = 0; i < *data_len; i++) {
261                 if (p[i] == 0) {
262                     goto error;
263                 }
264             }
265         }
266 
267         /* Step 5: output the payload. */
268         if (*data_len > data_size) {
269             goto error;
270         }
271         memcpy(data, p, *data_len);
272     }
273     mbedtls_free(der);
274 
275     return 0;
276 
277 error:
278     mbedtls_free(der);
279     return MBEDTLS_ERR_X509_INVALID_NAME;
280 }
281 
oid_parse_number(unsigned int * num,const char ** p,const char * bound)282 static int oid_parse_number(unsigned int *num, const char **p, const char *bound)
283 {
284     int ret = MBEDTLS_ERR_ASN1_INVALID_DATA;
285 
286     *num = 0;
287 
288     while (*p < bound && **p >= '0' && **p <= '9') {
289         ret = 0;
290         if (*num > (UINT_MAX / 10)) {
291             return MBEDTLS_ERR_ASN1_INVALID_DATA;
292         }
293         *num *= 10;
294         *num += **p - '0';
295         (*p)++;
296     }
297     return ret;
298 }
299 
oid_subidentifier_num_bytes(unsigned int value)300 static size_t oid_subidentifier_num_bytes(unsigned int value)
301 {
302     size_t num_bytes = 0;
303 
304     do {
305         value >>= 7;
306         num_bytes++;
307     } while (value != 0);
308 
309     return num_bytes;
310 }
311 
oid_subidentifier_encode_into(unsigned char ** p,unsigned char * bound,unsigned int value)312 static int oid_subidentifier_encode_into(unsigned char **p,
313                                          unsigned char *bound,
314                                          unsigned int value)
315 {
316     size_t num_bytes = oid_subidentifier_num_bytes(value);
317 
318     if ((size_t) (bound - *p) < num_bytes) {
319         return PSA_ERROR_BUFFER_TOO_SMALL;
320     }
321     (*p)[num_bytes - 1] = (unsigned char) (value & 0x7f);
322     value >>= 7;
323 
324     for (size_t i = 2; i <= num_bytes; i++) {
325         (*p)[num_bytes - i] = 0x80 | (unsigned char) (value & 0x7f);
326         value >>= 7;
327     }
328     *p += num_bytes;
329 
330     return 0;
331 }
332 
333 /* Return the OID for the given x.y.z.... style numeric string  */
mbedtls_oid_from_numeric_string(mbedtls_asn1_buf * oid,const char * oid_str,size_t size)334 int mbedtls_oid_from_numeric_string(mbedtls_asn1_buf *oid,
335                                     const char *oid_str, size_t size)
336 {
337     int ret = MBEDTLS_ERR_ASN1_INVALID_DATA;
338     const char *str_ptr = oid_str;
339     const char *str_bound = oid_str + size;
340     unsigned int val = 0;
341     unsigned int component1, component2;
342     size_t encoded_len;
343     unsigned char *resized_mem;
344 
345     /* Count the number of dots to get a worst-case allocation size. */
346     size_t num_dots = 0;
347     for (size_t i = 0; i < size; i++) {
348         if (oid_str[i] == '.') {
349             num_dots++;
350         }
351     }
352     /* Allocate maximum possible required memory:
353      * There are (num_dots + 1) integer components, but the first 2 share the
354      * same subidentifier, so we only need num_dots subidentifiers maximum. */
355     if (num_dots == 0 || (num_dots > MBEDTLS_OID_MAX_COMPONENTS - 1)) {
356         return MBEDTLS_ERR_ASN1_INVALID_DATA;
357     }
358     /* Each byte can store 7 bits, calculate number of bytes for a
359      * subidentifier:
360      *
361      * bytes = ceil(subidentifer_size * 8 / 7)
362      */
363     size_t bytes_per_subidentifier = (((sizeof(unsigned int) * 8) - 1) / 7)
364                                      + 1;
365     size_t max_possible_bytes = num_dots * bytes_per_subidentifier;
366     oid->p = mbedtls_calloc(max_possible_bytes, 1);
367     if (oid->p == NULL) {
368         return MBEDTLS_ERR_ASN1_ALLOC_FAILED;
369     }
370     unsigned char *out_ptr = oid->p;
371     unsigned char *out_bound = oid->p + max_possible_bytes;
372 
373     ret = oid_parse_number(&component1, &str_ptr, str_bound);
374     if (ret != 0) {
375         goto error;
376     }
377     if (component1 > 2) {
378         /* First component can't be > 2 */
379         ret = MBEDTLS_ERR_ASN1_INVALID_DATA;
380         goto error;
381     }
382     if (str_ptr >= str_bound || *str_ptr != '.') {
383         ret = MBEDTLS_ERR_ASN1_INVALID_DATA;
384         goto error;
385     }
386     str_ptr++;
387 
388     ret = oid_parse_number(&component2, &str_ptr, str_bound);
389     if (ret != 0) {
390         goto error;
391     }
392     if ((component1 < 2) && (component2 > 39)) {
393         /* Root nodes 0 and 1 may have up to 40 children, numbered 0-39 */
394         ret = MBEDTLS_ERR_ASN1_INVALID_DATA;
395         goto error;
396     }
397     if (str_ptr < str_bound) {
398         if (*str_ptr == '.') {
399             str_ptr++;
400         } else {
401             ret = MBEDTLS_ERR_ASN1_INVALID_DATA;
402             goto error;
403         }
404     }
405 
406     if (component2 > (UINT_MAX - (component1 * 40))) {
407         ret = MBEDTLS_ERR_ASN1_INVALID_DATA;
408         goto error;
409     }
410     ret = oid_subidentifier_encode_into(&out_ptr, out_bound,
411                                         (component1 * 40) + component2);
412     if (ret != 0) {
413         goto error;
414     }
415 
416     while (str_ptr < str_bound) {
417         ret = oid_parse_number(&val, &str_ptr, str_bound);
418         if (ret != 0) {
419             goto error;
420         }
421         if (str_ptr < str_bound) {
422             if (*str_ptr == '.') {
423                 str_ptr++;
424             } else {
425                 ret = MBEDTLS_ERR_ASN1_INVALID_DATA;
426                 goto error;
427             }
428         }
429 
430         ret = oid_subidentifier_encode_into(&out_ptr, out_bound, val);
431         if (ret != 0) {
432             goto error;
433         }
434     }
435 
436     encoded_len = (size_t) (out_ptr - oid->p);
437     resized_mem = mbedtls_calloc(encoded_len, 1);
438     if (resized_mem == NULL) {
439         ret = MBEDTLS_ERR_ASN1_ALLOC_FAILED;
440         goto error;
441     }
442     memcpy(resized_mem, oid->p, encoded_len);
443     mbedtls_free(oid->p);
444     oid->p = resized_mem;
445     oid->len = encoded_len;
446 
447     oid->tag = MBEDTLS_ASN1_OID;
448 
449     return 0;
450 
451 error:
452     mbedtls_free(oid->p);
453     oid->p = NULL;
454     oid->len = 0;
455     return ret;
456 }
457 
mbedtls_x509_string_to_names(mbedtls_asn1_named_data ** head,const char * name)458 int mbedtls_x509_string_to_names(mbedtls_asn1_named_data **head, const char *name)
459 {
460     int ret = MBEDTLS_ERR_X509_INVALID_NAME;
461     int parse_ret = 0;
462     const char *s = name, *c = s;
463     const char *end = s + strlen(s);
464     mbedtls_asn1_buf oid = { .p = NULL, .len = 0, .tag = MBEDTLS_ASN1_NULL };
465     const x509_attr_descriptor_t *attr_descr = NULL;
466     int in_attr_type = 1;
467     int tag;
468     int numericoid = 0;
469     unsigned char data[MBEDTLS_X509_MAX_DN_NAME_SIZE];
470     size_t data_len = 0;
471 
472     /* Ensure the output parameter is not already populated.
473      * (If it were, overwriting it would likely cause a memory leak.)
474      */
475     if (*head != NULL) {
476         return MBEDTLS_ERR_X509_BAD_INPUT_DATA;
477     }
478 
479     while (c <= end) {
480         if (in_attr_type && *c == '=') {
481             if ((attr_descr = x509_attr_descr_from_name(s, (size_t) (c - s))) == NULL) {
482                 if ((mbedtls_oid_from_numeric_string(&oid, s, (size_t) (c - s))) != 0) {
483                     return MBEDTLS_ERR_X509_INVALID_NAME;
484                 } else {
485                     numericoid = 1;
486                 }
487             } else {
488                 oid.len = strlen(attr_descr->oid);
489                 oid.p = mbedtls_calloc(1, oid.len);
490                 memcpy(oid.p, attr_descr->oid, oid.len);
491                 numericoid = 0;
492             }
493 
494             s = c + 1;
495             in_attr_type = 0;
496         }
497 
498         if (!in_attr_type && ((*c == ',' && *(c-1) != '\\') || c == end)) {
499             if (s == c) {
500                 mbedtls_free(oid.p);
501                 return MBEDTLS_ERR_X509_INVALID_NAME;
502             } else if (*s == '#') {
503                 /* We know that c >= s (loop invariant) and c != s (in this
504                  * else branch), hence c - s - 1 >= 0. */
505                 parse_ret = parse_attribute_value_hex_der_encoded(
506                     s + 1, (size_t) (c - s) - 1,
507                     data, sizeof(data), &data_len, &tag);
508                 if (parse_ret != 0) {
509                     mbedtls_free(oid.p);
510                     return parse_ret;
511                 }
512             } else {
513                 if (numericoid) {
514                     mbedtls_free(oid.p);
515                     return MBEDTLS_ERR_X509_INVALID_NAME;
516                 } else {
517                     if ((parse_ret =
518                              parse_attribute_value_string(s, (int) (c - s), data,
519                                                           &data_len)) != 0) {
520                         mbedtls_free(oid.p);
521                         return parse_ret;
522                     }
523                     tag = attr_descr->default_tag;
524                 }
525             }
526 
527             mbedtls_asn1_named_data *cur =
528                 mbedtls_asn1_store_named_data(head, (char *) oid.p, oid.len,
529                                               (unsigned char *) data,
530                                               data_len);
531             mbedtls_free(oid.p);
532             oid.p = NULL;
533             if (cur == NULL) {
534                 return MBEDTLS_ERR_X509_ALLOC_FAILED;
535             }
536 
537             // set tagType
538             cur->val.tag = tag;
539 
540             while (c < end && *(c + 1) == ' ') {
541                 c++;
542             }
543 
544             s = c + 1;
545             in_attr_type = 1;
546 
547             /* Successfully parsed one name, update ret to success */
548             ret = 0;
549         }
550         c++;
551     }
552     if (oid.p != NULL) {
553         mbedtls_free(oid.p);
554     }
555     return ret;
556 }
557 
558 /* The first byte of the value in the mbedtls_asn1_named_data structure is reserved
559  * to store the critical boolean for us
560  */
mbedtls_x509_set_extension(mbedtls_asn1_named_data ** head,const char * oid,size_t oid_len,int critical,const unsigned char * val,size_t val_len)561 int mbedtls_x509_set_extension(mbedtls_asn1_named_data **head, const char *oid, size_t oid_len,
562                                int critical, const unsigned char *val, size_t val_len)
563 {
564     mbedtls_asn1_named_data *cur;
565 
566     if (val_len > (SIZE_MAX  - 1)) {
567         return MBEDTLS_ERR_X509_BAD_INPUT_DATA;
568     }
569 
570     if ((cur = mbedtls_asn1_store_named_data(head, oid, oid_len,
571                                              NULL, val_len + 1)) == NULL) {
572         return MBEDTLS_ERR_X509_ALLOC_FAILED;
573     }
574 
575     cur->val.p[0] = critical;
576     memcpy(cur->val.p + 1, val, val_len);
577 
578     return 0;
579 }
580 
581 /*
582  *  RelativeDistinguishedName ::=
583  *    SET OF AttributeTypeAndValue
584  *
585  *  AttributeTypeAndValue ::= SEQUENCE {
586  *    type     AttributeType,
587  *    value    AttributeValue }
588  *
589  *  AttributeType ::= OBJECT IDENTIFIER
590  *
591  *  AttributeValue ::= ANY DEFINED BY AttributeType
592  */
x509_write_name(unsigned char ** p,unsigned char * start,mbedtls_asn1_named_data * cur_name)593 static int x509_write_name(unsigned char **p,
594                            unsigned char *start,
595                            mbedtls_asn1_named_data *cur_name)
596 {
597     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
598     size_t len = 0;
599     const char *oid             = (const char *) cur_name->oid.p;
600     size_t oid_len              = cur_name->oid.len;
601     const unsigned char *name   = cur_name->val.p;
602     size_t name_len             = cur_name->val.len;
603 
604     // Write correct string tag and value
605     MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_tagged_string(p, start,
606                                                                cur_name->val.tag,
607                                                                (const char *) name,
608                                                                name_len));
609     // Write OID
610     //
611     MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_oid(p, start, oid,
612                                                      oid_len));
613 
614     MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(p, start, len));
615     MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_tag(p, start,
616                                                      MBEDTLS_ASN1_CONSTRUCTED |
617                                                      MBEDTLS_ASN1_SEQUENCE));
618 
619     MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(p, start, len));
620     MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_tag(p, start,
621                                                      MBEDTLS_ASN1_CONSTRUCTED |
622                                                      MBEDTLS_ASN1_SET));
623 
624     return (int) len;
625 }
626 
mbedtls_x509_write_names(unsigned char ** p,unsigned char * start,mbedtls_asn1_named_data * first)627 int mbedtls_x509_write_names(unsigned char **p, unsigned char *start,
628                              mbedtls_asn1_named_data *first)
629 {
630     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
631     size_t len = 0;
632     mbedtls_asn1_named_data *cur = first;
633 
634     while (cur != NULL) {
635         MBEDTLS_ASN1_CHK_ADD(len, x509_write_name(p, start, cur));
636         cur = cur->next;
637     }
638 
639     MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(p, start, len));
640     MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_tag(p, start, MBEDTLS_ASN1_CONSTRUCTED |
641                                                      MBEDTLS_ASN1_SEQUENCE));
642 
643     return (int) len;
644 }
645 
mbedtls_x509_write_sig(unsigned char ** p,unsigned char * start,const char * oid,size_t oid_len,unsigned char * sig,size_t size,mbedtls_pk_sigalg_t pk_alg)646 int mbedtls_x509_write_sig(unsigned char **p, unsigned char *start,
647                            const char *oid, size_t oid_len,
648                            unsigned char *sig, size_t size,
649                            mbedtls_pk_sigalg_t pk_alg)
650 {
651     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
652     int write_null_par;
653     size_t len = 0;
654 
655     if (*p < start || (size_t) (*p - start) < size) {
656         return MBEDTLS_ERR_ASN1_BUF_TOO_SMALL;
657     }
658 
659     len = size;
660     (*p) -= len;
661     memcpy(*p, sig, len);
662 
663     if (*p - start < 1) {
664         return MBEDTLS_ERR_ASN1_BUF_TOO_SMALL;
665     }
666 
667     *--(*p) = 0;
668     len += 1;
669 
670     MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(p, start, len));
671     MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_tag(p, start, MBEDTLS_ASN1_BIT_STRING));
672 
673     // Write OID
674     //
675     if (pk_alg == MBEDTLS_PK_SIGALG_ECDSA) {
676         /*
677          * The AlgorithmIdentifier's parameters field must be absent for DSA/ECDSA signature
678          * algorithms, see https://www.rfc-editor.org/rfc/rfc5480#page-17 and
679          * https://www.rfc-editor.org/rfc/rfc5758#section-3.
680          */
681         write_null_par = 0;
682     } else {
683         write_null_par = 1;
684     }
685     MBEDTLS_ASN1_CHK_ADD(len,
686                          mbedtls_asn1_write_algorithm_identifier_ext(p, start, oid, oid_len,
687                                                                      0, write_null_par));
688 
689     return (int) len;
690 }
691 
x509_write_extension(unsigned char ** p,unsigned char * start,mbedtls_asn1_named_data * ext)692 static int x509_write_extension(unsigned char **p, unsigned char *start,
693                                 mbedtls_asn1_named_data *ext)
694 {
695     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
696     size_t len = 0;
697 
698     MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_raw_buffer(p, start, ext->val.p + 1,
699                                                             ext->val.len - 1));
700     MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(p, start, ext->val.len - 1));
701     MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_tag(p, start, MBEDTLS_ASN1_OCTET_STRING));
702 
703     if (ext->val.p[0] != 0) {
704         MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_bool(p, start, 1));
705     }
706 
707     MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_raw_buffer(p, start, ext->oid.p,
708                                                             ext->oid.len));
709     MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(p, start, ext->oid.len));
710     MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_tag(p, start, MBEDTLS_ASN1_OID));
711 
712     MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(p, start, len));
713     MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_tag(p, start, MBEDTLS_ASN1_CONSTRUCTED |
714                                                      MBEDTLS_ASN1_SEQUENCE));
715 
716     return (int) len;
717 }
718 
719 /*
720  * Extension  ::=  SEQUENCE  {
721  *     extnID      OBJECT IDENTIFIER,
722  *     critical    BOOLEAN DEFAULT FALSE,
723  *     extnValue   OCTET STRING
724  *                 -- contains the DER encoding of an ASN.1 value
725  *                 -- corresponding to the extension type identified
726  *                 -- by extnID
727  *     }
728  */
mbedtls_x509_write_extensions(unsigned char ** p,unsigned char * start,mbedtls_asn1_named_data * first)729 int mbedtls_x509_write_extensions(unsigned char **p, unsigned char *start,
730                                   mbedtls_asn1_named_data *first)
731 {
732     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
733     size_t len = 0;
734     mbedtls_asn1_named_data *cur_ext = first;
735 
736     while (cur_ext != NULL) {
737         MBEDTLS_ASN1_CHK_ADD(len, x509_write_extension(p, start, cur_ext));
738         cur_ext = cur_ext->next;
739     }
740 
741     return (int) len;
742 }
743 
744 #endif /* MBEDTLS_X509_CREATE_C */
745