blob: e74fe9d342e6e5f67d8d0e313ad98224fb53e9df [file] [log] [blame]
Martijn Coenen95194842020-09-24 16:56:46 +02001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <android-base/logging.h>
18#include <android-base/result.h>
19
20#include <openssl/bn.h>
21#include <openssl/crypto.h>
22#include <openssl/pkcs7.h>
23#include <openssl/rsa.h>
24#include <openssl/x509v3.h>
25
26#include <fcntl.h>
27#include <vector>
Martijn Coenenba1c9dc2021-02-04 13:18:29 +010028
29#include "KeyConstants.h"
30
Martijn Coenen95194842020-09-24 16:56:46 +020031const char kBasicConstraints[] = "CA:TRUE";
32const char kKeyUsage[] = "critical,keyCertSign,cRLSign,digitalSignature";
33const char kSubjectKeyIdentifier[] = "hash";
34constexpr int kCertLifetimeSeconds = 10 * 365 * 24 * 60 * 60;
35
36using android::base::Result;
37// using android::base::ErrnoError;
38using android::base::Error;
39
40static bool add_ext(X509* cert, int nid, const char* value) {
41 size_t len = strlen(value) + 1;
42 std::vector<char> mutableValue(value, value + len);
43 X509V3_CTX context;
44
45 X509V3_set_ctx_nodb(&context);
46
47 X509V3_set_ctx(&context, cert, cert, nullptr, nullptr, 0);
48 X509_EXTENSION* ex = X509V3_EXT_nconf_nid(nullptr, &context, nid, mutableValue.data());
49 if (!ex) {
50 return false;
51 }
52
53 X509_add_ext(cert, ex, -1);
54 X509_EXTENSION_free(ex);
55 return true;
56}
57
58Result<void> createSelfSignedCertificate(
59 const std::vector<uint8_t>& publicKey,
60 const std::function<Result<std::string>(const std::string&)>& signFunction,
61 const std::string& path) {
62 bssl::UniquePtr<X509> x509(X509_new());
63 if (!x509) {
64 return Error() << "Unable to allocate x509 container";
65 }
66 X509_set_version(x509.get(), 2);
67
68 ASN1_INTEGER_set(X509_get_serialNumber(x509.get()), 1);
69 X509_gmtime_adj(X509_get_notBefore(x509.get()), 0);
70 X509_gmtime_adj(X509_get_notAfter(x509.get()), kCertLifetimeSeconds);
71
Martijn Coenenba1c9dc2021-02-04 13:18:29 +010072 // "publicKey" corresponds to the raw public key bytes - need to create
73 // a new RSA key with the correct exponent.
74 RSA* rsaPubkey = RSA_new();
75 rsaPubkey->n = BN_new();
76 rsaPubkey->e = BN_new();
77
78 BN_bin2bn(publicKey.data(), publicKey.size(), rsaPubkey->n);
79 BN_set_word(rsaPubkey->e, kRsaKeyExponent);
80
81 EVP_PKEY* public_key = EVP_PKEY_new();
82 EVP_PKEY_assign_RSA(public_key, rsaPubkey);
83
Martijn Coenen95194842020-09-24 16:56:46 +020084 if (!X509_set_pubkey(x509.get(), public_key)) {
85 return Error() << "Unable to set x509 public key";
86 }
87
88 X509_NAME* name = X509_get_subject_name(x509.get());
89 if (!name) {
90 return Error() << "Unable to get x509 subject name";
91 }
92 X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC,
93 reinterpret_cast<const unsigned char*>("US"), -1, -1, 0);
94 X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC,
95 reinterpret_cast<const unsigned char*>("Android"), -1, -1, 0);
96 X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
97 reinterpret_cast<const unsigned char*>("ODS"), -1, -1, 0);
98 if (!X509_set_issuer_name(x509.get(), name)) {
99 return Error() << "Unable to set x509 issuer name";
100 }
101
102 add_ext(x509.get(), NID_basic_constraints, kBasicConstraints);
103 add_ext(x509.get(), NID_key_usage, kKeyUsage);
104 add_ext(x509.get(), NID_subject_key_identifier, kSubjectKeyIdentifier);
105 add_ext(x509.get(), NID_authority_key_identifier, "keyid:always");
106
107 X509_ALGOR_set0(x509->cert_info->signature, OBJ_nid2obj(NID_sha256WithRSAEncryption),
108 V_ASN1_NULL, NULL);
109 X509_ALGOR_set0(x509->sig_alg, OBJ_nid2obj(NID_sha256WithRSAEncryption), V_ASN1_NULL, NULL);
110
111 // Get the data to be signed
112 char* to_be_signed_buf(nullptr);
113 size_t to_be_signed_length = i2d_re_X509_tbs(x509.get(), (unsigned char**)&to_be_signed_buf);
114
115 auto signed_data = signFunction(std::string(to_be_signed_buf, to_be_signed_length));
116 if (!signed_data.ok()) {
117 return signed_data.error();
118 }
119
120 // This is the only part that doesn't use boringssl default functions - we manually copy in the
121 // signature that was provided to us.
122 x509->signature->data = (unsigned char*)OPENSSL_malloc(signed_data->size());
123 memcpy(x509->signature->data, signed_data->c_str(), signed_data->size());
124 x509->signature->length = signed_data->size();
125
126 x509->signature->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07);
127 x509->signature->flags |= ASN1_STRING_FLAG_BITS_LEFT;
128 auto f = fopen(path.c_str(), "wb");
129 // TODO error checking
130 i2d_X509_fp(f, x509.get());
131 fclose(f);
132
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100133 EVP_PKEY_free(public_key);
Martijn Coenen95194842020-09-24 16:56:46 +0200134 return {};
135}
136
137Result<std::vector<uint8_t>> extractPublicKey(EVP_PKEY* pkey) {
138 if (pkey == nullptr) {
139 return Error() << "Failed to extract public key from x509 cert";
140 }
141
142 if (EVP_PKEY_type(pkey->type) != EVP_PKEY_RSA) {
143 return Error() << "The public key is not an RSA key";
144 }
145
146 RSA* rsa = EVP_PKEY_get1_RSA(pkey);
147 auto num_bytes = BN_num_bytes(rsa->n);
148 std::vector<uint8_t> pubKey(num_bytes);
149 int res = BN_bn2bin(rsa->n, pubKey.data());
150 RSA_free(rsa);
151
152 if (!res) {
153 return Error() << "Failed to convert public key to bytes";
154 }
155
156 return pubKey;
157}
158
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100159Result<std::vector<uint8_t>>
160extractPublicKeyFromSubjectPublicKeyInfo(const std::vector<uint8_t>& keyData) {
Martijn Coenen95194842020-09-24 16:56:46 +0200161 auto keyDataBytes = keyData.data();
162 EVP_PKEY* public_key = d2i_PUBKEY(nullptr, &keyDataBytes, keyData.size());
163
164 return extractPublicKey(public_key);
165}
166
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100167Result<std::vector<uint8_t>> extractPublicKeyFromX509(const std::vector<uint8_t>& keyData) {
168 auto keyDataBytes = keyData.data();
169 bssl::UniquePtr<X509> decoded_cert(d2i_X509(nullptr, &keyDataBytes, keyData.size()));
170 if (decoded_cert.get() == nullptr) {
171 return Error() << "Failed to decode X509 certificate.";
172 }
173 bssl::UniquePtr<EVP_PKEY> decoded_pkey(X509_get_pubkey(decoded_cert.get()));
174
175 return extractPublicKey(decoded_pkey.get());
176}
177
Martijn Coenen95194842020-09-24 16:56:46 +0200178Result<std::vector<uint8_t>> extractPublicKeyFromX509(const std::string& path) {
179 X509* cert;
180 auto f = fopen(path.c_str(), "r");
181 if (!d2i_X509_fp(f, &cert)) {
182 return Error() << "Unable to decode x509 cert at " << path;
183 }
184
185 fclose(f);
186 return extractPublicKey(X509_get_pubkey(cert));
187}
188
189Result<std::vector<uint8_t>> createPkcs7(const std::vector<uint8_t>& signed_digest) {
190 CBB out, outer_seq, wrapped_seq, seq, digest_algos_set, digest_algo, null;
191 CBB content_info, issuer_and_serial, signer_infos, signer_info, sign_algo, signature;
192 uint8_t *pkcs7_data, *name_der;
193 size_t pkcs7_data_len, name_der_len;
194 BIGNUM* serial = BN_new();
195 int sig_nid = NID_rsaEncryption;
196
197 X509_NAME* name = X509_NAME_new();
198 if (!name) {
199 return Error() << "Unable to get x509 subject name";
200 }
201 X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC,
202 reinterpret_cast<const unsigned char*>("US"), -1, -1, 0);
203 X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC,
204 reinterpret_cast<const unsigned char*>("Android"), -1, -1, 0);
205 X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
206 reinterpret_cast<const unsigned char*>("ODS"), -1, -1, 0);
207
208 BN_set_word(serial, 1);
209 name_der_len = i2d_X509_NAME(name, &name_der);
210 CBB_init(&out, 1024);
211
212 if (!CBB_add_asn1(&out, &outer_seq, CBS_ASN1_SEQUENCE) ||
213 !OBJ_nid2cbb(&outer_seq, NID_pkcs7_signed) ||
214 !CBB_add_asn1(&outer_seq, &wrapped_seq,
215 CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0) ||
216 // See https://tools.ietf.org/html/rfc2315#section-9.1
217 !CBB_add_asn1(&wrapped_seq, &seq, CBS_ASN1_SEQUENCE) ||
218 !CBB_add_asn1_uint64(&seq, 1 /* version */) ||
219 !CBB_add_asn1(&seq, &digest_algos_set, CBS_ASN1_SET) ||
220 !CBB_add_asn1(&digest_algos_set, &digest_algo, CBS_ASN1_SEQUENCE) ||
221 !OBJ_nid2cbb(&digest_algo, NID_sha256) ||
222 !CBB_add_asn1(&digest_algo, &null, CBS_ASN1_NULL) ||
223 !CBB_add_asn1(&seq, &content_info, CBS_ASN1_SEQUENCE) ||
224 !OBJ_nid2cbb(&content_info, NID_pkcs7_data) ||
225 !CBB_add_asn1(&seq, &signer_infos, CBS_ASN1_SET) ||
226 !CBB_add_asn1(&signer_infos, &signer_info, CBS_ASN1_SEQUENCE) ||
227 !CBB_add_asn1_uint64(&signer_info, 1 /* version */) ||
228 !CBB_add_asn1(&signer_info, &issuer_and_serial, CBS_ASN1_SEQUENCE) ||
229 !CBB_add_bytes(&issuer_and_serial, name_der, name_der_len) ||
230 !BN_marshal_asn1(&issuer_and_serial, serial) ||
231 !CBB_add_asn1(&signer_info, &digest_algo, CBS_ASN1_SEQUENCE) ||
232 !OBJ_nid2cbb(&digest_algo, NID_sha256) ||
233 !CBB_add_asn1(&digest_algo, &null, CBS_ASN1_NULL) ||
234 !CBB_add_asn1(&signer_info, &sign_algo, CBS_ASN1_SEQUENCE) ||
235 !OBJ_nid2cbb(&sign_algo, sig_nid) || !CBB_add_asn1(&sign_algo, &null, CBS_ASN1_NULL) ||
236 !CBB_add_asn1(&signer_info, &signature, CBS_ASN1_OCTETSTRING) ||
237 !CBB_add_bytes(&signature, signed_digest.data(), signed_digest.size()) ||
238 !CBB_finish(&out, &pkcs7_data, &pkcs7_data_len)) {
239 return Error() << "Failed to create PKCS7 certificate.";
240 }
241
242 return std::vector<uint8_t>(&pkcs7_data[0], &pkcs7_data[pkcs7_data_len]);
243}