a284bf72cabc432f51623e5702dc76a14e7d73ad
[openssl.git] / crypto / x509 / x509_r2x.c
1 /*
2  * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <stdio.h>
11 #include "internal/cryptlib.h"
12 #include <openssl/bn.h>
13 #include <openssl/evp.h>
14 #include <openssl/asn1.h>
15 #include <openssl/x509.h>
16 #include "crypto/x509.h"
17 #include <openssl/objects.h>
18 #include <openssl/buffer.h>
19
20 DEFINE_STACK_OF(X509_ATTRIBUTE)
21
22 X509 *X509_REQ_to_X509(X509_REQ *r, int days, EVP_PKEY *pkey)
23 {
24     X509 *ret = NULL;
25     X509_CINF *xi = NULL;
26     const X509_NAME *xn;
27     EVP_PKEY *pubkey = NULL;
28
29     if ((ret = X509_new()) == NULL) {
30         X509err(X509_F_X509_REQ_TO_X509, ERR_R_MALLOC_FAILURE);
31         return NULL;
32     }
33
34     /* duplicate the request */
35     xi = &ret->cert_info;
36
37     if (sk_X509_ATTRIBUTE_num(r->req_info.attributes) != 0) {
38         if ((xi->version = ASN1_INTEGER_new()) == NULL)
39             goto err;
40         if (!ASN1_INTEGER_set(xi->version, 2))
41             goto err;
42 /*-     xi->extensions=ri->attributes; <- bad, should not ever be done
43         ri->attributes=NULL; */
44     }
45
46     xn = X509_REQ_get_subject_name(r);
47     if (X509_set_subject_name(ret, xn) == 0)
48         goto err;
49     if (X509_set_issuer_name(ret, xn) == 0)
50         goto err;
51
52     if (X509_gmtime_adj(xi->validity.notBefore, 0) == NULL)
53         goto err;
54     if (X509_gmtime_adj(xi->validity.notAfter, (long)60 * 60 * 24 * days) ==
55         NULL)
56         goto err;
57
58     pubkey = X509_REQ_get0_pubkey(r);
59     if (pubkey == NULL || !X509_set_pubkey(ret, pubkey))
60         goto err;
61
62     if (!X509_sign(ret, pkey, EVP_md5()))
63         goto err;
64     return ret;
65
66  err:
67     X509_free(ret);
68     return NULL;
69 }