blob: 10abfe2dbe459f80db05133c7c2e5054b5ee603a [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>
David Benjamin891b9542021-05-06 13:36:46 -040024#include <openssl/x509.h>
Martijn Coenen95194842020-09-24 16:56:46 +020025#include <openssl/x509v3.h>
26
27#include <fcntl.h>
28#include <vector>
Martijn Coenenba1c9dc2021-02-04 13:18:29 +010029
30#include "KeyConstants.h"
31
Martijn Coenen95194842020-09-24 16:56:46 +020032const char kBasicConstraints[] = "CA:TRUE";
33const char kKeyUsage[] = "critical,keyCertSign,cRLSign,digitalSignature";
34const char kSubjectKeyIdentifier[] = "hash";
35constexpr int kCertLifetimeSeconds = 10 * 365 * 24 * 60 * 60;
36
37using android::base::Result;
38// using android::base::ErrnoError;
39using android::base::Error;
40
41static bool add_ext(X509* cert, int nid, const char* value) {
42 size_t len = strlen(value) + 1;
43 std::vector<char> mutableValue(value, value + len);
44 X509V3_CTX context;
45
46 X509V3_set_ctx_nodb(&context);
47
48 X509V3_set_ctx(&context, cert, cert, nullptr, nullptr, 0);
49 X509_EXTENSION* ex = X509V3_EXT_nconf_nid(nullptr, &context, nid, mutableValue.data());
50 if (!ex) {
51 return false;
52 }
53
54 X509_add_ext(cert, ex, -1);
55 X509_EXTENSION_free(ex);
56 return true;
57}
58
Martijn Coenendc05bb32021-03-08 10:52:48 +010059Result<bssl::UniquePtr<RSA>> getRsa(const std::vector<uint8_t>& publicKey) {
David Benjamin891b9542021-05-06 13:36:46 -040060 bssl::UniquePtr<BIGNUM> n(BN_new());
61 bssl::UniquePtr<BIGNUM> e(BN_new());
Martijn Coenendc05bb32021-03-08 10:52:48 +010062 bssl::UniquePtr<RSA> rsaPubkey(RSA_new());
David Benjamin891b9542021-05-06 13:36:46 -040063 if (!n || !e || !rsaPubkey || !BN_bin2bn(publicKey.data(), publicKey.size(), n.get()) ||
64 !BN_set_word(e.get(), kRsaKeyExponent) ||
65 !RSA_set0_key(rsaPubkey.get(), n.get(), e.get(), /*d=*/nullptr)) {
66 return Error() << "Failed to create RSA key";
67 }
68 // RSA_set0_key takes ownership of |n| and |e| on success.
69 (void)n.release();
70 (void)e.release();
Martijn Coenendc05bb32021-03-08 10:52:48 +010071
72 return rsaPubkey;
73}
74
75Result<void> verifySignature(const std::string& message, const std::string& signature,
76 const std::vector<uint8_t>& publicKey) {
77 auto rsaKey = getRsa(publicKey);
David Benjamin891b9542021-05-06 13:36:46 -040078 if (!rsaKey.ok()) {
79 return rsaKey.error();
80 }
Martijn Coenendc05bb32021-03-08 10:52:48 +010081 uint8_t hashBuf[SHA256_DIGEST_LENGTH];
82 SHA256(const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(message.c_str())),
83 message.length(), hashBuf);
84
85 bool success = RSA_verify(NID_sha256, hashBuf, sizeof(hashBuf),
86 (const uint8_t*)signature.c_str(), signature.length(), rsaKey->get());
87
88 if (!success) {
89 return Error() << "Failed to verify signature.";
90 }
91 return {};
92}
93
Martijn Coenen95194842020-09-24 16:56:46 +020094Result<void> createSelfSignedCertificate(
95 const std::vector<uint8_t>& publicKey,
96 const std::function<Result<std::string>(const std::string&)>& signFunction,
97 const std::string& path) {
98 bssl::UniquePtr<X509> x509(X509_new());
99 if (!x509) {
100 return Error() << "Unable to allocate x509 container";
101 }
102 X509_set_version(x509.get(), 2);
103
104 ASN1_INTEGER_set(X509_get_serialNumber(x509.get()), 1);
105 X509_gmtime_adj(X509_get_notBefore(x509.get()), 0);
106 X509_gmtime_adj(X509_get_notAfter(x509.get()), kCertLifetimeSeconds);
107
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100108 // "publicKey" corresponds to the raw public key bytes - need to create
109 // a new RSA key with the correct exponent.
Martijn Coenendc05bb32021-03-08 10:52:48 +0100110 auto rsaPubkey = getRsa(publicKey);
David Benjamin891b9542021-05-06 13:36:46 -0400111 if (!rsaPubkey.ok()) {
112 return rsaPubkey.error();
113 }
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100114
David Benjamin891b9542021-05-06 13:36:46 -0400115 bssl::UniquePtr<EVP_PKEY> public_key(EVP_PKEY_new());
116 EVP_PKEY_assign_RSA(public_key.get(), rsaPubkey->release());
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100117
David Benjamin891b9542021-05-06 13:36:46 -0400118 if (!X509_set_pubkey(x509.get(), public_key.get())) {
Martijn Coenen95194842020-09-24 16:56:46 +0200119 return Error() << "Unable to set x509 public key";
120 }
121
122 X509_NAME* name = X509_get_subject_name(x509.get());
123 if (!name) {
124 return Error() << "Unable to get x509 subject name";
125 }
126 X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC,
127 reinterpret_cast<const unsigned char*>("US"), -1, -1, 0);
128 X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC,
129 reinterpret_cast<const unsigned char*>("Android"), -1, -1, 0);
130 X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
131 reinterpret_cast<const unsigned char*>("ODS"), -1, -1, 0);
132 if (!X509_set_issuer_name(x509.get(), name)) {
133 return Error() << "Unable to set x509 issuer name";
134 }
135
136 add_ext(x509.get(), NID_basic_constraints, kBasicConstraints);
137 add_ext(x509.get(), NID_key_usage, kKeyUsage);
138 add_ext(x509.get(), NID_subject_key_identifier, kSubjectKeyIdentifier);
139 add_ext(x509.get(), NID_authority_key_identifier, "keyid:always");
140
David Benjamin891b9542021-05-06 13:36:46 -0400141 bssl::UniquePtr<X509_ALGOR> algor(X509_ALGOR_new());
142 if (!algor ||
143 !X509_ALGOR_set0(algor.get(), OBJ_nid2obj(NID_sha256WithRSAEncryption), V_ASN1_NULL,
144 NULL) ||
145 !X509_set1_signature_algo(x509.get(), algor.get())) {
146 return Error() << "Unable to set x509 signature algorithm";
147 }
Martijn Coenen95194842020-09-24 16:56:46 +0200148
149 // Get the data to be signed
David Benjamin891b9542021-05-06 13:36:46 -0400150 unsigned char* to_be_signed_buf(nullptr);
151 size_t to_be_signed_length = i2d_re_X509_tbs(x509.get(), &to_be_signed_buf);
Martijn Coenen95194842020-09-24 16:56:46 +0200152
David Benjamin891b9542021-05-06 13:36:46 -0400153 auto signed_data = signFunction(
154 std::string(reinterpret_cast<const char*>(to_be_signed_buf), to_be_signed_length));
Martijn Coenen95194842020-09-24 16:56:46 +0200155 if (!signed_data.ok()) {
156 return signed_data.error();
157 }
158
David Benjamin891b9542021-05-06 13:36:46 -0400159 if (!X509_set1_signature_value(x509.get(),
160 reinterpret_cast<const uint8_t*>(signed_data->data()),
161 signed_data->size())) {
162 return Error() << "Unable to set x509 signature";
163 }
Martijn Coenen95194842020-09-24 16:56:46 +0200164
Martijn Coenenc101b132021-03-18 11:23:55 +0100165 auto f = fopen(path.c_str(), "wbe");
166 if (f == nullptr) {
167 return Error() << "Failed to open " << path;
168 }
Martijn Coenen95194842020-09-24 16:56:46 +0200169 i2d_X509_fp(f, x509.get());
170 fclose(f);
171
172 return {};
173}
174
175Result<std::vector<uint8_t>> extractPublicKey(EVP_PKEY* pkey) {
176 if (pkey == nullptr) {
177 return Error() << "Failed to extract public key from x509 cert";
178 }
179
David Benjamin891b9542021-05-06 13:36:46 -0400180 if (EVP_PKEY_id(pkey) != EVP_PKEY_RSA) {
Martijn Coenen95194842020-09-24 16:56:46 +0200181 return Error() << "The public key is not an RSA key";
182 }
183
David Benjamin891b9542021-05-06 13:36:46 -0400184 RSA* rsa = EVP_PKEY_get0_RSA(pkey);
185 auto num_bytes = BN_num_bytes(RSA_get0_n(rsa));
Martijn Coenen95194842020-09-24 16:56:46 +0200186 std::vector<uint8_t> pubKey(num_bytes);
David Benjamin891b9542021-05-06 13:36:46 -0400187 int res = BN_bn2bin(RSA_get0_n(rsa), pubKey.data());
Martijn Coenen95194842020-09-24 16:56:46 +0200188
189 if (!res) {
190 return Error() << "Failed to convert public key to bytes";
191 }
192
193 return pubKey;
194}
195
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100196Result<std::vector<uint8_t>>
197extractPublicKeyFromSubjectPublicKeyInfo(const std::vector<uint8_t>& keyData) {
Martijn Coenen95194842020-09-24 16:56:46 +0200198 auto keyDataBytes = keyData.data();
Alan Stokes3b885982021-06-07 11:34:26 +0100199 bssl::UniquePtr<EVP_PKEY> public_key(d2i_PUBKEY(nullptr, &keyDataBytes, keyData.size()));
Martijn Coenen95194842020-09-24 16:56:46 +0200200
Alan Stokes3b885982021-06-07 11:34:26 +0100201 return extractPublicKey(public_key.get());
Martijn Coenen95194842020-09-24 16:56:46 +0200202}
203
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100204Result<std::vector<uint8_t>> extractPublicKeyFromX509(const std::vector<uint8_t>& keyData) {
205 auto keyDataBytes = keyData.data();
206 bssl::UniquePtr<X509> decoded_cert(d2i_X509(nullptr, &keyDataBytes, keyData.size()));
207 if (decoded_cert.get() == nullptr) {
208 return Error() << "Failed to decode X509 certificate.";
209 }
210 bssl::UniquePtr<EVP_PKEY> decoded_pkey(X509_get_pubkey(decoded_cert.get()));
211
212 return extractPublicKey(decoded_pkey.get());
213}
214
Martijn Coenen95194842020-09-24 16:56:46 +0200215Result<std::vector<uint8_t>> extractPublicKeyFromX509(const std::string& path) {
Alan Stokes3b885982021-06-07 11:34:26 +0100216 X509* rawCert;
Martijn Coenenc101b132021-03-18 11:23:55 +0100217 auto f = fopen(path.c_str(), "re");
218 if (f == nullptr) {
219 return Error() << "Failed to open " << path;
220 }
Alan Stokes3b885982021-06-07 11:34:26 +0100221 if (!d2i_X509_fp(f, &rawCert)) {
Martijn Coenenc101b132021-03-18 11:23:55 +0100222 fclose(f);
Martijn Coenen95194842020-09-24 16:56:46 +0200223 return Error() << "Unable to decode x509 cert at " << path;
224 }
Alan Stokes3b885982021-06-07 11:34:26 +0100225 bssl::UniquePtr<X509> cert(rawCert);
Martijn Coenen95194842020-09-24 16:56:46 +0200226
227 fclose(f);
Alan Stokes3b885982021-06-07 11:34:26 +0100228 return extractPublicKey(X509_get_pubkey(cert.get()));
Martijn Coenen95194842020-09-24 16:56:46 +0200229}
230
231Result<std::vector<uint8_t>> createPkcs7(const std::vector<uint8_t>& signed_digest) {
232 CBB out, outer_seq, wrapped_seq, seq, digest_algos_set, digest_algo, null;
233 CBB content_info, issuer_and_serial, signer_infos, signer_info, sign_algo, signature;
234 uint8_t *pkcs7_data, *name_der;
235 size_t pkcs7_data_len, name_der_len;
236 BIGNUM* serial = BN_new();
237 int sig_nid = NID_rsaEncryption;
238
239 X509_NAME* name = X509_NAME_new();
240 if (!name) {
241 return Error() << "Unable to get x509 subject name";
242 }
243 X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC,
244 reinterpret_cast<const unsigned char*>("US"), -1, -1, 0);
245 X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC,
246 reinterpret_cast<const unsigned char*>("Android"), -1, -1, 0);
247 X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
248 reinterpret_cast<const unsigned char*>("ODS"), -1, -1, 0);
249
250 BN_set_word(serial, 1);
251 name_der_len = i2d_X509_NAME(name, &name_der);
252 CBB_init(&out, 1024);
253
254 if (!CBB_add_asn1(&out, &outer_seq, CBS_ASN1_SEQUENCE) ||
255 !OBJ_nid2cbb(&outer_seq, NID_pkcs7_signed) ||
256 !CBB_add_asn1(&outer_seq, &wrapped_seq,
257 CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0) ||
258 // See https://tools.ietf.org/html/rfc2315#section-9.1
259 !CBB_add_asn1(&wrapped_seq, &seq, CBS_ASN1_SEQUENCE) ||
260 !CBB_add_asn1_uint64(&seq, 1 /* version */) ||
261 !CBB_add_asn1(&seq, &digest_algos_set, CBS_ASN1_SET) ||
262 !CBB_add_asn1(&digest_algos_set, &digest_algo, CBS_ASN1_SEQUENCE) ||
263 !OBJ_nid2cbb(&digest_algo, NID_sha256) ||
264 !CBB_add_asn1(&digest_algo, &null, CBS_ASN1_NULL) ||
265 !CBB_add_asn1(&seq, &content_info, CBS_ASN1_SEQUENCE) ||
266 !OBJ_nid2cbb(&content_info, NID_pkcs7_data) ||
267 !CBB_add_asn1(&seq, &signer_infos, CBS_ASN1_SET) ||
268 !CBB_add_asn1(&signer_infos, &signer_info, CBS_ASN1_SEQUENCE) ||
269 !CBB_add_asn1_uint64(&signer_info, 1 /* version */) ||
270 !CBB_add_asn1(&signer_info, &issuer_and_serial, CBS_ASN1_SEQUENCE) ||
271 !CBB_add_bytes(&issuer_and_serial, name_der, name_der_len) ||
272 !BN_marshal_asn1(&issuer_and_serial, serial) ||
273 !CBB_add_asn1(&signer_info, &digest_algo, CBS_ASN1_SEQUENCE) ||
274 !OBJ_nid2cbb(&digest_algo, NID_sha256) ||
275 !CBB_add_asn1(&digest_algo, &null, CBS_ASN1_NULL) ||
276 !CBB_add_asn1(&signer_info, &sign_algo, CBS_ASN1_SEQUENCE) ||
277 !OBJ_nid2cbb(&sign_algo, sig_nid) || !CBB_add_asn1(&sign_algo, &null, CBS_ASN1_NULL) ||
278 !CBB_add_asn1(&signer_info, &signature, CBS_ASN1_OCTETSTRING) ||
279 !CBB_add_bytes(&signature, signed_digest.data(), signed_digest.size()) ||
280 !CBB_finish(&out, &pkcs7_data, &pkcs7_data_len)) {
281 return Error() << "Failed to create PKCS7 certificate.";
282 }
283
284 return std::vector<uint8_t>(&pkcs7_data[0], &pkcs7_data[pkcs7_data_len]);
285}