]> git.ipfire.org Git - thirdparty/squid.git/blame - src/ssl/support.cc
Squid crashes on shutdown while cleaning up idle ICAP connections, part2
[thirdparty/squid.git] / src / ssl / support.cc
CommitLineData
f484cdf5 1/*
ef57eb7b 2 * Copyright (C) 1996-2016 The Squid Software Foundation and contributors
f484cdf5 3 *
bbc27441
AJ
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
f484cdf5 7 */
8
bbc27441
AJ
9/* DEBUG: section 83 SSL accelerator support */
10
582c2af2 11#include "squid.h"
454e8283 12
13/* MS Visual Studio Projects are monolithic, so we need the following
14 * #if to exclude the SSL code from compile process when not needed.
15 */
cb4f4424 16#if USE_OPENSSL
454e8283 17
c0941a6a 18#include "acl/FilledChecklist.h"
86660d64 19#include "anyp/PortCfg.h"
ed6e9fb9 20#include "fatal.h"
b3a8ae1b 21#include "fd.h"
582c2af2
FC
22#include "fde.h"
23#include "globals.h"
86c63190 24#include "ipc/MemMap.h"
4d5904f7 25#include "SquidConfig.h"
10a69fc0 26#include "SquidTime.h"
b3a8ae1b 27#include "ssl/bio.h"
2cef0ca6 28#include "ssl/Config.h"
4d16918e 29#include "ssl/ErrorDetail.h"
95d2589c 30#include "ssl/gadgets.h"
602d9612 31#include "ssl/support.h"
fc54b8d2 32#include "URL.h"
f484cdf5 33
1a30fdf5 34#include <cerrno>
21d845b1 35
55369ae6
AR
36// TODO: Move ssl_ex_index_* global variables from global.cc here.
37int ssl_ex_index_ssl_untrusted_chain = -1;
38
824d4656
AJ
39Ipc::MemMap *Ssl::SessionCache = NULL;
40const char *Ssl::SessionCacheName = "ssl_session_cache";
10a69fc0 41
55369ae6
AR
42static Ssl::CertsIndexedList SquidUntrustedCerts;
43
3c26b00a
CT
44const EVP_MD *Ssl::DefaultSignHash = NULL;
45
caf3666d
AR
46const char *Ssl::BumpModeStr[] = {
47 "none",
48 "client-first",
49 "server-first",
5d65362c
CT
50 "peek",
51 "stare",
52 "bump",
7f4e9b73 53 "splice",
5d65362c 54 "terminate",
1110989a 55 /*"err",*/
caf3666d
AR
56 NULL
57};
58
63be0a78 59/**
60 \defgroup ServerProtocolSSLInternal Server-Side SSL Internals
61 \ingroup ServerProtocolSSLAPI
62 */
63
64/// \ingroup ServerProtocolSSLInternal
307b83b7 65static int
66ssl_ask_password_cb(char *buf, int size, int rwflag, void *userdata)
67{
68 FILE *in;
69 int len = 0;
70 char cmdline[1024];
71
72 snprintf(cmdline, sizeof(cmdline), "\"%s\" \"%s\"", Config.Program.ssl_password, (const char *)userdata);
73 in = popen(cmdline, "r");
74
75 if (fgets(buf, size, in))
76
77 len = strlen(buf);
78
79 while (len > 0 && (buf[len - 1] == '\n' || buf[len - 1] == '\r'))
5e263176 80 --len;
307b83b7 81
82 buf[len] = '\0';
83
84 pclose(in);
85
86 return len;
87}
88
63be0a78 89/// \ingroup ServerProtocolSSLInternal
307b83b7 90static void
91ssl_ask_password(SSL_CTX * context, const char * prompt)
92{
93 if (Config.Program.ssl_password) {
94 SSL_CTX_set_default_passwd_cb(context, ssl_ask_password_cb);
95 SSL_CTX_set_default_passwd_cb_userdata(context, (void *)prompt);
96 }
97}
98
63be0a78 99/// \ingroup ServerProtocolSSLInternal
f484cdf5 100static RSA *
e6ccf245 101ssl_temp_rsa_cb(SSL * ssl, int anInt, int keylen)
f484cdf5 102{
e01f02ed 103 static RSA *rsa_512 = NULL;
104 static RSA *rsa_1024 = NULL;
105 RSA *rsa = NULL;
106 int newkey = 0;
f484cdf5 107
e01f02ed 108 switch (keylen) {
109
110 case 512:
111
112 if (!rsa_512) {
113 rsa_512 = RSA_generate_key(512, RSA_F4, NULL, NULL);
114 newkey = 1;
115 }
116
117 rsa = rsa_512;
118 break;
119
120 case 1024:
121
122 if (!rsa_1024) {
123 rsa_1024 = RSA_generate_key(1024, RSA_F4, NULL, NULL);
124 newkey = 1;
125 }
126
127 rsa = rsa_1024;
128 break;
129
130 default:
e0236918 131 debugs(83, DBG_IMPORTANT, "ssl_temp_rsa_cb: Unexpected key length " << keylen);
e01f02ed 132 return NULL;
133 }
134
135 if (rsa == NULL) {
e0236918 136 debugs(83, DBG_IMPORTANT, "ssl_temp_rsa_cb: Failed to generate key " << keylen);
e01f02ed 137 return NULL;
138 }
139
140 if (newkey) {
014adac1 141 if (Debug::Enabled(83, 5))
e01f02ed 142 PEM_write_RSAPrivateKey(debug_log, rsa, NULL, NULL, 0, NULL, NULL);
143
e0236918 144 debugs(83, DBG_IMPORTANT, "Generated ephemeral RSA key of length " << keylen);
e01f02ed 145 }
62e76326 146
f484cdf5 147 return rsa;
148}
149
4d16918e
CT
150int Ssl::asn1timeToString(ASN1_TIME *tm, char *buf, int len)
151{
152 BIO *bio;
153 int write = 0;
154 bio = BIO_new(BIO_s_mem());
155 if (bio) {
e34763f4
A
156 if (ASN1_TIME_print(bio, tm))
157 write = BIO_read(bio, buf, len-1);
158 BIO_free(bio);
4d16918e
CT
159 }
160 buf[write]='\0';
161 return write;
162}
163
164int Ssl::matchX509CommonNames(X509 *peer_cert, void *check_data, int (*check_func)(void *check_data, ASN1_STRING *cn_data))
165{
166 assert(peer_cert);
167
168 X509_NAME *name = X509_get_subject_name(peer_cert);
169
170 for (int i = X509_NAME_get_index_by_NID(name, NID_commonName, -1); i >= 0; i = X509_NAME_get_index_by_NID(name, NID_commonName, i)) {
e34763f4 171
4d16918e
CT
172 ASN1_STRING *cn_data = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, i));
173
174 if ( (*check_func)(check_data, cn_data) == 0)
175 return 1;
176 }
177
178 STACK_OF(GENERAL_NAME) * altnames;
179 altnames = (STACK_OF(GENERAL_NAME)*)X509_get_ext_d2i(peer_cert, NID_subject_alt_name, NULL, NULL);
180
181 if (altnames) {
182 int numalts = sk_GENERAL_NAME_num(altnames);
d7ae3534 183 for (int i = 0; i < numalts; ++i) {
4d16918e
CT
184 const GENERAL_NAME *check = sk_GENERAL_NAME_value(altnames, i);
185 if (check->type != GEN_DNS) {
186 continue;
187 }
188 ASN1_STRING *cn_data = check->d.dNSName;
e34763f4 189
40dd2b59
CT
190 if ( (*check_func)(check_data, cn_data) == 0) {
191 sk_GENERAL_NAME_pop_free(altnames, GENERAL_NAME_free);
4d16918e 192 return 1;
40dd2b59 193 }
4d16918e
CT
194 }
195 sk_GENERAL_NAME_pop_free(altnames, GENERAL_NAME_free);
196 }
197 return 0;
198}
199
200static int check_domain( void *check_data, ASN1_STRING *cn_data)
201{
202 char cn[1024];
203 const char *server = (const char *)check_data;
204
abbd7825
CT
205 if (cn_data->length == 0)
206 return 1; // zero length cn, ignore
207
208 if (cn_data->length > (int)sizeof(cn) - 1)
4d16918e 209 return 1; //if does not fit our buffer just ignore
abbd7825 210
0f7f4cfc
AJ
211 char *s = reinterpret_cast<char*>(cn_data->data);
212 char *d = cn;
213 for (int i = 0; i < cn_data->length; ++i, ++d, ++s) {
214 if (*s == '\0')
215 return 1; // always a domain mismatch. contains 0x00
216 *d = *s;
217 }
4d16918e
CT
218 cn[cn_data->length] = '\0';
219 debugs(83, 4, "Verifying server domain " << server << " to certificate name/subjectAltName " << cn);
abbd7825 220 return matchDomainName(server, (cn[0] == '*' ? cn + 1 : cn), mdnRejectSubsubDomains);
4d16918e
CT
221}
222
8eb0a7ee
CT
223bool Ssl::checkX509ServerValidity(X509 *cert, const char *server)
224{
225 return matchX509CommonNames(cert, (void *)server, check_domain);
226}
227
63be0a78 228/// \ingroup ServerProtocolSSLInternal
f484cdf5 229static int
230ssl_verify_cb(int ok, X509_STORE_CTX * ctx)
231{
7698a79c 232 // preserve original ctx->error before SSL_ calls can overwrite it
13cd7dee 233 Security::ErrorCode error_no = ok ? SSL_ERROR_NONE : ctx->error;
7698a79c
CT
234
235 char buffer[256] = "";
a7ad6e4e 236 SSL *ssl = (SSL *)X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
96993ee0 237 Security::ContextPtr sslctx = SSL_get_SSL_CTX(ssl);
68920ad8 238 SBuf *server = (SBuf *)SSL_get_ex_data(ssl, ssl_ex_index_server);
a7ad6e4e 239 void *dont_verify_domain = SSL_CTX_get_ex_data(sslctx, ssl_ctx_ex_index_dont_verify_domain);
815eaa44 240 ACLChecklist *check = (ACLChecklist*)SSL_get_ex_data(ssl, ssl_ex_index_cert_error_check);
e7bcc25f 241 X509 *peeked_cert = (X509 *)SSL_get_ex_data(ssl, ssl_ex_index_ssl_peeked_cert);
a7ad6e4e 242 X509 *peer_cert = ctx->cert;
f484cdf5 243
a7ad6e4e 244 X509_NAME_oneline(X509_get_subject_name(peer_cert), buffer,
62e76326 245 sizeof(buffer));
a7ad6e4e 246
0ad3ff51
CT
247 // detect infinite loops
248 uint32_t *validationCounter = static_cast<uint32_t *>(SSL_get_ex_data(ssl, ssl_ex_index_ssl_validation_counter));
249 if (!validationCounter) {
250 validationCounter = new uint32_t(1);
251 SSL_set_ex_data(ssl, ssl_ex_index_ssl_validation_counter, validationCounter);
252 } else {
253 // overflows allowed if SQUID_CERT_VALIDATION_ITERATION_MAX >= UINT32_MAX
254 (*validationCounter)++;
255 }
256
257 if ((*validationCounter) >= SQUID_CERT_VALIDATION_ITERATION_MAX) {
258 ok = 0; // or the validation loop will never stop
259 error_no = SQUID_X509_V_ERR_INFINITE_VALIDATION;
260 debugs(83, 2, "SQUID_X509_V_ERR_INFINITE_VALIDATION: " <<
261 *validationCounter << " iterations while checking " << buffer);
262 }
263
a7ad6e4e 264 if (ok) {
bf8fe701 265 debugs(83, 5, "SSL Certificate signature OK: " << buffer);
62e76326 266
4747ea4c 267 // Check for domain mismatch only if the current certificate is the peer certificate.
2e52fa2b 268 if (!dont_verify_domain && server && peer_cert == X509_STORE_CTX_get_current_cert(ctx)) {
68920ad8 269 if (!Ssl::checkX509ServerValidity(peer_cert, server->c_str())) {
815eaa44 270 debugs(83, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " << buffer << " does not match domainname " << server);
62e76326 271 ok = 0;
4d16918e 272 error_no = SQUID_X509_V_ERR_DOMAIN_MISMATCH;
62e76326 273 }
274 }
7698a79c 275 }
0db46e4f 276
e7bcc25f 277 if (ok && peeked_cert) {
7a957a93 278 // Check whether the already peeked certificate matches the new one.
e7bcc25f
CT
279 if (X509_cmp(peer_cert, peeked_cert) != 0) {
280 debugs(83, 2, "SQUID_X509_V_ERR_CERT_CHANGE: Certificate " << buffer << " does not match peeked certificate");
281 ok = 0;
282 error_no = SQUID_X509_V_ERR_CERT_CHANGE;
283 }
284 }
285
7698a79c 286 if (!ok) {
62a7607e
CT
287 X509 *broken_cert = X509_STORE_CTX_get_current_cert(ctx);
288 if (!broken_cert)
289 broken_cert = peer_cert;
290
291 Ssl::CertErrors *errs = static_cast<Ssl::CertErrors *>(SSL_get_ex_data(ssl, ssl_ex_index_ssl_errors));
e36bc333 292 const int depth = X509_STORE_CTX_get_error_depth(ctx);
7a957a93 293 if (!errs) {
b4e6a8d4 294 errs = new Ssl::CertErrors(Ssl::CertError(error_no, broken_cert, depth));
7a957a93 295 if (!SSL_set_ex_data(ssl, ssl_ex_index_ssl_errors, (void *)errs)) {
fb2178bb 296 debugs(83, 2, "Failed to set ssl error_no in ssl_verify_cb: Certificate " << buffer);
7a957a93
AR
297 delete errs;
298 errs = NULL;
fb2178bb 299 }
87f237a9 300 } else // remember another error number
e36bc333 301 errs->push_back_unique(Ssl::CertError(error_no, broken_cert, depth));
fb2178bb 302
7698a79c 303 if (const char *err_descr = Ssl::GetErrorDescr(error_no))
cf09bec7
CT
304 debugs(83, 5, err_descr << ": " << buffer);
305 else
7698a79c
CT
306 debugs(83, DBG_IMPORTANT, "SSL unknown certificate error " << error_no << " in " << buffer);
307
0ad3ff51
CT
308 // Check if the certificate error can be bypassed.
309 // Infinity validation loop errors can not bypassed.
310 if (error_no != SQUID_X509_V_ERR_INFINITE_VALIDATION) {
311 if (check) {
312 ACLFilledChecklist *filledCheck = Filled(check);
313 assert(!filledCheck->sslErrors);
314 filledCheck->sslErrors = new Ssl::CertErrors(Ssl::CertError(error_no, broken_cert));
315 filledCheck->serverCert.resetAndLock(peer_cert);
316 if (check->fastCheck() == ACCESS_ALLOWED) {
317 debugs(83, 3, "bypassing SSL error " << error_no << " in " << buffer);
318 ok = 1;
319 } else {
320 debugs(83, 5, "confirming SSL error " << error_no);
321 }
322 delete filledCheck->sslErrors;
323 filledCheck->sslErrors = NULL;
58a5291c 324 filledCheck->serverCert.reset();
7698a79c 325 }
0ad3ff51
CT
326 // If the certificate validator is used then we need to allow all errors and
327 // pass them to certficate validator for more processing
328 else if (Ssl::TheConfig.ssl_crt_validator) {
7698a79c 329 ok = 1;
7698a79c 330 }
815eaa44 331 }
a7ad6e4e 332 }
62e76326 333
081be7eb
CT
334 if (Ssl::TheConfig.ssl_crt_validator) {
335 // Check if we have stored certificates chain. Store if not.
336 if (!SSL_get_ex_data(ssl, ssl_ex_index_ssl_cert_chain)) {
337 STACK_OF(X509) *certStack = X509_STORE_CTX_get1_chain(ctx);
338 if (certStack && !SSL_set_ex_data(ssl, ssl_ex_index_ssl_cert_chain, certStack))
339 sk_X509_pop_free(certStack, X509_free);
340 }
341 }
342
7698a79c 343 if (!ok && !SSL_get_ex_data(ssl, ssl_ex_index_ssl_error_detail) ) {
f622c461
MF
344
345 // Find the broken certificate. It may be intermediate.
346 X509 *broken_cert = peer_cert; // reasonable default if search fails
347 // Our SQUID_X509_V_ERR_DOMAIN_MISMATCH implies peer_cert is at fault.
348 if (error_no != SQUID_X509_V_ERR_DOMAIN_MISMATCH) {
349 if (X509 *last_used_cert = X509_STORE_CTX_get_current_cert(ctx))
350 broken_cert = last_used_cert;
351 }
352
353 Ssl::ErrorDetail *errDetail =
de878a55 354 new Ssl::ErrorDetail(error_no, peer_cert, broken_cert);
f622c461 355
e34763f4 356 if (!SSL_set_ex_data(ssl, ssl_ex_index_ssl_error_detail, errDetail)) {
4d16918e
CT
357 debugs(83, 2, "Failed to set Ssl::ErrorDetail in ssl_verify_cb: Certificate " << buffer);
358 delete errDetail;
359 }
360 }
361
f484cdf5 362 return ok;
363}
364
815eaa44 365// "dup" function for SSL_get_ex_new_index("cert_err_check")
366static int
367ssl_dupAclChecklist(CRYPTO_EX_DATA *, CRYPTO_EX_DATA *, void *,
26ac0430
AJ
368 int, long, void *)
369{
815eaa44 370 // We do not support duplication of ACLCheckLists.
371 // If duplication is needed, we can count copies with cbdata.
372 assert(false);
373 return 0;
374}
375
376// "free" function for SSL_get_ex_new_index("cert_err_check")
377static void
378ssl_freeAclChecklist(void *, void *ptr, CRYPTO_EX_DATA *,
26ac0430
AJ
379 int, long, void *)
380{
815eaa44 381 delete static_cast<ACLChecklist *>(ptr); // may be NULL
382}
a7ad6e4e 383
4d16918e
CT
384// "free" function for SSL_get_ex_new_index("ssl_error_detail")
385static void
386ssl_free_ErrorDetail(void *, void *ptr, CRYPTO_EX_DATA *,
387 int, long, void *)
388{
389 Ssl::ErrorDetail *errDetail = static_cast <Ssl::ErrorDetail *>(ptr);
390 delete errDetail;
391}
392
fb2178bb 393static void
7a957a93 394ssl_free_SslErrors(void *, void *ptr, CRYPTO_EX_DATA *,
87f237a9 395 int, long, void *)
fb2178bb 396{
62a7607e 397 Ssl::CertErrors *errs = static_cast <Ssl::CertErrors*>(ptr);
7a957a93 398 delete errs;
fb2178bb
CT
399}
400
0ad3ff51
CT
401// "free" function for SSL_get_ex_new_index("ssl_ex_index_ssl_validation_counter")
402static void
403ssl_free_int(void *, void *ptr, CRYPTO_EX_DATA *,
3cc296c4 404 int, long, void *)
0ad3ff51
CT
405{
406 uint32_t *counter = static_cast <uint32_t *>(ptr);
407 delete counter;
408}
409
4747ea4c
CT
410/// \ingroup ServerProtocolSSLInternal
411/// Callback handler function to release STACK_OF(X509) "ex" data stored
412/// in an SSL object.
413static void
414ssl_free_CertChain(void *, void *ptr, CRYPTO_EX_DATA *,
415 int, long, void *)
416{
417 STACK_OF(X509) *certsChain = static_cast <STACK_OF(X509) *>(ptr);
418 sk_X509_pop_free(certsChain,X509_free);
419}
420
e7bcc25f
CT
421// "free" function for X509 certificates
422static void
423ssl_free_X509(void *, void *ptr, CRYPTO_EX_DATA *,
87f237a9 424 int, long, void *)
e7bcc25f
CT
425{
426 X509 *cert = static_cast <X509 *>(ptr);
427 X509_free(cert);
428}
429
c1d50c01 430// "free" function for SBuf
68920ad8
CT
431static void
432ssl_free_SBuf(void *, void *ptr, CRYPTO_EX_DATA *,
433 int, long, void *)
434{
435 SBuf *buf = static_cast <SBuf *>(ptr);
436 delete buf;
437}
438
0a28c16a
AJ
439void
440Ssl::Initialize(void)
f484cdf5 441{
56a35ad1
AR
442 static bool initialized = false;
443 if (initialized)
444 return;
445 initialized = true;
62e76326 446
56a35ad1
AR
447 SSL_load_error_strings();
448 SSLeay_add_ssl_algorithms();
62e76326 449
56a35ad1 450#if HAVE_OPENSSL_ENGINE_H
0a28c16a 451 if (::Config.SSL.ssl_engine) {
56a35ad1 452 ENGINE *e;
0a28c16a
AJ
453 if (!(e = ENGINE_by_id(::Config.SSL.ssl_engine)))
454 fatalf("Unable to find SSL engine '%s'\n", ::Config.SSL.ssl_engine);
56a35ad1
AR
455
456 if (!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
f5518dca 457 const int ssl_error = ERR_get_error();
56a35ad1 458 fatalf("Failed to initialise SSL engine: %s\n", ERR_error_string(ssl_error, NULL));
62e76326 459 }
56a35ad1 460 }
a7ad6e4e 461#else
0a28c16a 462 if (::Config.SSL.ssl_engine)
56a35ad1 463 fatalf("Your OpenSSL has no SSL engine support\n");
a7ad6e4e 464#endif
62e76326 465
0a28c16a 466 const char *defName = ::Config.SSL.certSignHash ? ::Config.SSL.certSignHash : SQUID_SSL_SIGN_HASH_IF_NONE;
3c26b00a
CT
467 Ssl::DefaultSignHash = EVP_get_digestbyname(defName);
468 if (!Ssl::DefaultSignHash)
469 fatalf("Sign hash '%s' is not supported\n", defName);
470
fa1cf51e 471 ssl_ex_index_server = SSL_get_ex_new_index(0, (void *) "server", NULL, NULL, ssl_free_SBuf);
a7ad6e4e 472 ssl_ctx_ex_index_dont_verify_domain = SSL_CTX_get_ex_new_index(0, (void *) "dont_verify_domain", NULL, NULL, NULL);
815eaa44 473 ssl_ex_index_cert_error_check = SSL_get_ex_new_index(0, (void *) "cert_error_check", NULL, &ssl_dupAclChecklist, &ssl_freeAclChecklist);
4d16918e 474 ssl_ex_index_ssl_error_detail = SSL_get_ex_new_index(0, (void *) "ssl_error_detail", NULL, NULL, &ssl_free_ErrorDetail);
e7bcc25f 475 ssl_ex_index_ssl_peeked_cert = SSL_get_ex_new_index(0, (void *) "ssl_peeked_cert", NULL, NULL, &ssl_free_X509);
7a957a93 476 ssl_ex_index_ssl_errors = SSL_get_ex_new_index(0, (void *) "ssl_errors", NULL, NULL, &ssl_free_SslErrors);
4747ea4c 477 ssl_ex_index_ssl_cert_chain = SSL_get_ex_new_index(0, (void *) "ssl_cert_chain", NULL, NULL, &ssl_free_CertChain);
0ad3ff51 478 ssl_ex_index_ssl_validation_counter = SSL_get_ex_new_index(0, (void *) "ssl_validation_counter", NULL, NULL, &ssl_free_int);
55369ae6
AR
479 ssl_ex_index_ssl_untrusted_chain = SSL_get_ex_new_index(0, (void *) "ssl_untrusted_chain", NULL, NULL, &ssl_free_CertChain);
480}
481
3834ada4
PM
482#if defined(SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)
483static void
484ssl_info_cb(const SSL *ssl, int where, int ret)
485{
486 (void)ret;
487 if ((where & SSL_CB_HANDSHAKE_DONE) != 0) {
488 // disable renegotiation (CVE-2009-3555)
489 ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS;
490 }
491}
492#endif
493
86660d64 494static bool
96993ee0 495configureSslContext(Security::ContextPtr sslContext, AnyP::PortCfg &port)
86660d64
CT
496{
497 int ssl_error;
9a622f3e 498 SSL_CTX_set_options(sslContext, port.secure.parsedOptions);
f484cdf5 499
3834ada4
PM
500#if defined(SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)
501 SSL_CTX_set_info_callback(sslContext, ssl_info_cb);
502#endif
503
86660d64
CT
504 if (port.sslContextSessionId)
505 SSL_CTX_set_session_id_context(sslContext, (const unsigned char *)port.sslContextSessionId, strlen(port.sslContextSessionId));
6b2936d5 506
9a622f3e 507 if (port.secure.parsedFlags & SSL_FLAG_NO_SESSION_REUSE) {
b13877cc 508 SSL_CTX_set_session_cache_mode(sslContext, SSL_SESS_CACHE_OFF);
509 }
510
a9d79803 511 if (Config.SSL.unclean_shutdown) {
bf8fe701 512 debugs(83, 5, "Enabling quiet SSL shutdowns (RFC violation).");
a9d79803 513
514 SSL_CTX_set_quiet_shutdown(sslContext, 1);
515 }
516
9a622f3e
AJ
517 if (!port.secure.sslCipher.isEmpty()) {
518 debugs(83, 5, "Using chiper suite " << port.secure.sslCipher << ".");
62e76326 519
9a622f3e 520 if (!SSL_CTX_set_cipher_list(sslContext, port.secure.sslCipher.c_str())) {
62e76326 521 ssl_error = ERR_get_error();
9a622f3e 522 debugs(83, DBG_CRITICAL, "ERROR: Failed to set SSL cipher suite '" << port.secure.sslCipher << "': " << ERR_error_string(ssl_error, NULL));
86660d64 523 return false;
62e76326 524 }
79d4ccdf 525 }
62e76326 526
bf8fe701 527 debugs(83, 9, "Setting RSA key generation callback.");
a7ad6e4e 528 SSL_CTX_set_tmp_rsa_callback(sslContext, ssl_temp_rsa_cb);
529
474f076e 530 port.secure.updateContextEecdh(sslContext);
86a84cc0 531 port.secure.updateContextCa(sslContext);
62e76326 532
86660d64 533 if (port.clientCA.get()) {
8c1ff4ef 534 ERR_clear_error();
e0f4e4e0
AR
535 if (STACK_OF(X509_NAME) *clientca = SSL_dup_CA_list(port.clientCA.get())) {
536 SSL_CTX_set_client_CA_list(sslContext, clientca);
537 } else {
538 ssl_error = ERR_get_error();
539 debugs(83, DBG_CRITICAL, "ERROR: Failed to dupe the client CA list: " << ERR_error_string(ssl_error, NULL));
540 return false;
541 }
62e76326 542
9a622f3e 543 if (port.secure.parsedFlags & SSL_FLAG_DELAYED_AUTH) {
bf8fe701 544 debugs(83, 9, "Not requesting client certificates until acl processing requires one");
62e76326 545 SSL_CTX_set_verify(sslContext, SSL_VERIFY_NONE, NULL);
546 } else {
bf8fe701 547 debugs(83, 9, "Requiring client certificates.");
62e76326 548 SSL_CTX_set_verify(sslContext, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, ssl_verify_cb);
549 }
a82a4fe4 550
6b19d1f9 551 port.secure.updateContextCrl(sslContext);
a82a4fe4 552
a7ad6e4e 553 } else {
bf8fe701 554 debugs(83, 9, "Not requiring any client certificates");
62e76326 555 SSL_CTX_set_verify(sslContext, SSL_VERIFY_NONE, NULL);
a7ad6e4e 556 }
f484cdf5 557
9a622f3e 558 if (port.secure.parsedFlags & SSL_FLAG_DONT_VERIFY_DOMAIN)
86660d64
CT
559 SSL_CTX_set_ex_data(sslContext, ssl_ctx_ex_index_dont_verify_domain, (void *) -1);
560
824d4656 561 Ssl::SetSessionCallbacks(sslContext);
10a69fc0 562
86660d64
CT
563 return true;
564}
565
c75aba02 566bool
9ad528b8 567Ssl::InitServerContext(const Security::ContextPointer &ctx, AnyP::PortCfg &port)
86660d64 568{
9ad528b8 569 if (!ctx)
c75aba02 570 return false;
86660d64 571
9ad528b8 572 if (!SSL_CTX_use_certificate(ctx.get(), port.signingCert.get())) {
f5518dca 573 const int ssl_error = ERR_get_error();
d1d72d43
AJ
574 const auto &keys = port.secure.certs.front();
575 debugs(83, DBG_CRITICAL, "ERROR: Failed to acquire TLS certificate '" << keys.certFile << "': " << ERR_error_string(ssl_error, NULL));
c75aba02 576 return false;
86660d64
CT
577 }
578
9ad528b8 579 if (!SSL_CTX_use_PrivateKey(ctx.get(), port.signPkey.get())) {
f5518dca 580 const int ssl_error = ERR_get_error();
d1d72d43
AJ
581 const auto &keys = port.secure.certs.front();
582 debugs(83, DBG_CRITICAL, "ERROR: Failed to acquire TLS private key '" << keys.privateKeyFile << "': " << ERR_error_string(ssl_error, NULL));
c75aba02 583 return false;
86660d64
CT
584 }
585
9ad528b8 586 Ssl::addChainToSslContext(ctx.get(), port.certsToChain.get());
86660d64
CT
587
588 /* Alternate code;
589 debugs(83, DBG_IMPORTANT, "Using certificate in " << certfile);
590
9ad528b8 591 if (!SSL_CTX_use_certificate_chain_file(ctx.get(), certfile)) {
86660d64
CT
592 ssl_error = ERR_get_error();
593 debugs(83, DBG_CRITICAL, "ERROR: Failed to acquire SSL certificate '" << certfile << "': " << ERR_error_string(ssl_error, NULL));
c75aba02 594 return false;
35105e4b 595 }
596
86660d64 597 debugs(83, DBG_IMPORTANT, "Using private key in " << keyfile);
9ad528b8 598 ssl_ask_password(ctx.get(), keyfile);
86660d64 599
9ad528b8 600 if (!SSL_CTX_use_PrivateKey_file(ctx.get(), keyfile, SSL_FILETYPE_PEM)) {
86660d64
CT
601 ssl_error = ERR_get_error();
602 debugs(83, DBG_CRITICAL, "ERROR: Failed to acquire SSL private key '" << keyfile << "': " << ERR_error_string(ssl_error, NULL));
c75aba02 603 return false;
35105e4b 604 }
605
86660d64 606 debugs(83, 5, "Comparing private and public SSL keys.");
35105e4b 607
9ad528b8 608 if (!SSL_CTX_check_private_key(ctx.get())) {
86660d64
CT
609 ssl_error = ERR_get_error();
610 debugs(83, DBG_CRITICAL, "ERROR: SSL private key '" << certfile << "' does not match public key '" <<
611 keyfile << "': " << ERR_error_string(ssl_error, NULL));
c75aba02 612 return false;
86660d64
CT
613 }
614 */
615
9ad528b8 616 if (!configureSslContext(ctx.get(), port)) {
86660d64 617 debugs(83, DBG_CRITICAL, "ERROR: Configuring static SSL context");
c75aba02 618 return false;
86660d64 619 }
62e76326 620
c75aba02 621 return true;
a7ad6e4e 622}
623
c75aba02
AJ
624bool
625Ssl::InitClientContext(Security::ContextPtr &sslContext, Security::PeerOptions &peer, long options, long fl)
d620ae0e 626{
42a5dae8 627 if (!sslContext)
c75aba02 628 return false;
62e76326 629
6bd62757 630 SSL_CTX_set_options(sslContext, options);
a7ad6e4e 631
3834ada4
PM
632#if defined(SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)
633 SSL_CTX_set_info_callback(sslContext, ssl_info_cb);
634#endif
635
d1d72d43
AJ
636 if (!peer.sslCipher.isEmpty()) {
637 debugs(83, 5, "Using chiper suite " << peer.sslCipher << ".");
62e76326 638
d1d72d43 639 const char *cipher = peer.sslCipher.c_str();
62e76326 640 if (!SSL_CTX_set_cipher_list(sslContext, cipher)) {
f5518dca 641 const int ssl_error = ERR_get_error();
62e76326 642 fatalf("Failed to set SSL cipher suite '%s': %s\n",
643 cipher, ERR_error_string(ssl_error, NULL));
644 }
a7ad6e4e 645 }
62e76326 646
332c979d
AJ
647 if (!peer.certs.empty()) {
648 // TODO: support loading multiple cert/key pairs
649 auto &keys = peer.certs.front();
650 if (!keys.certFile.isEmpty()) {
651 debugs(83, DBG_IMPORTANT, "Using certificate in " << keys.certFile);
652
653 const char *certfile = keys.certFile.c_str();
654 if (!SSL_CTX_use_certificate_chain_file(sslContext, certfile)) {
655 const int ssl_error = ERR_get_error();
656 fatalf("Failed to acquire SSL certificate '%s': %s\n",
657 certfile, ERR_error_string(ssl_error, NULL));
658 }
62e76326 659
332c979d
AJ
660 debugs(83, DBG_IMPORTANT, "Using private key in " << keys.privateKeyFile);
661 const char *keyfile = keys.privateKeyFile.c_str();
662 ssl_ask_password(sslContext, keyfile);
62e76326 663
332c979d
AJ
664 if (!SSL_CTX_use_PrivateKey_file(sslContext, keyfile, SSL_FILETYPE_PEM)) {
665 const int ssl_error = ERR_get_error();
666 fatalf("Failed to acquire SSL private key '%s': %s\n",
667 keyfile, ERR_error_string(ssl_error, NULL));
668 }
62e76326 669
332c979d 670 debugs(83, 5, "Comparing private and public SSL keys.");
62e76326 671
332c979d
AJ
672 if (!SSL_CTX_check_private_key(sslContext)) {
673 const int ssl_error = ERR_get_error();
674 fatalf("SSL private key '%s' does not match public key '%s': %s\n",
675 certfile, keyfile, ERR_error_string(ssl_error, NULL));
676 }
62e76326 677 }
a7ad6e4e 678 }
62e76326 679
bf8fe701 680 debugs(83, 9, "Setting RSA key generation callback.");
f484cdf5 681 SSL_CTX_set_tmp_rsa_callback(sslContext, ssl_temp_rsa_cb);
682
a7ad6e4e 683 if (fl & SSL_FLAG_DONT_VERIFY_PEER) {
48e7baac 684 debugs(83, 2, "NOTICE: Peer certificates are not verified for validity!");
62e76326 685 SSL_CTX_set_verify(sslContext, SSL_VERIFY_NONE, NULL);
a7ad6e4e 686 } else {
bf8fe701 687 debugs(83, 9, "Setting certificate verification callback.");
62e76326 688 SSL_CTX_set_verify(sslContext, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, ssl_verify_cb);
a7ad6e4e 689 }
f484cdf5 690
c75aba02 691 return true;
f484cdf5 692}
693
63be0a78 694/// \ingroup ServerProtocolSSLInternal
d193a436 695int
e6ccf245 696ssl_read_method(int fd, char *buf, int len)
f484cdf5 697{
33cc0629 698 auto ssl = fd_table[fd].ssl.get();
79d4ccdf 699
6de9e64b 700#if DONT_DO_THIS
701
702 if (!SSL_is_init_finished(ssl)) {
703 errno = ENOTCONN;
704 return -1;
705 }
79d4ccdf 706
6de9e64b 707#endif
708
33cc0629 709 int i = SSL_read(ssl, buf, len);
6de9e64b 710
711 if (i > 0 && SSL_pending(ssl) > 0) {
bf8fe701 712 debugs(83, 2, "SSL FD " << fd << " is pending");
be4d35dc 713 fd_table[fd].flags.read_pending = true;
79d4ccdf 714 } else
be4d35dc 715 fd_table[fd].flags.read_pending = false;
79d4ccdf 716
717 return i;
f484cdf5 718}
719
63be0a78 720/// \ingroup ServerProtocolSSLInternal
d193a436 721int
e6ccf245 722ssl_write_method(int fd, const char *buf, int len)
f484cdf5 723{
33cc0629 724 auto ssl = fd_table[fd].ssl.get();
6de9e64b 725 if (!SSL_is_init_finished(ssl)) {
726 errno = ENOTCONN;
727 return -1;
728 }
729
33cc0629 730 int i = SSL_write(ssl, buf, len);
6de9e64b 731 return i;
f484cdf5 732}
79d4ccdf 733
734void
575d05c4 735ssl_shutdown_method(SSL *ssl)
79d4ccdf 736{
79d4ccdf 737 SSL_shutdown(ssl);
738}
a7ad6e4e 739
63be0a78 740/// \ingroup ServerProtocolSSLInternal
a7ad6e4e 741static const char *
742ssl_get_attribute(X509_NAME * name, const char *attribute_name)
743{
744 static char buffer[1024];
a7ad6e4e 745 buffer[0] = '\0';
746
747 if (strcmp(attribute_name, "DN") == 0) {
62e76326 748 X509_NAME_oneline(name, buffer, sizeof(buffer));
627059a5
AJ
749 } else {
750 int nid = OBJ_txt2nid(const_cast<char *>(attribute_name));
751 if (nid == 0) {
752 debugs(83, DBG_IMPORTANT, "WARNING: Unknown SSL attribute name '" << attribute_name << "'");
753 return nullptr;
754 }
755 X509_NAME_get_text_by_NID(name, nid, buffer, sizeof(buffer));
a7ad6e4e 756 }
62e76326 757
627059a5 758 return *buffer ? buffer : nullptr;
a7ad6e4e 759}
760
63be0a78 761/// \ingroup ServerProtocolSSLInternal
a7ad6e4e 762const char *
00352183 763Ssl::GetX509UserAttribute(X509 * cert, const char *attribute_name)
a7ad6e4e 764{
a7ad6e4e 765 X509_NAME *name;
23e6c4ae 766 const char *ret;
a7ad6e4e 767
a7ad6e4e 768 if (!cert)
62e76326 769 return NULL;
a7ad6e4e 770
5a4684b6 771 name = X509_get_subject_name(cert);
a7ad6e4e 772
23e6c4ae 773 ret = ssl_get_attribute(name, attribute_name);
774
23e6c4ae 775 return ret;
a7ad6e4e 776}
777
00352183
AR
778const char *
779Ssl::GetX509Fingerprint(X509 * cert, const char *)
780{
781 static char buf[1024];
782 if (!cert)
783 return NULL;
960e100b 784
00352183
AR
785 unsigned int n;
786 unsigned char md[EVP_MAX_MD_SIZE];
787 if (!X509_digest(cert, EVP_sha1(), md, &n))
788 return NULL;
789
790 assert(3 * n + 1 < sizeof(buf));
791
792 char *s = buf;
793 for (unsigned int i=0; i < n; ++i, s += 3) {
794 const char term = (i + 1 < n) ? ':' : '\0';
795 snprintf(s, 4, "%02X%c", md[i], term);
796 }
797
798 return buf;
799}
800
63be0a78 801/// \ingroup ServerProtocolSSLInternal
a7ad6e4e 802const char *
00352183 803Ssl::GetX509CAAttribute(X509 * cert, const char *attribute_name)
a7ad6e4e 804{
00352183 805
a7ad6e4e 806 X509_NAME *name;
23e6c4ae 807 const char *ret;
a7ad6e4e 808
a7ad6e4e 809 if (!cert)
62e76326 810 return NULL;
a7ad6e4e 811
5a4684b6 812 name = X509_get_issuer_name(cert);
a7ad6e4e 813
23e6c4ae 814 ret = ssl_get_attribute(name, attribute_name);
815
00352183
AR
816 return ret;
817}
818
819const char *sslGetUserAttribute(SSL *ssl, const char *attribute_name)
820{
821 if (!ssl)
822 return NULL;
823
824 X509 *cert = SSL_get_peer_certificate(ssl);
825
826 const char *attr = Ssl::GetX509UserAttribute(cert, attribute_name);
827
23e6c4ae 828 X509_free(cert);
00352183
AR
829 return attr;
830}
23e6c4ae 831
00352183
AR
832const char *sslGetCAAttribute(SSL *ssl, const char *attribute_name)
833{
834 if (!ssl)
835 return NULL;
836
837 X509 *cert = SSL_get_peer_certificate(ssl);
838
839 const char *attr = Ssl::GetX509CAAttribute(cert, attribute_name);
840
841 X509_free(cert);
842 return attr;
a7ad6e4e 843}
844
a7ad6e4e 845const char *
846sslGetUserEmail(SSL * ssl)
847{
e6ceef10 848 return sslGetUserAttribute(ssl, "emailAddress");
a7ad6e4e 849}
4ac9968f 850
851const char *
852sslGetUserCertificatePEM(SSL *ssl)
853{
854 X509 *cert;
855 BIO *mem;
856 static char *str = NULL;
857 char *ptr;
858 long len;
859
860 safe_free(str);
861
862 if (!ssl)
863 return NULL;
864
865 cert = SSL_get_peer_certificate(ssl);
866
867 if (!cert)
868 return NULL;
869
870 mem = BIO_new(BIO_s_mem());
871
872 PEM_write_bio_X509(mem, cert);
873
4ac9968f 874 len = BIO_get_mem_data(mem, &ptr);
875
876 str = (char *)xmalloc(len + 1);
877
878 memcpy(str, ptr, len);
879
880 str[len] = '\0';
881
882 X509_free(cert);
883
884 BIO_free(mem);
885
886 return str;
887}
3d61c476 888
889const char *
890sslGetUserCertificateChainPEM(SSL *ssl)
891{
892 STACK_OF(X509) *chain;
893 BIO *mem;
894 static char *str = NULL;
895 char *ptr;
896 long len;
897 int i;
898
899 safe_free(str);
900
901 if (!ssl)
902 return NULL;
903
904 chain = SSL_get_peer_cert_chain(ssl);
905
906 if (!chain)
907 return sslGetUserCertificatePEM(ssl);
908
909 mem = BIO_new(BIO_s_mem());
910
d7ae3534 911 for (i = 0; i < sk_X509_num(chain); ++i) {
3d61c476 912 X509 *cert = sk_X509_value(chain, i);
913 PEM_write_bio_X509(mem, cert);
914 }
915
916 len = BIO_get_mem_data(mem, &ptr);
917
918 str = (char *)xmalloc(len + 1);
919 memcpy(str, ptr, len);
920 str[len] = '\0';
921
922 BIO_free(mem);
923
924 return str;
925}
454e8283 926
95d2589c 927/// Create SSL context and apply ssl certificate and private key to it.
96993ee0 928Security::ContextPtr
f97700a0 929Ssl::createSSLContext(Security::CertPointer & x509, Ssl::EVP_PKEY_Pointer & pkey, AnyP::PortCfg &port)
95d2589c 930{
0806013a 931#if (OPENSSL_VERSION_NUMBER >= 0x10100000L)
3db3be00 932 Security::ContextPointer sslContext(SSL_CTX_new(TLS_server_method()));
0806013a 933#else
3db3be00 934 Security::ContextPointer sslContext(SSL_CTX_new(SSLv23_server_method()));
0806013a 935#endif
95d2589c
CT
936
937 if (!SSL_CTX_use_certificate(sslContext.get(), x509.get()))
938 return NULL;
939
940 if (!SSL_CTX_use_PrivateKey(sslContext.get(), pkey.get()))
941 return NULL;
86660d64
CT
942
943 if (!configureSslContext(sslContext.get(), port))
944 return NULL;
945
95d2589c
CT
946 return sslContext.release();
947}
948
96993ee0 949Security::ContextPtr
86660d64 950Ssl::generateSslContextUsingPkeyAndCertFromMemory(const char * data, AnyP::PortCfg &port)
95d2589c 951{
f97700a0 952 Security::CertPointer cert;
95d2589c 953 Ssl::EVP_PKEY_Pointer pkey;
96993ee0
AJ
954 if (!readCertAndPrivateKeyFromMemory(cert, pkey, data) || !cert || !pkey)
955 return nullptr;
95d2589c 956
86660d64 957 return createSSLContext(cert, pkey, port);
95d2589c
CT
958}
959
96993ee0 960Security::ContextPtr
86660d64 961Ssl::generateSslContext(CertificateProperties const &properties, AnyP::PortCfg &port)
95d2589c 962{
f97700a0 963 Security::CertPointer cert;
95d2589c 964 Ssl::EVP_PKEY_Pointer pkey;
96993ee0
AJ
965 if (!generateSslCertificate(cert, pkey, properties) || !cert || !pkey)
966 return nullptr;
95d2589c 967
86660d64 968 return createSSLContext(cert, pkey, port);
95d2589c
CT
969}
970
d8f0ceab
CT
971void
972Ssl::chainCertificatesToSSLContext(SSL_CTX *sslContext, AnyP::PortCfg &port)
973{
974 assert(sslContext != NULL);
975 // Add signing certificate to the certificates chain
976 X509 *signingCert = port.signingCert.get();
977 if (SSL_CTX_add_extra_chain_cert(sslContext, signingCert)) {
978 // increase the certificate lock
979 CRYPTO_add(&(signingCert->references),1,CRYPTO_LOCK_X509);
980 } else {
981 const int ssl_error = ERR_get_error();
982 debugs(33, DBG_IMPORTANT, "WARNING: can not add signing certificate to SSL context chain: " << ERR_error_string(ssl_error, NULL));
983 }
984 Ssl::addChainToSslContext(sslContext, port.certsToChain.get());
985}
986
987void
988Ssl::configureUnconfiguredSslContext(SSL_CTX *sslContext, Ssl::CertSignAlgorithm signAlgorithm,AnyP::PortCfg &port)
989{
990 if (sslContext && signAlgorithm == Ssl::algSignTrusted) {
991 Ssl::chainCertificatesToSSLContext(sslContext, port);
992 }
993}
994
d620ae0e
CT
995bool
996Ssl::configureSSL(SSL *ssl, CertificateProperties const &properties, AnyP::PortCfg &port)
997{
f97700a0 998 Security::CertPointer cert;
d620ae0e
CT
999 Ssl::EVP_PKEY_Pointer pkey;
1000 if (!generateSslCertificate(cert, pkey, properties))
1001 return false;
1002
1003 if (!cert)
1004 return false;
1005
1006 if (!pkey)
1007 return false;
1008
1009 if (!SSL_use_certificate(ssl, cert.get()))
1010 return false;
1011
1012 if (!SSL_use_PrivateKey(ssl, pkey.get()))
1013 return false;
1014
1015 return true;
1016}
1017
1018bool
1019Ssl::configureSSLUsingPkeyAndCertFromMemory(SSL *ssl, const char *data, AnyP::PortCfg &port)
1020{
f97700a0 1021 Security::CertPointer cert;
d620ae0e
CT
1022 Ssl::EVP_PKEY_Pointer pkey;
1023 if (!readCertAndPrivateKeyFromMemory(cert, pkey, data))
1024 return false;
1025
1026 if (!cert || !pkey)
1027 return false;
1028
1029 if (!SSL_use_certificate(ssl, cert.get()))
1030 return false;
1031
1032 if (!SSL_use_PrivateKey(ssl, pkey.get()))
1033 return false;
1034
1035 return true;
1036}
1037
96993ee0 1038bool Ssl::verifySslCertificate(Security::ContextPtr sslContext, CertificateProperties const &properties)
95d2589c 1039{
b8658552 1040 // SSL_get_certificate is buggy in openssl versions 1.0.1d and 1.0.1e
96993ee0 1041 // Try to retrieve certificate directly from Security::ContextPtr object
fc321c30 1042#if SQUID_USE_SSLGETCERTIFICATE_HACK
b8658552
CT
1043 X509 ***pCert = (X509 ***)sslContext->cert;
1044 X509 * cert = pCert && *pCert ? **pCert : NULL;
fc321c30
CT
1045#elif SQUID_SSLGETCERTIFICATE_BUGGY
1046 X509 * cert = NULL;
1047 assert(0);
b8658552 1048#else
95d2589c 1049 // Temporary ssl for getting X509 certificate from SSL_CTX.
33cc0629 1050 Security::SessionPointer ssl(SSL_new(sslContext));
95d2589c 1051 X509 * cert = SSL_get_certificate(ssl.get());
b8658552
CT
1052#endif
1053 if (!cert)
1054 return false;
95d2589c
CT
1055 ASN1_TIME * time_notBefore = X509_get_notBefore(cert);
1056 ASN1_TIME * time_notAfter = X509_get_notAfter(cert);
1057 bool ret = (X509_cmp_current_time(time_notBefore) < 0 && X509_cmp_current_time(time_notAfter) > 0);
e7bcc25f
CT
1058 if (!ret)
1059 return false;
1060
4ece76b2 1061 return certificateMatchesProperties(cert, properties);
95d2589c
CT
1062}
1063
253749a8
CT
1064bool
1065Ssl::setClientSNI(SSL *ssl, const char *fqdn)
1066{
1067 //The SSL_CTRL_SET_TLSEXT_HOSTNAME is a openssl macro which indicates
1068 // if the TLS servername extension (SNI) is enabled in openssl library.
1069#if defined(SSL_CTRL_SET_TLSEXT_HOSTNAME)
1070 if (!SSL_set_tlsext_host_name(ssl, fqdn)) {
1071 const int ssl_error = ERR_get_error();
1072 debugs(83, 3, "WARNING: unable to set TLS servername extension (SNI): " <<
1073 ERR_error_string(ssl_error, NULL) << "\n");
1074 return false;
1075 }
1076 return true;
1077#else
1078 debugs(83, 7, "no support for TLS servername extension (SNI)\n");
1079 return false;
1080#endif
1081}
1082
96993ee0 1083void Ssl::addChainToSslContext(Security::ContextPtr sslContext, STACK_OF(X509) *chain)
a594dbfa
CT
1084{
1085 if (!chain)
1086 return;
1087
d7ae3534 1088 for (int i = 0; i < sk_X509_num(chain); ++i) {
a594dbfa
CT
1089 X509 *cert = sk_X509_value(chain, i);
1090 if (SSL_CTX_add_extra_chain_cert(sslContext, cert)) {
1091 // increase the certificate lock
1092 CRYPTO_add(&(cert->references),1,CRYPTO_LOCK_X509);
1093 } else {
1094 const int ssl_error = ERR_get_error();
1095 debugs(83, DBG_IMPORTANT, "WARNING: can not add certificate to SSL context chain: " << ERR_error_string(ssl_error, NULL));
1096 }
1097 }
1098}
1099
55369ae6
AR
1100static const char *
1101hasAuthorityInfoAccessCaIssuers(X509 *cert)
1102{
1103 AUTHORITY_INFO_ACCESS *info;
1104 if (!cert)
168d2b30 1105 return nullptr;
4b5ea8a6 1106 info = static_cast<AUTHORITY_INFO_ACCESS *>(X509_get_ext_d2i(cert, NID_info_access, NULL, NULL));
55369ae6 1107 if (!info)
168d2b30 1108 return nullptr;
55369ae6
AR
1109
1110 static char uri[MAX_URL];
1111 uri[0] = '\0';
1112
1113 for (int i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1114 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1115 if (OBJ_obj2nid(ad->method) == NID_ad_ca_issuers) {
1116 if (ad->location->type == GEN_URI) {
4b5ea8a6 1117 xstrncpy(uri, reinterpret_cast<char *>(ASN1_STRING_data(ad->location->d.uniformResourceIdentifier)), sizeof(uri));
55369ae6
AR
1118 }
1119 break;
1120 }
1121 }
1122 AUTHORITY_INFO_ACCESS_free(info);
168d2b30 1123 return uri[0] != '\0' ? uri : nullptr;
55369ae6
AR
1124}
1125
866be11c
CT
1126bool
1127Ssl::loadCerts(const char *certsFile, Ssl::CertsIndexedList &list)
1128{
1129 BIO *in = BIO_new_file(certsFile, "r");
1130 if (!in) {
1131 debugs(83, DBG_IMPORTANT, "Failed to open '" << certsFile << "' to load certificates");
1132 return false;
1133 }
1134
1135 X509 *aCert;
1136 while((aCert = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
1137 static char buffer[2048];
1138 X509_NAME_oneline(X509_get_subject_name(aCert), buffer, sizeof(buffer));
1139 list.insert(std::pair<SBuf, X509 *>(SBuf(buffer), aCert));
1140 }
1141 debugs(83, 4, "Loaded " << list.size() << " certificates from file: '" << certsFile << "'");
1142 BIO_free(in);
1143 return true;
1144}
1145
6c4905ef
CT
1146/// quickly find the issuer certificate of a certificate cert in the
1147/// Ssl::CertsIndexedList list
55369ae6 1148static X509 *
6c4905ef 1149findCertIssuerFast(Ssl::CertsIndexedList &list, X509 *cert)
55369ae6
AR
1150{
1151 static char buffer[2048];
1152
1153 if (X509_NAME *issuerName = X509_get_issuer_name(cert))
1154 X509_NAME_oneline(issuerName, buffer, sizeof(buffer));
1155 else
1156 return NULL;
1157
1158 const auto ret = list.equal_range(SBuf(buffer));
1159 for (Ssl::CertsIndexedList::iterator it = ret.first; it != ret.second; ++it) {
1160 X509 *issuer = it->second;
1161 if (X509_check_issued(cert, issuer)) {
1162 return issuer;
1163 }
1164 }
1165 return NULL;
1166}
1167
6c4905ef 1168/// slowly find the issuer certificate of a given cert using linear search
a34d1d2d
CT
1169static bool
1170findCertIssuer(Security::CertList const &list, X509 *cert)
55369ae6 1171{
a34d1d2d
CT
1172 for (Security::CertList::const_iterator it = list.begin(); it != list.end(); ++it) {
1173 if (X509_check_issued(it->get(), cert) == X509_V_OK)
1174 return true;
55369ae6 1175 }
a34d1d2d 1176 return false;
55369ae6
AR
1177}
1178
1179const char *
a34d1d2d 1180Ssl::uriOfIssuerIfMissing(X509 *cert, Security::CertList const &serverCertificates)
55369ae6 1181{
a34d1d2d 1182 if (!cert || !serverCertificates.size())
168d2b30 1183 return nullptr;
55369ae6 1184
a34d1d2d 1185 if (!findCertIssuer(serverCertificates, cert)) {
168d2b30 1186 //if issuer is missing
6c4905ef 1187 if (!findCertIssuerFast(SquidUntrustedCerts, cert)) {
3945c91d 1188 // and issuer not found in local untrusted certificates database
55369ae6
AR
1189 if (const char *issuerUri = hasAuthorityInfoAccessCaIssuers(cert)) {
1190 // There is a URI where we can download a certificate.
55369ae6
AR
1191 return issuerUri;
1192 }
1193 }
1194 }
168d2b30 1195 return nullptr;
55369ae6
AR
1196}
1197
1198void
a34d1d2d 1199Ssl::missingChainCertificatesUrls(std::queue<SBuf> &URIs, Security::CertList const &serverCertificates)
55369ae6 1200{
a34d1d2d 1201 if (!serverCertificates.size())
55369ae6
AR
1202 return;
1203
4b5ea8a6
CT
1204 for (const auto &i : serverCertificates) {
1205 if (const char *issuerUri = uriOfIssuerIfMissing(i.get(), serverCertificates))
55369ae6
AR
1206 URIs.push(SBuf(issuerUri));
1207 }
1208}
1209
1210void
1211Ssl::SSL_add_untrusted_cert(SSL *ssl, X509 *cert)
1212{
1213 STACK_OF(X509) *untrustedStack = static_cast <STACK_OF(X509) *>(SSL_get_ex_data(ssl, ssl_ex_index_ssl_untrusted_chain));
1214 if (!untrustedStack) {
1215 untrustedStack = sk_X509_new_null();
1216 if (!SSL_set_ex_data(ssl, ssl_ex_index_ssl_untrusted_chain, untrustedStack)) {
168d2b30
CT
1217 sk_X509_pop_free(untrustedStack, X509_free);
1218 throw TextException("Failed to attach untrusted certificates chain");
55369ae6
AR
1219 }
1220 }
1221 sk_X509_push(untrustedStack, cert);
1222}
1223
6c4905ef 1224/// Search for the issuer certificate of cert in sk list.
a34d1d2d 1225static X509 *
6c4905ef 1226sk_x509_findIssuer(STACK_OF(X509) *sk, X509 *cert)
a34d1d2d
CT
1227{
1228 if (!sk)
1229 return NULL;
1230
1231 const int skItemsNum = sk_X509_num(sk);
1232 for (int i = 0; i < skItemsNum; ++i) {
1233 X509 *issuer = sk_X509_value(sk, i);
1234 if (X509_check_issued(issuer, cert) == X509_V_OK)
1235 return issuer;
1236 }
1237 return NULL;
1238}
1239
55369ae6
AR
1240/// add missing issuer certificates to untrustedCerts
1241static void
1242completeIssuers(X509_STORE_CTX *ctx, STACK_OF(X509) *untrustedCerts)
1243{
1244 debugs(83, 2, "completing " << sk_X509_num(untrustedCerts) << " OpenSSL untrusted certs using " << SquidUntrustedCerts.size() << " configured untrusted certificates");
1245
1246 int depth = ctx->param->depth;
1247 X509 *current = ctx->cert;
1248 int i = 0;
1249 for (i = 0; current && (i < depth); ++i) {
1250 if (X509_check_issued(current, current)) {
1251 // either ctx->cert is itself self-signed or untrustedCerts
1252 // aready contain the self-signed current certificate
1253 break;
1254 }
1255
1256 // untrustedCerts is short, not worth indexing
6c4905ef 1257 X509 *issuer = sk_x509_findIssuer(untrustedCerts, current);
55369ae6 1258 if (!issuer) {
6c4905ef 1259 if ((issuer = findCertIssuerFast(SquidUntrustedCerts, current)))
55369ae6
AR
1260 sk_X509_push(untrustedCerts, issuer);
1261 }
1262 current = issuer;
1263 }
1264
1265 if (i >= depth)
1266 debugs(83, 2, "exceeded the maximum certificate chain length: " << depth);
1267}
1268
1269/// OpenSSL certificate validation callback.
1270static int
1271untrustedToStoreCtx_cb(X509_STORE_CTX *ctx,void *data)
1272{
1273 debugs(83, 4, "Try to use pre-downloaded intermediate certificates\n");
1274
4b5ea8a6 1275 SSL *ssl = static_cast<SSL *>(X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
55369ae6
AR
1276 STACK_OF(X509) *sslUntrustedStack = static_cast <STACK_OF(X509) *>(SSL_get_ex_data(ssl, ssl_ex_index_ssl_untrusted_chain));
1277
1278 // OpenSSL already maintains ctx->untrusted but we cannot modify
1279 // internal OpenSSL list directly. We have to give OpenSSL our own
1280 // list, but it must include certificates on the OpenSSL ctx->untrusted
1281 STACK_OF(X509) *oldUntrusted = ctx->untrusted;
1282 STACK_OF(X509) *sk = sk_X509_dup(oldUntrusted); // oldUntrusted is always not NULL
1283
1284 for (int i = 0; i < sk_X509_num(sslUntrustedStack); ++i) {
1285 X509 *cert = sk_X509_value(sslUntrustedStack, i);
1286 sk_X509_push(sk, cert);
1287 }
1288
1289 // If the local untrusted certificates internal database is used
1290 // run completeIssuers to add missing certificates if possible.
1291 if (SquidUntrustedCerts.size() > 0)
1292 completeIssuers(ctx, sk);
1293
1294 X509_STORE_CTX_set_chain(ctx, sk); // No locking/unlocking, just sets ctx->untrusted
1295 int ret = X509_verify_cert(ctx);
1296 X509_STORE_CTX_set_chain(ctx, oldUntrusted); // Set back the old untrusted list
1297 sk_X509_free(sk); // Release sk list
1298 return ret;
1299}
1300
1301void
1302Ssl::useSquidUntrusted(SSL_CTX *sslContext)
1303{
1304 SSL_CTX_set_cert_verify_callback(sslContext, untrustedToStoreCtx_cb, NULL);
1305}
1306
1307bool
1308Ssl::loadSquidUntrusted(const char *path)
1309{
1310 return Ssl::loadCerts(path, SquidUntrustedCerts);
1311}
1312
1313void
1314Ssl::unloadSquidUntrusted()
1315{
1316 if (SquidUntrustedCerts.size()) {
1317 for (Ssl::CertsIndexedList::iterator it = SquidUntrustedCerts.begin(); it != SquidUntrustedCerts.end(); ++it) {
1318 X509_free(it->second);
1319 }
1320 SquidUntrustedCerts.clear();
1321 }
1322}
1323
a594dbfa
CT
1324/**
1325 \ingroup ServerProtocolSSLInternal
1326 * Read certificate from file.
1327 * See also: static readSslX509Certificate function, gadgets.cc file
1328 */
1329static X509 * readSslX509CertificatesChain(char const * certFilename, STACK_OF(X509)* chain)
1330{
1331 if (!certFilename)
1332 return NULL;
1333 Ssl::BIO_Pointer bio(BIO_new(BIO_s_file_internal()));
1334 if (!bio)
1335 return NULL;
1336 if (!BIO_read_filename(bio.get(), certFilename))
1337 return NULL;
1338 X509 *certificate = PEM_read_bio_X509(bio.get(), NULL, NULL, NULL);
1339
1340 if (certificate && chain) {
1341
c11211d9 1342 if (X509_check_issued(certificate, certificate) == X509_V_OK)
a594dbfa
CT
1343 debugs(83, 5, "Certificate is self-signed, will not be chained");
1344 else {
a411d213 1345 // and add to the chain any other certificate exist in the file
a594dbfa
CT
1346 while (X509 *ca = PEM_read_bio_X509(bio.get(), NULL, NULL, NULL)) {
1347 if (!sk_X509_push(chain, ca))
1348 debugs(83, DBG_IMPORTANT, "WARNING: unable to add CA certificate to cert chain");
1349 }
1350 }
1351 }
c11211d9 1352
a594dbfa
CT
1353 return certificate;
1354}
1355
f97700a0 1356void Ssl::readCertChainAndPrivateKeyFromFiles(Security::CertPointer & cert, EVP_PKEY_Pointer & pkey, X509_STACK_Pointer & chain, char const * certFilename, char const * keyFilename)
a594dbfa
CT
1357{
1358 if (keyFilename == NULL)
1359 keyFilename = certFilename;
86660d64
CT
1360
1361 if (certFilename == NULL)
1362 certFilename = keyFilename;
1363
1364 debugs(83, DBG_IMPORTANT, "Using certificate in " << certFilename);
1365
a594dbfa
CT
1366 if (!chain)
1367 chain.reset(sk_X509_new_null());
1368 if (!chain)
1369 debugs(83, DBG_IMPORTANT, "WARNING: unable to allocate memory for cert chain");
37144aca
AR
1370 // XXX: ssl_ask_password_cb needs SSL_CTX_set_default_passwd_cb_userdata()
1371 // so this may not fully work iff Config.Program.ssl_password is set.
1372 pem_password_cb *cb = ::Config.Program.ssl_password ? &ssl_ask_password_cb : NULL;
35b3559c
AJ
1373 pkey.resetWithoutLocking(readSslPrivateKey(keyFilename, cb));
1374 cert.resetWithoutLocking(readSslX509CertificatesChain(certFilename, chain.get()));
a594dbfa 1375 if (!pkey || !cert || !X509_check_private_key(cert.get(), pkey.get())) {
58a5291c
AJ
1376 pkey.reset();
1377 cert.reset();
a594dbfa
CT
1378 }
1379}
1380
f97700a0 1381bool Ssl::generateUntrustedCert(Security::CertPointer &untrustedCert, EVP_PKEY_Pointer &untrustedPkey, Security::CertPointer const &cert, EVP_PKEY_Pointer const & pkey)
95588170
CT
1382{
1383 // Generate the self-signed certificate, using a hard-coded subject prefix
1384 Ssl::CertificateProperties certProperties;
1385 if (const char *cn = CommonHostName(cert.get())) {
1386 certProperties.commonName = "Not trusted by \"";
1387 certProperties.commonName += cn;
1388 certProperties.commonName += "\"";
87f237a9 1389 } else if (const char *org = getOrganization(cert.get())) {
95588170
CT
1390 certProperties.commonName = "Not trusted by \"";
1391 certProperties.commonName += org;
1392 certProperties.commonName += "\"";
87f237a9 1393 } else
95588170
CT
1394 certProperties.commonName = "Not trusted";
1395 certProperties.setCommonName = true;
1396 // O, OU, and other CA subject fields will be mimicked
1397 // Expiration date and other common properties will be mimicked
1398 certProperties.signAlgorithm = Ssl::algSignSelf;
1399 certProperties.signWithPkey.resetAndLock(pkey.get());
1400 certProperties.mimicCert.resetAndLock(cert.get());
1401 return Ssl::generateSslCertificate(untrustedCert, untrustedPkey, certProperties);
1402}
1403
157c5ace
AJ
1404static bool
1405SslCreate(Security::ContextPtr sslContext, const Comm::ConnectionPointer &conn, Ssl::Bio::Type type, const char *squidCtx)
b3a8ae1b 1406{
157c5ace 1407 if (!Comm::IsConnOpen(conn)) {
b418d9c8 1408 debugs(83, DBG_IMPORTANT, "Gone connection");
157c5ace 1409 return false;
b418d9c8
CT
1410 }
1411
b3a8ae1b
AR
1412 const char *errAction = NULL;
1413 int errCode = 0;
33cc0629 1414 if (auto ssl = SSL_new(sslContext)) {
157c5ace 1415 const int fd = conn->fd;
b3a8ae1b 1416 // without BIO, we would call SSL_set_fd(ssl, fd) instead
d620ae0e 1417 if (BIO *bio = Ssl::Bio::Create(fd, type)) {
b3a8ae1b
AR
1418 Ssl::Bio::Link(ssl, bio); // cannot fail
1419
35b3559c 1420 fd_table[fd].ssl.resetWithoutLocking(ssl);
b3a8ae1b
AR
1421 fd_table[fd].read_method = &ssl_read_method;
1422 fd_table[fd].write_method = &ssl_write_method;
1423 fd_note(fd, squidCtx);
157c5ace 1424 return true;
b3a8ae1b
AR
1425 }
1426 errCode = ERR_get_error();
1427 errAction = "failed to initialize I/O";
1428 SSL_free(ssl);
1429 } else {
1430 errCode = ERR_get_error();
1431 errAction = "failed to allocate handle";
1432 }
1433
1434 debugs(83, DBG_IMPORTANT, "ERROR: " << squidCtx << ' ' << errAction <<
1435 ": " << ERR_error_string(errCode, NULL));
157c5ace 1436 return false;
b3a8ae1b
AR
1437}
1438
157c5ace
AJ
1439bool
1440Ssl::CreateClient(Security::ContextPtr sslContext, const Comm::ConnectionPointer &c, const char *squidCtx)
d620ae0e 1441{
157c5ace 1442 return SslCreate(sslContext, c, Ssl::Bio::BIO_TO_SERVER, squidCtx);
d620ae0e
CT
1443}
1444
157c5ace
AJ
1445bool
1446Ssl::CreateServer(Security::ContextPtr sslContext, const Comm::ConnectionPointer &c, const char *squidCtx)
d620ae0e 1447{
157c5ace 1448 return SslCreate(sslContext, c, Ssl::Bio::BIO_TO_CLIENT, squidCtx);
d620ae0e
CT
1449}
1450
13cd7dee 1451Ssl::CertError::CertError(Security::ErrorCode anErr, X509 *aCert, int aDepth): code(anErr), depth(aDepth)
170cb017 1452{
62a7607e
CT
1453 cert.resetAndLock(aCert);
1454}
1455
10a69fc0
CT
1456static int
1457store_session_cb(SSL *ssl, SSL_SESSION *session)
1458{
824d4656 1459 if (!Ssl::SessionCache)
10a69fc0
CT
1460 return 0;
1461
1462 debugs(83, 5, "Request to store SSL Session ");
1463
1464 SSL_SESSION_set_timeout(session, Config.SSL.session_ttl);
1465
1466 unsigned char *id = session->session_id;
1467 unsigned int idlen = session->session_id_length;
1468 unsigned char key[MEMMAP_SLOT_KEY_SIZE];
1469 // Session ids are of size 32bytes. They should always fit to a
86c63190 1470 // MemMap::Slot::key
10a69fc0
CT
1471 assert(idlen <= MEMMAP_SLOT_KEY_SIZE);
1472 memset(key, 0, sizeof(key));
1473 memcpy(key, id, idlen);
1474 int pos;
824d4656 1475 Ipc::MemMap::Slot *slotW = Ssl::SessionCache->openForWriting((const cache_key*)key, pos);
10a69fc0
CT
1476 if (slotW) {
1477 int lenRequired = i2d_SSL_SESSION(session, NULL);
1478 if (lenRequired < MEMMAP_SLOT_DATA_SIZE) {
1479 unsigned char *p = (unsigned char *)slotW->p;
1480 lenRequired = i2d_SSL_SESSION(session, &p);
1481 slotW->set(key, NULL, lenRequired, squid_curtime + Config.SSL.session_ttl);
1482 }
824d4656 1483 Ssl::SessionCache->closeForWriting(pos);
10a69fc0
CT
1484 debugs(83, 5, "wrote an ssl session entry of size " << lenRequired << " at pos " << pos);
1485 }
1486 return 0;
1487}
1488
1489static void
1490remove_session_cb(SSL_CTX *, SSL_SESSION *sessionID)
1491{
824d4656 1492 if (!Ssl::SessionCache)
10a69fc0
CT
1493 return ;
1494
1495 debugs(83, 5, "Request to remove corrupted or not valid SSL Session ");
1496 int pos;
824d4656 1497 Ipc::MemMap::Slot const *slot = Ssl::SessionCache->openForReading((const cache_key*)sessionID, pos);
10a69fc0
CT
1498 if (slot == NULL)
1499 return;
824d4656 1500 Ssl::SessionCache->closeForReading(pos);
10a69fc0
CT
1501 // TODO:
1502 // What if we are not able to remove the session?
1503 // Maybe schedule a job to remove it later?
1504 // For now we just have an invalid entry in cache until will be expired
1505 // The openSSL will reject it when we try to use it
824d4656 1506 Ssl::SessionCache->free(pos);
10a69fc0
CT
1507}
1508
1509static SSL_SESSION *
1510get_session_cb(SSL *, unsigned char *sessionID, int len, int *copy)
1511{
824d4656 1512 if (!Ssl::SessionCache)
10a69fc0
CT
1513 return NULL;
1514
1515 SSL_SESSION *session = NULL;
1516 const unsigned int *p;
1517 p = (unsigned int *)sessionID;
1518 debugs(83, 5, "Request to search for SSL Session of len:" <<
1519 len << p[0] << ":" << p[1]);
1520
1521 int pos;
824d4656 1522 Ipc::MemMap::Slot const *slot = Ssl::SessionCache->openForReading((const cache_key*)sessionID, pos);
10a69fc0
CT
1523 if (slot != NULL) {
1524 if (slot->expire > squid_curtime) {
1525 const unsigned char *ptr = slot->p;
1526 session = d2i_SSL_SESSION(NULL, &ptr, slot->pSize);
1527 debugs(83, 5, "Session retrieved from cache at pos " << pos);
1528 } else
1529 debugs(83, 5, "Session in cache expired");
824d4656 1530 Ssl::SessionCache->closeForReading(pos);
10a69fc0
CT
1531 }
1532
1533 if (!session)
1534 debugs(83, 5, "Failed to retrieved from cache\n");
1535
1536 // With the parameter copy the callback can require the SSL engine
1537 // to increment the reference count of the SSL_SESSION object, Normally
1538 // the reference count is not incremented and therefore the session must
1539 // not be explicitly freed with SSL_SESSION_free(3).
1540 *copy = 0;
1541 return session;
1542}
1543
824d4656
AJ
1544void
1545Ssl::SetSessionCallbacks(Security::ContextPtr ctx)
10a69fc0 1546{
824d4656 1547 if (Ssl::SessionCache) {
10a69fc0
CT
1548 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER|SSL_SESS_CACHE_NO_INTERNAL);
1549 SSL_CTX_sess_set_new_cb(ctx, store_session_cb);
1550 SSL_CTX_sess_set_remove_cb(ctx, remove_session_cb);
1551 SSL_CTX_sess_set_get_cb(ctx, get_session_cb);
1552 }
1553}
1554
cb4f4424 1555#endif /* USE_OPENSSL */
f53969cc 1556