blob: 6b243917bda8c87f6b4636d928e2d63fa6deee85 [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>
28const char kBasicConstraints[] = "CA:TRUE";
29const char kKeyUsage[] = "critical,keyCertSign,cRLSign,digitalSignature";
30const char kSubjectKeyIdentifier[] = "hash";
31constexpr int kCertLifetimeSeconds = 10 * 365 * 24 * 60 * 60;
32
33using android::base::Result;
34// using android::base::ErrnoError;
35using android::base::Error;
36
37static bool add_ext(X509* cert, int nid, const char* value) {
38 size_t len = strlen(value) + 1;
39 std::vector<char> mutableValue(value, value + len);
40 X509V3_CTX context;
41
42 X509V3_set_ctx_nodb(&context);
43
44 X509V3_set_ctx(&context, cert, cert, nullptr, nullptr, 0);
45 X509_EXTENSION* ex = X509V3_EXT_nconf_nid(nullptr, &context, nid, mutableValue.data());
46 if (!ex) {
47 return false;
48 }
49
50 X509_add_ext(cert, ex, -1);
51 X509_EXTENSION_free(ex);
52 return true;
53}
54
55Result<void> createSelfSignedCertificate(
56 const std::vector<uint8_t>& publicKey,
57 const std::function<Result<std::string>(const std::string&)>& signFunction,
58 const std::string& path) {
59 bssl::UniquePtr<X509> x509(X509_new());
60 if (!x509) {
61 return Error() << "Unable to allocate x509 container";
62 }
63 X509_set_version(x509.get(), 2);
64
65 ASN1_INTEGER_set(X509_get_serialNumber(x509.get()), 1);
66 X509_gmtime_adj(X509_get_notBefore(x509.get()), 0);
67 X509_gmtime_adj(X509_get_notAfter(x509.get()), kCertLifetimeSeconds);
68
69 auto pubKeyData = publicKey.data();
70 EVP_PKEY* public_key = d2i_PUBKEY(nullptr, &pubKeyData, publicKey.size());
71 if (!X509_set_pubkey(x509.get(), public_key)) {
72 return Error() << "Unable to set x509 public key";
73 }
74
75 X509_NAME* name = X509_get_subject_name(x509.get());
76 if (!name) {
77 return Error() << "Unable to get x509 subject name";
78 }
79 X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC,
80 reinterpret_cast<const unsigned char*>("US"), -1, -1, 0);
81 X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC,
82 reinterpret_cast<const unsigned char*>("Android"), -1, -1, 0);
83 X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
84 reinterpret_cast<const unsigned char*>("ODS"), -1, -1, 0);
85 if (!X509_set_issuer_name(x509.get(), name)) {
86 return Error() << "Unable to set x509 issuer name";
87 }
88
89 add_ext(x509.get(), NID_basic_constraints, kBasicConstraints);
90 add_ext(x509.get(), NID_key_usage, kKeyUsage);
91 add_ext(x509.get(), NID_subject_key_identifier, kSubjectKeyIdentifier);
92 add_ext(x509.get(), NID_authority_key_identifier, "keyid:always");
93
94 X509_ALGOR_set0(x509->cert_info->signature, OBJ_nid2obj(NID_sha256WithRSAEncryption),
95 V_ASN1_NULL, NULL);
96 X509_ALGOR_set0(x509->sig_alg, OBJ_nid2obj(NID_sha256WithRSAEncryption), V_ASN1_NULL, NULL);
97
98 // Get the data to be signed
99 char* to_be_signed_buf(nullptr);
100 size_t to_be_signed_length = i2d_re_X509_tbs(x509.get(), (unsigned char**)&to_be_signed_buf);
101
102 auto signed_data = signFunction(std::string(to_be_signed_buf, to_be_signed_length));
103 if (!signed_data.ok()) {
104 return signed_data.error();
105 }
106
107 // This is the only part that doesn't use boringssl default functions - we manually copy in the
108 // signature that was provided to us.
109 x509->signature->data = (unsigned char*)OPENSSL_malloc(signed_data->size());
110 memcpy(x509->signature->data, signed_data->c_str(), signed_data->size());
111 x509->signature->length = signed_data->size();
112
113 x509->signature->flags &= ~(ASN1_STRING_FLAG_BITS_LEFT | 0x07);
114 x509->signature->flags |= ASN1_STRING_FLAG_BITS_LEFT;
115 auto f = fopen(path.c_str(), "wb");
116 // TODO error checking
117 i2d_X509_fp(f, x509.get());
118 fclose(f);
119
120 return {};
121}
122
123Result<std::vector<uint8_t>> extractPublicKey(EVP_PKEY* pkey) {
124 if (pkey == nullptr) {
125 return Error() << "Failed to extract public key from x509 cert";
126 }
127
128 if (EVP_PKEY_type(pkey->type) != EVP_PKEY_RSA) {
129 return Error() << "The public key is not an RSA key";
130 }
131
132 RSA* rsa = EVP_PKEY_get1_RSA(pkey);
133 auto num_bytes = BN_num_bytes(rsa->n);
134 std::vector<uint8_t> pubKey(num_bytes);
135 int res = BN_bn2bin(rsa->n, pubKey.data());
136 RSA_free(rsa);
137
138 if (!res) {
139 return Error() << "Failed to convert public key to bytes";
140 }
141
142 return pubKey;
143}
144
145Result<std::vector<uint8_t>> extractPublicKeyFromX509(const std::vector<uint8_t>& keyData) {
146 auto keyDataBytes = keyData.data();
147 EVP_PKEY* public_key = d2i_PUBKEY(nullptr, &keyDataBytes, keyData.size());
148
149 return extractPublicKey(public_key);
150}
151
152Result<std::vector<uint8_t>> extractPublicKeyFromX509(const std::string& path) {
153 X509* cert;
154 auto f = fopen(path.c_str(), "r");
155 if (!d2i_X509_fp(f, &cert)) {
156 return Error() << "Unable to decode x509 cert at " << path;
157 }
158
159 fclose(f);
160 return extractPublicKey(X509_get_pubkey(cert));
161}
162
163Result<std::vector<uint8_t>> createPkcs7(const std::vector<uint8_t>& signed_digest) {
164 CBB out, outer_seq, wrapped_seq, seq, digest_algos_set, digest_algo, null;
165 CBB content_info, issuer_and_serial, signer_infos, signer_info, sign_algo, signature;
166 uint8_t *pkcs7_data, *name_der;
167 size_t pkcs7_data_len, name_der_len;
168 BIGNUM* serial = BN_new();
169 int sig_nid = NID_rsaEncryption;
170
171 X509_NAME* name = X509_NAME_new();
172 if (!name) {
173 return Error() << "Unable to get x509 subject name";
174 }
175 X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC,
176 reinterpret_cast<const unsigned char*>("US"), -1, -1, 0);
177 X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC,
178 reinterpret_cast<const unsigned char*>("Android"), -1, -1, 0);
179 X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,
180 reinterpret_cast<const unsigned char*>("ODS"), -1, -1, 0);
181
182 BN_set_word(serial, 1);
183 name_der_len = i2d_X509_NAME(name, &name_der);
184 CBB_init(&out, 1024);
185
186 if (!CBB_add_asn1(&out, &outer_seq, CBS_ASN1_SEQUENCE) ||
187 !OBJ_nid2cbb(&outer_seq, NID_pkcs7_signed) ||
188 !CBB_add_asn1(&outer_seq, &wrapped_seq,
189 CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0) ||
190 // See https://tools.ietf.org/html/rfc2315#section-9.1
191 !CBB_add_asn1(&wrapped_seq, &seq, CBS_ASN1_SEQUENCE) ||
192 !CBB_add_asn1_uint64(&seq, 1 /* version */) ||
193 !CBB_add_asn1(&seq, &digest_algos_set, CBS_ASN1_SET) ||
194 !CBB_add_asn1(&digest_algos_set, &digest_algo, CBS_ASN1_SEQUENCE) ||
195 !OBJ_nid2cbb(&digest_algo, NID_sha256) ||
196 !CBB_add_asn1(&digest_algo, &null, CBS_ASN1_NULL) ||
197 !CBB_add_asn1(&seq, &content_info, CBS_ASN1_SEQUENCE) ||
198 !OBJ_nid2cbb(&content_info, NID_pkcs7_data) ||
199 !CBB_add_asn1(&seq, &signer_infos, CBS_ASN1_SET) ||
200 !CBB_add_asn1(&signer_infos, &signer_info, CBS_ASN1_SEQUENCE) ||
201 !CBB_add_asn1_uint64(&signer_info, 1 /* version */) ||
202 !CBB_add_asn1(&signer_info, &issuer_and_serial, CBS_ASN1_SEQUENCE) ||
203 !CBB_add_bytes(&issuer_and_serial, name_der, name_der_len) ||
204 !BN_marshal_asn1(&issuer_and_serial, serial) ||
205 !CBB_add_asn1(&signer_info, &digest_algo, CBS_ASN1_SEQUENCE) ||
206 !OBJ_nid2cbb(&digest_algo, NID_sha256) ||
207 !CBB_add_asn1(&digest_algo, &null, CBS_ASN1_NULL) ||
208 !CBB_add_asn1(&signer_info, &sign_algo, CBS_ASN1_SEQUENCE) ||
209 !OBJ_nid2cbb(&sign_algo, sig_nid) || !CBB_add_asn1(&sign_algo, &null, CBS_ASN1_NULL) ||
210 !CBB_add_asn1(&signer_info, &signature, CBS_ASN1_OCTETSTRING) ||
211 !CBB_add_bytes(&signature, signed_digest.data(), signed_digest.size()) ||
212 !CBB_finish(&out, &pkcs7_data, &pkcs7_data_len)) {
213 return Error() << "Failed to create PKCS7 certificate.";
214 }
215
216 return std::vector<uint8_t>(&pkcs7_data[0], &pkcs7_data[pkcs7_data_len]);
217}