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