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::usePrivateKey(const Poco::Crypto::RSAKey& key)
211{
212 int errCode = SSL_CTX_use_RSAPrivateKey(_pSSLContext, key.impl()->getRSA());
213 if (errCode != 1)
214 {
215 std::string msg = Utility::getLastError();
216 throw SSLContextException("Cannot set private key for Context", msg);
217 }
218}
219
220
221void Context::enableSessionCache(bool flag)
222{
223 if (flag)
224 {
225 SSL_CTX_set_session_cache_mode(_pSSLContext, isForServerUse() ? SSL_SESS_CACHE_SERVER : SSL_SESS_CACHE_CLIENT);
226 }
227 else
228 {
229 SSL_CTX_set_session_cache_mode(_pSSLContext, SSL_SESS_CACHE_OFF);
230 }
231}
232
233
234void Context::enableSessionCache(bool flag, const std::string& sessionIdContext)
235{
236 poco_assert (isForServerUse());
237
238 if (flag)
239 {
240 SSL_CTX_set_session_cache_mode(_pSSLContext, SSL_SESS_CACHE_SERVER);
241 }
242 else
243 {
244 SSL_CTX_set_session_cache_mode(_pSSLContext, SSL_SESS_CACHE_OFF);
245 }
246
247 unsigned length = static_cast<unsigned>(sessionIdContext.length());
248 if (length > SSL_MAX_SSL_SESSION_ID_LENGTH) length = SSL_MAX_SSL_SESSION_ID_LENGTH;
249 int rc = SSL_CTX_set_session_id_context(_pSSLContext, reinterpret_cast<const unsigned char*>(sessionIdContext.data()), length);
250 if (rc != 1) throw SSLContextException("cannot set session ID context");
251}
252
253
254bool Context::sessionCacheEnabled() const
255{
256 return SSL_CTX_get_session_cache_mode(_pSSLContext) != SSL_SESS_CACHE_OFF;
257}
258
259
260void Context::setSessionCacheSize(std::size_t size)
261{
262 poco_assert (isForServerUse());
263
264 SSL_CTX_sess_set_cache_size(_pSSLContext, static_cast<long>(size));
265}
266
267
268std::size_t Context::getSessionCacheSize() const
269{
270 poco_assert (isForServerUse());
271
272 return static_cast<std::size_t>(SSL_CTX_sess_get_cache_size(_pSSLContext));
273}
274
275
276void Context::setSessionTimeout(long seconds)
277{
278 poco_assert (isForServerUse());
279
280 SSL_CTX_set_timeout(_pSSLContext, seconds);
281}
282
283
284long Context::getSessionTimeout() const
285{
286 poco_assert (isForServerUse());
287
288 return SSL_CTX_get_timeout(_pSSLContext);
289}
290
291
292void Context::flushSessionCache()
293{
294 poco_assert (isForServerUse());
295
296 Poco::Timestamp now;
297 SSL_CTX_flush_sessions(_pSSLContext, static_cast<long>(now.epochTime()));
298}
299
300
301void Context::enableExtendedCertificateVerification(bool flag)
302{
303 _extendedCertificateVerification = flag;
304}
305
306
307void Context::disableStatelessSessionResumption()
308{
309#if defined(SSL_OP_NO_TICKET)
310 SSL_CTX_set_options(_pSSLContext, SSL_OP_NO_TICKET);
311#endif
312}
313
314
315void Context::disableProtocols(int protocols)
316{
317 if (protocols & PROTO_SSLV2)
318 {
319#if defined(SSL_OP_NO_SSLv2)
320 SSL_CTX_set_options(_pSSLContext, SSL_OP_NO_SSLv2);
321#endif
322 }
323 if (protocols & PROTO_SSLV3)
324 {
325#if defined(SSL_OP_NO_SSLv3)
326 SSL_CTX_set_options(_pSSLContext, SSL_OP_NO_SSLv3);
327#endif
328 }
329 if (protocols & PROTO_TLSV1)
330 {
331#if defined(SSL_OP_NO_TLSv1)
332 SSL_CTX_set_options(_pSSLContext, SSL_OP_NO_TLSv1);
333#endif
334 }
335 if (protocols & PROTO_TLSV1_1)
336 {
337#if defined(SSL_OP_NO_TLSv1_1)
338 SSL_CTX_set_options(_pSSLContext, SSL_OP_NO_TLSv1_1);
339#endif
340 }
341 if (protocols & PROTO_TLSV1_2)
342 {
343#if defined(SSL_OP_NO_TLSv1_2)
344 SSL_CTX_set_options(_pSSLContext, SSL_OP_NO_TLSv1_2);
345#endif
346 }
347}
348
349
350void Context::preferServerCiphers()
351{
352#if defined(SSL_OP_CIPHER_SERVER_PREFERENCE)
353 SSL_CTX_set_options(_pSSLContext, SSL_OP_CIPHER_SERVER_PREFERENCE);
354#endif
355}
356
357
358void Context::createSSLContext()
359{
360 if (SSLManager::isFIPSEnabled())
361 {
362 _pSSLContext = SSL_CTX_new(TLSv1_method());
363 }
364 else
365 {
366 switch (_usage)
367 {
368 case CLIENT_USE:
369#if OPENSSL_VERSION_NUMBER >= 0x10100000L
370 _pSSLContext = SSL_CTX_new(TLS_client_method());
371#else
372 _pSSLContext = SSL_CTX_new(SSLv23_client_method());
373#endif
374 break;
375 case SERVER_USE:
376#if OPENSSL_VERSION_NUMBER >= 0x10100000L
377 _pSSLContext = SSL_CTX_new(TLS_server_method());
378#else
379 _pSSLContext = SSL_CTX_new(SSLv23_server_method());
380#endif
381 break;
382#if defined(SSL_OP_NO_TLSv1) && !defined(OPENSSL_NO_TLS1)
383 case TLSV1_CLIENT_USE:
384 _pSSLContext = SSL_CTX_new(TLSv1_client_method());
385 break;
386 case TLSV1_SERVER_USE:
387 _pSSLContext = SSL_CTX_new(TLSv1_server_method());
388 break;
389#endif
390#if defined(SSL_OP_NO_TLSv1_1) && !defined(OPENSSL_NO_TLS1)
391/* SSL_OP_NO_TLSv1_1 is defined in ssl.h if the library version supports TLSv1.1.
392 * OPENSSL_NO_TLS1 is defined in opensslconf.h or on the compiler command line
393 * if TLS1.x was removed at OpenSSL library build time via Configure options.
394 */
395 case TLSV1_1_CLIENT_USE:
396 _pSSLContext = SSL_CTX_new(TLSv1_1_client_method());
397 break;
398 case TLSV1_1_SERVER_USE:
399 _pSSLContext = SSL_CTX_new(TLSv1_1_server_method());
400 break;
401#endif
402#if defined(SSL_OP_NO_TLSv1_2) && !defined(OPENSSL_NO_TLS1)
403 case TLSV1_2_CLIENT_USE:
404 _pSSLContext = SSL_CTX_new(TLSv1_2_client_method());
405 break;
406 case TLSV1_2_SERVER_USE:
407 _pSSLContext = SSL_CTX_new(TLSv1_2_server_method());
408 break;
409#endif
410 default:
411 throw Poco::InvalidArgumentException("Invalid or unsupported usage");
412 }
413 }
414 if (!_pSSLContext)
415 {
416 unsigned long err = ERR_get_error();
417 throw SSLException("Cannot create SSL_CTX object", ERR_error_string(err, 0));
418 }
419
420 SSL_CTX_set_default_passwd_cb(_pSSLContext, &SSLManager::privateKeyPassphraseCallback);
421 Utility::clearErrorStack();
422 SSL_CTX_set_options(_pSSLContext, SSL_OP_ALL);
423}
424
425
426void Context::initDH(const std::string& dhParamsFile)
427{
428#ifndef OPENSSL_NO_DH
429 // 1024-bit MODP Group with 160-bit prime order subgroup (RFC5114)
430 // -----BEGIN DH PARAMETERS-----
431 // MIIBDAKBgQCxC4+WoIDgHd6S3l6uXVTsUsmfvPsGo8aaap3KUtI7YWBz4oZ1oj0Y
432 // mDjvHi7mUsAT7LSuqQYRIySXXDzUm4O/rMvdfZDEvXCYSI6cIZpzck7/1vrlZEc4
433 // +qMaT/VbzMChUa9fDci0vUW/N982XBpl5oz9p21NpwjfH7K8LkpDcQKBgQCk0cvV
434 // w/00EmdlpELvuZkF+BBN0lisUH/WQGz/FCZtMSZv6h5cQVZLd35pD1UE8hMWAhe0
435 // sBuIal6RVH+eJ0n01/vX07mpLuGQnQ0iY/gKdqaiTAh6CR9THb8KAWm2oorWYqTR
436 // jnOvoy13nVkY0IvIhY9Nzvl8KiSFXm7rIrOy5QICAKA=
437 // -----END DH PARAMETERS-----
438 //
439
440 static const unsigned char dh1024_p[] =
441 {
442 0xB1,0x0B,0x8F,0x96,0xA0,0x80,0xE0,0x1D,0xDE,0x92,0xDE,0x5E,
443 0xAE,0x5D,0x54,0xEC,0x52,0xC9,0x9F,0xBC,0xFB,0x06,0xA3,0xC6,
444 0x9A,0x6A,0x9D,0xCA,0x52,0xD2,0x3B,0x61,0x60,0x73,0xE2,0x86,
445 0x75,0xA2,0x3D,0x18,0x98,0x38,0xEF,0x1E,0x2E,0xE6,0x52,0xC0,
446 0x13,0xEC,0xB4,0xAE,0xA9,0x06,0x11,0x23,0x24,0x97,0x5C,0x3C,
447 0xD4,0x9B,0x83,0xBF,0xAC,0xCB,0xDD,0x7D,0x90,0xC4,0xBD,0x70,
448 0x98,0x48,0x8E,0x9C,0x21,0x9A,0x73,0x72,0x4E,0xFF,0xD6,0xFA,
449 0xE5,0x64,0x47,0x38,0xFA,0xA3,0x1A,0x4F,0xF5,0x5B,0xCC,0xC0,
450 0xA1,0x51,0xAF,0x5F,0x0D,0xC8,0xB4,0xBD,0x45,0xBF,0x37,0xDF,
451 0x36,0x5C,0x1A,0x65,0xE6,0x8C,0xFD,0xA7,0x6D,0x4D,0xA7,0x08,
452 0xDF,0x1F,0xB2,0xBC,0x2E,0x4A,0x43,0x71,
453 };
454
455 static const unsigned char dh1024_g[] =
456 {
457 0xA4,0xD1,0xCB,0xD5,0xC3,0xFD,0x34,0x12,0x67,0x65,0xA4,0x42,
458 0xEF,0xB9,0x99,0x05,0xF8,0x10,0x4D,0xD2,0x58,0xAC,0x50,0x7F,
459 0xD6,0x40,0x6C,0xFF,0x14,0x26,0x6D,0x31,0x26,0x6F,0xEA,0x1E,
460 0x5C,0x41,0x56,0x4B,0x77,0x7E,0x69,0x0F,0x55,0x04,0xF2,0x13,
461 0x16,0x02,0x17,0xB4,0xB0,0x1B,0x88,0x6A,0x5E,0x91,0x54,0x7F,
462 0x9E,0x27,0x49,0xF4,0xD7,0xFB,0xD7,0xD3,0xB9,0xA9,0x2E,0xE1,
463 0x90,0x9D,0x0D,0x22,0x63,0xF8,0x0A,0x76,0xA6,0xA2,0x4C,0x08,
464 0x7A,0x09,0x1F,0x53,0x1D,0xBF,0x0A,0x01,0x69,0xB6,0xA2,0x8A,
465 0xD6,0x62,0xA4,0xD1,0x8E,0x73,0xAF,0xA3,0x2D,0x77,0x9D,0x59,
466 0x18,0xD0,0x8B,0xC8,0x85,0x8F,0x4D,0xCE,0xF9,0x7C,0x2A,0x24,
467 0x85,0x5E,0x6E,0xEB,0x22,0xB3,0xB2,0xE5,
468 };
469
470 DH* dh = 0;
471 if (!dhParamsFile.empty())
472 {
473 BIO* bio = BIO_new_file(dhParamsFile.c_str(), "r");
474 if (!bio)
475 {
476 std::string msg = Utility::getLastError();
477 throw SSLContextException(std::string("Error opening Diffie-Hellman parameters file ") + dhParamsFile, msg);
478 }
479 dh = PEM_read_bio_DHparams(bio, 0, 0, 0);
480 BIO_free(bio);
481 if (!dh)
482 {
483 std::string msg = Utility::getLastError();
484 throw SSLContextException(std::string("Error reading Diffie-Hellman parameters from file ") + dhParamsFile, msg);
485 }
486 }
487 else
488 {
489 dh = DH_new();
490 if (!dh)
491 {
492 std::string msg = Utility::getLastError();
493 throw SSLContextException("Error creating Diffie-Hellman parameters", msg);
494 }
495#if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
496 BIGNUM* p = BN_bin2bn(dh1024_p, sizeof(dh1024_p), 0);
497 BIGNUM* g = BN_bin2bn(dh1024_g, sizeof(dh1024_g), 0);
498 DH_set0_pqg(dh, p, 0, g);
499 DH_set_length(dh, 160);
500 if (!p || !g)
501 {
502 DH_free(dh);
503 throw SSLContextException("Error creating Diffie-Hellman parameters");
504 }
505#else
506 dh->p = BN_bin2bn(dh1024_p, sizeof(dh1024_p), 0);
507 dh->g = BN_bin2bn(dh1024_g, sizeof(dh1024_g), 0);
508 dh->length = 160;
509 if ((!dh->p) || (!dh->g))
510 {
511 DH_free(dh);
512 throw SSLContextException("Error creating Diffie-Hellman parameters");
513 }
514#endif
515 }
516 SSL_CTX_set_tmp_dh(_pSSLContext, dh);
517 SSL_CTX_set_options(_pSSLContext, SSL_OP_SINGLE_DH_USE);
518 DH_free(dh);
519#else
520 if (!dhParamsFile.empty())
521 throw SSLContextException("OpenSSL does not support DH");
522#endif
523}
524
525
526void Context::initECDH(const std::string& curve)
527{
528#if OPENSSL_VERSION_NUMBER >= 0x0090800fL
529#ifndef OPENSSL_NO_ECDH
530 int nid = 0;
531 if (!curve.empty())
532 {
533 nid = OBJ_sn2nid(curve.c_str());
534 }
535 else
536 {
537 nid = OBJ_sn2nid("prime256v1");
538 }
539 if (nid == 0)
540 {
541 throw SSLContextException("Unknown ECDH curve name", curve);
542 }
543
544 EC_KEY* ecdh = EC_KEY_new_by_curve_name(nid);
545 if (!ecdh)
546 {
547 throw SSLContextException("Cannot create ECDH curve");
548 }
549 SSL_CTX_set_tmp_ecdh(_pSSLContext, ecdh);
550 SSL_CTX_set_options(_pSSLContext, SSL_OP_SINGLE_ECDH_USE);
551 EC_KEY_free(ecdh);
552#endif
553#endif
554}
555
556
557} } // namespace Poco::Net
558