blob: c93a487c19e310430336ff8860b58164c177b54e [file] [log] [blame]
Patrick Williamse129be32021-04-30 20:35:19 -05001#include "config.h"
2
3#include "csr.hpp"
4
5#include <openssl/pem.h>
6
7#include <filesystem>
8#include <phosphor-logging/elog-errors.hpp>
9#include <phosphor-logging/elog.hpp>
10#include <xyz/openbmc_project/Certs/error.hpp>
11#include <xyz/openbmc_project/Common/error.hpp>
12
13namespace phosphor
14{
15namespace certs
16{
17
18using X509_REQ_Ptr = std::unique_ptr<X509_REQ, decltype(&::X509_REQ_free)>;
19using BIO_Ptr = std::unique_ptr<BIO, decltype(&::BIO_free_all)>;
20using InternalFailure =
21 sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure;
22using namespace phosphor::logging;
23namespace fs = std::filesystem;
24
25CSR::CSR(sdbusplus::bus::bus& bus, const char* path,
26 CertInstallPath&& installPath, const Status& status) :
27 CSRIface(bus, path, true),
28 bus(bus), objectPath(path), certInstallPath(std::move(installPath)),
29 csrStatus(status)
30{
31 // Emit deferred signal.
32 this->emit_object_added();
33}
34
Patrick Williamse129be32021-04-30 20:35:19 -050035std::string CSR::csr()
Patrick Williamse129be32021-04-30 20:35:19 -050036{
37 if (csrStatus == Status::FAILURE)
38 {
39 log<level::ERR>("Failure in Generating CSR");
40 elog<InternalFailure>();
41 }
42 fs::path csrFilePath = certInstallPath;
43 csrFilePath = csrFilePath.parent_path() / CSR_FILE_NAME;
44 if (!fs::exists(csrFilePath))
45 {
46 log<level::ERR>("CSR file doesn't exists",
47 entry("FILENAME=%s", csrFilePath.c_str()));
48 elog<InternalFailure>();
49 }
50
51 FILE* fp = std::fopen(csrFilePath.c_str(), "r");
52 X509_REQ_Ptr x509Req(PEM_read_X509_REQ(fp, NULL, NULL, NULL),
53 ::X509_REQ_free);
54 if (x509Req == NULL || fp == NULL)
55 {
56 if (fp != NULL)
57 {
58 std::fclose(fp);
59 }
Nan Zhoubf3cf752021-12-28 11:02:07 -080060 log<level::ERR>("ERROR occurred while reading CSR file",
Patrick Williamse129be32021-04-30 20:35:19 -050061 entry("FILENAME=%s", csrFilePath.c_str()));
62 elog<InternalFailure>();
63 }
64 std::fclose(fp);
65
66 BIO_Ptr bio(BIO_new(BIO_s_mem()), ::BIO_free_all);
67 int ret = PEM_write_bio_X509_REQ(bio.get(), x509Req.get());
68 if (ret <= 0)
69 {
Nan Zhoubf3cf752021-12-28 11:02:07 -080070 log<level::ERR>("Error occurred while calling PEM_write_bio_X509_REQ");
Patrick Williamse129be32021-04-30 20:35:19 -050071 elog<InternalFailure>();
72 }
73
74 BUF_MEM* mem = NULL;
75 BIO_get_mem_ptr(bio.get(), &mem);
76 std::string pem(mem->data, mem->length);
77 return pem;
78}
79
80} // namespace certs
81} // namespace phosphor