Newer
Older
#include <vereign/crypto/cert.hh>
#include <vereign/crypto/bio.hh>
#include <vereign/crypto/errors.hh>
#include <vereign/encoding/base64.hh>
#include <openssl/x509v3.h>
#include <openssl/digest.h>
#include <openssl/pem.h>
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
namespace {
constexpr const char* certDefaultHashAlg = "SHA256";
constexpr const int certVersion = 2;
}
namespace vereign::crypto::cert {
static auto addCertExtension(
const X509* issuer_cert,
X509* cert,
int nid,
const std::string& value
) -> int {
X509V3_CTX ctx;
// This sets the 'context' of the extensions.
// No configuration database
X509V3_set_ctx_nodb(&ctx);
// Issuer and subject certs: both the target since it is self signed,
// no request and no CRL
X509V3_set_ctx(&ctx, const_cast<X509*>(issuer_cert), cert, nullptr, nullptr, 0);
bssl::UniquePtr<X509_EXTENSION> ex{X509V3_EXT_nconf_nid(
nullptr,
&ctx,
nid,
const_cast<std::string&>(value).data()
)};
if (!ex) {
return 0;
}
return X509_add_ext(cert, ex.get(), -1);
}
static void addSubjAltNameExt(X509* cert, const std::string& email, const std::string& url) {
auto gens = bssl::UniquePtr<GENERAL_NAMES>(sk_GENERAL_NAME_new_null());
if (!gens) {
throw OpenSSLError("creating GENERAL_NAMES stack failed");
}
if (!email.empty()) {
auto gen = bssl::UniquePtr<GENERAL_NAME>(GENERAL_NAME_new());
if (!gen) {
throw OpenSSLError("creating GENERAL_NAME failed");
}
auto ia5 = bssl::UniquePtr<ASN1_IA5STRING>(ASN1_IA5STRING_new());
if (!ia5) {
throw OpenSSLError("creating ASN1_IA5STRING failed");
}
auto r = ASN1_STRING_set(ia5.get(), email.data(), -1);
if (r != 1) {
throw OpenSSLError("set certificate alternative name email part failed");
}
GENERAL_NAME_set0_value(gen.get(), GEN_EMAIL, ia5.release());
r = sk_GENERAL_NAME_push(gens.get(), gen.release());
if (r == 0) {
throw OpenSSLError("pushing email to certificate subject alternative name failed");
}
}
if (!url.empty()) {
auto gen = bssl::UniquePtr<GENERAL_NAME>(GENERAL_NAME_new());
if (!gen) {
throw OpenSSLError("creating GENERAL_NAME failed");
}
auto ia5 = bssl::UniquePtr<ASN1_IA5STRING>(ASN1_IA5STRING_new());
if (!ia5) {
throw OpenSSLError("creating ASN1_IA5STRING failed");
}
auto r = ASN1_STRING_set(ia5.get(), url.data(), -1);
if (r != 1) {
throw OpenSSLError("set certificate alternative name URL part failed");
}
GENERAL_NAME_set0_value(gen.get(), GEN_DNS, ia5.release());
r = sk_GENERAL_NAME_push(gens.get(), gen.release());
if (r == 0) {
throw OpenSSLError("pushing URL to certificate subject alternative name failed");
}
}
auto r = X509_add1_ext_i2d(cert, NID_subject_alt_name, gens.get(), 0, 0);
if (r != 1) {
throw OpenSSLError("set certificate alternative name failed");
}
}
static void setCertSubject(const CertData& cert_data, X509* cert) {
const CertSubject& subject = cert_data.Subject;
auto subject_name = X509_get_subject_name(cert);
int r = 0;
if (!subject.CommonName.empty()) {
r = X509_NAME_add_entry_by_NID(
subject_name,
NID_commonName,
MBSTRING_ASC,
(unsigned char*) subject.CommonName.data(),
-1,
-1,
0
);
if (r != 1) {
throw OpenSSLError("set certificate subject Common Name failed");
}
}
if (!subject.Country.empty()) {
r = X509_NAME_add_entry_by_NID(
subject_name,
NID_countryName,
MBSTRING_ASC,
(unsigned char*) subject.Country.data(),
-1,
-1,
0
);
if (r != 1) {
throw OpenSSLError("set certificate subject Country Name failed");
}
}
if (!subject.Locality.empty()) {
r = X509_NAME_add_entry_by_NID(
subject_name,
NID_localityName,
MBSTRING_ASC,
(unsigned char*) subject.Locality.data(),
-1,
-1,
0
);
if (r != 1) {
throw OpenSSLError("set certificate subject Locality Name failed");
}
}
if (!subject.State.empty()) {
r = X509_NAME_add_entry_by_NID(
subject_name,
NID_stateOrProvinceName,
MBSTRING_ASC,
(unsigned char*) subject.State.data(),
-1,
-1,
0
);
if (r != 1) {
throw OpenSSLError("set certificate subject State Name failed");
}
}
if (!subject.Organization.empty()) {
r = X509_NAME_add_entry_by_NID(
subject_name,
NID_organizationName,
MBSTRING_ASC,
(unsigned char*) subject.Organization.data(),
-1,
-1,
0
);
if (r != 1) {
throw OpenSSLError("set certificate subject Organization Name failed");
}
}
if (!subject.OrganizationUnit.empty()) {
r = X509_NAME_add_entry_by_NID(
subject_name,
NID_organizationalUnitName,
MBSTRING_ASC,
(unsigned char*) subject.OrganizationUnit.data(),
-1,
-1,
0
);
if (r != 1) {
throw OpenSSLError("set certificate subject Organizational Unit Name failed");
}
}
if (!cert_data.Email.empty()) {
r = X509_NAME_add_entry_by_NID(
subject_name,
NID_pkcs9_emailAddress,
MBSTRING_ASC,
(unsigned char*) cert_data.Email.data(),
-1,
-1,
0
);
if (r != 1) {
throw OpenSSLError("set certificate subject Email Address failed");
}
}
}
static void addCertExtensions(const CertData& cert_data, const X509* issuer_cert, X509* cert) {
// basic constraints
const std::string basic_constraints = cert_data.IsCA ? "critical,CA:TRUE" : "critical,CA:FALSE";
auto r = addCertExtension(issuer_cert, cert, NID_basic_constraints, basic_constraints);
if (r != 1) {
throw OpenSSLError("set certificate basic constraints failed");
}
// key usage
const std::string key_usage = cert_data.IsCA
? "critical,digitalSignature,keyCertSign,cRLSign"
: "critical,digitalSignature,nonRepudiation,keyEncipherment,dataEncipherment";
r = addCertExtension(issuer_cert, cert, NID_key_usage, key_usage);
if (r != 1) {
throw OpenSSLError("set certificate key usage failed");
}
// extended key usage
if (!cert_data.IsCA && !cert_data.Email.empty()) {
r = addCertExtension(issuer_cert, cert, NID_ext_key_usage, "emailProtection");
if (r != 1) {
throw OpenSSLError("set certificate extended key usage failed");
}
}
// subject alternative name
if (!cert_data.Email.empty() || !cert_data.Url.empty()) {
addSubjAltNameExt(cert, cert_data.Email, cert_data.Url);
}
// subject key identifier
r = addCertExtension(issuer_cert, cert, NID_subject_key_identifier, "hash");
if (r != 1) {
throw OpenSSLError("set certificate key usage failed");
}
// authority key identifier
r = addCertExtension(issuer_cert, cert, NID_authority_key_identifier, "keyid,issuer:always");
if (r != 1) {
throw OpenSSLError("set certificate key usage failed");
}
}
static void setCertValidity(const CertData& cert_data, X509* cert) {
using clock = std::chrono::system_clock;
long not_before_adj = 0;
time_t not_before = cert_data.Validity.NotBefore;
if (not_before == 0) {
auto now = clock::now();
not_before = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch()).count();
not_before_adj = -(not_before % (24 * 60 * 60));
}
auto timeret = X509_time_adj(X509_get_notBefore(cert), not_before_adj, ¬_before);
if (timeret == nullptr) {
throw OpenSSLError("adjusting certificate not before validity failed");
}
long not_after_adj = 0;
time_t not_after = cert_data.Validity.NotAfter;
if (not_after == 0) {
not_after = not_before;
int valid_years = cert_data.Validity.ValidYears;
if (valid_years == 0) {
valid_years = 1;
}
not_after_adj = not_before_adj + valid_years * 365 * 24 * 60 * 60;
}
timeret = X509_time_adj(X509_get_notAfter(cert), not_after_adj, ¬_after);
if (timeret == nullptr) {
throw OpenSSLError("adjusting certificate not after validity failed");
}
}
static auto createCert(
const CertData& cert_data,
const X509* issuer_cert,
const EVP_PKEY* issuer_pkey,
const EVP_PKEY* pkey
) -> bssl::UniquePtr<X509> {
const EVP_MD* hash_alg = nullptr;
if (cert_data.Algorithms.HashAlg.empty()) {
hash_alg = EVP_get_digestbyname(certDefaultHashAlg);
} else {
hash_alg = EVP_get_digestbyname(cert_data.Algorithms.HashAlg.data());
}
if (hash_alg == nullptr) {
throw crypto::OpenSSLError("cannot find hash algorithm");
}
auto cert = bssl::UniquePtr<X509>(X509_new());
if (issuer_cert == nullptr || issuer_pkey == nullptr) {
issuer_cert = cert.get();
issuer_pkey = pkey;
}
// set public key
auto r = X509_set_pubkey(cert.get(), const_cast<EVP_PKEY*>(pkey));
if (r != 1) {
throw OpenSSLError("set public key to certificate failed");
}
// set certificate version
r = X509_set_version(cert.get(), certVersion);
if (r != 1) {
throw OpenSSLError("set version to certificate failed");
}
// set serial number
auto serial_number = cert_data.SerialNumber;
if (serial_number == 0) {
// FIXME: is using time ok ?
serial_number = std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::system_clock::now().time_since_epoch()
).count();
}
r = ASN1_INTEGER_set_uint64(X509_get_serialNumber(cert.get()), serial_number);
if (r != 1) {
throw OpenSSLError("set certificate serial number");
}
// set subject
setCertSubject(cert_data, cert.get());
// set issuer name
auto issuer_name = X509_get_subject_name(const_cast<X509*>(issuer_cert));
r = X509_set_issuer_name(cert.get(), issuer_name);
if (r != 1) {
throw OpenSSLError("set certificate issuer name failed");
}
// set validity
setCertValidity(cert_data, cert.get());
// add extensions
addCertExtensions(cert_data, issuer_cert, cert.get());
r = X509_sign(cert.get(), const_cast<EVP_PKEY*>(issuer_pkey), hash_alg);
if (r == 0) {
throw OpenSSLError("certificate sign failed");
}
return cert;
}
auto CreateCert(
const CertData& cert_data,
const X509* issuer_cert,
const EVP_PKEY* issuer_pkey,
const EVP_PKEY* pkey
) -> bssl::UniquePtr<X509> {
return createCert(cert_data, issuer_cert, issuer_pkey, pkey);
}
auto CreateSelfSignedCert(
const CertData& cert_data,
const EVP_PKEY* pkey
) -> bssl::UniquePtr<X509> {
return createCert(cert_data, nullptr, nullptr, pkey);
}
auto ExportCertToPEM(const X509* cert) -> bssl::UniquePtr<BIO> {
bssl::UniquePtr<BIO> mem(BIO_new(BIO_s_mem()));
if (!mem) {
throw OpenSSLError("creating memory buffer failed");
}
auto r = PEM_write_bio_X509(mem.get(), const_cast<X509*>(cert));
if (r != 1) {
throw OpenSSLError("exporting certificate to PEM failed");
}
return mem;
}
auto ImportCertFromPEM(bytes::View pem) -> bssl::UniquePtr<X509> {
bssl::UniquePtr<BIO> mem(BIO_new_mem_buf(pem.Data(), pem.Size()));
if (mem == nullptr) {
throw OpenSSLError("creating memory buffer failed");
}
auto cert = bssl::UniquePtr<X509>(PEM_read_bio_X509(mem.get(), nullptr, nullptr, nullptr));
if (cert == nullptr) {
throw OpenSSLError("importing certificate from PEM failed");
}
return cert;
}
void PrintCert(std::ostream& os, const X509* cert) {
bssl::UniquePtr<BIO> mem(BIO_new(BIO_s_mem()));
if (!mem) {
throw OpenSSLError("creating memory buffer failed");
}
auto r = X509_print(mem.get(), const_cast<X509*>(cert));
if (r != 1) {
throw OpenSSLError("printing certificate failed");
}
os << bio::View(mem.get()).String();
}
} // vereign::crypto::cert