blob: 15f93671411b610f9fb6e4bc18398e19b1f1ba68 [file] [log] [blame]
Marri Devender Rao6ceec402019-02-01 03:15:19 -06001#include "certificate.hpp"
2
3#include <openssl/bio.h>
4#include <openssl/crypto.h>
5#include <openssl/err.h>
6#include <openssl/evp.h>
7#include <openssl/pem.h>
8#include <openssl/x509v3.h>
9
10#include <fstream>
11#include <phosphor-logging/elog-errors.hpp>
Marri Devender Rao13bf74e2019-03-26 01:52:17 -050012#include <xyz/openbmc_project/Certs/error.hpp>
Marri Devender Rao6ceec402019-02-01 03:15:19 -060013#include <xyz/openbmc_project/Common/error.hpp>
Marri Devender Rao13bf74e2019-03-26 01:52:17 -050014
Marri Devender Rao6ceec402019-02-01 03:15:19 -060015namespace phosphor
16{
17namespace certs
18{
19// RAII support for openSSL functions.
20using BIO_MEM_Ptr = std::unique_ptr<BIO, decltype(&::BIO_free)>;
21using X509_STORE_CTX_Ptr =
22 std::unique_ptr<X509_STORE_CTX, decltype(&::X509_STORE_CTX_free)>;
23using X509_LOOKUP_Ptr =
24 std::unique_ptr<X509_LOOKUP, decltype(&::X509_LOOKUP_free)>;
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -060025using ASN1_TIME_ptr = std::unique_ptr<ASN1_TIME, decltype(&ASN1_STRING_free)>;
Marri Devender Rao6ceec402019-02-01 03:15:19 -060026using EVP_PKEY_Ptr = std::unique_ptr<EVP_PKEY, decltype(&::EVP_PKEY_free)>;
27using BUF_MEM_Ptr = std::unique_ptr<BUF_MEM, decltype(&::BUF_MEM_free)>;
28using InternalFailure =
29 sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure;
30using InvalidCertificate =
Marri Devender Rao13bf74e2019-03-26 01:52:17 -050031 sdbusplus::xyz::openbmc_project::Certs::Error::InvalidCertificate;
32using Reason = xyz::openbmc_project::Certs::InvalidCertificate::REASON;
Marri Devender Rao6ceec402019-02-01 03:15:19 -060033
34// Trust chain related errors.`
35#define TRUST_CHAIN_ERR(errnum) \
36 ((errnum == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT) || \
37 (errnum == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN) || \
38 (errnum == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY) || \
39 (errnum == X509_V_ERR_CERT_UNTRUSTED) || \
40 (errnum == X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE))
41
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -060042// Refer to schema 2018.3
43// http://redfish.dmtf.org/schemas/v1/Certificate.json#/definitions/KeyUsage for
44// supported KeyUsage types in redfish
45// Refer to
46// https://github.com/openssl/openssl/blob/master/include/openssl/x509v3.h for
47// key usage bit fields
48std::map<uint8_t, std::string> keyUsageToRfStr = {
49 {KU_DIGITAL_SIGNATURE, "DigitalSignature"},
50 {KU_NON_REPUDIATION, "NonRepudiation"},
51 {KU_KEY_ENCIPHERMENT, "KeyEncipherment"},
52 {KU_DATA_ENCIPHERMENT, "DataEncipherment"},
53 {KU_KEY_AGREEMENT, "KeyAgreement"},
54 {KU_KEY_CERT_SIGN, "KeyCertSign"},
55 {KU_CRL_SIGN, "CRLSigning"},
56 {KU_ENCIPHER_ONLY, "EncipherOnly"},
57 {KU_DECIPHER_ONLY, "DecipherOnly"}};
58
59// Refer to schema 2018.3
60// http://redfish.dmtf.org/schemas/v1/Certificate.json#/definitions/KeyUsage for
61// supported Extended KeyUsage types in redfish
62std::map<uint8_t, std::string> extendedKeyUsageToRfStr = {
63 {NID_server_auth, "ServerAuthentication"},
64 {NID_client_auth, "ClientAuthentication"},
65 {NID_email_protect, "EmailProtection"},
66 {NID_OCSP_sign, "OCSPSigning"},
67 {NID_ad_timeStamping, "Timestamping"},
68 {NID_code_sign, "CodeSigning"}};
69
Marri Devender Rao6ceec402019-02-01 03:15:19 -060070Certificate::Certificate(sdbusplus::bus::bus& bus, const std::string& objPath,
71 const CertificateType& type,
72 const UnitsToRestart& unit,
73 const CertInstallPath& installPath,
74 const CertUploadPath& uploadPath) :
Marri Devender Raoedd11312019-02-27 08:45:10 -060075 CertIfaces(bus, objPath.c_str(), true),
76 bus(bus), objectPath(objPath), certType(type), unitToRestart(unit),
Marri Devender Rao6ceec402019-02-01 03:15:19 -060077 certInstallPath(installPath)
78{
79 auto installHelper = [this](const auto& filePath) {
80 if (!compareKeys(filePath))
81 {
82 elog<InvalidCertificate>(
83 Reason("Private key does not match the Certificate"));
84 };
85 };
86 typeFuncMap[SERVER] = installHelper;
87 typeFuncMap[CLIENT] = installHelper;
88 typeFuncMap[AUTHORITY] = [](auto filePath) {};
89 install(uploadPath);
Marri Devender Raoedd11312019-02-27 08:45:10 -060090 this->emit_object_added();
Marri Devender Rao6ceec402019-02-01 03:15:19 -060091}
92
93Certificate::~Certificate()
94{
95 if (!fs::remove(certInstallPath))
96 {
97 log<level::INFO>("Certificate file not found!",
98 entry("PATH=%s", certInstallPath.c_str()));
99 }
100 else if (!unitToRestart.empty())
101 {
102 reloadOrReset(unitToRestart);
103 }
104}
105
Marri Devender Rao13bf74e2019-03-26 01:52:17 -0500106void Certificate::replace(const std::string filePath)
107{
108 install(filePath);
109}
110
111void Certificate::install(const std::string& filePath)
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600112{
113 log<level::INFO>("Certificate install ",
114 entry("FILEPATH=%s", filePath.c_str()));
115 auto errCode = X509_V_OK;
116
117 // Verify the certificate file
118 fs::path file(filePath);
119 if (!fs::exists(file))
120 {
121 log<level::ERR>("File is Missing", entry("FILE=%s", filePath.c_str()));
122 elog<InternalFailure>();
123 }
124
125 try
126 {
127 if (fs::file_size(filePath) == 0)
128 {
129 // file is empty
130 log<level::ERR>("File is empty",
131 entry("FILE=%s", filePath.c_str()));
132 elog<InvalidCertificate>(Reason("File is empty"));
133 }
134 }
135 catch (const fs::filesystem_error& e)
136 {
137 // Log Error message
138 log<level::ERR>(e.what(), entry("FILE=%s", filePath.c_str()));
139 elog<InternalFailure>();
140 }
141
142 // Defining store object as RAW to avoid double free.
143 // X509_LOOKUP_free free up store object.
144 // Create an empty X509_STORE structure for certificate validation.
145 auto x509Store = X509_STORE_new();
146 if (!x509Store)
147 {
148 log<level::ERR>("Error occured during X509_STORE_new call");
149 elog<InternalFailure>();
150 }
151
152 OpenSSL_add_all_algorithms();
153
154 // ADD Certificate Lookup method.
155 X509_LOOKUP_Ptr lookup(X509_STORE_add_lookup(x509Store, X509_LOOKUP_file()),
156 ::X509_LOOKUP_free);
157 if (!lookup)
158 {
159 // Normally lookup cleanup function interanlly does X509Store cleanup
160 // Free up the X509Store.
161 X509_STORE_free(x509Store);
162 log<level::ERR>("Error occured during X509_STORE_add_lookup call");
163 elog<InternalFailure>();
164 }
165 // Load Certificate file.
166 errCode = X509_LOOKUP_load_file(lookup.get(), filePath.c_str(),
167 X509_FILETYPE_PEM);
168 if (errCode != 1)
169 {
170 log<level::ERR>("Error occured during X509_LOOKUP_load_file call",
171 entry("FILE=%s", filePath.c_str()));
172 elog<InvalidCertificate>(Reason("Invalid certificate file format"));
173 }
174
175 // Load Certificate file into the X509 structre.
176 X509_Ptr cert = std::move(loadCert(filePath));
177 X509_STORE_CTX_Ptr storeCtx(X509_STORE_CTX_new(), ::X509_STORE_CTX_free);
178 if (!storeCtx)
179 {
180 log<level::ERR>("Error occured during X509_STORE_CTX_new call",
181 entry("FILE=%s", filePath.c_str()));
182 elog<InternalFailure>();
183 }
184
185 errCode = X509_STORE_CTX_init(storeCtx.get(), x509Store, cert.get(), NULL);
186 if (errCode != 1)
187 {
188 log<level::ERR>("Error occured during X509_STORE_CTX_init call",
189 entry("FILE=%s", filePath.c_str()));
190 elog<InternalFailure>();
191 }
192
193 // Set time to current time.
194 auto locTime = time(nullptr);
195
196 X509_STORE_CTX_set_time(storeCtx.get(), X509_V_FLAG_USE_CHECK_TIME,
197 locTime);
198
199 errCode = X509_verify_cert(storeCtx.get());
200 if (errCode == 1)
201 {
202 errCode = X509_V_OK;
203 }
204 else if (errCode == 0)
205 {
206 errCode = X509_STORE_CTX_get_error(storeCtx.get());
207 log<level::ERR>("Certificate verification failed",
208 entry("FILE=%s", filePath.c_str()),
209 entry("ERRCODE=%d", errCode));
210 }
211 else
212 {
213 log<level::ERR>("Error occured during X509_verify_cert call",
214 entry("FILE=%s", filePath.c_str()));
215 elog<InternalFailure>();
216 }
217
218 // Allow certificate upload, for "certificate is not yet valid" and
219 // trust chain related errors.
220 if (!((errCode == X509_V_OK) ||
221 (errCode == X509_V_ERR_CERT_NOT_YET_VALID) ||
222 TRUST_CHAIN_ERR(errCode)))
223 {
224 if (errCode == X509_V_ERR_CERT_HAS_EXPIRED)
225 {
226 elog<InvalidCertificate>(Reason("Expired Certificate"));
227 }
228 // Loging general error here.
229 elog<InvalidCertificate>(Reason("Certificate validation failed"));
230 }
231
232 // Invoke type specific compare keys function.
233 auto iter = typeFuncMap.find(certType);
234 if (iter == typeFuncMap.end())
235 {
236 log<level::ERR>("Unsupported Type", entry("TYPE=%s", certType.c_str()));
237 elog<InternalFailure>();
238 }
239 iter->second(filePath);
240
241 // Copy thecertificate to the installation path
242 auto path = fs::path(certInstallPath).parent_path();
243 try
244 {
245 fs::create_directories(path);
246 // During bootup will be parsing existing file so no need to
247 // copy it.
248 if (filePath != certInstallPath)
249 {
250 fs::copy_file(filePath, certInstallPath,
251 fs::copy_options::overwrite_existing);
252 }
253 }
254 catch (fs::filesystem_error& e)
255 {
256 log<level::ERR>("Failed to copy certificate", entry("ERR=%s", e.what()),
257 entry("SRC=%s", filePath.c_str()),
258 entry("DST=%s", certInstallPath.c_str()));
259 elog<InternalFailure>();
260 }
261 // restart the units
262 if (!unitToRestart.empty())
263 {
264 reloadOrReset(unitToRestart);
265 }
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600266
267 // Parse the certificate file and populate properties
268 populateProperties();
269}
270
271void Certificate::populateProperties()
272{
273 X509_Ptr cert = std::move(loadCert(certInstallPath));
274 // Update properties if no error thrown
275 BIO_MEM_Ptr certBio(BIO_new(BIO_s_mem()), BIO_free);
276 PEM_write_bio_X509(certBio.get(), cert.get());
277 BUF_MEM_Ptr certBuf(BUF_MEM_new(), BUF_MEM_free);
278 BUF_MEM* buf = certBuf.get();
279 BIO_get_mem_ptr(certBio.get(), &buf);
280 std::string certStr(buf->data, buf->length);
281 CertificateIface::certificateString(certStr);
282
283 static const int maxKeySize = 4096;
284 char subBuffer[maxKeySize] = {0};
285 // This pointer cannot be freed independantly.
286 X509_NAME* sub = X509_get_subject_name(cert.get());
287 X509_NAME_print_ex(certBio.get(), sub, 0, 0);
288 BIO_read(certBio.get(), subBuffer, maxKeySize);
289 CertificateIface::subject(subBuffer);
290
291 // This pointer cannot be freed independantly.
292 char issuerBuffer[maxKeySize] = {0};
293 X509_NAME* issuer_name = X509_get_issuer_name(cert.get());
294 X509_NAME_print_ex(certBio.get(), issuer_name, 0, 0);
295 BIO_read(certBio.get(), issuerBuffer, maxKeySize);
296 CertificateIface::issuer(issuerBuffer);
297
298 std::vector<std::string> keyUsageList;
299 ASN1_BIT_STRING* usage;
300
301 // Go through each usage in the bit string and convert to
302 // corresponding string value
303 if ((usage = static_cast<ASN1_BIT_STRING*>(
304 X509_get_ext_d2i(cert.get(), NID_key_usage, NULL, NULL))))
305 {
306 for (auto i = 0; i < usage->length; ++i)
307 {
308 for (auto& x : keyUsageToRfStr)
309 {
310 if (x.first & usage->data[i])
311 {
312 keyUsageList.push_back(x.second);
313 break;
314 }
315 }
316 }
317 }
318
319 EXTENDED_KEY_USAGE* extUsage;
320 if ((extUsage = static_cast<EXTENDED_KEY_USAGE*>(
321 X509_get_ext_d2i(cert.get(), NID_ext_key_usage, NULL, NULL))))
322 {
323 for (int i = 0; i < sk_ASN1_OBJECT_num(extUsage); i++)
324 {
325 keyUsageList.push_back(extendedKeyUsageToRfStr[OBJ_obj2nid(
326 sk_ASN1_OBJECT_value(extUsage, i))]);
327 }
328 }
329 CertificateIface::keyUsage(keyUsageList);
330
331 int days = 0;
332 int secs = 0;
333
334 ASN1_TIME_ptr epoch(ASN1_TIME_new(), ASN1_STRING_free);
335 // Set time to 12:00am GMT, Jan 1 1970
336 ASN1_TIME_set_string(epoch.get(), "700101120000Z");
337
338 static const int dayToSeconds = 24 * 60 * 60;
339 ASN1_TIME* notAfter = X509_get_notAfter(cert.get());
340 ASN1_TIME_diff(&days, &secs, epoch.get(), notAfter);
341 CertificateIface::validNotAfter((days * dayToSeconds) + secs);
342
343 ASN1_TIME* notBefore = X509_get_notBefore(cert.get());
344 ASN1_TIME_diff(&days, &secs, epoch.get(), notBefore);
345 CertificateIface::validNotBefore((days * dayToSeconds) + secs);
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600346}
347
348X509_Ptr Certificate::loadCert(const std::string& filePath)
349{
350 log<level::INFO>("Certificate loadCert",
351 entry("FILEPATH=%s", filePath.c_str()));
352 // Read Certificate file
353 X509_Ptr cert(X509_new(), ::X509_free);
354 if (!cert)
355 {
356 log<level::ERR>("Error occured during X509_new call",
357 entry("FILE=%s", filePath.c_str()),
358 entry("ERRCODE=%lu", ERR_get_error()));
359 elog<InternalFailure>();
360 }
361
362 BIO_MEM_Ptr bioCert(BIO_new_file(filePath.c_str(), "rb"), ::BIO_free);
363 if (!bioCert)
364 {
365 log<level::ERR>("Error occured during BIO_new_file call",
366 entry("FILE=%s", filePath.c_str()));
367 elog<InternalFailure>();
368 }
369
370 X509* x509 = cert.get();
371 if (!PEM_read_bio_X509(bioCert.get(), &x509, nullptr, nullptr))
372 {
373 log<level::ERR>("Error occured during PEM_read_bio_X509 call",
374 entry("FILE=%s", filePath.c_str()));
375 elog<InternalFailure>();
376 }
377 return cert;
378}
379bool Certificate::compareKeys(const std::string& filePath)
380{
381 log<level::INFO>("Certificate compareKeys",
382 entry("FILEPATH=%s", filePath.c_str()));
383 X509_Ptr cert(X509_new(), ::X509_free);
384 if (!cert)
385 {
386 log<level::ERR>("Error occured during X509_new call",
387 entry("FILE=%s", filePath.c_str()),
388 entry("ERRCODE=%lu", ERR_get_error()));
389 elog<InternalFailure>();
390 }
391
392 BIO_MEM_Ptr bioCert(BIO_new_file(filePath.c_str(), "rb"), ::BIO_free);
393 if (!bioCert)
394 {
395 log<level::ERR>("Error occured during BIO_new_file call",
396 entry("FILE=%s", filePath.c_str()));
397 elog<InternalFailure>();
398 }
399
400 X509* x509 = cert.get();
401 PEM_read_bio_X509(bioCert.get(), &x509, nullptr, nullptr);
402
403 EVP_PKEY_Ptr pubKey(X509_get_pubkey(cert.get()), ::EVP_PKEY_free);
404 if (!pubKey)
405 {
406 log<level::ERR>("Error occurred during X509_get_pubkey",
407 entry("FILE=%s", filePath.c_str()),
408 entry("ERRCODE=%lu", ERR_get_error()));
409 elog<InvalidCertificate>(Reason("Failed to get public key info"));
410 }
411
412 BIO_MEM_Ptr keyBio(BIO_new(BIO_s_file()), ::BIO_free);
413 if (!keyBio)
414 {
415 log<level::ERR>("Error occured during BIO_s_file call",
416 entry("FILE=%s", filePath.c_str()));
417 elog<InternalFailure>();
418 }
419 BIO_read_filename(keyBio.get(), filePath.c_str());
420
421 EVP_PKEY_Ptr priKey(
422 PEM_read_bio_PrivateKey(keyBio.get(), nullptr, nullptr, nullptr),
423 ::EVP_PKEY_free);
424 if (!priKey)
425 {
426 log<level::ERR>("Error occurred during PEM_read_bio_PrivateKey",
427 entry("FILE=%s", filePath.c_str()),
428 entry("ERRCODE=%lu", ERR_get_error()));
429 elog<InvalidCertificate>(Reason("Failed to get private key info"));
430 }
431
432 int32_t rc = EVP_PKEY_cmp(priKey.get(), pubKey.get());
433 if (rc != 1)
434 {
435 log<level::ERR>("Private key is not matching with Certificate",
436 entry("FILE=%s", filePath.c_str()),
437 entry("ERRCODE=%d", rc));
438 return false;
439 }
440 return true;
441}
442
443void Certificate::reloadOrReset(const UnitsToRestart& unit)
444{
445 constexpr auto SYSTEMD_SERVICE = "org.freedesktop.systemd1";
446 constexpr auto SYSTEMD_OBJ_PATH = "/org/freedesktop/systemd1";
447 constexpr auto SYSTEMD_INTERFACE = "org.freedesktop.systemd1.Manager";
448 try
449 {
450 auto method =
451 bus.new_method_call(SYSTEMD_SERVICE, SYSTEMD_OBJ_PATH,
452 SYSTEMD_INTERFACE, "ReloadOrRestartUnit");
453 method.append(unit, "replace");
454 bus.call_noreply(method);
455 }
456 catch (const sdbusplus::exception::SdBusError& e)
457 {
458 log<level::ERR>("Failed to reload or restart service",
459 entry("ERR=%s", e.what()),
460 entry("UNIT=%s", unit.c_str()));
461 elog<InternalFailure>();
462 }
463}
464} // namespace certs
465} // namespace phosphor