rippled
Loading...
Searching...
No Matches
RegisterSSLCerts.cpp
1#include <xrpl/net/RegisterSSLCerts.h>
2
3#if BOOST_OS_WINDOWS
4#include <boost/asio/ssl/error.hpp>
5#include <boost/system/error_code.hpp>
6
7#include <openssl/err.h>
8#include <openssl/ssl.h>
9#include <openssl/x509.h>
10
11#include <wincrypt.h>
12
13#include <memory>
14#endif
15
16namespace ripple {
17
18void
20 boost::asio::ssl::context& ctx,
21 boost::system::error_code& ec,
23{
24#if BOOST_OS_WINDOWS
25 auto certStoreDelete = [](void* h) {
26 if (h != nullptr)
27 CertCloseStore(h, 0);
28 };
29 std::unique_ptr<void, decltype(certStoreDelete)> hStore{
30 CertOpenSystemStore(0, "ROOT"), certStoreDelete};
31
32 if (!hStore)
33 {
34 ec = boost::system::error_code(
35 GetLastError(), boost::system::system_category());
36 return;
37 }
38
39 ERR_clear_error();
40
41 std::unique_ptr<X509_STORE, decltype(X509_STORE_free)*> store{
42 X509_STORE_new(), X509_STORE_free};
43
44 if (!store)
45 {
46 ec = boost::system::error_code(
47 static_cast<int>(::ERR_get_error()),
48 boost::asio::error::get_ssl_category());
49 return;
50 }
51
52 auto warn = [&](std::string const& mesg) {
53 // Buffer based on asio recommended size
54 char buf[256];
55 ::ERR_error_string_n(ec.value(), buf, sizeof(buf));
56 JLOG(j.warn()) << mesg << " " << buf;
57 ::ERR_clear_error();
58 };
59
60 PCCERT_CONTEXT pContext = NULL;
61 while ((pContext = CertEnumCertificatesInStore(hStore.get(), pContext)) !=
62 NULL)
63 {
64 unsigned char const* pbCertEncoded = pContext->pbCertEncoded;
65 std::unique_ptr<X509, decltype(X509_free)*> x509{
66 d2i_X509(NULL, &pbCertEncoded, pContext->cbCertEncoded), X509_free};
67 if (!x509)
68 {
69 warn("Error decoding certificate");
70 continue;
71 }
72
73 if (X509_STORE_add_cert(store.get(), x509.get()) != 1)
74 {
75 warn("Error adding certificate");
76 }
77 else
78 {
79 // Successfully adding to the store took ownership
80 x509.release();
81 }
82 }
83
84 // This takes ownership of the store
85 SSL_CTX_set_cert_store(ctx.native_handle(), store.release());
86
87#else
88 ctx.set_default_verify_paths(ec);
89#endif
90}
91
92} // namespace ripple
93
94// There is a very unpleasant interaction between <wincrypt> and
95// openssl x509 types (namely the former has macros that stomp
96// on the latter), these undefs allow this TU to be safely used in
97// unity builds without messing up subsequent TUs.
98#if BOOST_OS_WINDOWS
99#undef X509_NAME
100#undef X509_EXTENSIONS
101#undef X509_CERT_PAIR
102#undef PKCS7_ISSUER_AND_SERIAL
103#undef OCSP_REQUEST
104#undef OCSP_RESPONSE
105#endif
A generic endpoint for log messages.
Definition Journal.h:41
Stream warn() const
Definition Journal.h:321
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:6
void registerSSLCerts(boost::asio::ssl::context &, boost::system::error_code &, beast::Journal j)
Register default SSL certificates.