1//
2// Context.cpp
3//
4// Library: NetSSL_OpenSSL
5// Package: SSLCore
6// Module: Context
7//
8// Copyright (c) 2006-2010, Applied Informatics Software Engineering GmbH.
9// and Contributors.
10//
11// SPDX-License-Identifier: BSL-1.0
12//
13
14
15#include "Poco/Net/Context.h"
16#include "Poco/Net/SSLManager.h"
17#include "Poco/Net/SSLException.h"
18#include "Poco/Net/Utility.h"
19#include "Poco/Crypto/OpenSSLInitializer.h"
20#include "Poco/File.h"
21#include "Poco/Path.h"
22#include "Poco/Timestamp.h"
23#include <openssl/bio.h>
24#include <openssl/err.h>
25#include <openssl/ssl.h>
26#include <openssl/x509v3.h>
27
28
29namespace Poco {
30namespace Net {
31
32
33Context::Params::Params():
34 verificationMode(VERIFY_RELAXED),
35 verificationDepth(9),
36 loadDefaultCAs(false),
37 cipherList("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH")
38{
39}
40
41
42Context::Context(Usage usage, const Params& params):
43 _usage(usage),
44 _mode(params.verificationMode),
45 _pSSLContext(0),
46 _extendedCertificateVerification(true)
47{
48 init(params);
49}
50
51
52Context::Context(
53 Usage usage,
54 const std::string& privateKeyFile,
55 const std::string& certificateFile,
56 const std::string& caLocation,
57 VerificationMode verificationMode,
58 int verificationDepth,
59 bool loadDefaultCAs,
60 const std::string& cipherList):
61 _usage(usage),
62 _mode(verificationMode),
63 _pSSLContext(0),
64 _extendedCertificateVerification(true)
65{
66 Params params;
67 params.privateKeyFile = privateKeyFile;
68 params.certificateFile = certificateFile;
69 params.caLocation = caLocation;
70 params.verificationMode = verificationMode;
71 params.verificationDepth = verificationDepth;
72 params.loadDefaultCAs = loadDefaultCAs;
73 params.cipherList = cipherList;
74 init(params);
75}
76
77
78Context::Context(
79 Usage usage,
80 const std::string& caLocation,
81 VerificationMode verificationMode,
82 int verificationDepth,
83 bool loadDefaultCAs,
84 const std::string& cipherList):
85 _usage(usage),
86 _mode(verificationMode),
87 _pSSLContext(0),
88 _extendedCertificateVerification(true)
89{
90 Params params;
91 params.caLocation = caLocation;
92 params.verificationMode = verificationMode;
93 params.verificationDepth = verificationDepth;
94 params.loadDefaultCAs = loadDefaultCAs;
95 params.cipherList = cipherList;
96 init(params);
97}
98
99
100Context::~Context()
101{
102 try
103 {
104 SSL_CTX_free(_pSSLContext);
105 Poco::Crypto::OpenSSLInitializer::uninitialize();
106 }
107 catch (...)
108 {
109 poco_unexpected();
110 }
111}
112
113
114void Context::init(const Params& params)
115{
116 Poco::Crypto::OpenSSLInitializer::initialize();
117
118 createSSLContext();
119
120 try
121 {
122 int errCode = 0;
123 if (!params.caLocation.empty())
124 {
125 Poco::File aFile(params.caLocation);
126 if (aFile.isDirectory())
127 errCode = SSL_CTX_load_verify_locations(_pSSLContext, 0, Poco::Path::transcode(params.caLocation).c_str());
128 else
129 errCode = SSL_CTX_load_verify_locations(_pSSLContext, Poco::Path::transcode(params.caLocation).c_str(), 0);
130 if (errCode != 1)
131 {
132 std::string msg = Utility::getLastError();
133 throw SSLContextException(std::string("Cannot load CA file/directory at ") + params.caLocation, msg);
134 }
135 }
136
137 if (params.loadDefaultCAs)
138 {
139 errCode = SSL_CTX_set_default_verify_paths(_pSSLContext);
140 if (errCode != 1)
141 {
142 std::string msg = Utility::getLastError();
143 throw SSLContextException("Cannot load default CA certificates", msg);
144 }
145 }
146
147 if (!params.privateKeyFile.empty())
148 {
149 errCode = SSL_CTX_use_PrivateKey_file(_pSSLContext, Poco::Path::transcode(params.privateKeyFile).c_str(), SSL_FILETYPE_PEM);
150 if (errCode != 1)
151 {
152 std::string msg = Utility::getLastError();
153 throw SSLContextException(std::string("Error loading private key from file ") + params.privateKeyFile, msg);
154 }
155 }
156
157 if (!params.certificateFile.empty())
158 {
159 errCode = SSL_CTX_use_certificate_chain_file(_pSSLContext, Poco::Path::transcode(params.certificateFile).c_str());
160 if (errCode != 1)
161 {
162 std::string errMsg = Utility::getLastError();
163 throw SSLContextException(std::string("Error loading certificate from file ") + params.certificateFile, errMsg);
164 }
165 }
166
167 if (isForServerUse())
168 SSL_CTX_set_verify(_pSSLContext, params.verificationMode, &SSLManager::verifyServerCallback);
169 else
170 SSL_CTX_set_verify(_pSSLContext, params.verificationMode, &SSLManager::verifyClientCallback);
171
172 SSL_CTX_set_cipher_list(_pSSLContext, params.cipherList.c_str());
173 SSL_CTX_set_verify_depth(_pSSLContext, params.verificationDepth);
174 SSL_CTX_set_mode(_pSSLContext, SSL_MODE_AUTO_RETRY);
175 SSL_CTX_set_session_cache_mode(_pSSLContext, SSL_SESS_CACHE_OFF);
176
177 initDH(params.dhParamsFile);
178 initECDH(params.ecdhCurve);
179 }
180 catch (...)
181 {
182 SSL_CTX_free(_pSSLContext);
183 throw;
184 }
185}
186
187
188void Context::useCertificate(const Poco::Crypto::X509Certificate& certificate)
189{
190 int errCode = SSL_CTX_use_certificate(_pSSLContext, const_cast<X509*>(certificate.certificate()));
191 if (errCode != 1)
192 {
193 std::string msg = Utility::getLastError();
194 throw SSLContextException("Cannot set certificate for Context", msg);
195 }
196}
197
198
199void Context::addChainCertificate(const Poco::Crypto::X509Certificate& certificate)
200{
201 int errCode = SSL_CTX_add_extra_chain_cert(_pSSLContext, certificate.certificate());
202 if (errCode != 1)
203 {
204 std::string msg = Utility::getLastError();
205 throw SSLContextException("Cannot add chain certificate to Context", msg);
206 }
207}
208
209
210void Context::addCertificateAuthority(const Crypto::X509Certificate &certificate)
211{
212 if (X509_STORE* store = SSL_CTX_get_cert_store(_pSSLContext))
213 {
214 int errCode = X509_STORE_add_cert(store, const_cast<X509*>(certificate.certificate()));
215 if (errCode != 1)
216 {
217 std::string msg = Utility::getLastError();
218 throw SSLContextException("Cannot add certificate authority to Context", msg);
219 }
220 }
221 else
222 {
223 std::string msg = Utility::getLastError();
224 throw SSLContextException("Cannot add certificate authority to Context", msg);
225 }
226}
227
228
229void Context::usePrivateKey(const Poco::Crypto::RSAKey& key)
230{
231 int errCode = SSL_CTX_use_RSAPrivateKey(_pSSLContext, key.impl()->getRSA());
232 if (errCode != 1)
233 {
234 std::string msg = Utility::getLastError();
235 throw SSLContextException("Cannot set private key for Context", msg);
236 }
237}
238
239
240void Context::usePrivateKey(const Poco::Crypto::EVPPKey& pkey)
241{
242 int errCode = SSL_CTX_use_PrivateKey(_pSSLContext, const_cast<EVP_PKEY*>(static_cast<const EVP_PKEY*>(pkey)));
243 if (errCode != 1)
244 {
245 std::string msg = Utility::getLastError();
246 throw SSLContextException("Cannot set private key for Context", msg);
247 }
248}
249
250
251void Context::enableSessionCache(bool flag)
252{
253 if (flag)
254 {
255 SSL_CTX_set_session_cache_mode(_pSSLContext, isForServerUse() ? SSL_SESS_CACHE_SERVER : SSL_SESS_CACHE_CLIENT);
256 }
257 else
258 {
259 SSL_CTX_set_session_cache_mode(_pSSLContext, SSL_SESS_CACHE_OFF);
260 }
261}
262
263
264void Context::enableSessionCache(bool flag, const std::string& sessionIdContext)
265{
266 poco_assert (isForServerUse());
267
268 if (flag)
269 {
270 SSL_CTX_set_session_cache_mode(_pSSLContext, SSL_SESS_CACHE_SERVER);
271 }
272 else
273 {
274 SSL_CTX_set_session_cache_mode(_pSSLContext, SSL_SESS_CACHE_OFF);
275 }
276
277 unsigned length = static_cast<unsigned>(sessionIdContext.length());
278 if (length > SSL_MAX_SSL_SESSION_ID_LENGTH) length = SSL_MAX_SSL_SESSION_ID_LENGTH;
279 int rc = SSL_CTX_set_session_id_context(_pSSLContext, reinterpret_cast<const unsigned char*>(sessionIdContext.data()), length);
280 if (rc != 1) throw SSLContextException("cannot set session ID context");
281}
282
283
284bool Context::sessionCacheEnabled() const
285{
286 return SSL_CTX_get_session_cache_mode(_pSSLContext) != SSL_SESS_CACHE_OFF;
287}
288
289
290void Context::setSessionCacheSize(std::size_t size)
291{
292 poco_assert (isForServerUse());
293
294 SSL_CTX_sess_set_cache_size(_pSSLContext, static_cast<long>(size));
295}
296
297
298std::size_t Context::getSessionCacheSize() const
299{
300 poco_assert (isForServerUse());
301
302 return static_cast<std::size_t>(SSL_CTX_sess_get_cache_size(_pSSLContext));
303}
304
305
306void Context::setSessionTimeout(long seconds)
307{
308 poco_assert (isForServerUse());
309
310 SSL_CTX_set_timeout(_pSSLContext, seconds);
311}
312
313
314long Context::getSessionTimeout() const
315{
316 poco_assert (isForServerUse());
317
318 return SSL_CTX_get_timeout(_pSSLContext);
319}
320
321
322void Context::flushSessionCache()
323{
324 poco_assert (isForServerUse());
325
326 Poco::Timestamp now;
327 SSL_CTX_flush_sessions(_pSSLContext, static_cast<long>(now.epochTime()));
328}
329
330
331void Context::enableExtendedCertificateVerification(bool flag)
332{
333 _extendedCertificateVerification = flag;
334}
335
336
337void Context::disableStatelessSessionResumption()
338{
339#if defined(SSL_OP_NO_TICKET)
340 SSL_CTX_set_options(_pSSLContext, SSL_OP_NO_TICKET);
341#endif
342}
343
344
345void Context::disableProtocols(int protocols)
346{
347 if (protocols & PROTO_SSLV2)
348 {
349#if defined(SSL_OP_NO_SSLv2)
350 SSL_CTX_set_options(_pSSLContext, SSL_OP_NO_SSLv2);
351#endif
352 }
353 if (protocols & PROTO_SSLV3)
354 {
355#if defined(SSL_OP_NO_SSLv3)
356 SSL_CTX_set_options(_pSSLContext, SSL_OP_NO_SSLv3);
357#endif
358 }
359 if (protocols & PROTO_TLSV1)
360 {
361#if defined(SSL_OP_NO_TLSv1)
362 SSL_CTX_set_options(_pSSLContext, SSL_OP_NO_TLSv1);
363#endif
364 }
365 if (protocols & PROTO_TLSV1_1)
366 {
367#if defined(SSL_OP_NO_TLSv1_1)
368 SSL_CTX_set_options(_pSSLContext, SSL_OP_NO_TLSv1_1);
369#endif
370 }
371 if (protocols & PROTO_TLSV1_2)
372 {
373#if defined(SSL_OP_NO_TLSv1_2)
374 SSL_CTX_set_options(_pSSLContext, SSL_OP_NO_TLSv1_2);
375#endif
376 }
377 if (protocols & PROTO_TLSV1_3)
378 {
379#if defined(SSL_OP_NO_TLSv1_3)
380 SSL_CTX_set_options(_pSSLContext, SSL_OP_NO_TLSv1_3);
381#endif
382 }
383}
384
385
386void Context::preferServerCiphers()
387{
388#if defined(SSL_OP_CIPHER_SERVER_PREFERENCE)
389 SSL_CTX_set_options(_pSSLContext, SSL_OP_CIPHER_SERVER_PREFERENCE);
390#endif
391}
392
393
394void Context::createSSLContext()
395{
396 if (SSLManager::isFIPSEnabled())
397 {
398 _pSSLContext = SSL_CTX_new(TLSv1_method());
399 }
400 else
401 {
402 switch (_usage)
403 {
404 case CLIENT_USE:
405#if OPENSSL_VERSION_NUMBER >= 0x10100000L
406 _pSSLContext = SSL_CTX_new(TLS_client_method());
407#else
408 _pSSLContext = SSL_CTX_new(SSLv23_client_method());
409#endif
410 break;
411 case SERVER_USE:
412#if OPENSSL_VERSION_NUMBER >= 0x10100000L
413 _pSSLContext = SSL_CTX_new(TLS_server_method());
414#else
415 _pSSLContext = SSL_CTX_new(SSLv23_server_method());
416#endif
417 break;
418#if defined(SSL_OP_NO_TLSv1) && !defined(OPENSSL_NO_TLS1)
419 case TLSV1_CLIENT_USE:
420 _pSSLContext = SSL_CTX_new(TLSv1_client_method());
421 break;
422 case TLSV1_SERVER_USE:
423 _pSSLContext = SSL_CTX_new(TLSv1_server_method());
424 break;
425#endif
426#if defined(SSL_OP_NO_TLSv1_1) && !defined(OPENSSL_NO_TLS1)
427/* SSL_OP_NO_TLSv1_1 is defined in ssl.h if the library version supports TLSv1.1.
428 * OPENSSL_NO_TLS1 is defined in opensslconf.h or on the compiler command line
429 * if TLS1.x was removed at OpenSSL library build time via Configure options.
430 */
431 case TLSV1_1_CLIENT_USE:
432 _pSSLContext = SSL_CTX_new(TLSv1_1_client_method());
433 break;
434 case TLSV1_1_SERVER_USE:
435 _pSSLContext = SSL_CTX_new(TLSv1_1_server_method());
436 break;
437#endif
438#if defined(SSL_OP_NO_TLSv1_2) && !defined(OPENSSL_NO_TLS1)
439 case TLSV1_2_CLIENT_USE:
440 _pSSLContext = SSL_CTX_new(TLSv1_2_client_method());
441 break;
442 case TLSV1_2_SERVER_USE:
443 _pSSLContext = SSL_CTX_new(TLSv1_2_server_method());
444 break;
445#endif
446#if defined(SSL_OP_NO_TLSv1_3) && !defined(OPENSSL_NO_TLS1)
447 case TLSV1_3_CLIENT_USE:
448 _pSSLContext = SSL_CTX_new(TLS_client_method());
449 break;
450 case TLSV1_3_SERVER_USE:
451 _pSSLContext = SSL_CTX_new(TLS_server_method());
452 break;
453#endif
454 default:
455 throw Poco::InvalidArgumentException("Invalid or unsupported usage");
456 }
457 }
458 if (!_pSSLContext)
459 {
460 unsigned long err = ERR_get_error();
461 throw SSLException("Cannot create SSL_CTX object", ERR_error_string(err, 0));
462 }
463
464 SSL_CTX_set_default_passwd_cb(_pSSLContext, &SSLManager::privateKeyPassphraseCallback);
465 Utility::clearErrorStack();
466 SSL_CTX_set_options(_pSSLContext, SSL_OP_ALL);
467}
468
469
470void Context::initDH(const std::string& dhParamsFile)
471{
472#ifndef OPENSSL_NO_DH
473 // 1024-bit MODP Group with 160-bit prime order subgroup (RFC5114)
474 // -----BEGIN DH PARAMETERS-----
475 // MIIBDAKBgQCxC4+WoIDgHd6S3l6uXVTsUsmfvPsGo8aaap3KUtI7YWBz4oZ1oj0Y
476 // mDjvHi7mUsAT7LSuqQYRIySXXDzUm4O/rMvdfZDEvXCYSI6cIZpzck7/1vrlZEc4
477 // +qMaT/VbzMChUa9fDci0vUW/N982XBpl5oz9p21NpwjfH7K8LkpDcQKBgQCk0cvV
478 // w/00EmdlpELvuZkF+BBN0lisUH/WQGz/FCZtMSZv6h5cQVZLd35pD1UE8hMWAhe0
479 // sBuIal6RVH+eJ0n01/vX07mpLuGQnQ0iY/gKdqaiTAh6CR9THb8KAWm2oorWYqTR
480 // jnOvoy13nVkY0IvIhY9Nzvl8KiSFXm7rIrOy5QICAKA=
481 // -----END DH PARAMETERS-----
482 //
483
484 static const unsigned char dh1024_p[] =
485 {
486 0xB1,0x0B,0x8F,0x96,0xA0,0x80,0xE0,0x1D,0xDE,0x92,0xDE,0x5E,
487 0xAE,0x5D,0x54,0xEC,0x52,0xC9,0x9F,0xBC,0xFB,0x06,0xA3,0xC6,
488 0x9A,0x6A,0x9D,0xCA,0x52,0xD2,0x3B,0x61,0x60,0x73,0xE2,0x86,
489 0x75,0xA2,0x3D,0x18,0x98,0x38,0xEF,0x1E,0x2E,0xE6,0x52,0xC0,
490 0x13,0xEC,0xB4,0xAE,0xA9,0x06,0x11,0x23,0x24,0x97,0x5C,0x3C,
491 0xD4,0x9B,0x83,0xBF,0xAC,0xCB,0xDD,0x7D,0x90,0xC4,0xBD,0x70,
492 0x98,0x48,0x8E,0x9C,0x21,0x9A,0x73,0x72,0x4E,0xFF,0xD6,0xFA,
493 0xE5,0x64,0x47,0x38,0xFA,0xA3,0x1A,0x4F,0xF5,0x5B,0xCC,0xC0,
494 0xA1,0x51,0xAF,0x5F,0x0D,0xC8,0xB4,0xBD,0x45,0xBF,0x37,0xDF,
495 0x36,0x5C,0x1A,0x65,0xE6,0x8C,0xFD,0xA7,0x6D,0x4D,0xA7,0x08,
496 0xDF,0x1F,0xB2,0xBC,0x2E,0x4A,0x43,0x71,
497 };
498
499 static const unsigned char dh1024_g[] =
500 {
501 0xA4,0xD1,0xCB,0xD5,0xC3,0xFD,0x34,0x12,0x67,0x65,0xA4,0x42,
502 0xEF,0xB9,0x99,0x05,0xF8,0x10,0x4D,0xD2,0x58,0xAC,0x50,0x7F,
503 0xD6,0x40,0x6C,0xFF,0x14,0x26,0x6D,0x31,0x26,0x6F,0xEA,0x1E,
504 0x5C,0x41,0x56,0x4B,0x77,0x7E,0x69,0x0F,0x55,0x04,0xF2,0x13,
505 0x16,0x02,0x17,0xB4,0xB0,0x1B,0x88,0x6A,0x5E,0x91,0x54,0x7F,
506 0x9E,0x27,0x49,0xF4,0xD7,0xFB,0xD7,0xD3,0xB9,0xA9,0x2E,0xE1,
507 0x90,0x9D,0x0D,0x22,0x63,0xF8,0x0A,0x76,0xA6,0xA2,0x4C,0x08,
508 0x7A,0x09,0x1F,0x53,0x1D,0xBF,0x0A,0x01,0x69,0xB6,0xA2,0x8A,
509 0xD6,0x62,0xA4,0xD1,0x8E,0x73,0xAF,0xA3,0x2D,0x77,0x9D,0x59,
510 0x18,0xD0,0x8B,0xC8,0x85,0x8F,0x4D,0xCE,0xF9,0x7C,0x2A,0x24,
511 0x85,0x5E,0x6E,0xEB,0x22,0xB3,0xB2,0xE5,
512 };
513
514 DH* dh = 0;
515 if (!dhParamsFile.empty())
516 {
517 BIO* bio = BIO_new_file(dhParamsFile.c_str(), "r");
518 if (!bio)
519 {
520 std::string msg = Utility::getLastError();
521 throw SSLContextException(std::string("Error opening Diffie-Hellman parameters file ") + dhParamsFile, msg);
522 }
523 dh = PEM_read_bio_DHparams(bio, 0, 0, 0);
524 BIO_free(bio);
525 if (!dh)
526 {
527 std::string msg = Utility::getLastError();
528 throw SSLContextException(std::string("Error reading Diffie-Hellman parameters from file ") + dhParamsFile, msg);
529 }
530 }
531 else
532 {
533 dh = DH_new();
534 if (!dh)
535 {
536 std::string msg = Utility::getLastError();
537 throw SSLContextException("Error creating Diffie-Hellman parameters", msg);
538 }
539#if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
540 BIGNUM* p = BN_bin2bn(dh1024_p, sizeof(dh1024_p), 0);
541 BIGNUM* g = BN_bin2bn(dh1024_g, sizeof(dh1024_g), 0);
542 DH_set0_pqg(dh, p, 0, g);
543 DH_set_length(dh, 160);
544 if (!p || !g)
545 {
546 DH_free(dh);
547 throw SSLContextException("Error creating Diffie-Hellman parameters");
548 }
549#else
550 dh->p = BN_bin2bn(dh1024_p, sizeof(dh1024_p), 0);
551 dh->g = BN_bin2bn(dh1024_g, sizeof(dh1024_g), 0);
552 dh->length = 160;
553 if ((!dh->p) || (!dh->g))
554 {
555 DH_free(dh);
556 throw SSLContextException("Error creating Diffie-Hellman parameters");
557 }
558#endif
559 }
560 SSL_CTX_set_tmp_dh(_pSSLContext, dh);
561 SSL_CTX_set_options(_pSSLContext, SSL_OP_SINGLE_DH_USE);
562 DH_free(dh);
563#else
564 if (!dhParamsFile.empty())
565 throw SSLContextException("OpenSSL does not support DH");
566#endif
567}
568
569
570void Context::initECDH(const std::string& curve)
571{
572#if OPENSSL_VERSION_NUMBER >= 0x0090800fL
573#ifndef OPENSSL_NO_ECDH
574 int nid = 0;
575 if (!curve.empty())
576 {
577 nid = OBJ_sn2nid(curve.c_str());
578 }
579 else
580 {
581 nid = OBJ_sn2nid("prime256v1");
582 }
583 if (nid == 0)
584 {
585 throw SSLContextException("Unknown ECDH curve name", curve);
586 }
587
588 EC_KEY* ecdh = EC_KEY_new_by_curve_name(nid);
589 if (!ecdh)
590 {
591 throw SSLContextException("Cannot create ECDH curve");
592 }
593 SSL_CTX_set_tmp_ecdh(_pSSLContext, ecdh);
594 SSL_CTX_set_options(_pSSLContext, SSL_OP_SINGLE_ECDH_USE);
595 EC_KEY_free(ecdh);
596#endif
597#endif
598}
599
600
601} } // namespace Poco::Net
602