xref: /aosp_15_r20/external/boringssl/src/crypto/x509/x_x509.c (revision 8fb009dc861624b67b6cdb62ea21f0f22d0c584b)
1 /* Copyright (C) 1995-1998 Eric Young ([email protected])
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young ([email protected]).
6  * The implementation was written so as to conform with Netscapes SSL.
7  *
8  * This library is free for commercial and non-commercial use as long as
9  * the following conditions are aheared to.  The following conditions
10  * apply to all code found in this distribution, be it the RC4, RSA,
11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12  * included with this distribution is covered by the same copyright terms
13  * except that the holder is Tim Hudson ([email protected]).
14  *
15  * Copyright remains Eric Young's, and as such any Copyright notices in
16  * the code are not to be removed.
17  * If this package is used in a product, Eric Young should be given attribution
18  * as the author of the parts of the library used.
19  * This can be in the form of a textual message at program startup or
20  * in documentation (online or textual) provided with the package.
21  *
22  * Redistribution and use in source and binary forms, with or without
23  * modification, are permitted provided that the following conditions
24  * are met:
25  * 1. Redistributions of source code must retain the copyright
26  *    notice, this list of conditions and the following disclaimer.
27  * 2. Redistributions in binary form must reproduce the above copyright
28  *    notice, this list of conditions and the following disclaimer in the
29  *    documentation and/or other materials provided with the distribution.
30  * 3. All advertising materials mentioning features or use of this software
31  *    must display the following acknowledgement:
32  *    "This product includes cryptographic software written by
33  *     Eric Young ([email protected])"
34  *    The word 'cryptographic' can be left out if the rouines from the library
35  *    being used are not cryptographic related :-).
36  * 4. If you include any Windows specific code (or a derivative thereof) from
37  *    the apps directory (application code) you must include an acknowledgement:
38  *    "This product includes software written by Tim Hudson ([email protected])"
39  *
40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50  * SUCH DAMAGE.
51  *
52  * The licence and distribution terms for any publically available version or
53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
54  * copied and put under another distribution licence
55  * [including the GNU Public Licence.] */
56 
57 #include <assert.h>
58 #include <limits.h>
59 #include <stdio.h>
60 
61 #include <openssl/asn1t.h>
62 #include <openssl/evp.h>
63 #include <openssl/mem.h>
64 #include <openssl/obj.h>
65 #include <openssl/pool.h>
66 #include <openssl/thread.h>
67 #include <openssl/x509.h>
68 
69 #include "../asn1/internal.h"
70 #include "../bytestring/internal.h"
71 #include "../internal.h"
72 #include "internal.h"
73 
74 static CRYPTO_EX_DATA_CLASS g_ex_data_class = CRYPTO_EX_DATA_CLASS_INIT;
75 
76 ASN1_SEQUENCE_enc(X509_CINF, enc, 0) = {
77     ASN1_EXP_OPT(X509_CINF, version, ASN1_INTEGER, 0),
78     ASN1_SIMPLE(X509_CINF, serialNumber, ASN1_INTEGER),
79     ASN1_SIMPLE(X509_CINF, signature, X509_ALGOR),
80     ASN1_SIMPLE(X509_CINF, issuer, X509_NAME),
81     ASN1_SIMPLE(X509_CINF, validity, X509_VAL),
82     ASN1_SIMPLE(X509_CINF, subject, X509_NAME),
83     ASN1_SIMPLE(X509_CINF, key, X509_PUBKEY),
84     ASN1_IMP_OPT(X509_CINF, issuerUID, ASN1_BIT_STRING, 1),
85     ASN1_IMP_OPT(X509_CINF, subjectUID, ASN1_BIT_STRING, 2),
86     ASN1_EXP_SEQUENCE_OF_OPT(X509_CINF, extensions, X509_EXTENSION, 3),
87 } ASN1_SEQUENCE_END_enc(X509_CINF, X509_CINF)
88 
89 IMPLEMENT_ASN1_FUNCTIONS(X509_CINF)
90 
91 // x509_new_null returns a new |X509| object where the |cert_info|, |sig_alg|,
92 // and |signature| fields are not yet filled in.
93 static X509 *x509_new_null(void) {
94   X509 *ret = OPENSSL_zalloc(sizeof(X509));
95   if (ret == NULL) {
96     return NULL;
97   }
98 
99   ret->references = 1;
100   ret->ex_pathlen = -1;
101   CRYPTO_new_ex_data(&ret->ex_data);
102   CRYPTO_MUTEX_init(&ret->lock);
103   return ret;
104 }
105 
X509_new(void)106 X509 *X509_new(void) {
107   X509 *ret = x509_new_null();
108   if (ret == NULL) {
109     return NULL;
110   }
111 
112   ret->cert_info = X509_CINF_new();
113   ret->sig_alg = X509_ALGOR_new();
114   ret->signature = ASN1_BIT_STRING_new();
115   if (ret->cert_info == NULL || ret->sig_alg == NULL ||
116       ret->signature == NULL) {
117     X509_free(ret);
118     return NULL;
119   }
120 
121   return ret;
122 }
123 
X509_free(X509 * x509)124 void X509_free(X509 *x509) {
125   if (x509 == NULL || !CRYPTO_refcount_dec_and_test_zero(&x509->references)) {
126     return;
127   }
128 
129   CRYPTO_free_ex_data(&g_ex_data_class, x509, &x509->ex_data);
130 
131   X509_CINF_free(x509->cert_info);
132   X509_ALGOR_free(x509->sig_alg);
133   ASN1_BIT_STRING_free(x509->signature);
134   ASN1_OCTET_STRING_free(x509->skid);
135   AUTHORITY_KEYID_free(x509->akid);
136   CRL_DIST_POINTS_free(x509->crldp);
137   GENERAL_NAMES_free(x509->altname);
138   NAME_CONSTRAINTS_free(x509->nc);
139   X509_CERT_AUX_free(x509->aux);
140   CRYPTO_MUTEX_cleanup(&x509->lock);
141 
142   OPENSSL_free(x509);
143 }
144 
x509_parse(CBS * cbs,CRYPTO_BUFFER * buf)145 static X509 *x509_parse(CBS *cbs, CRYPTO_BUFFER *buf) {
146   CBS cert, tbs, sigalg, sig;
147   if (!CBS_get_asn1(cbs, &cert, CBS_ASN1_SEQUENCE) ||
148       // Bound the length to comfortably fit in an int. Lengths in this
149       // module often omit overflow checks.
150       CBS_len(&cert) > INT_MAX / 2 ||
151       !CBS_get_asn1_element(&cert, &tbs, CBS_ASN1_SEQUENCE) ||
152       !CBS_get_asn1_element(&cert, &sigalg, CBS_ASN1_SEQUENCE)) {
153     OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR);
154     return NULL;
155   }
156 
157   // For just the signature field, we accept non-minimal BER lengths, though not
158   // indefinite-length encoding. See b/18228011.
159   //
160   // TODO(crbug.com/boringssl/354): Switch the affected callers to convert the
161   // certificate before parsing and then remove this workaround.
162   CBS_ASN1_TAG tag;
163   size_t header_len;
164   int indefinite;
165   if (!CBS_get_any_ber_asn1_element(&cert, &sig, &tag, &header_len,
166                                     /*out_ber_found=*/NULL,
167                                     &indefinite) ||
168       tag != CBS_ASN1_BITSTRING || indefinite ||  //
169       !CBS_skip(&sig, header_len) ||              //
170       CBS_len(&cert) != 0) {
171     OPENSSL_PUT_ERROR(ASN1, ASN1_R_DECODE_ERROR);
172     return NULL;
173   }
174 
175   X509 *ret = x509_new_null();
176   if (ret == NULL) {
177     return NULL;
178   }
179 
180   // TODO(crbug.com/boringssl/443): When the rest of the library is decoupled
181   // from the tasn_*.c implementation, replace this with |CBS|-based functions.
182   const uint8_t *inp = CBS_data(&tbs);
183   if (ASN1_item_ex_d2i((ASN1_VALUE **)&ret->cert_info, &inp, CBS_len(&tbs),
184                        ASN1_ITEM_rptr(X509_CINF), /*tag=*/-1,
185                        /*aclass=*/0, /*opt=*/0, buf) <= 0 ||
186       inp != CBS_data(&tbs) + CBS_len(&tbs)) {
187     goto err;
188   }
189 
190   inp = CBS_data(&sigalg);
191   ret->sig_alg = d2i_X509_ALGOR(NULL, &inp, CBS_len(&sigalg));
192   if (ret->sig_alg == NULL || inp != CBS_data(&sigalg) + CBS_len(&sigalg)) {
193     goto err;
194   }
195 
196   inp = CBS_data(&sig);
197   ret->signature = c2i_ASN1_BIT_STRING(NULL, &inp, CBS_len(&sig));
198   if (ret->signature == NULL || inp != CBS_data(&sig) + CBS_len(&sig)) {
199     goto err;
200   }
201 
202   // The version must be one of v1(0), v2(1), or v3(2).
203   long version = X509_VERSION_1;
204   if (ret->cert_info->version != NULL) {
205     version = ASN1_INTEGER_get(ret->cert_info->version);
206     // TODO(https://crbug.com/boringssl/364): |X509_VERSION_1| should
207     // also be rejected here. This means an explicitly-encoded X.509v1
208     // version. v1 is DEFAULT, so DER requires it be omitted.
209     if (version < X509_VERSION_1 || version > X509_VERSION_3) {
210       OPENSSL_PUT_ERROR(X509, X509_R_INVALID_VERSION);
211       goto err;
212     }
213   }
214 
215   // Per RFC 5280, section 4.1.2.8, these fields require v2 or v3.
216   if (version == X509_VERSION_1 && (ret->cert_info->issuerUID != NULL ||
217                                     ret->cert_info->subjectUID != NULL)) {
218     OPENSSL_PUT_ERROR(X509, X509_R_INVALID_FIELD_FOR_VERSION);
219     goto err;
220   }
221 
222   // Per RFC 5280, section 4.1.2.9, extensions require v3.
223   if (version != X509_VERSION_3 && ret->cert_info->extensions != NULL) {
224     OPENSSL_PUT_ERROR(X509, X509_R_INVALID_FIELD_FOR_VERSION);
225     goto err;
226   }
227 
228   return ret;
229 
230 err:
231   X509_free(ret);
232   return NULL;
233 }
234 
d2i_X509(X509 ** out,const uint8_t ** inp,long len)235 X509 *d2i_X509(X509 **out, const uint8_t **inp, long len) {
236   X509 *ret = NULL;
237   if (len < 0) {
238     OPENSSL_PUT_ERROR(ASN1, ASN1_R_BUFFER_TOO_SMALL);
239     goto err;
240   }
241 
242   CBS cbs;
243   CBS_init(&cbs, *inp, (size_t)len);
244   ret = x509_parse(&cbs, NULL);
245   if (ret == NULL) {
246     goto err;
247   }
248 
249   *inp = CBS_data(&cbs);
250 
251 err:
252   if (out != NULL) {
253     X509_free(*out);
254     *out = ret;
255   }
256   return ret;
257 }
258 
i2d_X509(X509 * x509,uint8_t ** outp)259 int i2d_X509(X509 *x509, uint8_t **outp) {
260   if (x509 == NULL) {
261     OPENSSL_PUT_ERROR(ASN1, ASN1_R_MISSING_VALUE);
262     return -1;
263   }
264 
265   CBB cbb, cert;
266   if (!CBB_init(&cbb, 64) ||  //
267       !CBB_add_asn1(&cbb, &cert, CBS_ASN1_SEQUENCE)) {
268     goto err;
269   }
270 
271   // TODO(crbug.com/boringssl/443): When the rest of the library is decoupled
272   // from the tasn_*.c implementation, replace this with |CBS|-based functions.
273   uint8_t *out;
274   int len = i2d_X509_CINF(x509->cert_info, NULL);
275   if (len < 0 ||  //
276       !CBB_add_space(&cert, &out, (size_t)len) ||
277       i2d_X509_CINF(x509->cert_info, &out) != len) {
278     goto err;
279   }
280 
281   len = i2d_X509_ALGOR(x509->sig_alg, NULL);
282   if (len < 0 ||  //
283       !CBB_add_space(&cert, &out, (size_t)len) ||
284       i2d_X509_ALGOR(x509->sig_alg, &out) != len) {
285     goto err;
286   }
287 
288   len = i2d_ASN1_BIT_STRING(x509->signature, NULL);
289   if (len < 0 ||  //
290       !CBB_add_space(&cert, &out, (size_t)len) ||
291       i2d_ASN1_BIT_STRING(x509->signature, &out) != len) {
292     goto err;
293   }
294 
295   return CBB_finish_i2d(&cbb, outp);
296 
297 err:
298   CBB_cleanup(&cbb);
299   return -1;
300 }
301 
x509_new_cb(ASN1_VALUE ** pval,const ASN1_ITEM * it)302 static int x509_new_cb(ASN1_VALUE **pval, const ASN1_ITEM *it) {
303   *pval = (ASN1_VALUE *)X509_new();
304   return *pval != NULL;
305 }
306 
x509_free_cb(ASN1_VALUE ** pval,const ASN1_ITEM * it)307 static void x509_free_cb(ASN1_VALUE **pval, const ASN1_ITEM *it) {
308   X509_free((X509 *)*pval);
309   *pval = NULL;
310 }
311 
x509_d2i_cb(ASN1_VALUE ** pval,const unsigned char ** in,long len,const ASN1_ITEM * it,int opt,ASN1_TLC * ctx)312 static int x509_d2i_cb(ASN1_VALUE **pval, const unsigned char **in, long len,
313                        const ASN1_ITEM *it, int opt, ASN1_TLC *ctx) {
314   if (len < 0) {
315     OPENSSL_PUT_ERROR(ASN1, ASN1_R_BUFFER_TOO_SMALL);
316     return 0;
317   }
318 
319   CBS cbs;
320   CBS_init(&cbs, *in, len);
321   if (opt && !CBS_peek_asn1_tag(&cbs, CBS_ASN1_SEQUENCE)) {
322     return -1;
323   }
324 
325   X509 *ret = x509_parse(&cbs, NULL);
326   if (ret == NULL) {
327     return 0;
328   }
329 
330   *in = CBS_data(&cbs);
331   X509_free((X509 *)*pval);
332   *pval = (ASN1_VALUE *)ret;
333   return 1;
334 }
335 
x509_i2d_cb(ASN1_VALUE ** pval,unsigned char ** out,const ASN1_ITEM * it)336 static int x509_i2d_cb(ASN1_VALUE **pval, unsigned char **out,
337                        const ASN1_ITEM *it) {
338   return i2d_X509((X509 *)*pval, out);
339 }
340 
341 static const ASN1_EXTERN_FUNCS x509_extern_funcs = {
342     x509_new_cb,
343     x509_free_cb,
344     x509_d2i_cb,
345     x509_i2d_cb,
346 };
347 
IMPLEMENT_EXTERN_ASN1(X509,V_ASN1_SEQUENCE,x509_extern_funcs)348 IMPLEMENT_EXTERN_ASN1(X509, V_ASN1_SEQUENCE, x509_extern_funcs)
349 
350 X509 *X509_dup(X509 *x509) {
351   uint8_t *der = NULL;
352   int len = i2d_X509(x509, &der);
353   if (len < 0) {
354     return NULL;
355   }
356 
357   const uint8_t *inp = der;
358   X509 *ret = d2i_X509(NULL, &inp, len);
359   OPENSSL_free(der);
360   return ret;
361 }
362 
X509_parse_from_buffer(CRYPTO_BUFFER * buf)363 X509 *X509_parse_from_buffer(CRYPTO_BUFFER *buf) {
364   CBS cbs;
365   CBS_init(&cbs, CRYPTO_BUFFER_data(buf), CRYPTO_BUFFER_len(buf));
366   X509 *ret = x509_parse(&cbs, buf);
367   if (ret == NULL || CBS_len(&cbs) != 0) {
368     X509_free(ret);
369     return NULL;
370   }
371 
372   return ret;
373 }
374 
X509_up_ref(X509 * x)375 int X509_up_ref(X509 *x) {
376   CRYPTO_refcount_inc(&x->references);
377   return 1;
378 }
379 
X509_get_ex_new_index(long argl,void * argp,CRYPTO_EX_unused * unused,CRYPTO_EX_dup * dup_unused,CRYPTO_EX_free * free_func)380 int X509_get_ex_new_index(long argl, void *argp, CRYPTO_EX_unused *unused,
381                           CRYPTO_EX_dup *dup_unused,
382                           CRYPTO_EX_free *free_func) {
383   return CRYPTO_get_ex_new_index_ex(&g_ex_data_class, argl, argp, free_func);
384 }
385 
X509_set_ex_data(X509 * r,int idx,void * arg)386 int X509_set_ex_data(X509 *r, int idx, void *arg) {
387   return (CRYPTO_set_ex_data(&r->ex_data, idx, arg));
388 }
389 
X509_get_ex_data(X509 * r,int idx)390 void *X509_get_ex_data(X509 *r, int idx) {
391   return (CRYPTO_get_ex_data(&r->ex_data, idx));
392 }
393 
394 // X509_AUX ASN1 routines. X509_AUX is the name given to a certificate with
395 // extra info tagged on the end. Since these functions set how a certificate
396 // is trusted they should only be used when the certificate comes from a
397 // reliable source such as local storage.
398 
d2i_X509_AUX(X509 ** a,const unsigned char ** pp,long length)399 X509 *d2i_X509_AUX(X509 **a, const unsigned char **pp, long length) {
400   const unsigned char *q = *pp;
401   X509 *ret;
402   int freeret = 0;
403 
404   if (!a || *a == NULL) {
405     freeret = 1;
406   }
407   ret = d2i_X509(a, &q, length);
408   // If certificate unreadable then forget it
409   if (!ret) {
410     return NULL;
411   }
412   // update length
413   length -= q - *pp;
414   // Parse auxiliary information if there is any.
415   if (length > 0 && !d2i_X509_CERT_AUX(&ret->aux, &q, length)) {
416     goto err;
417   }
418   *pp = q;
419   return ret;
420 err:
421   if (freeret) {
422     X509_free(ret);
423     if (a) {
424       *a = NULL;
425     }
426   }
427   return NULL;
428 }
429 
430 // Serialize trusted certificate to *pp or just return the required buffer
431 // length if pp == NULL.  We ultimately want to avoid modifying *pp in the
432 // error path, but that depends on similar hygiene in lower-level functions.
433 // Here we avoid compounding the problem.
i2d_x509_aux_internal(X509 * a,unsigned char ** pp)434 static int i2d_x509_aux_internal(X509 *a, unsigned char **pp) {
435   int length, tmplen;
436   unsigned char *start = pp != NULL ? *pp : NULL;
437 
438   assert(pp == NULL || *pp != NULL);
439 
440   // This might perturb *pp on error, but fixing that belongs in i2d_X509()
441   // not here.  It should be that if a == NULL length is zero, but we check
442   // both just in case.
443   length = i2d_X509(a, pp);
444   if (length <= 0 || a == NULL) {
445     return length;
446   }
447 
448   if (a->aux != NULL) {
449     tmplen = i2d_X509_CERT_AUX(a->aux, pp);
450     if (tmplen < 0) {
451       if (start != NULL) {
452         *pp = start;
453       }
454       return tmplen;
455     }
456     length += tmplen;
457   }
458 
459   return length;
460 }
461 
462 // Serialize trusted certificate to *pp, or just return the required buffer
463 // length if pp == NULL.
464 //
465 // When pp is not NULL, but *pp == NULL, we allocate the buffer, but since
466 // we're writing two ASN.1 objects back to back, we can't have i2d_X509() do
467 // the allocation, nor can we allow i2d_X509_CERT_AUX() to increment the
468 // allocated buffer.
i2d_X509_AUX(X509 * a,unsigned char ** pp)469 int i2d_X509_AUX(X509 *a, unsigned char **pp) {
470   int length;
471   unsigned char *tmp;
472 
473   // Buffer provided by caller
474   if (pp == NULL || *pp != NULL) {
475     return i2d_x509_aux_internal(a, pp);
476   }
477 
478   // Obtain the combined length
479   if ((length = i2d_x509_aux_internal(a, NULL)) <= 0) {
480     return length;
481   }
482 
483   // Allocate requisite combined storage
484   *pp = tmp = OPENSSL_malloc(length);
485   if (tmp == NULL) {
486     return -1;  // Push error onto error stack?
487   }
488 
489   // Encode, but keep *pp at the originally malloced pointer
490   length = i2d_x509_aux_internal(a, &tmp);
491   if (length <= 0) {
492     OPENSSL_free(*pp);
493     *pp = NULL;
494   }
495   return length;
496 }
497 
i2d_re_X509_tbs(X509 * x509,unsigned char ** outp)498 int i2d_re_X509_tbs(X509 *x509, unsigned char **outp) {
499   asn1_encoding_clear(&x509->cert_info->enc);
500   return i2d_X509_CINF(x509->cert_info, outp);
501 }
502 
i2d_X509_tbs(X509 * x509,unsigned char ** outp)503 int i2d_X509_tbs(X509 *x509, unsigned char **outp) {
504   return i2d_X509_CINF(x509->cert_info, outp);
505 }
506 
X509_set1_signature_algo(X509 * x509,const X509_ALGOR * algo)507 int X509_set1_signature_algo(X509 *x509, const X509_ALGOR *algo) {
508   X509_ALGOR *copy1 = X509_ALGOR_dup(algo);
509   X509_ALGOR *copy2 = X509_ALGOR_dup(algo);
510   if (copy1 == NULL || copy2 == NULL) {
511     X509_ALGOR_free(copy1);
512     X509_ALGOR_free(copy2);
513     return 0;
514   }
515 
516   X509_ALGOR_free(x509->sig_alg);
517   x509->sig_alg = copy1;
518   X509_ALGOR_free(x509->cert_info->signature);
519   x509->cert_info->signature = copy2;
520   return 1;
521 }
522 
X509_set1_signature_value(X509 * x509,const uint8_t * sig,size_t sig_len)523 int X509_set1_signature_value(X509 *x509, const uint8_t *sig, size_t sig_len) {
524   if (!ASN1_STRING_set(x509->signature, sig, sig_len)) {
525     return 0;
526   }
527   x509->signature->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07);
528   x509->signature->flags |= ASN1_STRING_FLAG_BITS_LEFT;
529   return 1;
530 }
531 
X509_get0_signature(const ASN1_BIT_STRING ** psig,const X509_ALGOR ** palg,const X509 * x)532 void X509_get0_signature(const ASN1_BIT_STRING **psig, const X509_ALGOR **palg,
533                          const X509 *x) {
534   if (psig) {
535     *psig = x->signature;
536   }
537   if (palg) {
538     *palg = x->sig_alg;
539   }
540 }
541 
X509_get_signature_nid(const X509 * x)542 int X509_get_signature_nid(const X509 *x) {
543   return OBJ_obj2nid(x->sig_alg->algorithm);
544 }
545