-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathMkCert.cpp
373 lines (344 loc) · 13.4 KB
/
MkCert.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
/*
* MkCert.cpp
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2013-2024 Apple Inc. and the FoundationDB project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "flow/Arena.h"
#include "flow/AutoCPointer.h"
#include "flow/IRandom.h"
#include "flow/MkCert.h"
#include "flow/PKey.h"
#include "flow/ScopeExit.h"
#include "flow/Trace.h"
#include <limits>
#include <memory>
#include <string>
#include <cstring>
#include <openssl/bio.h>
#include <openssl/ec.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/objects.h>
#include <openssl/pem.h>
#include <openssl/rsa.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
namespace {
[[noreturn]] void traceAndThrow(const char* condition, int line) {
auto te = TraceEvent(SevWarnAlways, "MkCertOrKeyError");
te.suppressFor(10).detail("Line", line).detail("Condition", condition);
if (auto err = ::ERR_get_error()) {
char buf[256]{
0,
};
::ERR_error_string_n(err, buf, sizeof(buf));
te.detail("OpenSSLError", static_cast<const char*>(buf));
}
throw tls_error();
}
} // anonymous namespace
#define OSSL_ASSERT(condition) \
do { \
if (!(condition)) \
traceAndThrow(#condition, __LINE__); \
} while (false)
namespace mkcert {
// Helper functions working with OpenSSL native types
std::shared_ptr<X509> readX509CertPem(StringRef x509CertPem);
StringRef writeX509CertPem(Arena& arena, const std::shared_ptr<X509>& nativeCert);
struct CertAndKeyNative {
std::shared_ptr<X509> cert;
PrivateKey privateKey;
bool valid() const noexcept { return cert && privateKey; }
// self-signed cert case
bool null() const noexcept { return !cert && !privateKey; }
using SelfType = CertAndKeyNative;
using PemType = CertAndKeyRef;
static SelfType fromPem(PemType certAndKey) {
auto ret = SelfType{};
if (certAndKey.empty())
return ret;
auto [certPem, keyPem] = certAndKey;
// either both set or both unset
ASSERT(!certPem.empty() && !keyPem.empty());
ret.cert = readX509CertPem(certPem);
ret.privateKey = PrivateKey(PemEncoded{}, keyPem);
return ret;
}
PemType toPem(Arena& arena) {
auto ret = PemType{};
if (null())
return ret;
ASSERT(valid());
ret.certPem = writeX509CertPem(arena, cert);
ret.privateKeyPem = privateKey.writePem(arena);
return ret;
}
};
CertAndKeyNative makeCertNative(CertSpecRef spec, CertAndKeyNative issuer);
void printCert(FILE* out, StringRef certPem) {
auto x = readX509CertPem(certPem);
OSSL_ASSERT(0 < ::X509_print_fp(out, x.get()));
}
void printPrivateKey(FILE* out, StringRef privateKeyPem) {
auto key = PrivateKey(PemEncoded{}, privateKeyPem);
auto bio = AutoCPointer(::BIO_new_fp(out, BIO_NOCLOSE), &::BIO_free);
OSSL_ASSERT(bio);
OSSL_ASSERT(0 < ::EVP_PKEY_print_private(bio, key.nativeHandle(), 0, nullptr));
}
std::shared_ptr<X509> readX509CertPem(StringRef x509CertPem) {
ASSERT(!x509CertPem.empty());
auto bio_mem = AutoCPointer(::BIO_new_mem_buf(x509CertPem.begin(), x509CertPem.size()), &::BIO_free);
OSSL_ASSERT(bio_mem);
auto ret = ::PEM_read_bio_X509(bio_mem, nullptr, nullptr, nullptr);
OSSL_ASSERT(ret);
return std::shared_ptr<X509>(ret, &::X509_free);
}
StringRef writeX509CertPem(Arena& arena, const std::shared_ptr<X509>& nativeCert) {
auto mem = AutoCPointer(::BIO_new(::BIO_s_mem()), &::BIO_free);
OSSL_ASSERT(mem);
OSSL_ASSERT(::PEM_write_bio_X509(mem, nativeCert.get()));
auto bioBuf = std::add_pointer_t<char>{};
auto const len = ::BIO_get_mem_data(mem, &bioBuf);
ASSERT_GT(len, 0);
auto buf = new (arena) uint8_t[len];
::memcpy(buf, bioBuf, len);
return StringRef(buf, static_cast<int>(len));
}
PrivateKey makeEcP256() {
auto params = AutoCPointer(nullptr, &::EVP_PKEY_free);
{
auto paramsRaw = std::add_pointer_t<EVP_PKEY>();
auto pctx = AutoCPointer(::EVP_PKEY_CTX_new_id(EVP_PKEY_EC, nullptr), &::EVP_PKEY_CTX_free);
OSSL_ASSERT(pctx);
OSSL_ASSERT(0 < ::EVP_PKEY_paramgen_init(pctx));
OSSL_ASSERT(0 < ::EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx, NID_X9_62_prime256v1));
OSSL_ASSERT(0 < ::EVP_PKEY_paramgen(pctx, ¶msRaw));
OSSL_ASSERT(paramsRaw);
params.reset(paramsRaw);
}
// keygen
auto kctx = AutoCPointer(::EVP_PKEY_CTX_new(params, nullptr), &::EVP_PKEY_CTX_free);
OSSL_ASSERT(kctx);
auto key = AutoCPointer(nullptr, &::EVP_PKEY_free);
auto keyRaw = std::add_pointer_t<EVP_PKEY>();
OSSL_ASSERT(0 < ::EVP_PKEY_keygen_init(kctx));
OSSL_ASSERT(0 < ::EVP_PKEY_keygen(kctx, &keyRaw));
OSSL_ASSERT(keyRaw);
key.reset(keyRaw);
auto len = 0;
len = ::i2d_PrivateKey(key, nullptr);
ASSERT_LT(0, len);
auto tmpArena = Arena();
auto buf = new (tmpArena) uint8_t[len];
auto out = std::add_pointer_t<uint8_t>(buf);
len = ::i2d_PrivateKey(key, &out);
return PrivateKey(DerEncoded{}, StringRef(buf, len));
}
PrivateKey makeRsa4096Bit() {
auto kctx = AutoCPointer(::EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, nullptr), &::EVP_PKEY_CTX_free);
OSSL_ASSERT(kctx);
auto key = AutoCPointer(nullptr, &::EVP_PKEY_free);
auto keyRaw = std::add_pointer_t<EVP_PKEY>();
OSSL_ASSERT(0 < ::EVP_PKEY_keygen_init(kctx));
OSSL_ASSERT(0 < ::EVP_PKEY_CTX_set_rsa_keygen_bits(kctx, 4096));
OSSL_ASSERT(0 < ::EVP_PKEY_keygen(kctx, &keyRaw));
OSSL_ASSERT(keyRaw);
key.reset(keyRaw);
auto len = 0;
len = ::i2d_PrivateKey(key, nullptr);
ASSERT_LT(0, len);
auto tmpArena = Arena();
auto buf = new (tmpArena) uint8_t[len];
auto out = std::add_pointer_t<uint8_t>(buf);
len = ::i2d_PrivateKey(key, &out);
return PrivateKey(DerEncoded{}, StringRef(buf, len));
}
CertAndKeyNative makeCertNative(CertSpecRef spec, CertAndKeyNative issuer) {
// issuer key/cert must be both set or both null (self-signed case)
ASSERT(issuer.valid() || issuer.null());
auto const isSelfSigned = issuer.null();
auto keypair = makeEcP256();
auto newX = ::X509_new();
OSSL_ASSERT(newX);
auto x509Guard = ScopeExit([&newX]() {
if (newX)
::X509_free(newX);
});
auto smartX = std::shared_ptr<X509>(newX, &::X509_free);
newX = nullptr;
auto x = smartX.get();
OSSL_ASSERT(0 < ::X509_set_version(x, 2 /*X509_VERSION_3*/));
auto serialPtr = ::X509_get_serialNumber(x);
OSSL_ASSERT(serialPtr);
OSSL_ASSERT(0 < ::ASN1_INTEGER_set(serialPtr, spec.serialNumber));
auto notBefore = ::X509_getm_notBefore(x);
OSSL_ASSERT(notBefore);
OSSL_ASSERT(::X509_gmtime_adj(notBefore, spec.offsetNotBefore));
auto notAfter = ::X509_getm_notAfter(x);
OSSL_ASSERT(notAfter);
OSSL_ASSERT(::X509_gmtime_adj(notAfter, spec.offsetNotAfter));
OSSL_ASSERT(0 < ::X509_set_pubkey(x, keypair.nativeHandle()));
auto subjectName = ::X509_get_subject_name(x);
OSSL_ASSERT(subjectName);
for (const auto& entry : spec.subjectName) {
// field names are expected to null-terminate
auto fieldName = entry.field.toString();
OSSL_ASSERT(0 <
::X509_NAME_add_entry_by_txt(
subjectName, fieldName.c_str(), MBSTRING_ASC, entry.bytes.begin(), entry.bytes.size(), -1, 0));
}
auto issuerName = ::X509_get_issuer_name(x);
OSSL_ASSERT(issuerName);
OSSL_ASSERT(::X509_set_issuer_name(x, (isSelfSigned ? subjectName : ::X509_get_subject_name(issuer.cert.get()))));
auto ctx = X509V3_CTX{};
X509V3_set_ctx_nodb(&ctx);
::X509V3_set_ctx(&ctx, (isSelfSigned ? x : issuer.cert.get()), x, nullptr, nullptr, 0);
for (const auto& entry : spec.extensions) {
// extension field names and values are expected to null-terminate
auto extName = entry.field.toString();
auto extValue = entry.bytes.toString();
auto extNid = ::OBJ_txt2nid(extName.c_str());
if (extNid == NID_undef) {
TraceEvent(SevWarnAlways, "MkCertInvalidExtName").suppressFor(10).detail("Name", extName);
throw tls_error();
}
#ifdef OPENSSL_IS_BORINGSSL
auto ext = ::X509V3_EXT_nconf_nid(nullptr, &ctx, extNid, const_cast<char*>(extValue.c_str()));
#else
auto ext = ::X509V3_EXT_nconf_nid(nullptr, &ctx, extNid, extValue.c_str());
#endif
OSSL_ASSERT(ext);
auto extGuard = ScopeExit([ext]() { ::X509_EXTENSION_free(ext); });
OSSL_ASSERT(::X509_add_ext(x, ext, -1));
}
OSSL_ASSERT(
::X509_sign(x, (isSelfSigned ? keypair.nativeHandle() : issuer.privateKey.nativeHandle()), ::EVP_sha256()));
auto ret = CertAndKeyNative{};
ret.cert = smartX;
ret.privateKey = keypair;
return ret;
}
CertAndKeyRef CertAndKeyRef::make(Arena& arena, CertSpecRef spec, CertAndKeyRef issuerPem) {
auto issuer = CertAndKeyNative::fromPem(issuerPem);
auto newCertAndKey = makeCertNative(spec, issuer);
return newCertAndKey.toPem(arena);
}
CertSpecRef CertSpecRef::make(Arena& arena, CertKind kind) {
auto spec = CertSpecRef{};
spec.serialNumber = static_cast<long>(deterministicRandom()->randomInt64(0, 1e10));
spec.offsetNotBefore = 0; // now
spec.offsetNotAfter = 60 * 60 * 24 * 365; // 1 year from now
auto& subject = spec.subjectName;
subject.push_back(arena, { "countryName"_sr, "DE"_sr });
subject.push_back(arena, { "localityName"_sr, "Berlin"_sr });
subject.push_back(arena, { "organizationName"_sr, "FoundationDB"_sr });
subject.push_back(arena, { "commonName"_sr, kind.getCommonName("FDB Testing Services"_sr, arena) });
auto& ext = spec.extensions;
if (kind.isCA()) {
ext.push_back(arena, { "basicConstraints"_sr, "critical, CA:TRUE"_sr });
ext.push_back(arena, { "keyUsage"_sr, "critical, digitalSignature, keyCertSign, cRLSign"_sr });
} else {
ext.push_back(arena, { "basicConstraints"_sr, "critical, CA:FALSE"_sr });
ext.push_back(arena, { "keyUsage"_sr, "critical, digitalSignature, keyEncipherment"_sr });
ext.push_back(arena, { "extendedKeyUsage"_sr, "serverAuth, clientAuth"_sr });
}
ext.push_back(arena, { "subjectKeyIdentifier"_sr, "hash"_sr });
if (!kind.isRootCA())
ext.push_back(arena, { "authorityKeyIdentifier"_sr, "keyid, issuer"_sr });
return spec;
}
StringRef concatCertChain(Arena& arena, CertChainRef chain) {
auto len = 0;
for (const auto& entry : chain) {
len += entry.certPem.size();
}
if (len == 0)
return StringRef();
auto buf = new (arena) uint8_t[len];
auto offset = 0;
for (auto const& entry : chain) {
::memcpy(&buf[offset], entry.certPem.begin(), entry.certPem.size());
offset += entry.certPem.size();
}
UNSTOPPABLE_ASSERT(offset == len);
return StringRef(buf, len);
}
CertChainRef makeCertChain(Arena& arena, VectorRef<CertSpecRef> specs, Optional<CertAndKeyRef> rootAuthority) {
ASSERT_GT(specs.size(), 0);
// if rootAuthority is empty, use last element in specs to make root CA
if (!rootAuthority.present()) {
int const chainLength = specs.size();
auto chain = new (arena) CertAndKeyRef[chainLength];
auto caNative = makeCertNative(specs.back(), CertAndKeyNative{} /* empty issuer == self-signed */);
chain[chainLength - 1] = caNative.toPem(arena);
for (auto i = chainLength - 2; i >= 0; i--) {
auto cnkNative = makeCertNative(specs[i], caNative);
chain[i] = cnkNative.toPem(arena);
caNative = cnkNative;
}
return CertChainRef(chain, chainLength);
} else {
int const chainLength = specs.size() + 1; /* account for deep-copied rootAuthority */
auto chain = new (arena) CertAndKeyRef[chainLength];
auto caNative = CertAndKeyNative::fromPem(rootAuthority.get());
chain[chainLength - 1] = rootAuthority.get().deepCopy(arena);
for (auto i = chainLength - 2; i >= 0; i--) {
auto cnkNative = makeCertNative(specs[i], caNative);
chain[i] = cnkNative.toPem(arena);
caNative = cnkNative;
}
return CertChainRef(chain, chainLength);
}
}
VectorRef<CertSpecRef> makeCertChainSpec(Arena& arena, unsigned length, ESide side) {
if (!length)
return {};
auto specs = new (arena) CertSpecRef[length];
auto const isServerSide = side == ESide::Server;
for (auto i = 0u; i < length; i++) {
auto kind = CertKind{};
if (i == 0u)
kind = isServerSide ? CertKind(Server{}) : CertKind(Client{});
else if (i == length - 1)
kind = isServerSide ? CertKind(ServerRootCA{}) : CertKind(ClientRootCA{});
else
kind = isServerSide ? CertKind(ServerIntermediateCA{ i }) : CertKind(ClientIntermediateCA{ i });
specs[i] = CertSpecRef::make(arena, kind);
}
return VectorRef<CertSpecRef>(specs, length);
}
CertChainRef makeCertChain(Arena& arena, unsigned length, ESide side) {
if (!length)
return {};
// temporary arena for writing up specs
auto tmpArena = Arena();
auto specs = makeCertChainSpec(tmpArena, length, side);
return makeCertChain(arena, specs, {} /*root*/);
}
StringRef CertKind::getCommonName(StringRef prefix, Arena& arena) const {
auto const side = std::string(isClientSide() ? " Client" : " Server");
if (isIntermediateCA()) {
auto const level = isClientSide() ? get<ClientIntermediateCA>().level : get<ServerIntermediateCA>().level;
return prefix.withSuffix(fmt::format("{} Intermediate {}", side, level), arena);
} else if (isRootCA()) {
return prefix.withSuffix(fmt::format("{} Root", side), arena);
} else {
return prefix.withSuffix(side, arena);
}
}
} // namespace mkcert