1 #include "config.h"
2
3 #include "csr.hpp"
4
5 #include <openssl/bio.h>
6 #include <openssl/buffer.h>
7 #include <openssl/ossl_typ.h>
8 #include <openssl/pem.h>
9 #include <openssl/x509.h>
10
11 #include <phosphor-logging/elog-errors.hpp>
12 #include <phosphor-logging/elog.hpp>
13 #include <phosphor-logging/lg2.hpp>
14 #include <xyz/openbmc_project/Certs/error.hpp>
15 #include <xyz/openbmc_project/Common/error.hpp>
16
17 #include <cstdio>
18 #include <filesystem>
19 #include <memory>
20 #include <utility>
21
22 namespace phosphor::certs
23 {
24
25 using ::phosphor::logging::elog;
26 using ::sdbusplus::xyz::openbmc_project::Common::Error::InternalFailure;
27 namespace fs = std::filesystem;
28
29 using X509ReqPtr = std::unique_ptr<X509_REQ, decltype(&::X509_REQ_free)>;
30 using BIOPtr = std::unique_ptr<BIO, decltype(&::BIO_free_all)>;
31
CSR(sdbusplus::bus_t & bus,const char * path,std::string && installPath,const Status & status)32 CSR::CSR(sdbusplus::bus_t& bus, const char* path, std::string&& installPath,
33 const Status& status) :
34 internal::CSRInterface(bus, path,
35 internal::CSRInterface::action::defer_emit),
36 objectPath(path), certInstallPath(std::move(installPath)), csrStatus(status)
37 {
38 // Emit deferred signal.
39 this->emit_object_added();
40 }
41
csr()42 std::string CSR::csr()
43 {
44 if (csrStatus == Status::failure)
45 {
46 lg2::error("Failure in Generating CSR");
47 elog<InternalFailure>();
48 }
49 fs::path csrFilePath = certInstallPath;
50 csrFilePath = csrFilePath.parent_path() / defaultCSRFileName;
51 if (!fs::exists(csrFilePath))
52 {
53 lg2::error("CSR file doesn't exists, FILENAME:{FILENAME}", "FILENAME",
54 csrFilePath);
55 elog<InternalFailure>();
56 }
57
58 FILE* fp = std::fopen(csrFilePath.c_str(), "r");
59 X509ReqPtr x509Req(PEM_read_X509_REQ(fp, nullptr, nullptr, nullptr),
60 ::X509_REQ_free);
61 if (x509Req == nullptr || fp == nullptr)
62 {
63 if (fp != nullptr)
64 {
65 std::fclose(fp);
66 }
67 lg2::error("ERROR occurred while reading CSR file, FILENAME:{FILENAME}",
68 "FILENAME", csrFilePath);
69 elog<InternalFailure>();
70 }
71 std::fclose(fp);
72
73 BIOPtr bio(BIO_new(BIO_s_mem()), ::BIO_free_all);
74 int ret = PEM_write_bio_X509_REQ(bio.get(), x509Req.get());
75 if (ret <= 0)
76 {
77 lg2::error("Error occurred while calling PEM_write_bio_X509_REQ");
78 elog<InternalFailure>();
79 }
80
81 BUF_MEM* mem = nullptr;
82 BIO_get_mem_ptr(bio.get(), &mem);
83 std::string pem(mem->data, mem->length);
84 return pem;
85 }
86
87 } // namespace phosphor::certs
88