blob: 9867f623c7fe60dc5e2e8ae9a172a6a986891f70 [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
Alan Stokesb1821782021-06-07 14:57:15 +010017#include "CertUtils.h"
18
Martijn Coenen95194842020-09-24 16:56:46 +020019#include <android-base/logging.h>
20#include <android-base/result.h>
21
22#include <openssl/bn.h>
23#include <openssl/crypto.h>
24#include <openssl/pkcs7.h>
25#include <openssl/rsa.h>
David Benjamin891b9542021-05-06 13:36:46 -040026#include <openssl/x509.h>
Martijn Coenen95194842020-09-24 16:56:46 +020027#include <openssl/x509v3.h>
28
29#include <fcntl.h>
30#include <vector>
Martijn Coenenba1c9dc2021-02-04 13:18:29 +010031
32#include "KeyConstants.h"
33
Martijn Coenen95194842020-09-24 16:56:46 +020034const char kBasicConstraints[] = "CA:TRUE";
35const char kKeyUsage[] = "critical,keyCertSign,cRLSign,digitalSignature";
36const char kSubjectKeyIdentifier[] = "hash";
Alan Stokesb1821782021-06-07 14:57:15 +010037const char kAuthorityKeyIdentifier[] = "keyid:always";
Martijn Coenen95194842020-09-24 16:56:46 +020038constexpr int kCertLifetimeSeconds = 10 * 365 * 24 * 60 * 60;
39
40using android::base::Result;
41// using android::base::ErrnoError;
42using android::base::Error;
43
44static bool add_ext(X509* cert, int nid, const char* value) {
45 size_t len = strlen(value) + 1;
46 std::vector<char> mutableValue(value, value + len);
47 X509V3_CTX context;
48
49 X509V3_set_ctx_nodb(&context);
50
51 X509V3_set_ctx(&context, cert, cert, nullptr, nullptr, 0);
52 X509_EXTENSION* ex = X509V3_EXT_nconf_nid(nullptr, &context, nid, mutableValue.data());
53 if (!ex) {
54 return false;
55 }
56
57 X509_add_ext(cert, ex, -1);
58 X509_EXTENSION_free(ex);
59 return true;
60}
61
Martijn Coenendc05bb32021-03-08 10:52:48 +010062Result<bssl::UniquePtr<RSA>> getRsa(const std::vector<uint8_t>& publicKey) {
David Benjamin891b9542021-05-06 13:36:46 -040063 bssl::UniquePtr<BIGNUM> n(BN_new());
64 bssl::UniquePtr<BIGNUM> e(BN_new());
Martijn Coenendc05bb32021-03-08 10:52:48 +010065 bssl::UniquePtr<RSA> rsaPubkey(RSA_new());
David Benjamin891b9542021-05-06 13:36:46 -040066 if (!n || !e || !rsaPubkey || !BN_bin2bn(publicKey.data(), publicKey.size(), n.get()) ||
67 !BN_set_word(e.get(), kRsaKeyExponent) ||
68 !RSA_set0_key(rsaPubkey.get(), n.get(), e.get(), /*d=*/nullptr)) {
69 return Error() << "Failed to create RSA key";
70 }
71 // RSA_set0_key takes ownership of |n| and |e| on success.
72 (void)n.release();
73 (void)e.release();
Martijn Coenendc05bb32021-03-08 10:52:48 +010074
75 return rsaPubkey;
76}
77
78Result<void> verifySignature(const std::string& message, const std::string& signature,
79 const std::vector<uint8_t>& publicKey) {
80 auto rsaKey = getRsa(publicKey);
David Benjamin891b9542021-05-06 13:36:46 -040081 if (!rsaKey.ok()) {
82 return rsaKey.error();
83 }
Martijn Coenendc05bb32021-03-08 10:52:48 +010084 uint8_t hashBuf[SHA256_DIGEST_LENGTH];
85 SHA256(const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(message.c_str())),
86 message.length(), hashBuf);
87
88 bool success = RSA_verify(NID_sha256, hashBuf, sizeof(hashBuf),
89 (const uint8_t*)signature.c_str(), signature.length(), rsaKey->get());
90
91 if (!success) {
92 return Error() << "Failed to verify signature.";
93 }
94 return {};
95}
96
Alan Stokesb1821782021-06-07 14:57:15 +010097static Result<bssl::UniquePtr<EVP_PKEY>> toRsaPkey(const std::vector<uint8_t>& publicKey) {
98 // "publicKey" corresponds to the raw public key bytes - need to create
99 // a new RSA key with the correct exponent.
100 auto rsaPubkey = getRsa(publicKey);
101 if (!rsaPubkey.ok()) {
102 return rsaPubkey.error();
103 }
104
105 bssl::UniquePtr<EVP_PKEY> public_key(EVP_PKEY_new());
106 if (!EVP_PKEY_assign_RSA(public_key.get(), rsaPubkey->release())) {
107 return Error() << "Failed to assign key";
108 }
109 return public_key;
110}
111
Martijn Coenen95194842020-09-24 16:56:46 +0200112Result<void> createSelfSignedCertificate(
113 const std::vector<uint8_t>& publicKey,
114 const std::function<Result<std::string>(const std::string&)>& signFunction,
115 const std::string& path) {
116 bssl::UniquePtr<X509> x509(X509_new());
117 if (!x509) {
118 return Error() << "Unable to allocate x509 container";
119 }
120 X509_set_version(x509.get(), 2);
121
122 ASN1_INTEGER_set(X509_get_serialNumber(x509.get()), 1);
123 X509_gmtime_adj(X509_get_notBefore(x509.get()), 0);
124 X509_gmtime_adj(X509_get_notAfter(x509.get()), kCertLifetimeSeconds);
125
Alan Stokesb1821782021-06-07 14:57:15 +0100126 auto public_key = toRsaPkey(publicKey);
127 if (!public_key.ok()) {
128 return public_key.error();
David Benjamin891b9542021-05-06 13:36:46 -0400129 }
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100130
Alan Stokesb1821782021-06-07 14:57:15 +0100131 if (!X509_set_pubkey(x509.get(), public_key.value().get())) {
Martijn Coenen95194842020-09-24 16:56:46 +0200132 return Error() << "Unable to set x509 public key";
133 }
134
135 X509_NAME* name = X509_get_subject_name(x509.get());
136 if (!name) {
137 return Error() << "Unable to get x509 subject name";
138 }
139 X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC,
140 reinterpret_cast<const unsigned char*>("US"), -1, -1, 0);
141 X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC,
142 reinterpret_cast<const unsigned char*>("Android"), -1, -1, 0);
143 X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
144 reinterpret_cast<const unsigned char*>("ODS"), -1, -1, 0);
145 if (!X509_set_issuer_name(x509.get(), name)) {
146 return Error() << "Unable to set x509 issuer name";
147 }
148
149 add_ext(x509.get(), NID_basic_constraints, kBasicConstraints);
150 add_ext(x509.get(), NID_key_usage, kKeyUsage);
151 add_ext(x509.get(), NID_subject_key_identifier, kSubjectKeyIdentifier);
Alan Stokesb1821782021-06-07 14:57:15 +0100152 add_ext(x509.get(), NID_authority_key_identifier, kAuthorityKeyIdentifier);
Martijn Coenen95194842020-09-24 16:56:46 +0200153
David Benjamin891b9542021-05-06 13:36:46 -0400154 bssl::UniquePtr<X509_ALGOR> algor(X509_ALGOR_new());
155 if (!algor ||
156 !X509_ALGOR_set0(algor.get(), OBJ_nid2obj(NID_sha256WithRSAEncryption), V_ASN1_NULL,
157 NULL) ||
158 !X509_set1_signature_algo(x509.get(), algor.get())) {
159 return Error() << "Unable to set x509 signature algorithm";
160 }
Martijn Coenen95194842020-09-24 16:56:46 +0200161
162 // Get the data to be signed
David Benjamin891b9542021-05-06 13:36:46 -0400163 unsigned char* to_be_signed_buf(nullptr);
164 size_t to_be_signed_length = i2d_re_X509_tbs(x509.get(), &to_be_signed_buf);
Martijn Coenen95194842020-09-24 16:56:46 +0200165
David Benjamin891b9542021-05-06 13:36:46 -0400166 auto signed_data = signFunction(
167 std::string(reinterpret_cast<const char*>(to_be_signed_buf), to_be_signed_length));
Martijn Coenen95194842020-09-24 16:56:46 +0200168 if (!signed_data.ok()) {
169 return signed_data.error();
170 }
171
David Benjamin891b9542021-05-06 13:36:46 -0400172 if (!X509_set1_signature_value(x509.get(),
173 reinterpret_cast<const uint8_t*>(signed_data->data()),
174 signed_data->size())) {
175 return Error() << "Unable to set x509 signature";
176 }
Martijn Coenen95194842020-09-24 16:56:46 +0200177
Martijn Coenenc101b132021-03-18 11:23:55 +0100178 auto f = fopen(path.c_str(), "wbe");
179 if (f == nullptr) {
180 return Error() << "Failed to open " << path;
181 }
Martijn Coenen95194842020-09-24 16:56:46 +0200182 i2d_X509_fp(f, x509.get());
183 fclose(f);
184
185 return {};
186}
187
188Result<std::vector<uint8_t>> extractPublicKey(EVP_PKEY* pkey) {
189 if (pkey == nullptr) {
190 return Error() << "Failed to extract public key from x509 cert";
191 }
192
David Benjamin891b9542021-05-06 13:36:46 -0400193 if (EVP_PKEY_id(pkey) != EVP_PKEY_RSA) {
Martijn Coenen95194842020-09-24 16:56:46 +0200194 return Error() << "The public key is not an RSA key";
195 }
196
David Benjamin891b9542021-05-06 13:36:46 -0400197 RSA* rsa = EVP_PKEY_get0_RSA(pkey);
198 auto num_bytes = BN_num_bytes(RSA_get0_n(rsa));
Martijn Coenen95194842020-09-24 16:56:46 +0200199 std::vector<uint8_t> pubKey(num_bytes);
David Benjamin891b9542021-05-06 13:36:46 -0400200 int res = BN_bn2bin(RSA_get0_n(rsa), pubKey.data());
Martijn Coenen95194842020-09-24 16:56:46 +0200201
202 if (!res) {
203 return Error() << "Failed to convert public key to bytes";
204 }
205
206 return pubKey;
207}
208
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100209Result<std::vector<uint8_t>>
210extractPublicKeyFromSubjectPublicKeyInfo(const std::vector<uint8_t>& keyData) {
Martijn Coenen95194842020-09-24 16:56:46 +0200211 auto keyDataBytes = keyData.data();
Alan Stokes3b885982021-06-07 11:34:26 +0100212 bssl::UniquePtr<EVP_PKEY> public_key(d2i_PUBKEY(nullptr, &keyDataBytes, keyData.size()));
Martijn Coenen95194842020-09-24 16:56:46 +0200213
Alan Stokes3b885982021-06-07 11:34:26 +0100214 return extractPublicKey(public_key.get());
Martijn Coenen95194842020-09-24 16:56:46 +0200215}
216
Alan Stokesb1821782021-06-07 14:57:15 +0100217Result<std::vector<uint8_t>> extractPublicKeyFromX509(const std::vector<uint8_t>& derCert) {
218 auto derCertBytes = derCert.data();
219 bssl::UniquePtr<X509> decoded_cert(d2i_X509(nullptr, &derCertBytes, derCert.size()));
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100220 if (decoded_cert.get() == nullptr) {
221 return Error() << "Failed to decode X509 certificate.";
222 }
223 bssl::UniquePtr<EVP_PKEY> decoded_pkey(X509_get_pubkey(decoded_cert.get()));
224
225 return extractPublicKey(decoded_pkey.get());
226}
227
Alan Stokesb1821782021-06-07 14:57:15 +0100228static Result<bssl::UniquePtr<X509>> loadX509(const std::string& path) {
Alan Stokes3b885982021-06-07 11:34:26 +0100229 X509* rawCert;
Martijn Coenenc101b132021-03-18 11:23:55 +0100230 auto f = fopen(path.c_str(), "re");
231 if (f == nullptr) {
232 return Error() << "Failed to open " << path;
233 }
Alan Stokes3b885982021-06-07 11:34:26 +0100234 if (!d2i_X509_fp(f, &rawCert)) {
Martijn Coenenc101b132021-03-18 11:23:55 +0100235 fclose(f);
Martijn Coenen95194842020-09-24 16:56:46 +0200236 return Error() << "Unable to decode x509 cert at " << path;
237 }
Alan Stokes3b885982021-06-07 11:34:26 +0100238 bssl::UniquePtr<X509> cert(rawCert);
Martijn Coenen95194842020-09-24 16:56:46 +0200239
240 fclose(f);
Alan Stokesb1821782021-06-07 14:57:15 +0100241 return cert;
242}
243
244Result<std::vector<uint8_t>> extractPublicKeyFromX509(const std::string& path) {
245 auto cert = loadX509(path);
246 if (!cert.ok()) {
247 return cert.error();
248 }
249 return extractPublicKey(X509_get_pubkey(cert.value().get()));
250}
251
252Result<CertInfo> verifyAndExtractCertInfoFromX509(const std::string& path,
253 const std::vector<uint8_t>& publicKey) {
254 auto public_key = toRsaPkey(publicKey);
255 if (!public_key.ok()) {
256 return public_key.error();
257 }
258
259 auto cert = loadX509(path);
260 if (!cert.ok()) {
261 return cert.error();
262 }
263 X509* x509 = cert.value().get();
264
265 // Make sure we signed it.
266 if (X509_verify(x509, public_key.value().get()) != 1) {
267 return Error() << "Failed to verify certificate.";
268 }
269
270 bssl::UniquePtr<EVP_PKEY> pkey(X509_get_pubkey(x509));
271 auto subject_key = extractPublicKey(pkey.get());
272 if (!subject_key.ok()) {
273 return subject_key.error();
274 }
275
276 // The pointers here are all owned by x509, and each function handles an
277 // error return from the previous call correctly.
278 X509_NAME* name = X509_get_subject_name(x509);
279 int index = X509_NAME_get_index_by_NID(name, NID_commonName, -1);
280 X509_NAME_ENTRY* entry = X509_NAME_get_entry(name, index);
281 ASN1_STRING* asn1cn = X509_NAME_ENTRY_get_data(entry);
282 unsigned char* utf8cn;
283 int length = ASN1_STRING_to_UTF8(&utf8cn, asn1cn);
284 if (length < 0) {
285 return Error() << "Failed to read subject CN";
286 }
287
288 bssl::UniquePtr<unsigned char> utf8owner(utf8cn);
289 std::string cn(reinterpret_cast<char*>(utf8cn), static_cast<size_t>(length));
290
291 CertInfo cert_info{std::move(cn), std::move(subject_key.value())};
292 return cert_info;
Martijn Coenen95194842020-09-24 16:56:46 +0200293}
294
295Result<std::vector<uint8_t>> createPkcs7(const std::vector<uint8_t>& signed_digest) {
296 CBB out, outer_seq, wrapped_seq, seq, digest_algos_set, digest_algo, null;
297 CBB content_info, issuer_and_serial, signer_infos, signer_info, sign_algo, signature;
298 uint8_t *pkcs7_data, *name_der;
299 size_t pkcs7_data_len, name_der_len;
300 BIGNUM* serial = BN_new();
301 int sig_nid = NID_rsaEncryption;
302
303 X509_NAME* name = X509_NAME_new();
304 if (!name) {
305 return Error() << "Unable to get x509 subject name";
306 }
307 X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC,
308 reinterpret_cast<const unsigned char*>("US"), -1, -1, 0);
309 X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC,
310 reinterpret_cast<const unsigned char*>("Android"), -1, -1, 0);
311 X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
312 reinterpret_cast<const unsigned char*>("ODS"), -1, -1, 0);
313
314 BN_set_word(serial, 1);
315 name_der_len = i2d_X509_NAME(name, &name_der);
316 CBB_init(&out, 1024);
317
318 if (!CBB_add_asn1(&out, &outer_seq, CBS_ASN1_SEQUENCE) ||
319 !OBJ_nid2cbb(&outer_seq, NID_pkcs7_signed) ||
320 !CBB_add_asn1(&outer_seq, &wrapped_seq,
321 CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0) ||
322 // See https://tools.ietf.org/html/rfc2315#section-9.1
323 !CBB_add_asn1(&wrapped_seq, &seq, CBS_ASN1_SEQUENCE) ||
324 !CBB_add_asn1_uint64(&seq, 1 /* version */) ||
325 !CBB_add_asn1(&seq, &digest_algos_set, CBS_ASN1_SET) ||
326 !CBB_add_asn1(&digest_algos_set, &digest_algo, CBS_ASN1_SEQUENCE) ||
327 !OBJ_nid2cbb(&digest_algo, NID_sha256) ||
328 !CBB_add_asn1(&digest_algo, &null, CBS_ASN1_NULL) ||
329 !CBB_add_asn1(&seq, &content_info, CBS_ASN1_SEQUENCE) ||
330 !OBJ_nid2cbb(&content_info, NID_pkcs7_data) ||
331 !CBB_add_asn1(&seq, &signer_infos, CBS_ASN1_SET) ||
332 !CBB_add_asn1(&signer_infos, &signer_info, CBS_ASN1_SEQUENCE) ||
333 !CBB_add_asn1_uint64(&signer_info, 1 /* version */) ||
334 !CBB_add_asn1(&signer_info, &issuer_and_serial, CBS_ASN1_SEQUENCE) ||
335 !CBB_add_bytes(&issuer_and_serial, name_der, name_der_len) ||
336 !BN_marshal_asn1(&issuer_and_serial, serial) ||
337 !CBB_add_asn1(&signer_info, &digest_algo, CBS_ASN1_SEQUENCE) ||
338 !OBJ_nid2cbb(&digest_algo, NID_sha256) ||
339 !CBB_add_asn1(&digest_algo, &null, CBS_ASN1_NULL) ||
340 !CBB_add_asn1(&signer_info, &sign_algo, CBS_ASN1_SEQUENCE) ||
341 !OBJ_nid2cbb(&sign_algo, sig_nid) || !CBB_add_asn1(&sign_algo, &null, CBS_ASN1_NULL) ||
342 !CBB_add_asn1(&signer_info, &signature, CBS_ASN1_OCTETSTRING) ||
343 !CBB_add_bytes(&signature, signed_digest.data(), signed_digest.size()) ||
344 !CBB_finish(&out, &pkcs7_data, &pkcs7_data_len)) {
345 return Error() << "Failed to create PKCS7 certificate.";
346 }
347
348 return std::vector<uint8_t>(&pkcs7_data[0], &pkcs7_data[pkcs7_data_len]);
349}