blob: 18c68a0b55841f37941094a90f0e88387ec797c4 [file] [log] [blame]
Marri Devender Raocd30c492019-06-12 01:40:17 -05001#include "config.h"
2
Marri Devender Rao6ceec402019-02-01 03:15:19 -06003#include "certificate.hpp"
4
Zbigniew Kurzynskia3bb38f2019-09-17 13:34:25 +02005#include "certs_manager.hpp"
Nan Zhoue869bb62021-12-30 11:34:42 -08006#include "x509_utils.hpp"
Zbigniew Kurzynskia3bb38f2019-09-17 13:34:25 +02007
Nan Zhou014be0b2021-12-28 18:00:14 -08008#include <openssl/asn1.h>
Marri Devender Rao6ceec402019-02-01 03:15:19 -06009#include <openssl/bio.h>
Nan Zhou014be0b2021-12-28 18:00:14 -080010#include <openssl/buffer.h>
Marri Devender Rao6ceec402019-02-01 03:15:19 -060011#include <openssl/err.h>
12#include <openssl/evp.h>
Nan Zhou014be0b2021-12-28 18:00:14 -080013#include <openssl/obj_mac.h>
14#include <openssl/objects.h>
15#include <openssl/opensslv.h>
Marri Devender Rao6ceec402019-02-01 03:15:19 -060016#include <openssl/pem.h>
17#include <openssl/x509v3.h>
18
Patrick Williams223e4602023-05-10 07:51:11 -050019#include <phosphor-logging/elog-errors.hpp>
20#include <phosphor-logging/elog.hpp>
Ravi Tejaf2646272023-09-30 13:00:55 -050021#include <phosphor-logging/lg2.hpp>
Patrick Williams223e4602023-05-10 07:51:11 -050022#include <watch.hpp>
23#include <xyz/openbmc_project/Certs/error.hpp>
24#include <xyz/openbmc_project/Common/error.hpp>
25
Nan Zhou014be0b2021-12-28 18:00:14 -080026#include <cstdint>
27#include <cstdio>
28#include <cstdlib>
Nan Zhou014be0b2021-12-28 18:00:14 -080029#include <exception>
30#include <filesystem>
Marri Devender Rao6ceec402019-02-01 03:15:19 -060031#include <fstream>
Nan Zhou014be0b2021-12-28 18:00:14 -080032#include <map>
Jayanth Othayothcd24c232024-11-24 09:10:15 -060033#include <random>
Nan Zhou014be0b2021-12-28 18:00:14 -080034#include <utility>
35#include <vector>
Marri Devender Rao13bf74e2019-03-26 01:52:17 -050036
Nan Zhoue1289ad2021-12-28 11:02:56 -080037namespace phosphor::certs
Marri Devender Rao6ceec402019-02-01 03:15:19 -060038{
Nan Zhoucf06ccd2021-12-28 16:25:45 -080039
40namespace
41{
42namespace fs = std::filesystem;
43using ::phosphor::logging::elog;
Nan Zhoucf06ccd2021-12-28 16:25:45 -080044using InvalidCertificateError =
45 ::sdbusplus::xyz::openbmc_project::Certs::Error::InvalidCertificate;
46using ::phosphor::logging::xyz::openbmc_project::Certs::InvalidCertificate;
47using ::sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure;
48
Marri Devender Rao6ceec402019-02-01 03:15:19 -060049// RAII support for openSSL functions.
Nan Zhoucf06ccd2021-12-28 16:25:45 -080050using BIOMemPtr = std::unique_ptr<BIO, decltype(&::BIO_free)>;
51using X509StorePtr = std::unique_ptr<X509_STORE, decltype(&::X509_STORE_free)>;
Nan Zhoucf06ccd2021-12-28 16:25:45 -080052using ASN1TimePtr = std::unique_ptr<ASN1_TIME, decltype(&ASN1_STRING_free)>;
53using EVPPkeyPtr = std::unique_ptr<EVP_PKEY, decltype(&::EVP_PKEY_free)>;
54using BufMemPtr = std::unique_ptr<BUF_MEM, decltype(&::BUF_MEM_free)>;
Marri Devender Rao6ceec402019-02-01 03:15:19 -060055
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -060056// Refer to schema 2018.3
57// http://redfish.dmtf.org/schemas/v1/Certificate.json#/definitions/KeyUsage for
58// supported KeyUsage types in redfish
59// Refer to
60// https://github.com/openssl/openssl/blob/master/include/openssl/x509v3.h for
61// key usage bit fields
62std::map<uint8_t, std::string> keyUsageToRfStr = {
63 {KU_DIGITAL_SIGNATURE, "DigitalSignature"},
64 {KU_NON_REPUDIATION, "NonRepudiation"},
65 {KU_KEY_ENCIPHERMENT, "KeyEncipherment"},
66 {KU_DATA_ENCIPHERMENT, "DataEncipherment"},
67 {KU_KEY_AGREEMENT, "KeyAgreement"},
68 {KU_KEY_CERT_SIGN, "KeyCertSign"},
69 {KU_CRL_SIGN, "CRLSigning"},
70 {KU_ENCIPHER_ONLY, "EncipherOnly"},
71 {KU_DECIPHER_ONLY, "DecipherOnly"}};
72
73// Refer to schema 2018.3
74// http://redfish.dmtf.org/schemas/v1/Certificate.json#/definitions/KeyUsage for
75// supported Extended KeyUsage types in redfish
76std::map<uint8_t, std::string> extendedKeyUsageToRfStr = {
77 {NID_server_auth, "ServerAuthentication"},
78 {NID_client_auth, "ClientAuthentication"},
79 {NID_email_protect, "EmailProtection"},
80 {NID_OCSP_sign, "OCSPSigning"},
81 {NID_ad_timeStamping, "Timestamping"},
82 {NID_code_sign, "CodeSigning"}};
83
Nan Zhoue869bb62021-12-30 11:34:42 -080084/**
Nan Zhou6ec13c82021-12-30 11:34:50 -080085 * @brief Dumps the PEM encoded certificate to installFilePath
Nan Zhoue869bb62021-12-30 11:34:42 -080086 *
Nan Zhou6ec13c82021-12-30 11:34:50 -080087 * @param[in] pem - PEM encoded X509 certificate buffer.
88 * @param[in] certFilePath - Path to the destination file.
Nan Zhoue869bb62021-12-30 11:34:42 -080089 *
90 * @return void
91 */
Nan Zhou6ec13c82021-12-30 11:34:50 -080092
93void dumpCertificate(const std::string& pem, const std::string& certFilePath)
94{
95 std::ofstream outputCertFileStream;
96
97 outputCertFileStream.exceptions(
98 std::ofstream::failbit | std::ofstream::badbit | std::ofstream::eofbit);
99
100 try
101 {
102 outputCertFileStream.open(certFilePath, std::ios::out);
103 outputCertFileStream << pem << "\n" << std::flush;
104 outputCertFileStream.close();
105 }
106 catch (const std::exception& e)
107 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500108 lg2::error(
109 "Failed to dump certificate, ERR:{ERR}, SRC_PEM:{SRC_PEM}, DST:{DST}",
110 "ERR", e, "SRC_PEM", pem, "DST", certFilePath);
Nan Zhou6ec13c82021-12-30 11:34:50 -0800111 elog<InternalFailure>();
112 }
113}
114} // namespace
115
116void Certificate::copyCertificate(const std::string& certSrcFilePath,
117 const std::string& certFilePath)
Kowalski, Kamildb029c92019-07-08 17:09:39 +0200118{
Jayanth Othayothf44a39c2024-11-25 01:46:47 -0600119 try
Nan Zhoue869bb62021-12-30 11:34:42 -0800120 {
Jayanth Othayothf44a39c2024-11-25 01:46:47 -0600121 // Copy the certificate to the installation path
122 // During bootup will be parsing existing file so no need to
123 // copy it.
124 if (certSrcFilePath != certFilePath)
Nan Zhoue869bb62021-12-30 11:34:42 -0800125 {
Jayanth Othayothf44a39c2024-11-25 01:46:47 -0600126 fs::copy(certSrcFilePath, certFilePath,
127 fs::copy_options::overwrite_existing);
Nan Zhoue869bb62021-12-30 11:34:42 -0800128 }
129 }
Jayanth Othayothf44a39c2024-11-25 01:46:47 -0600130 catch (const fs::filesystem_error& e)
131 {
132 lg2::error(
133 "Failed to copy certificate, ERR:{ERR}, SRC:{SRC}, DST:{DST}",
134 "ERR", e.what(), "SRC", certSrcFilePath, "DST", certFilePath);
135 elog<InternalFailure>();
136 }
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100137}
138
139std::string
140 Certificate::generateUniqueFilePath(const std::string& directoryPath)
141{
Jayanth Othayothcd24c232024-11-24 09:10:15 -0600142 // Create a template for the temporary file name
143 std::string filePath = directoryPath + "/" + "cert-XXXXXX";
144 int fd = mkstemp(filePath.data());
145 if (fd == -1)
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100146 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500147 lg2::error(
148 "Error occurred while creating random certificate file path, DIR:{DIR}",
149 "DIR", directoryPath);
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100150 elog<InternalFailure>();
Jayanth Othayothcd24c232024-11-24 09:10:15 -0600151 throw std::runtime_error("Failed to create unique file path");
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100152 }
Jayanth Othayothcd24c232024-11-24 09:10:15 -0600153
154 // Close the file descriptor and file, just need the unique path
155 close(fd);
156 std::remove(filePath.data());
157 return filePath;
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100158}
159
160std::string Certificate::generateAuthCertFileX509Path(
161 const std::string& certSrcFilePath, const std::string& certDstDirPath)
162{
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800163 const internal::X509Ptr cert = loadCert(certSrcFilePath);
Kowalski, Kamildb029c92019-07-08 17:09:39 +0200164 unsigned long hash = X509_subject_name_hash(cert.get());
Nan Zhoue3d47cd2022-09-16 03:41:53 +0000165 static constexpr auto certHashLength = 9;
166 char hashBuf[certHashLength];
Kowalski, Kamildb029c92019-07-08 17:09:39 +0200167
Nan Zhoue3d47cd2022-09-16 03:41:53 +0000168 snprintf(hashBuf, certHashLength, "%08lx", hash);
Kowalski, Kamildb029c92019-07-08 17:09:39 +0200169
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100170 const std::string certHash(hashBuf);
Nan Zhou718eef32021-12-28 11:03:30 -0800171 for (size_t i = 0; i < maxNumAuthorityCertificates; ++i)
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100172 {
Zbigniew Lukwinski73d1fbf2020-01-15 15:31:12 +0100173 const std::string certDstFileX509Path =
174 certDstDirPath + "/" + certHash + "." + std::to_string(i);
175 if (!fs::exists(certDstFileX509Path))
176 {
177 return certDstFileX509Path;
178 }
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100179 }
Kowalski, Kamildb029c92019-07-08 17:09:39 +0200180
Ravi Tejaf2646272023-09-30 13:00:55 -0500181 lg2::error("Authority certificate x509 file path already used, DIR:{DIR}",
182 "DIR", certDstDirPath);
Zbigniew Lukwinski73d1fbf2020-01-15 15:31:12 +0100183 elog<InternalFailure>();
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100184}
185
186std::string
187 Certificate::generateAuthCertFilePath(const std::string& certSrcFilePath)
188{
189 // If there is a certificate file path (which means certificate replacement
190 // is doing) use it (do not create new one)
191 if (!certFilePath.empty())
192 {
193 return certFilePath;
194 }
195 // If source certificate file is located in the certificates directory use
196 // it (do not create new one)
197 else if (fs::path(certSrcFilePath).parent_path().string() ==
198 certInstallPath)
199 {
200 return certSrcFilePath;
201 }
202 // Otherwise generate new file name/path
203 else
204 {
205 return generateUniqueFilePath(certInstallPath);
206 }
207}
208
209std::string
210 Certificate::generateCertFilePath(const std::string& certSrcFilePath)
211{
Nan Zhoue3d47cd2022-09-16 03:41:53 +0000212 if (certType == CertificateType::authority)
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100213 {
214 return generateAuthCertFilePath(certSrcFilePath);
215 }
216 else
217 {
218 return certInstallPath;
219 }
Kowalski, Kamildb029c92019-07-08 17:09:39 +0200220}
221
Patrick Williamsb3dbfb32022-07-22 19:26:57 -0500222Certificate::Certificate(sdbusplus::bus_t& bus, const std::string& objPath,
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800223 CertificateType type, const std::string& installPath,
224 const std::string& uploadPath, Watch* watch,
Willy Tu698a5742022-09-23 21:33:01 +0000225 Manager& parent, bool restore) :
Patrick Williamsebd21ba2022-04-05 14:58:53 -0500226 internal::CertificateInterface(
227 bus, objPath.c_str(),
228 internal::CertificateInterface::action::defer_emit),
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800229 objectPath(objPath), certType(type), certInstallPath(installPath),
230 certWatch(watch), manager(parent)
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600231{
232 auto installHelper = [this](const auto& filePath) {
233 if (!compareKeys(filePath))
234 {
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800235 elog<InvalidCertificateError>(InvalidCertificate::REASON(
236 "Private key does not match the Certificate"));
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600237 };
238 };
Nan Zhoue3d47cd2022-09-16 03:41:53 +0000239 typeFuncMap[CertificateType::server] = installHelper;
240 typeFuncMap[CertificateType::client] = installHelper;
241 typeFuncMap[CertificateType::authority] = [](const std::string&) {};
Marri Devender Raocd30c492019-06-12 01:40:17 -0500242
243 auto appendPrivateKey = [this](const std::string& filePath) {
244 checkAndAppendPrivateKey(filePath);
245 };
246
Nan Zhoue3d47cd2022-09-16 03:41:53 +0000247 appendKeyMap[CertificateType::server] = appendPrivateKey;
248 appendKeyMap[CertificateType::client] = appendPrivateKey;
249 appendKeyMap[CertificateType::authority] = [](const std::string&) {};
Marri Devender Raocd30c492019-06-12 01:40:17 -0500250
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100251 // Generate certificate file path
252 certFilePath = generateCertFilePath(uploadPath);
253
Marri Devender Raocd30c492019-06-12 01:40:17 -0500254 // install the certificate
Willy Tu698a5742022-09-23 21:33:01 +0000255 install(uploadPath, restore);
Marri Devender Raocd30c492019-06-12 01:40:17 -0500256
Marri Devender Raoedd11312019-02-27 08:45:10 -0600257 this->emit_object_added();
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600258}
259
Patrick Williamsb3dbfb32022-07-22 19:26:57 -0500260Certificate::Certificate(sdbusplus::bus_t& bus, const std::string& objPath,
Nan Zhou6ec13c82021-12-30 11:34:50 -0800261 const CertificateType& type,
262 const std::string& installPath, X509_STORE& x509Store,
263 const std::string& pem, Watch* watchPtr,
Willy Tu698a5742022-09-23 21:33:01 +0000264 Manager& parent, bool restore) :
Patrick Williamsebd21ba2022-04-05 14:58:53 -0500265 internal::CertificateInterface(
266 bus, objPath.c_str(),
267 internal::CertificateInterface::action::defer_emit),
Nan Zhou6ec13c82021-12-30 11:34:50 -0800268 objectPath(objPath), certType(type), certInstallPath(installPath),
269 certWatch(watchPtr), manager(parent)
270{
271 // Generate certificate file path
272 certFilePath = generateUniqueFilePath(installPath);
273
274 // install the certificate
Willy Tu698a5742022-09-23 21:33:01 +0000275 install(x509Store, pem, restore);
Nan Zhou6ec13c82021-12-30 11:34:50 -0800276
277 this->emit_object_added();
278}
279
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600280Certificate::~Certificate()
281{
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100282 if (!fs::remove(certFilePath))
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600283 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500284 lg2::info("Certificate file not found! PATH:{PATH}", "PATH",
285 certFilePath);
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600286 }
287}
288
Marri Devender Rao13bf74e2019-03-26 01:52:17 -0500289void Certificate::replace(const std::string filePath)
290{
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100291 manager.replaceCertificate(this, filePath);
Marri Devender Rao13bf74e2019-03-26 01:52:17 -0500292}
293
Willy Tu698a5742022-09-23 21:33:01 +0000294void Certificate::install(const std::string& certSrcFilePath, bool restore)
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600295{
Willy Tu698a5742022-09-23 21:33:01 +0000296 if (restore)
297 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500298 lg2::debug("Certificate install, FILEPATH:{FILEPATH}", "FILEPATH",
299 certSrcFilePath);
Willy Tu698a5742022-09-23 21:33:01 +0000300 }
301 else
302 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500303 lg2::info("Certificate install, FILEPATH:{FILEPATH}", "FILEPATH",
304 certSrcFilePath);
Willy Tu698a5742022-09-23 21:33:01 +0000305 }
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600306
Marri Devender Raoffad1ef2019-06-03 04:54:12 -0500307 // stop watch for user initiated certificate install
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800308 if (certWatch != nullptr)
Marri Devender Raoffad1ef2019-06-03 04:54:12 -0500309 {
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800310 certWatch->stopWatch();
Marri Devender Raoffad1ef2019-06-03 04:54:12 -0500311 }
312
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600313 // Verify the certificate file
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100314 fs::path file(certSrcFilePath);
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600315 if (!fs::exists(file))
316 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500317 lg2::error("File is Missing, FILE:{FILE}", "FILE", certSrcFilePath);
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600318 elog<InternalFailure>();
319 }
320
321 try
322 {
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100323 if (fs::file_size(certSrcFilePath) == 0)
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600324 {
325 // file is empty
Ravi Tejaf2646272023-09-30 13:00:55 -0500326 lg2::error("File is empty, FILE:{FILE}", "FILE", certSrcFilePath);
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800327 elog<InvalidCertificateError>(
328 InvalidCertificate::REASON("File is empty"));
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600329 }
330 }
331 catch (const fs::filesystem_error& e)
332 {
333 // Log Error message
Ravi Tejaf2646272023-09-30 13:00:55 -0500334 lg2::error("File is empty, FILE:{FILE}, ERR:{ERR}", "FILE",
335 certSrcFilePath, "ERR", e);
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600336 elog<InternalFailure>();
337 }
338
Nan Zhoue869bb62021-12-30 11:34:42 -0800339 X509StorePtr x509Store = getX509Store(certSrcFilePath);
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600340
Nan Zhoubf3cf752021-12-28 11:02:07 -0800341 // Load Certificate file into the X509 structure.
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800342 internal::X509Ptr cert = loadCert(certSrcFilePath);
Nan Zhoue869bb62021-12-30 11:34:42 -0800343
344 // Perform validation
345 validateCertificateAgainstStore(*x509Store, *cert);
346 validateCertificateStartDate(*cert);
347 validateCertificateInSSLContext(*cert);
348
349 // Invoke type specific append private key function.
350 if (auto it = appendKeyMap.find(certType); it == appendKeyMap.end())
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600351 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500352 lg2::error("Unsupported Type, TYPE:{TYPE}", "TYPE",
353 certificateTypeToString(certType));
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600354 elog<InternalFailure>();
355 }
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600356 else
357 {
Nan Zhoue869bb62021-12-30 11:34:42 -0800358 it->second(certSrcFilePath);
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600359 }
360
Marri Devender Raocd30c492019-06-12 01:40:17 -0500361 // Invoke type specific compare keys function.
Nan Zhoue869bb62021-12-30 11:34:42 -0800362 if (auto it = typeFuncMap.find(certType); it == typeFuncMap.end())
Marri Devender Raocd30c492019-06-12 01:40:17 -0500363 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500364 lg2::error("Unsupported Type, TYPE:{TYPE}", "TYPE",
365 certificateTypeToString(certType));
Marri Devender Raocd30c492019-06-12 01:40:17 -0500366 elog<InternalFailure>();
367 }
Nan Zhoue869bb62021-12-30 11:34:42 -0800368 else
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600369 {
Nan Zhoue869bb62021-12-30 11:34:42 -0800370 it->second(certSrcFilePath);
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600371 }
Marri Devender Rao8f80c352019-05-13 00:53:01 -0500372
Nan Zhoue869bb62021-12-30 11:34:42 -0800373 copyCertificate(certSrcFilePath, certFilePath);
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100374 storageUpdate();
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600375
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100376 // Keep certificate ID
Nan Zhoue869bb62021-12-30 11:34:42 -0800377 certId = generateCertId(*cert);
Kowalski, Kamildb029c92019-07-08 17:09:39 +0200378
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600379 // Parse the certificate file and populate properties
Nan Zhoue869bb62021-12-30 11:34:42 -0800380 populateProperties(*cert);
Marri Devender Raoffad1ef2019-06-03 04:54:12 -0500381
382 // restart watch
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800383 if (certWatch != nullptr)
Marri Devender Raoffad1ef2019-06-03 04:54:12 -0500384 {
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800385 certWatch->startWatch();
Marri Devender Raoffad1ef2019-06-03 04:54:12 -0500386 }
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600387}
388
Willy Tu698a5742022-09-23 21:33:01 +0000389void Certificate::install(X509_STORE& x509Store, const std::string& pem,
390 bool restore)
Nan Zhou6ec13c82021-12-30 11:34:50 -0800391{
Willy Tu698a5742022-09-23 21:33:01 +0000392 if (restore)
393 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500394 lg2::debug("Certificate install, PEM_STR:{PEM_STR}", "PEM_STR", pem);
Willy Tu698a5742022-09-23 21:33:01 +0000395 }
396 else
397 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500398 lg2::info("Certificate install, PEM_STR:{PEM_STR} ", "PEM_STR", pem);
Willy Tu698a5742022-09-23 21:33:01 +0000399 }
Nan Zhou6ec13c82021-12-30 11:34:50 -0800400
Nan Zhoue3d47cd2022-09-16 03:41:53 +0000401 if (certType != CertificateType::authority)
Nan Zhou6ec13c82021-12-30 11:34:50 -0800402 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500403 lg2::error("Bulk install error: Unsupported Type; only authority "
404 "supports bulk install, TYPE:{TYPE}",
405 "TYPE", certificateTypeToString(certType));
Nan Zhou6ec13c82021-12-30 11:34:50 -0800406 elog<InternalFailure>();
407 }
408
409 // stop watch for user initiated certificate install
410 if (certWatch)
411 {
412 certWatch->stopWatch();
413 }
414
415 // Load Certificate file into the X509 structure.
416 internal::X509Ptr cert = parseCert(pem);
417 // Perform validation; no type specific compare keys function
418 validateCertificateAgainstStore(x509Store, *cert);
419 validateCertificateStartDate(*cert);
420 validateCertificateInSSLContext(*cert);
421
422 // Copy the PEM to the installation path
423 dumpCertificate(pem, certFilePath);
424 storageUpdate();
425 // Keep certificate ID
426 certId = generateCertId(*cert);
427 // Parse the certificate file and populate properties
428 populateProperties(*cert);
429 // restart watch
430 if (certWatch)
431 {
432 certWatch->startWatch();
433 }
434}
435
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600436void Certificate::populateProperties()
437{
Nan Zhoue869bb62021-12-30 11:34:42 -0800438 internal::X509Ptr cert = loadCert(certInstallPath);
439 populateProperties(*cert);
Kowalski, Kamildb029c92019-07-08 17:09:39 +0200440}
441
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100442std::string Certificate::getCertId() const
Kowalski, Kamildb029c92019-07-08 17:09:39 +0200443{
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100444 return certId;
445}
446
447bool Certificate::isSame(const std::string& certPath)
448{
Nan Zhoue869bb62021-12-30 11:34:42 -0800449 internal::X509Ptr cert = loadCert(certPath);
450 return getCertId() == generateCertId(*cert);
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100451}
452
453void Certificate::storageUpdate()
454{
Nan Zhoue3d47cd2022-09-16 03:41:53 +0000455 if (certType == CertificateType::authority)
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100456 {
457 // Create symbolic link in the certificate directory
458 std::string certFileX509Path;
459 try
460 {
461 if (!certFilePath.empty() &&
462 fs::is_regular_file(fs::path(certFilePath)))
463 {
464 certFileX509Path =
465 generateAuthCertFileX509Path(certFilePath, certInstallPath);
466 fs::create_symlink(fs::path(certFilePath),
467 fs::path(certFileX509Path));
468 }
469 }
470 catch (const std::exception& e)
471 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500472 lg2::error("Failed to create symlink for certificate, ERR:{ERR},"
473 "FILE:{FILE}, SYMLINK:{SYMLINK}",
474 "ERR", e, "FILE", certFilePath, "SYMLINK",
475 certFileX509Path);
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100476 elog<InternalFailure>();
477 }
478 }
Kowalski, Kamildb029c92019-07-08 17:09:39 +0200479}
480
Nan Zhoue869bb62021-12-30 11:34:42 -0800481void Certificate::populateProperties(X509& cert)
Kowalski, Kamildb029c92019-07-08 17:09:39 +0200482{
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600483 // Update properties if no error thrown
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800484 BIOMemPtr certBio(BIO_new(BIO_s_mem()), BIO_free);
Nan Zhoue869bb62021-12-30 11:34:42 -0800485 PEM_write_bio_X509(certBio.get(), &cert);
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800486 BufMemPtr certBuf(BUF_MEM_new(), BUF_MEM_free);
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600487 BUF_MEM* buf = certBuf.get();
488 BIO_get_mem_ptr(certBio.get(), &buf);
489 std::string certStr(buf->data, buf->length);
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800490 certificateString(certStr);
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600491
492 static const int maxKeySize = 4096;
493 char subBuffer[maxKeySize] = {0};
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800494 BIOMemPtr subBio(BIO_new(BIO_s_mem()), BIO_free);
Manojkiran Eda5d4f7932024-06-17 11:49:21 +0530495 // This pointer cannot be freed independently.
Nan Zhoue869bb62021-12-30 11:34:42 -0800496 X509_NAME* sub = X509_get_subject_name(&cert);
Marri Devender Raodec58772019-06-11 03:10:00 -0500497 X509_NAME_print_ex(subBio.get(), sub, 0, XN_FLAG_SEP_COMMA_PLUS);
498 BIO_read(subBio.get(), subBuffer, maxKeySize);
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800499 subject(subBuffer);
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600500
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600501 char issuerBuffer[maxKeySize] = {0};
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800502 BIOMemPtr issuerBio(BIO_new(BIO_s_mem()), BIO_free);
Manojkiran Eda5d4f7932024-06-17 11:49:21 +0530503 // This pointer cannot be freed independently.
Nan Zhoue3d47cd2022-09-16 03:41:53 +0000504 X509_NAME* issuerName = X509_get_issuer_name(&cert);
505 X509_NAME_print_ex(issuerBio.get(), issuerName, 0, XN_FLAG_SEP_COMMA_PLUS);
Marri Devender Raodec58772019-06-11 03:10:00 -0500506 BIO_read(issuerBio.get(), issuerBuffer, maxKeySize);
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800507 issuer(issuerBuffer);
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600508
509 std::vector<std::string> keyUsageList;
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600510
511 // Go through each usage in the bit string and convert to
512 // corresponding string value
Jayanth Othayothcb1ee9d2024-11-24 22:23:33 -0600513 ASN1_BIT_STRING* usage = static_cast<ASN1_BIT_STRING*>(
514 X509_get_ext_d2i(&cert, NID_key_usage, nullptr, nullptr));
515 if (usage != nullptr)
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600516 {
517 for (auto i = 0; i < usage->length; ++i)
518 {
519 for (auto& x : keyUsageToRfStr)
520 {
521 if (x.first & usage->data[i])
522 {
523 keyUsageList.push_back(x.second);
524 break;
525 }
526 }
527 }
528 }
529
Jayanth Othayothcb1ee9d2024-11-24 22:23:33 -0600530 EXTENDED_KEY_USAGE* extUsage = static_cast<EXTENDED_KEY_USAGE*>(
531 X509_get_ext_d2i(&cert, NID_ext_key_usage, nullptr, nullptr));
532 if (extUsage == nullptr)
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600533 {
534 for (int i = 0; i < sk_ASN1_OBJECT_num(extUsage); i++)
535 {
536 keyUsageList.push_back(extendedKeyUsageToRfStr[OBJ_obj2nid(
537 sk_ASN1_OBJECT_value(extUsage, i))]);
538 }
539 }
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800540 keyUsage(keyUsageList);
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600541
542 int days = 0;
543 int secs = 0;
544
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800545 ASN1TimePtr epoch(ASN1_TIME_new(), ASN1_STRING_free);
Nan Zhoucf811c42021-12-02 14:56:17 -0800546 // Set time to 00:00am GMT, Jan 1 1970; format: YYYYMMDDHHMMSSZ
547 ASN1_TIME_set_string(epoch.get(), "19700101000000Z");
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600548
Jayanth Othayoth8a59ea22024-11-24 23:14:10 -0600549 constexpr uint64_t dayToSeconds = 86400; // 24 * 60 * 60
Nan Zhoue869bb62021-12-30 11:34:42 -0800550 ASN1_TIME* notAfter = X509_get_notAfter(&cert);
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600551 ASN1_TIME_diff(&days, &secs, epoch.get(), notAfter);
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800552 validNotAfter((days * dayToSeconds) + secs);
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600553
Nan Zhoue869bb62021-12-30 11:34:42 -0800554 ASN1_TIME* notBefore = X509_get_notBefore(&cert);
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600555 ASN1_TIME_diff(&days, &secs, epoch.get(), notBefore);
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800556 validNotBefore((days * dayToSeconds) + secs);
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600557}
558
Marri Devender Raocd30c492019-06-12 01:40:17 -0500559void Certificate::checkAndAppendPrivateKey(const std::string& filePath)
560{
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800561 BIOMemPtr keyBio(BIO_new(BIO_s_file()), ::BIO_free);
Marri Devender Raocd30c492019-06-12 01:40:17 -0500562 if (!keyBio)
563 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500564 lg2::error("Error occurred during BIO_s_file call, FILE:{FILE}", "FILE",
565 filePath);
Marri Devender Raocd30c492019-06-12 01:40:17 -0500566 elog<InternalFailure>();
567 }
568 BIO_read_filename(keyBio.get(), filePath.c_str());
569
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800570 EVPPkeyPtr priKey(
Marri Devender Raocd30c492019-06-12 01:40:17 -0500571 PEM_read_bio_PrivateKey(keyBio.get(), nullptr, nullptr, nullptr),
572 ::EVP_PKEY_free);
573 if (!priKey)
574 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500575 lg2::info("Private key not present in file, FILE:{FILE}", "FILE",
576 filePath);
Marri Devender Raocd30c492019-06-12 01:40:17 -0500577 fs::path privateKeyFile = fs::path(certInstallPath).parent_path();
Nan Zhou718eef32021-12-28 11:03:30 -0800578 privateKeyFile = privateKeyFile / defaultPrivateKeyFileName;
Marri Devender Raocd30c492019-06-12 01:40:17 -0500579 if (!fs::exists(privateKeyFile))
580 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500581 lg2::error("Private key file is not found, FILE:{FILE}", "FILE",
582 privateKeyFile);
Marri Devender Raocd30c492019-06-12 01:40:17 -0500583 elog<InternalFailure>();
584 }
585
586 std::ifstream privKeyFileStream;
587 std::ofstream certFileStream;
Patrick Williamsa2f68d82024-08-16 15:21:36 -0400588 privKeyFileStream.exceptions(
589 std::ifstream::failbit | std::ifstream::badbit |
590 std::ifstream::eofbit);
591 certFileStream.exceptions(
592 std::ofstream::failbit | std::ofstream::badbit |
593 std::ofstream::eofbit);
Marri Devender Raocd30c492019-06-12 01:40:17 -0500594 try
595 {
596 privKeyFileStream.open(privateKeyFile);
597 certFileStream.open(filePath, std::ios::app);
Marri Devender Rao18e51c92019-07-15 04:59:01 -0500598 certFileStream << std::endl; // insert line break
Marri Devender Raocd30c492019-06-12 01:40:17 -0500599 certFileStream << privKeyFileStream.rdbuf() << std::flush;
600 privKeyFileStream.close();
601 certFileStream.close();
602 }
603 catch (const std::exception& e)
604 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500605 lg2::error(
606 "Failed to append private key, ERR:{ERR}, SRC:{SRC}, DST:{DST}",
607 "ERR", e, "SRC", privateKeyFile, "DST", filePath);
Marri Devender Raocd30c492019-06-12 01:40:17 -0500608 elog<InternalFailure>();
609 }
610 }
611}
612
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600613bool Certificate::compareKeys(const std::string& filePath)
614{
Ravi Tejaf2646272023-09-30 13:00:55 -0500615 lg2::info("Certificate compareKeys, FILEPATH:{FILEPATH}", "FILEPATH",
616 filePath);
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800617 internal::X509Ptr cert(X509_new(), ::X509_free);
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600618 if (!cert)
619 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500620 lg2::error(
621 "Error occurred during X509_new call, FILE:{FILE}, ERRCODE:{ERRCODE}",
622 "FILE", filePath, "ERRCODE", ERR_get_error());
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600623 elog<InternalFailure>();
624 }
625
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800626 BIOMemPtr bioCert(BIO_new_file(filePath.c_str(), "rb"), ::BIO_free);
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600627 if (!bioCert)
628 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500629 lg2::error("Error occurred during BIO_new_file call, FILE:{FILE}",
630 "FILE", filePath);
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600631 elog<InternalFailure>();
632 }
633
634 X509* x509 = cert.get();
635 PEM_read_bio_X509(bioCert.get(), &x509, nullptr, nullptr);
636
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800637 EVPPkeyPtr pubKey(X509_get_pubkey(cert.get()), ::EVP_PKEY_free);
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600638 if (!pubKey)
639 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500640 lg2::error(
641 "Error occurred during X509_get_pubkey, FILE:{FILE}, ERRCODE:{ERRCODE}",
642 "FILE", filePath, "ERRCODE", ERR_get_error());
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800643 elog<InvalidCertificateError>(
644 InvalidCertificate::REASON("Failed to get public key info"));
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600645 }
646
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800647 BIOMemPtr keyBio(BIO_new(BIO_s_file()), ::BIO_free);
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600648 if (!keyBio)
649 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500650 lg2::error("Error occurred during BIO_s_file call, FILE:{FILE}", "FILE",
651 filePath);
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600652 elog<InternalFailure>();
653 }
654 BIO_read_filename(keyBio.get(), filePath.c_str());
655
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800656 EVPPkeyPtr priKey(
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600657 PEM_read_bio_PrivateKey(keyBio.get(), nullptr, nullptr, nullptr),
658 ::EVP_PKEY_free);
659 if (!priKey)
660 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500661 lg2::error(
662 "Error occurred during PEM_read_bio_PrivateKey, FILE:{FILE}, ERRCODE:{ERRCODE}",
663 "FILE", filePath, "ERRCODE", ERR_get_error());
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800664 elog<InvalidCertificateError>(
665 InvalidCertificate::REASON("Failed to get private key info"));
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600666 }
667
Patrick Williams55ceaa22021-12-14 06:52:26 -0600668#if (OPENSSL_VERSION_NUMBER < 0x30000000L)
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600669 int32_t rc = EVP_PKEY_cmp(priKey.get(), pubKey.get());
Patrick Williams55ceaa22021-12-14 06:52:26 -0600670#else
671 int32_t rc = EVP_PKEY_eq(priKey.get(), pubKey.get());
672#endif
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600673 if (rc != 1)
674 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500675 lg2::error(
676 "Private key is not matching with Certificate, FILE:{FILE}, ERRCODE:{ERRCODE}",
677 "FILE", filePath, "ERRCODE", rc);
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600678 return false;
679 }
680 return true;
681}
682
Zbigniew Kurzynskia3bb38f2019-09-17 13:34:25 +0200683void Certificate::delete_()
684{
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100685 manager.deleteCertificate(this);
Zbigniew Kurzynskia3bb38f2019-09-17 13:34:25 +0200686}
Nan Zhou6ec13c82021-12-30 11:34:50 -0800687
688std::string Certificate::getObjectPath()
689{
690 return objectPath;
691}
692
693std::string Certificate::getCertFilePath()
694{
695 return certFilePath;
696}
697
698void Certificate::setCertFilePath(const std::string& path)
699{
700 certFilePath = path;
701}
702
703void Certificate::setCertInstallPath(const std::string& path)
704{
705 certInstallPath = path;
706}
707
Nan Zhoue1289ad2021-12-28 11:02:56 -0800708} // namespace phosphor::certs