1 #pragma once
2 #ifdef BMCWEB_ENABLE_SSL
3 
4 #include <openssl/bio.h>
5 #include <openssl/dh.h>
6 #include <openssl/dsa.h>
7 #include <openssl/err.h>
8 #include <openssl/evp.h>
9 #include <openssl/pem.h>
10 #include <openssl/rand.h>
11 #include <openssl/rsa.h>
12 #include <openssl/ssl.h>
13 
14 #include <boost/asio/ssl/context.hpp>
15 
16 #include <random>
17 
18 namespace ensuressl
19 {
20 constexpr char const* trustStorePath = "/etc/ssl/certs/authority";
21 static void initOpenssl();
22 static EVP_PKEY* createEcKey();
23 
24 // Trust chain related errors.`
25 inline bool isTrustChainError(int errnum)
26 {
27     if ((errnum == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT) ||
28         (errnum == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN) ||
29         (errnum == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY) ||
30         (errnum == X509_V_ERR_CERT_UNTRUSTED) ||
31         (errnum == X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE))
32     {
33         return true;
34     }
35     else
36     {
37         return false;
38     }
39 }
40 
41 inline bool validateCertificate(X509* const cert)
42 {
43     // Create an empty X509_STORE structure for certificate validation.
44     X509_STORE* x509Store = X509_STORE_new();
45     if (!x509Store)
46     {
47         BMCWEB_LOG_ERROR << "Error occurred during X509_STORE_new call";
48         return false;
49     }
50 
51     // Load Certificate file into the X509 structure.
52     X509_STORE_CTX* storeCtx = X509_STORE_CTX_new();
53     if (!storeCtx)
54     {
55         BMCWEB_LOG_ERROR << "Error occurred during X509_STORE_CTX_new call";
56         X509_STORE_free(x509Store);
57         return false;
58     }
59 
60     int errCode = X509_STORE_CTX_init(storeCtx, x509Store, cert, nullptr);
61     if (errCode != 1)
62     {
63         BMCWEB_LOG_ERROR << "Error occurred during X509_STORE_CTX_init call";
64         X509_STORE_CTX_free(storeCtx);
65         X509_STORE_free(x509Store);
66         return false;
67     }
68 
69     errCode = X509_verify_cert(storeCtx);
70     if (errCode == 1)
71     {
72         BMCWEB_LOG_INFO << "Certificate verification is success";
73         X509_STORE_CTX_free(storeCtx);
74         X509_STORE_free(x509Store);
75         return true;
76     }
77     if (errCode == 0)
78     {
79         errCode = X509_STORE_CTX_get_error(storeCtx);
80         X509_STORE_CTX_free(storeCtx);
81         X509_STORE_free(x509Store);
82         if (isTrustChainError(errCode))
83         {
84             BMCWEB_LOG_DEBUG << "Ignoring Trust Chain error. Reason: "
85                              << X509_verify_cert_error_string(errCode);
86             return true;
87         }
88         else
89         {
90             BMCWEB_LOG_ERROR << "Certificate verification failed. Reason: "
91                              << X509_verify_cert_error_string(errCode);
92             return false;
93         }
94     }
95 
96     BMCWEB_LOG_ERROR
97         << "Error occurred during X509_verify_cert call. ErrorCode: "
98         << errCode;
99     X509_STORE_CTX_free(storeCtx);
100     X509_STORE_free(x509Store);
101     return false;
102 }
103 
104 inline bool verifyOpensslKeyCert(const std::string& filepath)
105 {
106     bool privateKeyValid = false;
107     bool certValid = false;
108 
109     std::cout << "Checking certs in file " << filepath << "\n";
110 
111     FILE* file = fopen(filepath.c_str(), "r");
112     if (file != nullptr)
113     {
114         EVP_PKEY* pkey = PEM_read_PrivateKey(file, nullptr, nullptr, nullptr);
115         if (pkey != nullptr)
116         {
117             RSA* rsa = EVP_PKEY_get1_RSA(pkey);
118             if (rsa != nullptr)
119             {
120                 std::cout << "Found an RSA key\n";
121                 if (RSA_check_key(rsa) == 1)
122                 {
123                     privateKeyValid = true;
124                 }
125                 else
126                 {
127                     std::cerr << "Key not valid error number "
128                               << ERR_get_error() << "\n";
129                 }
130                 RSA_free(rsa);
131             }
132             else
133             {
134                 EC_KEY* ec = EVP_PKEY_get1_EC_KEY(pkey);
135                 if (ec != nullptr)
136                 {
137                     std::cout << "Found an EC key\n";
138                     if (EC_KEY_check_key(ec) == 1)
139                     {
140                         privateKeyValid = true;
141                     }
142                     else
143                     {
144                         std::cerr << "Key not valid error number "
145                                   << ERR_get_error() << "\n";
146                     }
147                     EC_KEY_free(ec);
148                 }
149             }
150 
151             if (privateKeyValid)
152             {
153                 // If the order is certificate followed by key in input file
154                 // then, certificate read will fail. So, setting the file
155                 // pointer to point beginning of file to avoid certificate and
156                 // key order issue.
157                 fseek(file, 0, SEEK_SET);
158 
159                 X509* x509 = PEM_read_X509(file, nullptr, nullptr, nullptr);
160                 if (x509 == nullptr)
161                 {
162                     std::cout << "error getting x509 cert " << ERR_get_error()
163                               << "\n";
164                 }
165                 else
166                 {
167                     certValid = validateCertificate(x509);
168                     X509_free(x509);
169                 }
170             }
171 
172             EVP_PKEY_free(pkey);
173         }
174         fclose(file);
175     }
176     return certValid;
177 }
178 
179 inline void generateSslCertificate(const std::string& filepath)
180 {
181     FILE* pFile = nullptr;
182     std::cout << "Generating new keys\n";
183     initOpenssl();
184 
185     std::cerr << "Generating EC key\n";
186     EVP_PKEY* pPrivKey = createEcKey();
187     if (pPrivKey != nullptr)
188     {
189         std::cerr << "Generating x509 Certificate\n";
190         // Use this code to directly generate a certificate
191         X509* x509;
192         x509 = X509_new();
193         if (x509 != nullptr)
194         {
195             // get a random number from the RNG for the certificate serial
196             // number If this is not random, regenerating certs throws broswer
197             // errors
198             std::random_device rd;
199             int serial = static_cast<int>(rd());
200 
201             ASN1_INTEGER_set(X509_get_serialNumber(x509), serial);
202 
203             // not before this moment
204             X509_gmtime_adj(X509_get_notBefore(x509), 0);
205             // Cert is valid for 10 years
206             X509_gmtime_adj(X509_get_notAfter(x509),
207                             60L * 60L * 24L * 365L * 10L);
208 
209             // set the public key to the key we just generated
210             X509_set_pubkey(x509, pPrivKey);
211 
212             // get the subject name
213             X509_NAME* name;
214             name = X509_get_subject_name(x509);
215 
216             X509_NAME_add_entry_by_txt(
217                 name, "C", MBSTRING_ASC,
218                 reinterpret_cast<const unsigned char*>("US"), -1, -1, 0);
219             X509_NAME_add_entry_by_txt(
220                 name, "O", MBSTRING_ASC,
221                 reinterpret_cast<const unsigned char*>("OpenBMC"), -1, -1, 0);
222             X509_NAME_add_entry_by_txt(
223                 name, "CN", MBSTRING_ASC,
224                 reinterpret_cast<const unsigned char*>("testhost"), -1, -1, 0);
225             // set the CSR options
226             X509_set_issuer_name(x509, name);
227 
228             // Sign the certificate with our private key
229             X509_sign(x509, pPrivKey, EVP_sha256());
230 
231             pFile = fopen(filepath.c_str(), "wt");
232 
233             if (pFile != nullptr)
234             {
235                 PEM_write_PrivateKey(pFile, pPrivKey, nullptr, nullptr, 0,
236                                      nullptr, nullptr);
237 
238                 PEM_write_X509(pFile, x509);
239                 fclose(pFile);
240                 pFile = nullptr;
241             }
242 
243             X509_free(x509);
244         }
245 
246         EVP_PKEY_free(pPrivKey);
247         pPrivKey = nullptr;
248     }
249 
250     // cleanup_openssl();
251 }
252 
253 EVP_PKEY* createEcKey()
254 {
255     EVP_PKEY* pKey = nullptr;
256     int eccgrp = 0;
257     eccgrp = OBJ_txt2nid("secp384r1");
258 
259     EC_KEY* myecc = EC_KEY_new_by_curve_name(eccgrp);
260     if (myecc != nullptr)
261     {
262         EC_KEY_set_asn1_flag(myecc, OPENSSL_EC_NAMED_CURVE);
263         EC_KEY_generate_key(myecc);
264         pKey = EVP_PKEY_new();
265         if (pKey != nullptr)
266         {
267             if (EVP_PKEY_assign_EC_KEY(pKey, myecc))
268             {
269                 /* pKey owns myecc from now */
270                 if (EC_KEY_check_key(myecc) <= 0)
271                 {
272                     fprintf(stderr, "EC_check_key failed.\n");
273                 }
274             }
275         }
276     }
277     return pKey;
278 }
279 
280 void initOpenssl()
281 {
282 #if OPENSSL_VERSION_NUMBER < 0x10100000L
283     SSL_load_error_strings();
284     OpenSSL_add_all_algorithms();
285     RAND_load_file("/dev/urandom", 1024);
286 #endif
287 }
288 
289 inline void ensureOpensslKeyPresentAndValid(const std::string& filepath)
290 {
291     bool pemFileValid = false;
292 
293     pemFileValid = verifyOpensslKeyCert(filepath);
294 
295     if (!pemFileValid)
296     {
297         std::cerr << "Error in verifying signature, regenerating\n";
298         generateSslCertificate(filepath);
299     }
300 }
301 
302 inline std::shared_ptr<boost::asio::ssl::context>
303     getSslContext(const std::string& ssl_pem_file)
304 {
305     std::shared_ptr<boost::asio::ssl::context> mSslContext =
306         std::make_shared<boost::asio::ssl::context>(
307             boost::asio::ssl::context::tls_server);
308     mSslContext->set_options(boost::asio::ssl::context::default_workarounds |
309                              boost::asio::ssl::context::no_sslv2 |
310                              boost::asio::ssl::context::no_sslv3 |
311                              boost::asio::ssl::context::single_dh_use |
312                              boost::asio::ssl::context::no_tlsv1 |
313                              boost::asio::ssl::context::no_tlsv1_1);
314 
315     // BIG WARNING: This needs to stay disabled, as there will always be
316     // unauthenticated endpoints
317     // mSslContext->set_verify_mode(boost::asio::ssl::verify_peer);
318 
319     SSL_CTX_set_options(mSslContext->native_handle(), SSL_OP_NO_RENEGOTIATION);
320 
321     BMCWEB_LOG_DEBUG << "Using default TrustStore location: " << trustStorePath;
322     mSslContext->add_verify_path(trustStorePath);
323 
324     mSslContext->use_certificate_file(ssl_pem_file,
325                                       boost::asio::ssl::context::pem);
326     mSslContext->use_private_key_file(ssl_pem_file,
327                                       boost::asio::ssl::context::pem);
328 
329     // Set up EC curves to auto (boost asio doesn't have a method for this)
330     // There is a pull request to add this.  Once this is included in an asio
331     // drop, use the right way
332     // http://stackoverflow.com/questions/18929049/boost-asio-with-ecdsa-certificate-issue
333     if (SSL_CTX_set_ecdh_auto(mSslContext->native_handle(), 1) != 1)
334     {
335         BMCWEB_LOG_ERROR << "Error setting tmp ecdh list\n";
336     }
337 
338     std::string mozillaModern = "ECDHE-ECDSA-AES256-GCM-SHA384:"
339                                 "ECDHE-RSA-AES256-GCM-SHA384:"
340                                 "ECDHE-ECDSA-CHACHA20-POLY1305:"
341                                 "ECDHE-RSA-CHACHA20-POLY1305:"
342                                 "ECDHE-ECDSA-AES128-GCM-SHA256:"
343                                 "ECDHE-RSA-AES128-GCM-SHA256:"
344                                 "ECDHE-ECDSA-AES256-SHA384:"
345                                 "ECDHE-RSA-AES256-SHA384:"
346                                 "ECDHE-ECDSA-AES128-SHA256:"
347                                 "ECDHE-RSA-AES128-SHA256";
348 
349     if (SSL_CTX_set_cipher_list(mSslContext->native_handle(),
350                                 mozillaModern.c_str()) != 1)
351     {
352         BMCWEB_LOG_ERROR << "Error setting cipher list\n";
353     }
354     return mSslContext;
355 }
356 } // namespace ensuressl
357 
358 #endif
359