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