blob: cbd194234f86a73b27676c7c7b1ac7970a524000 [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
Martijn Coenendc05bb32021-03-08 10:52:48 +010058Result<bssl::UniquePtr<RSA>> getRsa(const std::vector<uint8_t>& publicKey) {
59 bssl::UniquePtr<RSA> rsaPubkey(RSA_new());
60 rsaPubkey->n = BN_new();
61 rsaPubkey->e = BN_new();
62
63 BN_bin2bn(publicKey.data(), publicKey.size(), rsaPubkey->n);
64 BN_set_word(rsaPubkey->e, kRsaKeyExponent);
65
66 return rsaPubkey;
67}
68
69Result<void> verifySignature(const std::string& message, const std::string& signature,
70 const std::vector<uint8_t>& publicKey) {
71 auto rsaKey = getRsa(publicKey);
72 uint8_t hashBuf[SHA256_DIGEST_LENGTH];
73 SHA256(const_cast<uint8_t*>(reinterpret_cast<const uint8_t*>(message.c_str())),
74 message.length(), hashBuf);
75
76 bool success = RSA_verify(NID_sha256, hashBuf, sizeof(hashBuf),
77 (const uint8_t*)signature.c_str(), signature.length(), rsaKey->get());
78
79 if (!success) {
80 return Error() << "Failed to verify signature.";
81 }
82 return {};
83}
84
Martijn Coenen95194842020-09-24 16:56:46 +020085Result<void> createSelfSignedCertificate(
86 const std::vector<uint8_t>& publicKey,
87 const std::function<Result<std::string>(const std::string&)>& signFunction,
88 const std::string& path) {
89 bssl::UniquePtr<X509> x509(X509_new());
90 if (!x509) {
91 return Error() << "Unable to allocate x509 container";
92 }
93 X509_set_version(x509.get(), 2);
94
95 ASN1_INTEGER_set(X509_get_serialNumber(x509.get()), 1);
96 X509_gmtime_adj(X509_get_notBefore(x509.get()), 0);
97 X509_gmtime_adj(X509_get_notAfter(x509.get()), kCertLifetimeSeconds);
98
Martijn Coenenba1c9dc2021-02-04 13:18:29 +010099 // "publicKey" corresponds to the raw public key bytes - need to create
100 // a new RSA key with the correct exponent.
Martijn Coenendc05bb32021-03-08 10:52:48 +0100101 auto rsaPubkey = getRsa(publicKey);
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100102
103 EVP_PKEY* public_key = EVP_PKEY_new();
Martijn Coenendc05bb32021-03-08 10:52:48 +0100104 EVP_PKEY_assign_RSA(public_key, rsaPubkey->release());
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100105
Martijn Coenen95194842020-09-24 16:56:46 +0200106 if (!X509_set_pubkey(x509.get(), public_key)) {
107 return Error() << "Unable to set x509 public key";
108 }
109
110 X509_NAME* name = X509_get_subject_name(x509.get());
111 if (!name) {
112 return Error() << "Unable to get x509 subject name";
113 }
114 X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC,
115 reinterpret_cast<const unsigned char*>("US"), -1, -1, 0);
116 X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC,
117 reinterpret_cast<const unsigned char*>("Android"), -1, -1, 0);
118 X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
119 reinterpret_cast<const unsigned char*>("ODS"), -1, -1, 0);
120 if (!X509_set_issuer_name(x509.get(), name)) {
121 return Error() << "Unable to set x509 issuer name";
122 }
123
124 add_ext(x509.get(), NID_basic_constraints, kBasicConstraints);
125 add_ext(x509.get(), NID_key_usage, kKeyUsage);
126 add_ext(x509.get(), NID_subject_key_identifier, kSubjectKeyIdentifier);
127 add_ext(x509.get(), NID_authority_key_identifier, "keyid:always");
128
129 X509_ALGOR_set0(x509->cert_info->signature, OBJ_nid2obj(NID_sha256WithRSAEncryption),
130 V_ASN1_NULL, NULL);
131 X509_ALGOR_set0(x509->sig_alg, OBJ_nid2obj(NID_sha256WithRSAEncryption), V_ASN1_NULL, NULL);
132
133 // Get the data to be signed
134 char* to_be_signed_buf(nullptr);
135 size_t to_be_signed_length = i2d_re_X509_tbs(x509.get(), (unsigned char**)&to_be_signed_buf);
136
137 auto signed_data = signFunction(std::string(to_be_signed_buf, to_be_signed_length));
138 if (!signed_data.ok()) {
139 return signed_data.error();
140 }
141
142 // This is the only part that doesn't use boringssl default functions - we manually copy in the
143 // signature that was provided to us.
144 x509->signature->data = (unsigned char*)OPENSSL_malloc(signed_data->size());
145 memcpy(x509->signature->data, signed_data->c_str(), signed_data->size());
146 x509->signature->length = signed_data->size();
147
148 x509->signature->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07);
149 x509->signature->flags |= ASN1_STRING_FLAG_BITS_LEFT;
150 auto f = fopen(path.c_str(), "wb");
151 // TODO error checking
152 i2d_X509_fp(f, x509.get());
153 fclose(f);
154
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100155 EVP_PKEY_free(public_key);
Martijn Coenen95194842020-09-24 16:56:46 +0200156 return {};
157}
158
159Result<std::vector<uint8_t>> extractPublicKey(EVP_PKEY* pkey) {
160 if (pkey == nullptr) {
161 return Error() << "Failed to extract public key from x509 cert";
162 }
163
164 if (EVP_PKEY_type(pkey->type) != EVP_PKEY_RSA) {
165 return Error() << "The public key is not an RSA key";
166 }
167
168 RSA* rsa = EVP_PKEY_get1_RSA(pkey);
169 auto num_bytes = BN_num_bytes(rsa->n);
170 std::vector<uint8_t> pubKey(num_bytes);
171 int res = BN_bn2bin(rsa->n, pubKey.data());
172 RSA_free(rsa);
173
174 if (!res) {
175 return Error() << "Failed to convert public key to bytes";
176 }
177
178 return pubKey;
179}
180
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100181Result<std::vector<uint8_t>>
182extractPublicKeyFromSubjectPublicKeyInfo(const std::vector<uint8_t>& keyData) {
Martijn Coenen95194842020-09-24 16:56:46 +0200183 auto keyDataBytes = keyData.data();
184 EVP_PKEY* public_key = d2i_PUBKEY(nullptr, &keyDataBytes, keyData.size());
185
186 return extractPublicKey(public_key);
187}
188
Martijn Coenenba1c9dc2021-02-04 13:18:29 +0100189Result<std::vector<uint8_t>> extractPublicKeyFromX509(const std::vector<uint8_t>& keyData) {
190 auto keyDataBytes = keyData.data();
191 bssl::UniquePtr<X509> decoded_cert(d2i_X509(nullptr, &keyDataBytes, keyData.size()));
192 if (decoded_cert.get() == nullptr) {
193 return Error() << "Failed to decode X509 certificate.";
194 }
195 bssl::UniquePtr<EVP_PKEY> decoded_pkey(X509_get_pubkey(decoded_cert.get()));
196
197 return extractPublicKey(decoded_pkey.get());
198}
199
Martijn Coenen95194842020-09-24 16:56:46 +0200200Result<std::vector<uint8_t>> extractPublicKeyFromX509(const std::string& path) {
201 X509* cert;
202 auto f = fopen(path.c_str(), "r");
203 if (!d2i_X509_fp(f, &cert)) {
204 return Error() << "Unable to decode x509 cert at " << path;
205 }
206
207 fclose(f);
208 return extractPublicKey(X509_get_pubkey(cert));
209}
210
211Result<std::vector<uint8_t>> createPkcs7(const std::vector<uint8_t>& signed_digest) {
212 CBB out, outer_seq, wrapped_seq, seq, digest_algos_set, digest_algo, null;
213 CBB content_info, issuer_and_serial, signer_infos, signer_info, sign_algo, signature;
214 uint8_t *pkcs7_data, *name_der;
215 size_t pkcs7_data_len, name_der_len;
216 BIGNUM* serial = BN_new();
217 int sig_nid = NID_rsaEncryption;
218
219 X509_NAME* name = X509_NAME_new();
220 if (!name) {
221 return Error() << "Unable to get x509 subject name";
222 }
223 X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC,
224 reinterpret_cast<const unsigned char*>("US"), -1, -1, 0);
225 X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC,
226 reinterpret_cast<const unsigned char*>("Android"), -1, -1, 0);
227 X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
228 reinterpret_cast<const unsigned char*>("ODS"), -1, -1, 0);
229
230 BN_set_word(serial, 1);
231 name_der_len = i2d_X509_NAME(name, &name_der);
232 CBB_init(&out, 1024);
233
234 if (!CBB_add_asn1(&out, &outer_seq, CBS_ASN1_SEQUENCE) ||
235 !OBJ_nid2cbb(&outer_seq, NID_pkcs7_signed) ||
236 !CBB_add_asn1(&outer_seq, &wrapped_seq,
237 CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0) ||
238 // See https://tools.ietf.org/html/rfc2315#section-9.1
239 !CBB_add_asn1(&wrapped_seq, &seq, CBS_ASN1_SEQUENCE) ||
240 !CBB_add_asn1_uint64(&seq, 1 /* version */) ||
241 !CBB_add_asn1(&seq, &digest_algos_set, CBS_ASN1_SET) ||
242 !CBB_add_asn1(&digest_algos_set, &digest_algo, CBS_ASN1_SEQUENCE) ||
243 !OBJ_nid2cbb(&digest_algo, NID_sha256) ||
244 !CBB_add_asn1(&digest_algo, &null, CBS_ASN1_NULL) ||
245 !CBB_add_asn1(&seq, &content_info, CBS_ASN1_SEQUENCE) ||
246 !OBJ_nid2cbb(&content_info, NID_pkcs7_data) ||
247 !CBB_add_asn1(&seq, &signer_infos, CBS_ASN1_SET) ||
248 !CBB_add_asn1(&signer_infos, &signer_info, CBS_ASN1_SEQUENCE) ||
249 !CBB_add_asn1_uint64(&signer_info, 1 /* version */) ||
250 !CBB_add_asn1(&signer_info, &issuer_and_serial, CBS_ASN1_SEQUENCE) ||
251 !CBB_add_bytes(&issuer_and_serial, name_der, name_der_len) ||
252 !BN_marshal_asn1(&issuer_and_serial, serial) ||
253 !CBB_add_asn1(&signer_info, &digest_algo, CBS_ASN1_SEQUENCE) ||
254 !OBJ_nid2cbb(&digest_algo, NID_sha256) ||
255 !CBB_add_asn1(&digest_algo, &null, CBS_ASN1_NULL) ||
256 !CBB_add_asn1(&signer_info, &sign_algo, CBS_ASN1_SEQUENCE) ||
257 !OBJ_nid2cbb(&sign_algo, sig_nid) || !CBB_add_asn1(&sign_algo, &null, CBS_ASN1_NULL) ||
258 !CBB_add_asn1(&signer_info, &signature, CBS_ASN1_OCTETSTRING) ||
259 !CBB_add_bytes(&signature, signed_digest.data(), signed_digest.size()) ||
260 !CBB_finish(&out, &pkcs7_data, &pkcs7_data_len)) {
261 return Error() << "Failed to create PKCS7 certificate.";
262 }
263
264 return std::vector<uint8_t>(&pkcs7_data[0], &pkcs7_data[pkcs7_data_len]);
265}