blob: 047482d4019862627c3739aa4c29a68245ad28ed [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>
Nan Zhou014be0b2021-12-28 18:00:14 -080033#include <utility>
34#include <vector>
Marri Devender Rao13bf74e2019-03-26 01:52:17 -050035
Nan Zhoue1289ad2021-12-28 11:02:56 -080036namespace phosphor::certs
Marri Devender Rao6ceec402019-02-01 03:15:19 -060037{
Nan Zhoucf06ccd2021-12-28 16:25:45 -080038
39namespace
40{
41namespace fs = std::filesystem;
42using ::phosphor::logging::elog;
Nan Zhoucf06ccd2021-12-28 16:25:45 -080043using InvalidCertificateError =
44 ::sdbusplus::xyz::openbmc_project::Certs::Error::InvalidCertificate;
45using ::phosphor::logging::xyz::openbmc_project::Certs::InvalidCertificate;
46using ::sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure;
47
Marri Devender Rao6ceec402019-02-01 03:15:19 -060048// RAII support for openSSL functions.
Nan Zhoucf06ccd2021-12-28 16:25:45 -080049using BIOMemPtr = std::unique_ptr<BIO, decltype(&::BIO_free)>;
50using X509StorePtr = std::unique_ptr<X509_STORE, decltype(&::X509_STORE_free)>;
Nan Zhoucf06ccd2021-12-28 16:25:45 -080051using ASN1TimePtr = std::unique_ptr<ASN1_TIME, decltype(&ASN1_STRING_free)>;
52using EVPPkeyPtr = std::unique_ptr<EVP_PKEY, decltype(&::EVP_PKEY_free)>;
53using BufMemPtr = std::unique_ptr<BUF_MEM, decltype(&::BUF_MEM_free)>;
Marri Devender Rao6ceec402019-02-01 03:15:19 -060054
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -060055// Refer to schema 2018.3
56// http://redfish.dmtf.org/schemas/v1/Certificate.json#/definitions/KeyUsage for
57// supported KeyUsage types in redfish
58// Refer to
59// https://github.com/openssl/openssl/blob/master/include/openssl/x509v3.h for
60// key usage bit fields
61std::map<uint8_t, std::string> keyUsageToRfStr = {
62 {KU_DIGITAL_SIGNATURE, "DigitalSignature"},
63 {KU_NON_REPUDIATION, "NonRepudiation"},
64 {KU_KEY_ENCIPHERMENT, "KeyEncipherment"},
65 {KU_DATA_ENCIPHERMENT, "DataEncipherment"},
66 {KU_KEY_AGREEMENT, "KeyAgreement"},
67 {KU_KEY_CERT_SIGN, "KeyCertSign"},
68 {KU_CRL_SIGN, "CRLSigning"},
69 {KU_ENCIPHER_ONLY, "EncipherOnly"},
70 {KU_DECIPHER_ONLY, "DecipherOnly"}};
71
72// Refer to schema 2018.3
73// http://redfish.dmtf.org/schemas/v1/Certificate.json#/definitions/KeyUsage for
74// supported Extended KeyUsage types in redfish
75std::map<uint8_t, std::string> extendedKeyUsageToRfStr = {
76 {NID_server_auth, "ServerAuthentication"},
77 {NID_client_auth, "ClientAuthentication"},
78 {NID_email_protect, "EmailProtection"},
79 {NID_OCSP_sign, "OCSPSigning"},
80 {NID_ad_timeStamping, "Timestamping"},
81 {NID_code_sign, "CodeSigning"}};
82
Nan Zhoue869bb62021-12-30 11:34:42 -080083/**
Nan Zhou6ec13c82021-12-30 11:34:50 -080084 * @brief Dumps the PEM encoded certificate to installFilePath
Nan Zhoue869bb62021-12-30 11:34:42 -080085 *
Nan Zhou6ec13c82021-12-30 11:34:50 -080086 * @param[in] pem - PEM encoded X509 certificate buffer.
87 * @param[in] certFilePath - Path to the destination file.
Nan Zhoue869bb62021-12-30 11:34:42 -080088 *
89 * @return void
90 */
Nan Zhou6ec13c82021-12-30 11:34:50 -080091
92void dumpCertificate(const std::string& pem, const std::string& certFilePath)
93{
94 std::ofstream outputCertFileStream;
95
96 outputCertFileStream.exceptions(
97 std::ofstream::failbit | std::ofstream::badbit | std::ofstream::eofbit);
98
99 try
100 {
101 outputCertFileStream.open(certFilePath, std::ios::out);
102 outputCertFileStream << pem << "\n" << std::flush;
103 outputCertFileStream.close();
104 }
105 catch (const std::exception& e)
106 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500107 lg2::error(
108 "Failed to dump certificate, ERR:{ERR}, SRC_PEM:{SRC_PEM}, DST:{DST}",
109 "ERR", e, "SRC_PEM", pem, "DST", certFilePath);
Nan Zhou6ec13c82021-12-30 11:34:50 -0800110 elog<InternalFailure>();
111 }
112}
113} // namespace
114
115void Certificate::copyCertificate(const std::string& certSrcFilePath,
116 const std::string& certFilePath)
Kowalski, Kamildb029c92019-07-08 17:09:39 +0200117{
Nan Zhoue869bb62021-12-30 11:34:42 -0800118 // Copy the certificate to the installation path
Manojkiran Eda5d4f7932024-06-17 11:49:21 +0530119 // During boot up will be parsing existing file so no need to
Nan Zhoue869bb62021-12-30 11:34:42 -0800120 // copy it.
121 if (certSrcFilePath != certFilePath)
122 {
123 std::ifstream inputCertFileStream;
124 std::ofstream outputCertFileStream;
125 inputCertFileStream.exceptions(std::ifstream::failbit |
126 std::ifstream::badbit |
127 std::ifstream::eofbit);
128 outputCertFileStream.exceptions(std::ofstream::failbit |
129 std::ofstream::badbit |
130 std::ofstream::eofbit);
131 try
132 {
133 inputCertFileStream.open(certSrcFilePath);
134 outputCertFileStream.open(certFilePath, std::ios::out);
135 outputCertFileStream << inputCertFileStream.rdbuf() << std::flush;
136 inputCertFileStream.close();
137 outputCertFileStream.close();
138 }
139 catch (const std::exception& e)
140 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500141 lg2::error(
142 "Failed to copy certificate, ERR:{ERR}, SRC:{SRC}, DST:{DST}",
143 "ERR", e, "SRC", certSrcFilePath, "DST", certFilePath);
Nan Zhoue869bb62021-12-30 11:34:42 -0800144 elog<InternalFailure>();
145 }
146 }
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100147}
148
149std::string
150 Certificate::generateUniqueFilePath(const std::string& directoryPath)
151{
Nan Zhoucfb58022021-12-28 11:02:26 -0800152 char* filePath = tempnam(directoryPath.c_str(), nullptr);
153 if (filePath == nullptr)
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100154 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500155 lg2::error(
156 "Error occurred while creating random certificate file path, DIR:{DIR}",
157 "DIR", directoryPath);
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100158 elog<InternalFailure>();
159 }
160 std::string filePathStr(filePath);
161 free(filePath);
162 return filePathStr;
163}
164
165std::string Certificate::generateAuthCertFileX509Path(
166 const std::string& certSrcFilePath, const std::string& certDstDirPath)
167{
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800168 const internal::X509Ptr cert = loadCert(certSrcFilePath);
Kowalski, Kamildb029c92019-07-08 17:09:39 +0200169 unsigned long hash = X509_subject_name_hash(cert.get());
Nan Zhoue3d47cd2022-09-16 03:41:53 +0000170 static constexpr auto certHashLength = 9;
171 char hashBuf[certHashLength];
Kowalski, Kamildb029c92019-07-08 17:09:39 +0200172
Nan Zhoue3d47cd2022-09-16 03:41:53 +0000173 snprintf(hashBuf, certHashLength, "%08lx", hash);
Kowalski, Kamildb029c92019-07-08 17:09:39 +0200174
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100175 const std::string certHash(hashBuf);
Nan Zhou718eef32021-12-28 11:03:30 -0800176 for (size_t i = 0; i < maxNumAuthorityCertificates; ++i)
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100177 {
Zbigniew Lukwinski73d1fbf2020-01-15 15:31:12 +0100178 const std::string certDstFileX509Path =
179 certDstDirPath + "/" + certHash + "." + std::to_string(i);
180 if (!fs::exists(certDstFileX509Path))
181 {
182 return certDstFileX509Path;
183 }
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100184 }
Kowalski, Kamildb029c92019-07-08 17:09:39 +0200185
Ravi Tejaf2646272023-09-30 13:00:55 -0500186 lg2::error("Authority certificate x509 file path already used, DIR:{DIR}",
187 "DIR", certDstDirPath);
Zbigniew Lukwinski73d1fbf2020-01-15 15:31:12 +0100188 elog<InternalFailure>();
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100189}
190
191std::string
192 Certificate::generateAuthCertFilePath(const std::string& certSrcFilePath)
193{
194 // If there is a certificate file path (which means certificate replacement
195 // is doing) use it (do not create new one)
196 if (!certFilePath.empty())
197 {
198 return certFilePath;
199 }
200 // If source certificate file is located in the certificates directory use
201 // it (do not create new one)
202 else if (fs::path(certSrcFilePath).parent_path().string() ==
203 certInstallPath)
204 {
205 return certSrcFilePath;
206 }
207 // Otherwise generate new file name/path
208 else
209 {
210 return generateUniqueFilePath(certInstallPath);
211 }
212}
213
214std::string
215 Certificate::generateCertFilePath(const std::string& certSrcFilePath)
216{
Nan Zhoue3d47cd2022-09-16 03:41:53 +0000217 if (certType == CertificateType::authority)
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100218 {
219 return generateAuthCertFilePath(certSrcFilePath);
220 }
221 else
222 {
223 return certInstallPath;
224 }
Kowalski, Kamildb029c92019-07-08 17:09:39 +0200225}
226
Patrick Williamsb3dbfb32022-07-22 19:26:57 -0500227Certificate::Certificate(sdbusplus::bus_t& bus, const std::string& objPath,
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800228 CertificateType type, const std::string& installPath,
229 const std::string& uploadPath, Watch* watch,
Willy Tu698a5742022-09-23 21:33:01 +0000230 Manager& parent, bool restore) :
Patrick Williamsebd21ba2022-04-05 14:58:53 -0500231 internal::CertificateInterface(
232 bus, objPath.c_str(),
233 internal::CertificateInterface::action::defer_emit),
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800234 objectPath(objPath), certType(type), certInstallPath(installPath),
235 certWatch(watch), manager(parent)
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600236{
237 auto installHelper = [this](const auto& filePath) {
238 if (!compareKeys(filePath))
239 {
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800240 elog<InvalidCertificateError>(InvalidCertificate::REASON(
241 "Private key does not match the Certificate"));
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600242 };
243 };
Nan Zhoue3d47cd2022-09-16 03:41:53 +0000244 typeFuncMap[CertificateType::server] = installHelper;
245 typeFuncMap[CertificateType::client] = installHelper;
246 typeFuncMap[CertificateType::authority] = [](const std::string&) {};
Marri Devender Raocd30c492019-06-12 01:40:17 -0500247
248 auto appendPrivateKey = [this](const std::string& filePath) {
249 checkAndAppendPrivateKey(filePath);
250 };
251
Nan Zhoue3d47cd2022-09-16 03:41:53 +0000252 appendKeyMap[CertificateType::server] = appendPrivateKey;
253 appendKeyMap[CertificateType::client] = appendPrivateKey;
254 appendKeyMap[CertificateType::authority] = [](const std::string&) {};
Marri Devender Raocd30c492019-06-12 01:40:17 -0500255
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100256 // Generate certificate file path
257 certFilePath = generateCertFilePath(uploadPath);
258
Marri Devender Raocd30c492019-06-12 01:40:17 -0500259 // install the certificate
Willy Tu698a5742022-09-23 21:33:01 +0000260 install(uploadPath, restore);
Marri Devender Raocd30c492019-06-12 01:40:17 -0500261
Marri Devender Raoedd11312019-02-27 08:45:10 -0600262 this->emit_object_added();
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600263}
264
Patrick Williamsb3dbfb32022-07-22 19:26:57 -0500265Certificate::Certificate(sdbusplus::bus_t& bus, const std::string& objPath,
Nan Zhou6ec13c82021-12-30 11:34:50 -0800266 const CertificateType& type,
267 const std::string& installPath, X509_STORE& x509Store,
268 const std::string& pem, Watch* watchPtr,
Willy Tu698a5742022-09-23 21:33:01 +0000269 Manager& parent, bool restore) :
Patrick Williamsebd21ba2022-04-05 14:58:53 -0500270 internal::CertificateInterface(
271 bus, objPath.c_str(),
272 internal::CertificateInterface::action::defer_emit),
Nan Zhou6ec13c82021-12-30 11:34:50 -0800273 objectPath(objPath), certType(type), certInstallPath(installPath),
274 certWatch(watchPtr), manager(parent)
275{
276 // Generate certificate file path
277 certFilePath = generateUniqueFilePath(installPath);
278
279 // install the certificate
Willy Tu698a5742022-09-23 21:33:01 +0000280 install(x509Store, pem, restore);
Nan Zhou6ec13c82021-12-30 11:34:50 -0800281
282 this->emit_object_added();
283}
284
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600285Certificate::~Certificate()
286{
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100287 if (!fs::remove(certFilePath))
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600288 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500289 lg2::info("Certificate file not found! PATH:{PATH}", "PATH",
290 certFilePath);
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600291 }
292}
293
Marri Devender Rao13bf74e2019-03-26 01:52:17 -0500294void Certificate::replace(const std::string filePath)
295{
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100296 manager.replaceCertificate(this, filePath);
Marri Devender Rao13bf74e2019-03-26 01:52:17 -0500297}
298
Willy Tu698a5742022-09-23 21:33:01 +0000299void Certificate::install(const std::string& certSrcFilePath, bool restore)
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600300{
Willy Tu698a5742022-09-23 21:33:01 +0000301 if (restore)
302 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500303 lg2::debug("Certificate install, FILEPATH:{FILEPATH}", "FILEPATH",
304 certSrcFilePath);
Willy Tu698a5742022-09-23 21:33:01 +0000305 }
306 else
307 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500308 lg2::info("Certificate install, FILEPATH:{FILEPATH}", "FILEPATH",
309 certSrcFilePath);
Willy Tu698a5742022-09-23 21:33:01 +0000310 }
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600311
Marri Devender Raoffad1ef2019-06-03 04:54:12 -0500312 // stop watch for user initiated certificate install
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800313 if (certWatch != nullptr)
Marri Devender Raoffad1ef2019-06-03 04:54:12 -0500314 {
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800315 certWatch->stopWatch();
Marri Devender Raoffad1ef2019-06-03 04:54:12 -0500316 }
317
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600318 // Verify the certificate file
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100319 fs::path file(certSrcFilePath);
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600320 if (!fs::exists(file))
321 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500322 lg2::error("File is Missing, FILE:{FILE}", "FILE", certSrcFilePath);
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600323 elog<InternalFailure>();
324 }
325
326 try
327 {
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100328 if (fs::file_size(certSrcFilePath) == 0)
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600329 {
330 // file is empty
Ravi Tejaf2646272023-09-30 13:00:55 -0500331 lg2::error("File is empty, FILE:{FILE}", "FILE", certSrcFilePath);
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800332 elog<InvalidCertificateError>(
333 InvalidCertificate::REASON("File is empty"));
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600334 }
335 }
336 catch (const fs::filesystem_error& e)
337 {
338 // Log Error message
Ravi Tejaf2646272023-09-30 13:00:55 -0500339 lg2::error("File is empty, FILE:{FILE}, ERR:{ERR}", "FILE",
340 certSrcFilePath, "ERR", e);
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600341 elog<InternalFailure>();
342 }
343
Nan Zhoue869bb62021-12-30 11:34:42 -0800344 X509StorePtr x509Store = getX509Store(certSrcFilePath);
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600345
Nan Zhoubf3cf752021-12-28 11:02:07 -0800346 // Load Certificate file into the X509 structure.
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800347 internal::X509Ptr cert = loadCert(certSrcFilePath);
Nan Zhoue869bb62021-12-30 11:34:42 -0800348
349 // Perform validation
350 validateCertificateAgainstStore(*x509Store, *cert);
351 validateCertificateStartDate(*cert);
352 validateCertificateInSSLContext(*cert);
353
354 // Invoke type specific append private key function.
355 if (auto it = appendKeyMap.find(certType); it == appendKeyMap.end())
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600356 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500357 lg2::error("Unsupported Type, TYPE:{TYPE}", "TYPE",
358 certificateTypeToString(certType));
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600359 elog<InternalFailure>();
360 }
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600361 else
362 {
Nan Zhoue869bb62021-12-30 11:34:42 -0800363 it->second(certSrcFilePath);
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600364 }
365
Marri Devender Raocd30c492019-06-12 01:40:17 -0500366 // Invoke type specific compare keys function.
Nan Zhoue869bb62021-12-30 11:34:42 -0800367 if (auto it = typeFuncMap.find(certType); it == typeFuncMap.end())
Marri Devender Raocd30c492019-06-12 01:40:17 -0500368 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500369 lg2::error("Unsupported Type, TYPE:{TYPE}", "TYPE",
370 certificateTypeToString(certType));
Marri Devender Raocd30c492019-06-12 01:40:17 -0500371 elog<InternalFailure>();
372 }
Nan Zhoue869bb62021-12-30 11:34:42 -0800373 else
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600374 {
Nan Zhoue869bb62021-12-30 11:34:42 -0800375 it->second(certSrcFilePath);
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600376 }
Marri Devender Rao8f80c352019-05-13 00:53:01 -0500377
Nan Zhoue869bb62021-12-30 11:34:42 -0800378 copyCertificate(certSrcFilePath, certFilePath);
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100379 storageUpdate();
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600380
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100381 // Keep certificate ID
Nan Zhoue869bb62021-12-30 11:34:42 -0800382 certId = generateCertId(*cert);
Kowalski, Kamildb029c92019-07-08 17:09:39 +0200383
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600384 // Parse the certificate file and populate properties
Nan Zhoue869bb62021-12-30 11:34:42 -0800385 populateProperties(*cert);
Marri Devender Raoffad1ef2019-06-03 04:54:12 -0500386
387 // restart watch
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800388 if (certWatch != nullptr)
Marri Devender Raoffad1ef2019-06-03 04:54:12 -0500389 {
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800390 certWatch->startWatch();
Marri Devender Raoffad1ef2019-06-03 04:54:12 -0500391 }
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600392}
393
Willy Tu698a5742022-09-23 21:33:01 +0000394void Certificate::install(X509_STORE& x509Store, const std::string& pem,
395 bool restore)
Nan Zhou6ec13c82021-12-30 11:34:50 -0800396{
Willy Tu698a5742022-09-23 21:33:01 +0000397 if (restore)
398 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500399 lg2::debug("Certificate install, PEM_STR:{PEM_STR}", "PEM_STR", pem);
Willy Tu698a5742022-09-23 21:33:01 +0000400 }
401 else
402 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500403 lg2::info("Certificate install, PEM_STR:{PEM_STR} ", "PEM_STR", pem);
Willy Tu698a5742022-09-23 21:33:01 +0000404 }
Nan Zhou6ec13c82021-12-30 11:34:50 -0800405
Nan Zhoue3d47cd2022-09-16 03:41:53 +0000406 if (certType != CertificateType::authority)
Nan Zhou6ec13c82021-12-30 11:34:50 -0800407 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500408 lg2::error("Bulk install error: Unsupported Type; only authority "
409 "supports bulk install, TYPE:{TYPE}",
410 "TYPE", certificateTypeToString(certType));
Nan Zhou6ec13c82021-12-30 11:34:50 -0800411 elog<InternalFailure>();
412 }
413
414 // stop watch for user initiated certificate install
415 if (certWatch)
416 {
417 certWatch->stopWatch();
418 }
419
420 // Load Certificate file into the X509 structure.
421 internal::X509Ptr cert = parseCert(pem);
422 // Perform validation; no type specific compare keys function
423 validateCertificateAgainstStore(x509Store, *cert);
424 validateCertificateStartDate(*cert);
425 validateCertificateInSSLContext(*cert);
426
427 // Copy the PEM to the installation path
428 dumpCertificate(pem, certFilePath);
429 storageUpdate();
430 // Keep certificate ID
431 certId = generateCertId(*cert);
432 // Parse the certificate file and populate properties
433 populateProperties(*cert);
434 // restart watch
435 if (certWatch)
436 {
437 certWatch->startWatch();
438 }
439}
440
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600441void Certificate::populateProperties()
442{
Nan Zhoue869bb62021-12-30 11:34:42 -0800443 internal::X509Ptr cert = loadCert(certInstallPath);
444 populateProperties(*cert);
Kowalski, Kamildb029c92019-07-08 17:09:39 +0200445}
446
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100447std::string Certificate::getCertId() const
Kowalski, Kamildb029c92019-07-08 17:09:39 +0200448{
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100449 return certId;
450}
451
452bool Certificate::isSame(const std::string& certPath)
453{
Nan Zhoue869bb62021-12-30 11:34:42 -0800454 internal::X509Ptr cert = loadCert(certPath);
455 return getCertId() == generateCertId(*cert);
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100456}
457
458void Certificate::storageUpdate()
459{
Nan Zhoue3d47cd2022-09-16 03:41:53 +0000460 if (certType == CertificateType::authority)
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100461 {
462 // Create symbolic link in the certificate directory
463 std::string certFileX509Path;
464 try
465 {
466 if (!certFilePath.empty() &&
467 fs::is_regular_file(fs::path(certFilePath)))
468 {
469 certFileX509Path =
470 generateAuthCertFileX509Path(certFilePath, certInstallPath);
471 fs::create_symlink(fs::path(certFilePath),
472 fs::path(certFileX509Path));
473 }
474 }
475 catch (const std::exception& e)
476 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500477 lg2::error("Failed to create symlink for certificate, ERR:{ERR},"
478 "FILE:{FILE}, SYMLINK:{SYMLINK}",
479 "ERR", e, "FILE", certFilePath, "SYMLINK",
480 certFileX509Path);
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100481 elog<InternalFailure>();
482 }
483 }
Kowalski, Kamildb029c92019-07-08 17:09:39 +0200484}
485
Nan Zhoue869bb62021-12-30 11:34:42 -0800486void Certificate::populateProperties(X509& cert)
Kowalski, Kamildb029c92019-07-08 17:09:39 +0200487{
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600488 // Update properties if no error thrown
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800489 BIOMemPtr certBio(BIO_new(BIO_s_mem()), BIO_free);
Nan Zhoue869bb62021-12-30 11:34:42 -0800490 PEM_write_bio_X509(certBio.get(), &cert);
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800491 BufMemPtr certBuf(BUF_MEM_new(), BUF_MEM_free);
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600492 BUF_MEM* buf = certBuf.get();
493 BIO_get_mem_ptr(certBio.get(), &buf);
494 std::string certStr(buf->data, buf->length);
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800495 certificateString(certStr);
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600496
497 static const int maxKeySize = 4096;
498 char subBuffer[maxKeySize] = {0};
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800499 BIOMemPtr subBio(BIO_new(BIO_s_mem()), BIO_free);
Manojkiran Eda5d4f7932024-06-17 11:49:21 +0530500 // This pointer cannot be freed independently.
Nan Zhoue869bb62021-12-30 11:34:42 -0800501 X509_NAME* sub = X509_get_subject_name(&cert);
Marri Devender Raodec58772019-06-11 03:10:00 -0500502 X509_NAME_print_ex(subBio.get(), sub, 0, XN_FLAG_SEP_COMMA_PLUS);
503 BIO_read(subBio.get(), subBuffer, maxKeySize);
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800504 subject(subBuffer);
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600505
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600506 char issuerBuffer[maxKeySize] = {0};
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800507 BIOMemPtr issuerBio(BIO_new(BIO_s_mem()), BIO_free);
Manojkiran Eda5d4f7932024-06-17 11:49:21 +0530508 // This pointer cannot be freed independently.
Nan Zhoue3d47cd2022-09-16 03:41:53 +0000509 X509_NAME* issuerName = X509_get_issuer_name(&cert);
510 X509_NAME_print_ex(issuerBio.get(), issuerName, 0, XN_FLAG_SEP_COMMA_PLUS);
Marri Devender Raodec58772019-06-11 03:10:00 -0500511 BIO_read(issuerBio.get(), issuerBuffer, maxKeySize);
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800512 issuer(issuerBuffer);
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600513
514 std::vector<std::string> keyUsageList;
515 ASN1_BIT_STRING* usage;
516
517 // Go through each usage in the bit string and convert to
518 // corresponding string value
519 if ((usage = static_cast<ASN1_BIT_STRING*>(
Nan Zhoue869bb62021-12-30 11:34:42 -0800520 X509_get_ext_d2i(&cert, NID_key_usage, nullptr, nullptr))))
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600521 {
522 for (auto i = 0; i < usage->length; ++i)
523 {
524 for (auto& x : keyUsageToRfStr)
525 {
526 if (x.first & usage->data[i])
527 {
528 keyUsageList.push_back(x.second);
529 break;
530 }
531 }
532 }
533 }
534
535 EXTENDED_KEY_USAGE* extUsage;
Nan Zhoue869bb62021-12-30 11:34:42 -0800536 if ((extUsage = static_cast<EXTENDED_KEY_USAGE*>(
537 X509_get_ext_d2i(&cert, NID_ext_key_usage, nullptr, nullptr))))
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600538 {
539 for (int i = 0; i < sk_ASN1_OBJECT_num(extUsage); i++)
540 {
541 keyUsageList.push_back(extendedKeyUsageToRfStr[OBJ_obj2nid(
542 sk_ASN1_OBJECT_value(extUsage, i))]);
543 }
544 }
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800545 keyUsage(keyUsageList);
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600546
547 int days = 0;
548 int secs = 0;
549
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800550 ASN1TimePtr epoch(ASN1_TIME_new(), ASN1_STRING_free);
Nan Zhoucf811c42021-12-02 14:56:17 -0800551 // Set time to 00:00am GMT, Jan 1 1970; format: YYYYMMDDHHMMSSZ
552 ASN1_TIME_set_string(epoch.get(), "19700101000000Z");
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600553
Nan Zhoucf811c42021-12-02 14:56:17 -0800554 static const uint64_t dayToSeconds = 24 * 60 * 60;
Nan Zhoue869bb62021-12-30 11:34:42 -0800555 ASN1_TIME* notAfter = X509_get_notAfter(&cert);
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600556 ASN1_TIME_diff(&days, &secs, epoch.get(), notAfter);
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800557 validNotAfter((days * dayToSeconds) + secs);
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600558
Nan Zhoue869bb62021-12-30 11:34:42 -0800559 ASN1_TIME* notBefore = X509_get_notBefore(&cert);
Dhruvaraj Subhashchandran36f25142019-02-14 05:06:26 -0600560 ASN1_TIME_diff(&days, &secs, epoch.get(), notBefore);
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800561 validNotBefore((days * dayToSeconds) + secs);
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600562}
563
Marri Devender Raocd30c492019-06-12 01:40:17 -0500564void Certificate::checkAndAppendPrivateKey(const std::string& filePath)
565{
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800566 BIOMemPtr keyBio(BIO_new(BIO_s_file()), ::BIO_free);
Marri Devender Raocd30c492019-06-12 01:40:17 -0500567 if (!keyBio)
568 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500569 lg2::error("Error occurred during BIO_s_file call, FILE:{FILE}", "FILE",
570 filePath);
Marri Devender Raocd30c492019-06-12 01:40:17 -0500571 elog<InternalFailure>();
572 }
573 BIO_read_filename(keyBio.get(), filePath.c_str());
574
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800575 EVPPkeyPtr priKey(
Marri Devender Raocd30c492019-06-12 01:40:17 -0500576 PEM_read_bio_PrivateKey(keyBio.get(), nullptr, nullptr, nullptr),
577 ::EVP_PKEY_free);
578 if (!priKey)
579 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500580 lg2::info("Private key not present in file, FILE:{FILE}", "FILE",
581 filePath);
Marri Devender Raocd30c492019-06-12 01:40:17 -0500582 fs::path privateKeyFile = fs::path(certInstallPath).parent_path();
Nan Zhou718eef32021-12-28 11:03:30 -0800583 privateKeyFile = privateKeyFile / defaultPrivateKeyFileName;
Marri Devender Raocd30c492019-06-12 01:40:17 -0500584 if (!fs::exists(privateKeyFile))
585 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500586 lg2::error("Private key file is not found, FILE:{FILE}", "FILE",
587 privateKeyFile);
Marri Devender Raocd30c492019-06-12 01:40:17 -0500588 elog<InternalFailure>();
589 }
590
591 std::ifstream privKeyFileStream;
592 std::ofstream certFileStream;
593 privKeyFileStream.exceptions(std::ifstream::failbit |
594 std::ifstream::badbit |
595 std::ifstream::eofbit);
596 certFileStream.exceptions(std::ofstream::failbit |
597 std::ofstream::badbit |
598 std::ofstream::eofbit);
599 try
600 {
601 privKeyFileStream.open(privateKeyFile);
602 certFileStream.open(filePath, std::ios::app);
Marri Devender Rao18e51c92019-07-15 04:59:01 -0500603 certFileStream << std::endl; // insert line break
Marri Devender Raocd30c492019-06-12 01:40:17 -0500604 certFileStream << privKeyFileStream.rdbuf() << std::flush;
605 privKeyFileStream.close();
606 certFileStream.close();
607 }
608 catch (const std::exception& e)
609 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500610 lg2::error(
611 "Failed to append private key, ERR:{ERR}, SRC:{SRC}, DST:{DST}",
612 "ERR", e, "SRC", privateKeyFile, "DST", filePath);
Marri Devender Raocd30c492019-06-12 01:40:17 -0500613 elog<InternalFailure>();
614 }
615 }
616}
617
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600618bool Certificate::compareKeys(const std::string& filePath)
619{
Ravi Tejaf2646272023-09-30 13:00:55 -0500620 lg2::info("Certificate compareKeys, FILEPATH:{FILEPATH}", "FILEPATH",
621 filePath);
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800622 internal::X509Ptr cert(X509_new(), ::X509_free);
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600623 if (!cert)
624 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500625 lg2::error(
626 "Error occurred during X509_new call, FILE:{FILE}, ERRCODE:{ERRCODE}",
627 "FILE", filePath, "ERRCODE", ERR_get_error());
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600628 elog<InternalFailure>();
629 }
630
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800631 BIOMemPtr bioCert(BIO_new_file(filePath.c_str(), "rb"), ::BIO_free);
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600632 if (!bioCert)
633 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500634 lg2::error("Error occurred during BIO_new_file call, FILE:{FILE}",
635 "FILE", filePath);
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600636 elog<InternalFailure>();
637 }
638
639 X509* x509 = cert.get();
640 PEM_read_bio_X509(bioCert.get(), &x509, nullptr, nullptr);
641
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800642 EVPPkeyPtr pubKey(X509_get_pubkey(cert.get()), ::EVP_PKEY_free);
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600643 if (!pubKey)
644 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500645 lg2::error(
646 "Error occurred during X509_get_pubkey, FILE:{FILE}, ERRCODE:{ERRCODE}",
647 "FILE", filePath, "ERRCODE", ERR_get_error());
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800648 elog<InvalidCertificateError>(
649 InvalidCertificate::REASON("Failed to get public key info"));
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600650 }
651
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800652 BIOMemPtr keyBio(BIO_new(BIO_s_file()), ::BIO_free);
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600653 if (!keyBio)
654 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500655 lg2::error("Error occurred during BIO_s_file call, FILE:{FILE}", "FILE",
656 filePath);
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600657 elog<InternalFailure>();
658 }
659 BIO_read_filename(keyBio.get(), filePath.c_str());
660
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800661 EVPPkeyPtr priKey(
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600662 PEM_read_bio_PrivateKey(keyBio.get(), nullptr, nullptr, nullptr),
663 ::EVP_PKEY_free);
664 if (!priKey)
665 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500666 lg2::error(
667 "Error occurred during PEM_read_bio_PrivateKey, FILE:{FILE}, ERRCODE:{ERRCODE}",
668 "FILE", filePath, "ERRCODE", ERR_get_error());
Nan Zhoucf06ccd2021-12-28 16:25:45 -0800669 elog<InvalidCertificateError>(
670 InvalidCertificate::REASON("Failed to get private key info"));
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600671 }
672
Patrick Williams55ceaa22021-12-14 06:52:26 -0600673#if (OPENSSL_VERSION_NUMBER < 0x30000000L)
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600674 int32_t rc = EVP_PKEY_cmp(priKey.get(), pubKey.get());
Patrick Williams55ceaa22021-12-14 06:52:26 -0600675#else
676 int32_t rc = EVP_PKEY_eq(priKey.get(), pubKey.get());
677#endif
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600678 if (rc != 1)
679 {
Ravi Tejaf2646272023-09-30 13:00:55 -0500680 lg2::error(
681 "Private key is not matching with Certificate, FILE:{FILE}, ERRCODE:{ERRCODE}",
682 "FILE", filePath, "ERRCODE", rc);
Marri Devender Rao6ceec402019-02-01 03:15:19 -0600683 return false;
684 }
685 return true;
686}
687
Zbigniew Kurzynskia3bb38f2019-09-17 13:34:25 +0200688void Certificate::delete_()
689{
Zbigniew Lukwinski2f3563c2020-01-08 12:35:23 +0100690 manager.deleteCertificate(this);
Zbigniew Kurzynskia3bb38f2019-09-17 13:34:25 +0200691}
Nan Zhou6ec13c82021-12-30 11:34:50 -0800692
693std::string Certificate::getObjectPath()
694{
695 return objectPath;
696}
697
698std::string Certificate::getCertFilePath()
699{
700 return certFilePath;
701}
702
703void Certificate::setCertFilePath(const std::string& path)
704{
705 certFilePath = path;
706}
707
708void Certificate::setCertInstallPath(const std::string& path)
709{
710 certInstallPath = path;
711}
712
Nan Zhoue1289ad2021-12-28 11:02:56 -0800713} // namespace phosphor::certs