forked from ibm-openbmc/phosphor-certificate-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
certs_manager.cpp
507 lines (460 loc) · 16 KB
/
certs_manager.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
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
#include "certs_manager.hpp"
#include <openssl/pem.h>
#include <unistd.h>
#include <phosphor-logging/elog-errors.hpp>
#include <xyz/openbmc_project/Certs/error.hpp>
#include <xyz/openbmc_project/Common/error.hpp>
namespace phosphor
{
namespace certs
{
using InternalFailure =
sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure;
using InvalidCertificate =
sdbusplus::xyz::openbmc_project::Certs::Error::InvalidCertificate;
using Reason = xyz::openbmc_project::Certs::InvalidCertificate::REASON;
using X509_REQ_Ptr = std::unique_ptr<X509_REQ, decltype(&::X509_REQ_free)>;
using BIGNUM_Ptr = std::unique_ptr<BIGNUM, decltype(&::BN_free)>;
Manager::Manager(sdbusplus::bus::bus& bus, sdeventplus::Event& event,
const char* path, const CertificateType& type,
UnitsToRestart&& unit, CertInstallPath&& installPath) :
Ifaces(bus, path),
bus(bus), event(event), objectPath(path), certType(type),
unitToRestart(std::move(unit)), certInstallPath(std::move(installPath))
{
// restore any existing certificates
if (fs::exists(certInstallPath))
{
createCertificate();
}
// watch is not required for authority certificates
if (certType != AUTHORITY)
{
// watch for certificate file create/replace
certWatchPtr = std::make_unique<
Watch>(event, certInstallPath, [this]() {
try
{
// if certificate file existing update it
if (certificatePtr != nullptr)
{
log<level::INFO>(
"Inotify callback to update certificate properties");
certificatePtr->populateProperties();
}
else
{
log<level::INFO>(
"Inotify callback to create certificate object");
createCertificate();
}
}
catch (const InternalFailure& e)
{
commit<InternalFailure>();
}
catch (const InvalidCertificate& e)
{
commit<InvalidCertificate>();
}
});
}
}
void Manager::install(const std::string filePath)
{
using NotAllowed =
sdbusplus::xyz::openbmc_project::Common::Error::NotAllowed;
using Reason = xyz::openbmc_project::Common::NotAllowed::REASON;
// TODO: Issue#3 At present supporting only one certificate to be
// uploaded this need to be revisited to support multiple
// certificates
if (certificatePtr != nullptr)
{
elog<NotAllowed>(Reason("Certificate already exist"));
}
auto certObjectPath = objectPath + '/' + '1';
certificatePtr = std::make_unique<Certificate>(
bus, certObjectPath, certType, unitToRestart, certInstallPath, filePath,
false, certWatchPtr);
}
void Manager::delete_()
{
// TODO: #Issue 4 when a certificate is deleted system auto generates
// certificate file. At present we are not supporting creation of
// certificate object for the auto-generated certificate file as
// deletion if only applicable for REST server and Bmcweb does not allow
// deletion of certificates
if (certificatePtr != nullptr)
{
certificatePtr.reset(nullptr);
}
}
std::string Manager::generateCSR(
std::vector<std::string> alternativeNames, std::string challengePassword,
std::string city, std::string commonName, std::string contactPerson,
std::string country, std::string email, std::string givenName,
std::string initials, int64_t keyBitLength, std::string keyCurveId,
std::string keyPairAlgorithm, std::vector<std::string> keyUsage,
std::string organization, std::string organizationalUnit, std::string state,
std::string surname, std::string unstructuredName)
{
// We support only one CSR.
csrPtr.reset(nullptr);
auto pid = fork();
if (pid == -1)
{
log<level::ERR>("Error occurred during forking process");
report<InternalFailure>();
}
else if (pid == 0)
{
try
{
generateCSRHelper(alternativeNames, challengePassword, city,
commonName, contactPerson, country, email,
givenName, initials, keyBitLength, keyCurveId,
keyPairAlgorithm, keyUsage, organization,
organizationalUnit, state, surname,
unstructuredName);
exit(EXIT_SUCCESS);
}
catch (const InternalFailure& e)
{
// commit the error reported in child process and exit
// Callback method from SDEvent Loop looks for exit status
exit(EXIT_FAILURE);
commit<InternalFailure>();
}
}
else
{
using namespace sdeventplus::source;
Child::Callback callback = [this](Child& eventSource,
const siginfo_t* si) {
eventSource.set_enabled(Enabled::On);
if (si->si_status != 0)
{
this->createCSRObject(Status::FAILURE);
}
else
{
this->createCSRObject(Status::SUCCESS);
}
};
try
{
sigset_t ss;
if (sigemptyset(&ss) < 0)
{
log<level::ERR>("Unable to initialize signal set");
elog<InternalFailure>();
}
if (sigaddset(&ss, SIGCHLD) < 0)
{
log<level::ERR>("Unable to add signal to signal set");
elog<InternalFailure>();
}
// Block SIGCHLD first, so that the event loop can handle it
if (sigprocmask(SIG_BLOCK, &ss, NULL) < 0)
{
log<level::ERR>("Unable to block signal");
elog<InternalFailure>();
}
if (childPtr)
{
childPtr.reset();
}
childPtr = std::make_unique<Child>(event, pid, WEXITED | WSTOPPED,
std::move(callback));
}
catch (const InternalFailure& e)
{
commit<InternalFailure>();
}
}
auto csrObjectPath = objectPath + '/' + "csr";
return csrObjectPath;
}
CertificatePtr& Manager::getCertificate()
{
return certificatePtr;
}
void Manager::generateCSRHelper(
std::vector<std::string> alternativeNames, std::string challengePassword,
std::string city, std::string commonName, std::string contactPerson,
std::string country, std::string email, std::string givenName,
std::string initials, int64_t keyBitLength, std::string keyCurveId,
std::string keyPairAlgorithm, std::vector<std::string> keyUsage,
std::string organization, std::string organizationalUnit, std::string state,
std::string surname, std::string unstructuredName)
{
int ret = 0;
// set version of x509 req
int nVersion = 1;
// TODO: Issue#6 need to make version number configurable
X509_REQ_Ptr x509Req(X509_REQ_new(), ::X509_REQ_free);
ret = X509_REQ_set_version(x509Req.get(), nVersion);
if (ret == 0)
{
log<level::ERR>("Error occured during X509_REQ_set_version call");
elog<InternalFailure>();
}
// set subject of x509 req
X509_NAME* x509Name = X509_REQ_get_subject_name(x509Req.get());
if (!alternativeNames.empty())
{
for (auto& name : alternativeNames)
{
addEntry(x509Name, "subjectAltName", name);
}
}
addEntry(x509Name, "challengePassword", challengePassword);
addEntry(x509Name, "L", city);
addEntry(x509Name, "CN", commonName);
addEntry(x509Name, "name", contactPerson);
addEntry(x509Name, "C", country);
addEntry(x509Name, "emailAddress", email);
addEntry(x509Name, "GN", givenName);
addEntry(x509Name, "initials", initials);
addEntry(x509Name, "algorithm", keyPairAlgorithm);
if (!keyUsage.empty())
{
for (auto& usage : keyUsage)
{
addEntry(x509Name, "keyUsage", usage);
}
}
addEntry(x509Name, "O", organization);
addEntry(x509Name, "ST", state);
addEntry(x509Name, "SN", surname);
addEntry(x509Name, "unstructuredName", unstructuredName);
EVP_PKEY_Ptr pKey(nullptr, ::EVP_PKEY_free);
log<level::INFO>("Given Key pair algorithm",
entry("KEYPAIRALGORITHM=%s", keyPairAlgorithm.c_str()));
// Used EC algorithm as default if user did not give algorithm type.
if (keyPairAlgorithm == "RSA")
pKey = std::move(generateRSAKeyPair(keyBitLength));
else if ((keyPairAlgorithm == "EC") || (keyPairAlgorithm.empty()))
pKey = std::move(generateECKeyPair(keyCurveId));
else
{
using InvalidArgument =
sdbusplus::xyz::openbmc_project::Common::Error::InvalidArgument;
using Argument = xyz::openbmc_project::Common::InvalidArgument;
log<level::ERR>("Given Key pair algorithm is not supported. Supporting "
"RSA and EC only");
elog<InvalidArgument>(
Argument::ARGUMENT_NAME("KEYPAIRALGORITHM"),
Argument::ARGUMENT_VALUE(keyPairAlgorithm.c_str()));
}
ret = X509_REQ_set_pubkey(x509Req.get(), pKey.get());
if (ret == 0)
{
log<level::ERR>("Error occured while setting Public key");
elog<InternalFailure>();
}
// Write private key to file
writePrivateKey(pKey);
// set sign key of x509 req
ret = X509_REQ_sign(x509Req.get(), pKey.get(), EVP_sha256());
if (ret == 0)
{
log<level::ERR>("Error occured while signing key of x509");
elog<InternalFailure>();
}
log<level::INFO>("Writing CSR to file");
std::string path = fs::path(certInstallPath).parent_path();
std::string csrFilePath = path + '/' + CSR_FILE_NAME;
writeCSR(csrFilePath, x509Req);
}
EVP_PKEY_Ptr Manager::generateRSAKeyPair(const int64_t keyBitLength)
{
int ret = 0;
// generate rsa key
BIGNUM_Ptr bne(BN_new(), ::BN_free);
ret = BN_set_word(bne.get(), RSA_F4);
if (ret == 0)
{
log<level::ERR>("Error occured during BN_set_word call");
elog<InternalFailure>();
}
int64_t keyBitLen = keyBitLength;
// set keybit length to default value if not set
if (keyBitLen <= 0)
{
constexpr auto DEFAULT_KEYBITLENGTH = 2048;
log<level::INFO>(
"KeyBitLength is not given.Hence, using default KeyBitLength",
entry("DEFAULTKEYBITLENGTH=%d", DEFAULT_KEYBITLENGTH));
keyBitLen = DEFAULT_KEYBITLENGTH;
}
RSA* rsa = RSA_new();
ret = RSA_generate_key_ex(rsa, keyBitLen, bne.get(), NULL);
if (ret != 1)
{
free(rsa);
log<level::ERR>("Error occured during RSA_generate_key_ex call",
entry("KEYBITLENGTH=%PRIu64", keyBitLen));
elog<InternalFailure>();
}
// set public key of x509 req
EVP_PKEY_Ptr pKey(EVP_PKEY_new(), ::EVP_PKEY_free);
ret = EVP_PKEY_assign_RSA(pKey.get(), rsa);
if (ret == 0)
{
free(rsa);
log<level::ERR>("Error occured during assign rsa key into EVP");
elog<InternalFailure>();
}
return pKey;
}
EVP_PKEY_Ptr Manager::generateECKeyPair(const std::string& curveId)
{
std::string curId(curveId);
if (curId.empty())
{
// secp224r1 is equal to RSA 2048 KeyBitLength. Refer RFC 5349
constexpr auto DEFAULT_KEYCURVEID = "secp224r1";
log<level::INFO>(
"KeyCurveId is not given. Hence using default curve id",
entry("DEFAULTKEYCURVEID=%s", DEFAULT_KEYCURVEID));
curId = DEFAULT_KEYCURVEID;
}
int ecGrp = OBJ_txt2nid(curId.c_str());
if (ecGrp == NID_undef)
{
log<level::ERR>(
"Error occured during convert the curve id string format into NID",
entry("KEYCURVEID=%s", curId.c_str()));
elog<InternalFailure>();
}
EC_KEY* ecKey = EC_KEY_new_by_curve_name(ecGrp);
if (ecKey == NULL)
{
log<level::ERR>(
"Error occured during create the EC_Key object from NID",
entry("ECGROUP=%d", ecGrp));
elog<InternalFailure>();
}
// If you want to save a key and later load it with
// SSL_CTX_use_PrivateKey_file, then you must set the OPENSSL_EC_NAMED_CURVE
// flag on the key.
EC_KEY_set_asn1_flag(ecKey, OPENSSL_EC_NAMED_CURVE);
int ret = EC_KEY_generate_key(ecKey);
if (ret == 0)
{
EC_KEY_free(ecKey);
log<level::ERR>("Error occured during generate EC key");
elog<InternalFailure>();
}
EVP_PKEY_Ptr pKey(EVP_PKEY_new(), ::EVP_PKEY_free);
ret = EVP_PKEY_assign_EC_KEY(pKey.get(), ecKey);
if (ret == 0)
{
EC_KEY_free(ecKey);
log<level::ERR>("Error occured during assign EC Key into EVP");
elog<InternalFailure>();
}
return pKey;
}
void Manager::writePrivateKey(const EVP_PKEY_Ptr& pKey)
{
log<level::INFO>("Writing private key to file");
// write private key to file
std::string path = fs::path(certInstallPath).parent_path();
std::string privKeyPath = path + '/' + PRIV_KEY_FILE_NAME;
FILE* fp = std::fopen(privKeyPath.c_str(), "w");
if (fp == NULL)
{
log<level::ERR>("Error occured creating private key file");
elog<InternalFailure>();
}
int ret = PEM_write_PrivateKey(fp, pKey.get(), NULL, NULL, 0, 0, NULL);
std::fclose(fp);
if (ret == 0)
{
log<level::ERR>("Error occured while writing private key to file");
elog<InternalFailure>();
}
}
void Manager::addEntry(X509_NAME* x509Name, const char* field,
const std::string& bytes)
{
if (bytes.empty())
{
return;
}
int ret = X509_NAME_add_entry_by_txt(
x509Name, field, MBSTRING_ASC,
reinterpret_cast<const unsigned char*>(bytes.c_str()), -1, -1, 0);
if (ret != 1)
{
log<level::ERR>("Unable to set entry", entry("FIELD=%s", field),
entry("VALUE=%s", bytes.c_str()));
elog<InternalFailure>();
}
}
void Manager::createCSRObject(const Status& status)
{
if (csrPtr)
{
csrPtr.reset(nullptr);
}
auto csrObjectPath = objectPath + '/' + "csr";
csrPtr = std::make_unique<CSR>(bus, csrObjectPath.c_str(),
certInstallPath.c_str(), status);
}
void Manager::writeCSR(const std::string& filePath, const X509_REQ_Ptr& x509Req)
{
if (fs::exists(filePath))
{
log<level::INFO>("Removing the existing file",
entry("FILENAME=%s", filePath.c_str()));
if (!fs::remove(filePath.c_str()))
{
log<level::ERR>("Unable to remove the file",
entry("FILENAME=%s", filePath.c_str()));
elog<InternalFailure>();
}
}
FILE* fp = NULL;
if ((fp = std::fopen(filePath.c_str(), "w")) == NULL)
{
log<level::ERR>("Error opening the file to write the CSR",
entry("FILENAME=%s", filePath.c_str()));
elog<InternalFailure>();
}
int rc = PEM_write_X509_REQ(fp, x509Req.get());
if (!rc)
{
log<level::ERR>("PEM write routine failed",
entry("FILENAME=%s", filePath.c_str()));
std::fclose(fp);
elog<InternalFailure>();
}
std::fclose(fp);
}
void Manager::createCertificate()
{
try
{
// TODO: Issue#3 At present supporting only one certificate to be
// uploaded this need to be revisited to support multiple
// certificates
auto certObjectPath = objectPath + '/' + '1';
certificatePtr = std::make_unique<Certificate>(
bus, certObjectPath, certType, unitToRestart, certInstallPath,
certInstallPath, true, certWatchPtr);
}
catch (const InternalFailure& e)
{
report<InternalFailure>();
}
catch (const InvalidCertificate& e)
{
report<InvalidCertificate>(
Reason("Existing certificate file is corrupted"));
}
}
} // namespace certs
} // namespace phosphor