]> git.ipfire.org Git - thirdparty/squid.git/blame - src/ssl/support.cc
SourceFormat Enforcement
[thirdparty/squid.git] / src / ssl / support.cc
CommitLineData
f484cdf5 1/*
bde978a6 2 * Copyright (C) 1996-2015 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
10a69fc0
CT
36static void setSessionCallbacks(SSL_CTX *ctx);
37Ipc::MemMap *SslSessionCache = NULL;
38const char *SslSessionCacheName = "ssl_session_cache";
39
3c26b00a
CT
40const EVP_MD *Ssl::DefaultSignHash = NULL;
41
caf3666d
AR
42const char *Ssl::BumpModeStr[] = {
43 "none",
44 "client-first",
45 "server-first",
5d65362c
CT
46 "peek",
47 "stare",
48 "bump",
7f4e9b73 49 "splice",
5d65362c 50 "terminate",
1110989a 51 /*"err",*/
caf3666d
AR
52 NULL
53};
54
63be0a78 55/**
56 \defgroup ServerProtocolSSLInternal Server-Side SSL Internals
57 \ingroup ServerProtocolSSLAPI
58 */
59
60/// \ingroup ServerProtocolSSLInternal
307b83b7 61static int
62ssl_ask_password_cb(char *buf, int size, int rwflag, void *userdata)
63{
64 FILE *in;
65 int len = 0;
66 char cmdline[1024];
67
68 snprintf(cmdline, sizeof(cmdline), "\"%s\" \"%s\"", Config.Program.ssl_password, (const char *)userdata);
69 in = popen(cmdline, "r");
70
71 if (fgets(buf, size, in))
72
73 len = strlen(buf);
74
75 while (len > 0 && (buf[len - 1] == '\n' || buf[len - 1] == '\r'))
5e263176 76 --len;
307b83b7 77
78 buf[len] = '\0';
79
80 pclose(in);
81
82 return len;
83}
84
63be0a78 85/// \ingroup ServerProtocolSSLInternal
307b83b7 86static void
87ssl_ask_password(SSL_CTX * context, const char * prompt)
88{
89 if (Config.Program.ssl_password) {
90 SSL_CTX_set_default_passwd_cb(context, ssl_ask_password_cb);
91 SSL_CTX_set_default_passwd_cb_userdata(context, (void *)prompt);
92 }
93}
94
63be0a78 95/// \ingroup ServerProtocolSSLInternal
f484cdf5 96static RSA *
e6ccf245 97ssl_temp_rsa_cb(SSL * ssl, int anInt, int keylen)
f484cdf5 98{
e01f02ed 99 static RSA *rsa_512 = NULL;
100 static RSA *rsa_1024 = NULL;
101 RSA *rsa = NULL;
102 int newkey = 0;
f484cdf5 103
e01f02ed 104 switch (keylen) {
105
106 case 512:
107
108 if (!rsa_512) {
109 rsa_512 = RSA_generate_key(512, RSA_F4, NULL, NULL);
110 newkey = 1;
111 }
112
113 rsa = rsa_512;
114 break;
115
116 case 1024:
117
118 if (!rsa_1024) {
119 rsa_1024 = RSA_generate_key(1024, RSA_F4, NULL, NULL);
120 newkey = 1;
121 }
122
123 rsa = rsa_1024;
124 break;
125
126 default:
e0236918 127 debugs(83, DBG_IMPORTANT, "ssl_temp_rsa_cb: Unexpected key length " << keylen);
e01f02ed 128 return NULL;
129 }
130
131 if (rsa == NULL) {
e0236918 132 debugs(83, DBG_IMPORTANT, "ssl_temp_rsa_cb: Failed to generate key " << keylen);
e01f02ed 133 return NULL;
134 }
135
136 if (newkey) {
137 if (do_debug(83, 5))
138 PEM_write_RSAPrivateKey(debug_log, rsa, NULL, NULL, 0, NULL, NULL);
139
e0236918 140 debugs(83, DBG_IMPORTANT, "Generated ephemeral RSA key of length " << keylen);
e01f02ed 141 }
62e76326 142
f484cdf5 143 return rsa;
144}
145
4d16918e
CT
146int Ssl::asn1timeToString(ASN1_TIME *tm, char *buf, int len)
147{
148 BIO *bio;
149 int write = 0;
150 bio = BIO_new(BIO_s_mem());
151 if (bio) {
e34763f4
A
152 if (ASN1_TIME_print(bio, tm))
153 write = BIO_read(bio, buf, len-1);
154 BIO_free(bio);
4d16918e
CT
155 }
156 buf[write]='\0';
157 return write;
158}
159
160int Ssl::matchX509CommonNames(X509 *peer_cert, void *check_data, int (*check_func)(void *check_data, ASN1_STRING *cn_data))
161{
162 assert(peer_cert);
163
164 X509_NAME *name = X509_get_subject_name(peer_cert);
165
166 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 167
4d16918e
CT
168 ASN1_STRING *cn_data = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, i));
169
170 if ( (*check_func)(check_data, cn_data) == 0)
171 return 1;
172 }
173
174 STACK_OF(GENERAL_NAME) * altnames;
175 altnames = (STACK_OF(GENERAL_NAME)*)X509_get_ext_d2i(peer_cert, NID_subject_alt_name, NULL, NULL);
176
177 if (altnames) {
178 int numalts = sk_GENERAL_NAME_num(altnames);
d7ae3534 179 for (int i = 0; i < numalts; ++i) {
4d16918e
CT
180 const GENERAL_NAME *check = sk_GENERAL_NAME_value(altnames, i);
181 if (check->type != GEN_DNS) {
182 continue;
183 }
184 ASN1_STRING *cn_data = check->d.dNSName;
e34763f4 185
40dd2b59
CT
186 if ( (*check_func)(check_data, cn_data) == 0) {
187 sk_GENERAL_NAME_pop_free(altnames, GENERAL_NAME_free);
4d16918e 188 return 1;
40dd2b59 189 }
4d16918e
CT
190 }
191 sk_GENERAL_NAME_pop_free(altnames, GENERAL_NAME_free);
192 }
193 return 0;
194}
195
196static int check_domain( void *check_data, ASN1_STRING *cn_data)
197{
198 char cn[1024];
199 const char *server = (const char *)check_data;
200
e34763f4 201 if (cn_data->length > (int)sizeof(cn) - 1) {
4d16918e
CT
202 return 1; //if does not fit our buffer just ignore
203 }
204 memcpy(cn, cn_data->data, cn_data->length);
205 cn[cn_data->length] = '\0';
206 debugs(83, 4, "Verifying server domain " << server << " to certificate name/subjectAltName " << cn);
207 return matchDomainName(server, cn[0] == '*' ? cn + 1 : cn);
208}
209
8eb0a7ee
CT
210bool Ssl::checkX509ServerValidity(X509 *cert, const char *server)
211{
212 return matchX509CommonNames(cert, (void *)server, check_domain);
213}
214
63be0a78 215/// \ingroup ServerProtocolSSLInternal
f484cdf5 216static int
217ssl_verify_cb(int ok, X509_STORE_CTX * ctx)
218{
7698a79c
CT
219 // preserve original ctx->error before SSL_ calls can overwrite it
220 Ssl::ssl_error_t error_no = ok ? SSL_ERROR_NONE : ctx->error;
221
222 char buffer[256] = "";
a7ad6e4e 223 SSL *ssl = (SSL *)X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
224 SSL_CTX *sslctx = SSL_get_SSL_CTX(ssl);
225 const char *server = (const char *)SSL_get_ex_data(ssl, ssl_ex_index_server);
226 void *dont_verify_domain = SSL_CTX_get_ex_data(sslctx, ssl_ctx_ex_index_dont_verify_domain);
815eaa44 227 ACLChecklist *check = (ACLChecklist*)SSL_get_ex_data(ssl, ssl_ex_index_cert_error_check);
e7bcc25f 228 X509 *peeked_cert = (X509 *)SSL_get_ex_data(ssl, ssl_ex_index_ssl_peeked_cert);
a7ad6e4e 229 X509 *peer_cert = ctx->cert;
f484cdf5 230
a7ad6e4e 231 X509_NAME_oneline(X509_get_subject_name(peer_cert), buffer,
62e76326 232 sizeof(buffer));
a7ad6e4e 233
0ad3ff51
CT
234 // detect infinite loops
235 uint32_t *validationCounter = static_cast<uint32_t *>(SSL_get_ex_data(ssl, ssl_ex_index_ssl_validation_counter));
236 if (!validationCounter) {
237 validationCounter = new uint32_t(1);
238 SSL_set_ex_data(ssl, ssl_ex_index_ssl_validation_counter, validationCounter);
239 } else {
240 // overflows allowed if SQUID_CERT_VALIDATION_ITERATION_MAX >= UINT32_MAX
241 (*validationCounter)++;
242 }
243
244 if ((*validationCounter) >= SQUID_CERT_VALIDATION_ITERATION_MAX) {
245 ok = 0; // or the validation loop will never stop
246 error_no = SQUID_X509_V_ERR_INFINITE_VALIDATION;
247 debugs(83, 2, "SQUID_X509_V_ERR_INFINITE_VALIDATION: " <<
248 *validationCounter << " iterations while checking " << buffer);
249 }
250
a7ad6e4e 251 if (ok) {
bf8fe701 252 debugs(83, 5, "SSL Certificate signature OK: " << buffer);
62e76326 253
4747ea4c 254 // Check for domain mismatch only if the current certificate is the peer certificate.
2e52fa2b 255 if (!dont_verify_domain && server && peer_cert == X509_STORE_CTX_get_current_cert(ctx)) {
8eb0a7ee 256 if (!Ssl::checkX509ServerValidity(peer_cert, server)) {
815eaa44 257 debugs(83, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " << buffer << " does not match domainname " << server);
62e76326 258 ok = 0;
4d16918e 259 error_no = SQUID_X509_V_ERR_DOMAIN_MISMATCH;
62e76326 260 }
261 }
7698a79c 262 }
0db46e4f 263
e7bcc25f 264 if (ok && peeked_cert) {
7a957a93 265 // Check whether the already peeked certificate matches the new one.
e7bcc25f
CT
266 if (X509_cmp(peer_cert, peeked_cert) != 0) {
267 debugs(83, 2, "SQUID_X509_V_ERR_CERT_CHANGE: Certificate " << buffer << " does not match peeked certificate");
268 ok = 0;
269 error_no = SQUID_X509_V_ERR_CERT_CHANGE;
270 }
271 }
272
7698a79c 273 if (!ok) {
62a7607e
CT
274 X509 *broken_cert = X509_STORE_CTX_get_current_cert(ctx);
275 if (!broken_cert)
276 broken_cert = peer_cert;
277
278 Ssl::CertErrors *errs = static_cast<Ssl::CertErrors *>(SSL_get_ex_data(ssl, ssl_ex_index_ssl_errors));
7a957a93 279 if (!errs) {
62a7607e 280 errs = new Ssl::CertErrors(Ssl::CertError(error_no, broken_cert));
7a957a93 281 if (!SSL_set_ex_data(ssl, ssl_ex_index_ssl_errors, (void *)errs)) {
fb2178bb 282 debugs(83, 2, "Failed to set ssl error_no in ssl_verify_cb: Certificate " << buffer);
7a957a93
AR
283 delete errs;
284 errs = NULL;
fb2178bb 285 }
87f237a9 286 } else // remember another error number
62a7607e 287 errs->push_back_unique(Ssl::CertError(error_no, broken_cert));
fb2178bb 288
7698a79c 289 if (const char *err_descr = Ssl::GetErrorDescr(error_no))
cf09bec7
CT
290 debugs(83, 5, err_descr << ": " << buffer);
291 else
7698a79c
CT
292 debugs(83, DBG_IMPORTANT, "SSL unknown certificate error " << error_no << " in " << buffer);
293
0ad3ff51
CT
294 // Check if the certificate error can be bypassed.
295 // Infinity validation loop errors can not bypassed.
296 if (error_no != SQUID_X509_V_ERR_INFINITE_VALIDATION) {
297 if (check) {
298 ACLFilledChecklist *filledCheck = Filled(check);
299 assert(!filledCheck->sslErrors);
300 filledCheck->sslErrors = new Ssl::CertErrors(Ssl::CertError(error_no, broken_cert));
301 filledCheck->serverCert.resetAndLock(peer_cert);
302 if (check->fastCheck() == ACCESS_ALLOWED) {
303 debugs(83, 3, "bypassing SSL error " << error_no << " in " << buffer);
304 ok = 1;
305 } else {
306 debugs(83, 5, "confirming SSL error " << error_no);
307 }
308 delete filledCheck->sslErrors;
309 filledCheck->sslErrors = NULL;
310 filledCheck->serverCert.reset(NULL);
7698a79c 311 }
0ad3ff51
CT
312 // If the certificate validator is used then we need to allow all errors and
313 // pass them to certficate validator for more processing
314 else if (Ssl::TheConfig.ssl_crt_validator) {
7698a79c 315 ok = 1;
0ad3ff51
CT
316 // Check if we have stored certificates chain. Store if not.
317 if (!SSL_get_ex_data(ssl, ssl_ex_index_ssl_cert_chain)) {
318 STACK_OF(X509) *certStack = X509_STORE_CTX_get1_chain(ctx);
319 if (certStack && !SSL_set_ex_data(ssl, ssl_ex_index_ssl_cert_chain, certStack))
320 sk_X509_pop_free(certStack, X509_free);
321 }
7698a79c 322 }
815eaa44 323 }
a7ad6e4e 324 }
62e76326 325
7698a79c 326 if (!ok && !SSL_get_ex_data(ssl, ssl_ex_index_ssl_error_detail) ) {
f622c461
MF
327
328 // Find the broken certificate. It may be intermediate.
329 X509 *broken_cert = peer_cert; // reasonable default if search fails
330 // Our SQUID_X509_V_ERR_DOMAIN_MISMATCH implies peer_cert is at fault.
331 if (error_no != SQUID_X509_V_ERR_DOMAIN_MISMATCH) {
332 if (X509 *last_used_cert = X509_STORE_CTX_get_current_cert(ctx))
333 broken_cert = last_used_cert;
334 }
335
336 Ssl::ErrorDetail *errDetail =
de878a55 337 new Ssl::ErrorDetail(error_no, peer_cert, broken_cert);
f622c461 338
e34763f4 339 if (!SSL_set_ex_data(ssl, ssl_ex_index_ssl_error_detail, errDetail)) {
4d16918e
CT
340 debugs(83, 2, "Failed to set Ssl::ErrorDetail in ssl_verify_cb: Certificate " << buffer);
341 delete errDetail;
342 }
343 }
344
f484cdf5 345 return ok;
346}
347
63be0a78 348/// \ingroup ServerProtocolSSLInternal
26ac0430 349static struct ssl_option {
79d4ccdf 350 const char *name;
351 long value;
62e76326 352}
353
354ssl_options[] = {
79d4ccdf 355
32d002cb 356#if SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
26ac0430
AJ
357 {
358 "NETSCAPE_REUSE_CIPHER_CHANGE_BUG", SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
359 },
673cd7db 360#endif
32d002cb 361#if SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
26ac0430
AJ
362 {
363 "SSLREF2_REUSE_CERT_TYPE_BUG", SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
364 },
673cd7db 365#endif
32d002cb 366#if SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
26ac0430
AJ
367 {
368 "MICROSOFT_BIG_SSLV3_BUFFER", SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
369 },
673cd7db 370#endif
32d002cb 371#if SSL_OP_SSLEAY_080_CLIENT_DH_BUG
26ac0430
AJ
372 {
373 "SSLEAY_080_CLIENT_DH_BUG", SSL_OP_SSLEAY_080_CLIENT_DH_BUG
374 },
673cd7db 375#endif
32d002cb 376#if SSL_OP_TLS_D5_BUG
26ac0430
AJ
377 {
378 "TLS_D5_BUG", SSL_OP_TLS_D5_BUG
379 },
673cd7db 380#endif
32d002cb 381#if SSL_OP_TLS_BLOCK_PADDING_BUG
26ac0430
AJ
382 {
383 "TLS_BLOCK_PADDING_BUG", SSL_OP_TLS_BLOCK_PADDING_BUG
384 },
673cd7db 385#endif
32d002cb 386#if SSL_OP_TLS_ROLLBACK_BUG
26ac0430
AJ
387 {
388 "TLS_ROLLBACK_BUG", SSL_OP_TLS_ROLLBACK_BUG
389 },
673cd7db 390#endif
32d002cb 391#if SSL_OP_ALL
26ac0430 392 {
866eafc6 393 "ALL", (long)SSL_OP_ALL
26ac0430 394 },
673cd7db 395#endif
32d002cb 396#if SSL_OP_SINGLE_DH_USE
26ac0430
AJ
397 {
398 "SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE
399 },
673cd7db 400#endif
32d002cb 401#if SSL_OP_EPHEMERAL_RSA
26ac0430
AJ
402 {
403 "EPHEMERAL_RSA", SSL_OP_EPHEMERAL_RSA
404 },
673cd7db 405#endif
32d002cb 406#if SSL_OP_PKCS1_CHECK_1
26ac0430
AJ
407 {
408 "PKCS1_CHECK_1", SSL_OP_PKCS1_CHECK_1
409 },
673cd7db 410#endif
32d002cb 411#if SSL_OP_PKCS1_CHECK_2
26ac0430
AJ
412 {
413 "PKCS1_CHECK_2", SSL_OP_PKCS1_CHECK_2
414 },
673cd7db 415#endif
32d002cb 416#if SSL_OP_NETSCAPE_CA_DN_BUG
26ac0430
AJ
417 {
418 "NETSCAPE_CA_DN_BUG", SSL_OP_NETSCAPE_CA_DN_BUG
419 },
673cd7db 420#endif
32d002cb 421#if SSL_OP_NON_EXPORT_FIRST
26ac0430
AJ
422 {
423 "NON_EXPORT_FIRST", SSL_OP_NON_EXPORT_FIRST
424 },
673cd7db 425#endif
32d002cb 426#if SSL_OP_CIPHER_SERVER_PREFERENCE
26ac0430
AJ
427 {
428 "CIPHER_SERVER_PREFERENCE", SSL_OP_CIPHER_SERVER_PREFERENCE
429 },
673cd7db 430#endif
32d002cb 431#if SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
26ac0430
AJ
432 {
433 "NETSCAPE_DEMO_CIPHER_CHANGE_BUG", SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
434 },
673cd7db 435#endif
32d002cb 436#if SSL_OP_NO_SSLv3
26ac0430
AJ
437 {
438 "NO_SSLv3", SSL_OP_NO_SSLv3
439 },
673cd7db 440#endif
32d002cb 441#if SSL_OP_NO_TLSv1
26ac0430
AJ
442 {
443 "NO_TLSv1", SSL_OP_NO_TLSv1
444 },
3d96b0e8
AJ
445#endif
446#if SSL_OP_NO_TLSv1_1
447 {
448 "NO_TLSv1_1", SSL_OP_NO_TLSv1_1
449 },
450#endif
451#if SSL_OP_NO_TLSv1_2
452 {
453 "NO_TLSv1_2", SSL_OP_NO_TLSv1_2
454 },
71606c88
SW
455#endif
456#if SSL_OP_NO_COMPRESSION
457 {
458 "No_Compression", SSL_OP_NO_COMPRESSION
459 },
673cd7db 460#endif
26ac0430
AJ
461 {
462 "", 0
463 },
464 {
465 NULL, 0
466 }
467};
79d4ccdf 468
63be0a78 469/// \ingroup ServerProtocolSSLInternal
86660d64
CT
470long
471Ssl::parse_options(const char *options)
79d4ccdf 472{
943c5f16 473 long op = 0;
79d4ccdf 474 char *tmp;
475 char *option;
476
477 if (!options)
62e76326 478 goto no_options;
79d4ccdf 479
480 tmp = xstrdup(options);
62e76326 481
79d4ccdf 482 option = strtok(tmp, ":,");
62e76326 483
79d4ccdf 484 while (option) {
62e76326 485
486 struct ssl_option *opt = NULL, *opttmp;
487 long value = 0;
488 enum {
489 MODE_ADD, MODE_REMOVE
490 } mode;
491
492 switch (*option) {
493
494 case '!':
495
496 case '-':
497 mode = MODE_REMOVE;
d7ae3534 498 ++option;
62e76326 499 break;
500
501 case '+':
502 mode = MODE_ADD;
d7ae3534 503 ++option;
62e76326 504 break;
505
506 default:
507 mode = MODE_ADD;
508 break;
509 }
510
d7ae3534 511 for (opttmp = ssl_options; opttmp->name; ++opttmp) {
62e76326 512 if (strcmp(opttmp->name, option) == 0) {
513 opt = opttmp;
514 break;
515 }
516 }
517
518 if (opt)
519 value = opt->value;
520 else if (strncmp(option, "0x", 2) == 0) {
521 /* Special case.. hex specification */
522 value = strtol(option + 2, NULL, 16);
523 } else {
524 fatalf("Unknown SSL option '%s'", option);
f53969cc 525 value = 0; /* Keep GCC happy */
62e76326 526 }
527
528 switch (mode) {
529
530 case MODE_ADD:
531 op |= value;
532 break;
533
534 case MODE_REMOVE:
535 op &= ~value;
536 break;
537 }
538
539 option = strtok(NULL, ":,");
79d4ccdf 540 }
541
542 safe_free(tmp);
62e76326 543
544no_options:
47901e84
AJ
545#if SSL_OP_NO_SSLv2
546 // compliance with RFC 6176: Prohibiting Secure Sockets Layer (SSL) Version 2.0
547 op = op | SSL_OP_NO_SSLv2;
548#endif
79d4ccdf 549 return op;
550}
551
63be0a78 552/// \ingroup ServerProtocolSSLInternal
f53969cc 553#define SSL_FLAG_NO_DEFAULT_CA (1<<0)
63be0a78 554/// \ingroup ServerProtocolSSLInternal
f53969cc 555#define SSL_FLAG_DELAYED_AUTH (1<<1)
63be0a78 556/// \ingroup ServerProtocolSSLInternal
f53969cc 557#define SSL_FLAG_DONT_VERIFY_PEER (1<<2)
63be0a78 558/// \ingroup ServerProtocolSSLInternal
f53969cc 559#define SSL_FLAG_DONT_VERIFY_DOMAIN (1<<3)
63be0a78 560/// \ingroup ServerProtocolSSLInternal
f53969cc 561#define SSL_FLAG_NO_SESSION_REUSE (1<<4)
63be0a78 562/// \ingroup ServerProtocolSSLInternal
f53969cc 563#define SSL_FLAG_VERIFY_CRL (1<<5)
63be0a78 564/// \ingroup ServerProtocolSSLInternal
f53969cc 565#define SSL_FLAG_VERIFY_CRL_ALL (1<<6)
a7ad6e4e 566
63be0a78 567/// \ingroup ServerProtocolSSLInternal
86660d64
CT
568long
569Ssl::parse_flags(const char *flags)
a7ad6e4e 570{
571 long fl = 0;
572 char *tmp;
573 char *flag;
574
575 if (!flags)
62e76326 576 return 0;
a7ad6e4e 577
578 tmp = xstrdup(flags);
62e76326 579
a7ad6e4e 580 flag = strtok(tmp, ":,");
62e76326 581
a7ad6e4e 582 while (flag) {
62e76326 583 if (strcmp(flag, "NO_DEFAULT_CA") == 0)
584 fl |= SSL_FLAG_NO_DEFAULT_CA;
585 else if (strcmp(flag, "DELAYED_AUTH") == 0)
586 fl |= SSL_FLAG_DELAYED_AUTH;
587 else if (strcmp(flag, "DONT_VERIFY_PEER") == 0)
588 fl |= SSL_FLAG_DONT_VERIFY_PEER;
589 else if (strcmp(flag, "DONT_VERIFY_DOMAIN") == 0)
590 fl |= SSL_FLAG_DONT_VERIFY_DOMAIN;
b13877cc 591 else if (strcmp(flag, "NO_SESSION_REUSE") == 0)
592 fl |= SSL_FLAG_NO_SESSION_REUSE;
a82a4fe4 593
32d002cb 594#if X509_V_FLAG_CRL_CHECK
a82a4fe4 595
596 else if (strcmp(flag, "VERIFY_CRL") == 0)
597 fl |= SSL_FLAG_VERIFY_CRL;
598 else if (strcmp(flag, "VERIFY_CRL_ALL") == 0)
599 fl |= SSL_FLAG_VERIFY_CRL_ALL;
600
601#endif
602
62e76326 603 else
604 fatalf("Unknown ssl flag '%s'", flag);
605
606 flag = strtok(NULL, ":,");
a7ad6e4e 607 }
62e76326 608
a7ad6e4e 609 safe_free(tmp);
610 return fl;
611}
612
815eaa44 613// "dup" function for SSL_get_ex_new_index("cert_err_check")
614static int
615ssl_dupAclChecklist(CRYPTO_EX_DATA *, CRYPTO_EX_DATA *, void *,
26ac0430
AJ
616 int, long, void *)
617{
815eaa44 618 // We do not support duplication of ACLCheckLists.
619 // If duplication is needed, we can count copies with cbdata.
620 assert(false);
621 return 0;
622}
623
624// "free" function for SSL_get_ex_new_index("cert_err_check")
625static void
626ssl_freeAclChecklist(void *, void *ptr, CRYPTO_EX_DATA *,
26ac0430
AJ
627 int, long, void *)
628{
815eaa44 629 delete static_cast<ACLChecklist *>(ptr); // may be NULL
630}
a7ad6e4e 631
4d16918e
CT
632// "free" function for SSL_get_ex_new_index("ssl_error_detail")
633static void
634ssl_free_ErrorDetail(void *, void *ptr, CRYPTO_EX_DATA *,
635 int, long, void *)
636{
637 Ssl::ErrorDetail *errDetail = static_cast <Ssl::ErrorDetail *>(ptr);
638 delete errDetail;
639}
640
fb2178bb 641static void
7a957a93 642ssl_free_SslErrors(void *, void *ptr, CRYPTO_EX_DATA *,
87f237a9 643 int, long, void *)
fb2178bb 644{
62a7607e 645 Ssl::CertErrors *errs = static_cast <Ssl::CertErrors*>(ptr);
7a957a93 646 delete errs;
fb2178bb
CT
647}
648
0ad3ff51
CT
649// "free" function for SSL_get_ex_new_index("ssl_ex_index_ssl_validation_counter")
650static void
651ssl_free_int(void *, void *ptr, CRYPTO_EX_DATA *,
3cc296c4 652 int, long, void *)
0ad3ff51
CT
653{
654 uint32_t *counter = static_cast <uint32_t *>(ptr);
655 delete counter;
656}
657
4747ea4c
CT
658/// \ingroup ServerProtocolSSLInternal
659/// Callback handler function to release STACK_OF(X509) "ex" data stored
660/// in an SSL object.
661static void
662ssl_free_CertChain(void *, void *ptr, CRYPTO_EX_DATA *,
663 int, long, void *)
664{
665 STACK_OF(X509) *certsChain = static_cast <STACK_OF(X509) *>(ptr);
666 sk_X509_pop_free(certsChain,X509_free);
667}
668
e7bcc25f
CT
669// "free" function for X509 certificates
670static void
671ssl_free_X509(void *, void *ptr, CRYPTO_EX_DATA *,
87f237a9 672 int, long, void *)
e7bcc25f
CT
673{
674 X509 *cert = static_cast <X509 *>(ptr);
675 X509_free(cert);
676}
677
63be0a78 678/// \ingroup ServerProtocolSSLInternal
a7ad6e4e 679static void
680ssl_initialize(void)
f484cdf5 681{
56a35ad1
AR
682 static bool initialized = false;
683 if (initialized)
684 return;
685 initialized = true;
62e76326 686
56a35ad1
AR
687 SSL_load_error_strings();
688 SSLeay_add_ssl_algorithms();
62e76326 689
56a35ad1
AR
690#if HAVE_OPENSSL_ENGINE_H
691 if (Config.SSL.ssl_engine) {
692 ENGINE *e;
693 if (!(e = ENGINE_by_id(Config.SSL.ssl_engine)))
694 fatalf("Unable to find SSL engine '%s'\n", Config.SSL.ssl_engine);
695
696 if (!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
697 int ssl_error = ERR_get_error();
698 fatalf("Failed to initialise SSL engine: %s\n", ERR_error_string(ssl_error, NULL));
62e76326 699 }
56a35ad1 700 }
a7ad6e4e 701#else
56a35ad1
AR
702 if (Config.SSL.ssl_engine)
703 fatalf("Your OpenSSL has no SSL engine support\n");
a7ad6e4e 704#endif
62e76326 705
3c26b00a
CT
706 const char *defName = Config.SSL.certSignHash ? Config.SSL.certSignHash : SQUID_SSL_SIGN_HASH_IF_NONE;
707 Ssl::DefaultSignHash = EVP_get_digestbyname(defName);
708 if (!Ssl::DefaultSignHash)
709 fatalf("Sign hash '%s' is not supported\n", defName);
710
a7ad6e4e 711 ssl_ex_index_server = SSL_get_ex_new_index(0, (void *) "server", NULL, NULL, NULL);
712 ssl_ctx_ex_index_dont_verify_domain = SSL_CTX_get_ex_new_index(0, (void *) "dont_verify_domain", NULL, NULL, NULL);
815eaa44 713 ssl_ex_index_cert_error_check = SSL_get_ex_new_index(0, (void *) "cert_error_check", NULL, &ssl_dupAclChecklist, &ssl_freeAclChecklist);
4d16918e 714 ssl_ex_index_ssl_error_detail = SSL_get_ex_new_index(0, (void *) "ssl_error_detail", NULL, NULL, &ssl_free_ErrorDetail);
e7bcc25f 715 ssl_ex_index_ssl_peeked_cert = SSL_get_ex_new_index(0, (void *) "ssl_peeked_cert", NULL, NULL, &ssl_free_X509);
7a957a93 716 ssl_ex_index_ssl_errors = SSL_get_ex_new_index(0, (void *) "ssl_errors", NULL, NULL, &ssl_free_SslErrors);
4747ea4c 717 ssl_ex_index_ssl_cert_chain = SSL_get_ex_new_index(0, (void *) "ssl_cert_chain", NULL, NULL, &ssl_free_CertChain);
0ad3ff51 718 ssl_ex_index_ssl_validation_counter = SSL_get_ex_new_index(0, (void *) "ssl_validation_counter", NULL, NULL, &ssl_free_int);
a7ad6e4e 719}
720
63be0a78 721/// \ingroup ServerProtocolSSLInternal
a82a4fe4 722static int
723ssl_load_crl(SSL_CTX *sslContext, const char *CRLfile)
724{
725 X509_STORE *st = SSL_CTX_get_cert_store(sslContext);
726 X509_CRL *crl;
727 BIO *in = BIO_new_file(CRLfile, "r");
728 int count = 0;
729
730 if (!in) {
bf8fe701 731 debugs(83, 2, "WARNING: Failed to open CRL file '" << CRLfile << "'");
a82a4fe4 732 return 0;
733 }
734
735 while ((crl = PEM_read_bio_X509_CRL(in,NULL,NULL,NULL))) {
736 if (!X509_STORE_add_crl(st, crl))
bf8fe701 737 debugs(83, 2, "WARNING: Failed to add CRL from file '" << CRLfile << "'");
a82a4fe4 738 else
d7ae3534 739 ++count;
a82a4fe4 740
741 X509_CRL_free(crl);
742 }
743
744 BIO_free(in);
745 return count;
746}
747
86660d64
CT
748STACK_OF(X509_CRL) *
749Ssl::loadCrl(const char *CRLFile, long &flags)
a7ad6e4e 750{
86660d64
CT
751 X509_CRL *crl;
752 BIO *in = BIO_new_file(CRLFile, "r");
753 if (!in) {
754 debugs(83, 2, "WARNING: Failed to open CRL file '" << CRLFile << "'");
f4e4d4d6
CT
755 return NULL;
756 }
757
86660d64
CT
758 STACK_OF(X509_CRL) *CRLs = sk_X509_CRL_new_null();
759 if (!CRLs) {
760 debugs(83, 2, "WARNING: Failed to allocate X509_CRL stack to load file '" << CRLFile << "'");
50b4c080 761 return NULL;
86660d64 762 }
62e76326 763
86660d64
CT
764 int count = 0;
765 while ((crl = PEM_read_bio_X509_CRL(in,NULL,NULL,NULL))) {
766 if (!sk_X509_CRL_push(CRLs, crl))
767 debugs(83, 2, "WARNING: Failed to add CRL from file '" << CRLFile << "'");
768 else
769 ++count;
770 }
771 BIO_free(in);
62e76326 772
86660d64
CT
773 if (count)
774 flags |= SSL_FLAG_VERIFY_CRL;
3d96b0e8 775
86660d64
CT
776 return CRLs;
777}
3d96b0e8 778
86660d64
CT
779DH *
780Ssl::readDHParams(const char *dhfile)
781{
782 FILE *in = fopen(dhfile, "r");
783 DH *dh = NULL;
784 int codes;
62e76326 785
86660d64
CT
786 if (in) {
787 dh = PEM_read_DHparams(in, NULL, NULL, NULL);
788 fclose(in);
f484cdf5 789 }
790
86660d64
CT
791 if (!dh)
792 debugs(83, DBG_IMPORTANT, "WARNING: Failed to read DH parameters '" << dhfile << "'");
793 else if (dh && DH_check(dh, &codes) == 0) {
794 if (codes) {
795 debugs(83, DBG_IMPORTANT, "WARNING: Failed to verify DH parameters '" << dhfile << "' (" << std::hex << codes << ")");
796 DH_free(dh);
797 dh = NULL;
798 }
f484cdf5 799 }
86660d64
CT
800 return dh;
801}
62e76326 802
86660d64
CT
803static bool
804configureSslContext(SSL_CTX *sslContext, AnyP::PortCfg &port)
805{
806 int ssl_error;
807 SSL_CTX_set_options(sslContext, port.sslOptions);
f484cdf5 808
86660d64
CT
809 if (port.sslContextSessionId)
810 SSL_CTX_set_session_id_context(sslContext, (const unsigned char *)port.sslContextSessionId, strlen(port.sslContextSessionId));
6b2936d5 811
86660d64 812 if (port.sslContextFlags & SSL_FLAG_NO_SESSION_REUSE) {
b13877cc 813 SSL_CTX_set_session_cache_mode(sslContext, SSL_SESS_CACHE_OFF);
814 }
815
a9d79803 816 if (Config.SSL.unclean_shutdown) {
bf8fe701 817 debugs(83, 5, "Enabling quiet SSL shutdowns (RFC violation).");
a9d79803 818
819 SSL_CTX_set_quiet_shutdown(sslContext, 1);
820 }
821
86660d64
CT
822 if (port.cipher) {
823 debugs(83, 5, "Using chiper suite " << port.cipher << ".");
62e76326 824
86660d64 825 if (!SSL_CTX_set_cipher_list(sslContext, port.cipher)) {
62e76326 826 ssl_error = ERR_get_error();
86660d64
CT
827 debugs(83, DBG_CRITICAL, "ERROR: Failed to set SSL cipher suite '" << port.cipher << "': " << ERR_error_string(ssl_error, NULL));
828 return false;
62e76326 829 }
79d4ccdf 830 }
62e76326 831
bf8fe701 832 debugs(83, 9, "Setting RSA key generation callback.");
a7ad6e4e 833 SSL_CTX_set_tmp_rsa_callback(sslContext, ssl_temp_rsa_cb);
834
bf8fe701 835 debugs(83, 9, "Setting CA certificate locations.");
62e76326 836
86660d64
CT
837 const char *cafile = port.cafile ? port.cafile : port.clientca;
838 if ((cafile || port.capath) && !SSL_CTX_load_verify_locations(sslContext, cafile, port.capath)) {
62e76326 839 ssl_error = ERR_get_error();
48e7baac 840 debugs(83, DBG_IMPORTANT, "WARNING: Ignoring error setting CA certificate locations: " << ERR_error_string(ssl_error, NULL));
a7ad6e4e 841 }
62e76326 842
86660d64 843 if (!(port.sslContextFlags & SSL_FLAG_NO_DEFAULT_CA) &&
62e76326 844 !SSL_CTX_set_default_verify_paths(sslContext)) {
845 ssl_error = ERR_get_error();
48e7baac 846 debugs(83, DBG_IMPORTANT, "WARNING: Ignoring error setting default CA certificate location: " << ERR_error_string(ssl_error, NULL));
a7ad6e4e 847 }
62e76326 848
86660d64 849 if (port.clientCA.get()) {
8c1ff4ef 850 ERR_clear_error();
86660d64 851 SSL_CTX_set_client_CA_list(sslContext, port.clientCA.get());
62e76326 852
86660d64 853 if (port.sslContextFlags & SSL_FLAG_DELAYED_AUTH) {
bf8fe701 854 debugs(83, 9, "Not requesting client certificates until acl processing requires one");
62e76326 855 SSL_CTX_set_verify(sslContext, SSL_VERIFY_NONE, NULL);
856 } else {
bf8fe701 857 debugs(83, 9, "Requiring client certificates.");
62e76326 858 SSL_CTX_set_verify(sslContext, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, ssl_verify_cb);
859 }
a82a4fe4 860
86660d64
CT
861 if (port.clientVerifyCrls.get()) {
862 X509_STORE *st = SSL_CTX_get_cert_store(sslContext);
863 for (int i = 0; i < sk_X509_CRL_num(port.clientVerifyCrls.get()); ++i) {
864 X509_CRL *crl = sk_X509_CRL_value(port.clientVerifyCrls.get(), i);
865 if (!X509_STORE_add_crl(st, crl))
866 debugs(83, 2, "WARNING: Failed to add CRL");
867 }
a82a4fe4 868 }
869
32d002cb 870#if X509_V_FLAG_CRL_CHECK
86660d64 871 if (port.sslContextFlags & SSL_FLAG_VERIFY_CRL_ALL)
a82a4fe4 872 X509_STORE_set_flags(SSL_CTX_get_cert_store(sslContext), X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
86660d64 873 else if (port.sslContextFlags & SSL_FLAG_VERIFY_CRL)
a82a4fe4 874 X509_STORE_set_flags(SSL_CTX_get_cert_store(sslContext), X509_V_FLAG_CRL_CHECK);
a82a4fe4 875#endif
876
a7ad6e4e 877 } else {
bf8fe701 878 debugs(83, 9, "Not requiring any client certificates");
62e76326 879 SSL_CTX_set_verify(sslContext, SSL_VERIFY_NONE, NULL);
a7ad6e4e 880 }
f484cdf5 881
86660d64
CT
882 if (port.dhParams.get()) {
883 SSL_CTX_set_tmp_dh(sslContext, port.dhParams.get());
884 }
35105e4b 885
86660d64
CT
886 if (port.sslContextFlags & SSL_FLAG_DONT_VERIFY_DOMAIN)
887 SSL_CTX_set_ex_data(sslContext, ssl_ctx_ex_index_dont_verify_domain, (void *) -1);
888
10a69fc0
CT
889 setSessionCallbacks(sslContext);
890
86660d64
CT
891 return true;
892}
893
894SSL_CTX *
895sslCreateServerContext(AnyP::PortCfg &port)
896{
897 int ssl_error;
898 SSL_CTX *sslContext;
899 const char *keyfile, *certfile;
900 certfile = port.cert;
901 keyfile = port.key;
902
903 ssl_initialize();
904
905 if (!keyfile)
906 keyfile = certfile;
907
908 if (!certfile)
909 certfile = keyfile;
910
911 sslContext = SSL_CTX_new(port.contextMethod);
912
913 if (sslContext == NULL) {
914 ssl_error = ERR_get_error();
915 debugs(83, DBG_CRITICAL, "ERROR: Failed to allocate SSL context: " << ERR_error_string(ssl_error, NULL));
916 return NULL;
917 }
918
919 if (!SSL_CTX_use_certificate(sslContext, port.signingCert.get())) {
920 ssl_error = ERR_get_error();
921 debugs(83, DBG_CRITICAL, "ERROR: Failed to acquire SSL certificate '" << certfile << "': " << ERR_error_string(ssl_error, NULL));
922 SSL_CTX_free(sslContext);
923 return NULL;
924 }
925
926 if (!SSL_CTX_use_PrivateKey(sslContext, port.signPkey.get())) {
927 ssl_error = ERR_get_error();
928 debugs(83, DBG_CRITICAL, "ERROR: Failed to acquire SSL private key '" << keyfile << "': " << ERR_error_string(ssl_error, NULL));
929 SSL_CTX_free(sslContext);
930 return NULL;
931 }
932
933 Ssl::addChainToSslContext(sslContext, port.certsToChain.get());
934
935 /* Alternate code;
936 debugs(83, DBG_IMPORTANT, "Using certificate in " << certfile);
937
938 if (!SSL_CTX_use_certificate_chain_file(sslContext, certfile)) {
939 ssl_error = ERR_get_error();
940 debugs(83, DBG_CRITICAL, "ERROR: Failed to acquire SSL certificate '" << certfile << "': " << ERR_error_string(ssl_error, NULL));
941 SSL_CTX_free(sslContext);
942 return NULL;
35105e4b 943 }
944
86660d64
CT
945 debugs(83, DBG_IMPORTANT, "Using private key in " << keyfile);
946 ssl_ask_password(sslContext, keyfile);
947
948 if (!SSL_CTX_use_PrivateKey_file(sslContext, keyfile, SSL_FILETYPE_PEM)) {
949 ssl_error = ERR_get_error();
950 debugs(83, DBG_CRITICAL, "ERROR: Failed to acquire SSL private key '" << keyfile << "': " << ERR_error_string(ssl_error, NULL));
951 SSL_CTX_free(sslContext);
952 return NULL;
35105e4b 953 }
954
86660d64 955 debugs(83, 5, "Comparing private and public SSL keys.");
35105e4b 956
86660d64
CT
957 if (!SSL_CTX_check_private_key(sslContext)) {
958 ssl_error = ERR_get_error();
959 debugs(83, DBG_CRITICAL, "ERROR: SSL private key '" << certfile << "' does not match public key '" <<
960 keyfile << "': " << ERR_error_string(ssl_error, NULL));
961 SSL_CTX_free(sslContext);
962 return NULL;
963 }
964 */
965
966 if (!configureSslContext(sslContext, port)) {
967 debugs(83, DBG_CRITICAL, "ERROR: Configuring static SSL context");
968 SSL_CTX_free(sslContext);
969 return NULL;
970 }
62e76326 971
a7ad6e4e 972 return sslContext;
a7ad6e4e 973}
974
d620ae0e 975int Ssl::OpenSSLtoSquidSSLVersion(int sslVersion)
a7ad6e4e 976{
e1f72a8b 977 if (sslVersion == SSL2_VERSION)
d620ae0e 978 return 2;
e1f72a8b 979 else if (sslVersion == SSL3_VERSION)
d620ae0e 980 return 3;
e1f72a8b 981 else if (sslVersion == TLS1_VERSION)
d620ae0e
CT
982 return 4;
983#if OPENSSL_VERSION_NUMBER >= 0x10001000L
e1f72a8b 984 else if (sslVersion == TLS1_1_VERSION)
d620ae0e 985 return 5;
e1f72a8b 986 else if (sslVersion == TLS1_2_VERSION)
d620ae0e
CT
987 return 6;
988#endif
989 else
990 return 1;
991}
992
f1c9c850 993#if OPENSSL_VERSION_NUMBER < 0x00909000L
d620ae0e 994SSL_METHOD *
f1c9c850 995#else
d620ae0e 996const SSL_METHOD *
f1c9c850 997#endif
d620ae0e
CT
998Ssl::method(int version)
999{
1000 switch (version) {
a7ad6e4e 1001
d620ae0e 1002 case 2:
d620ae0e
CT
1003 debugs(83, DBG_IMPORTANT, "SSLv2 is not available in this Proxy.");
1004 return NULL;
d620ae0e 1005 break;
a7ad6e4e 1006
d620ae0e
CT
1007 case 3:
1008 debugs(83, 5, "Using SSLv3.");
1009 return SSLv3_client_method();
1010 break;
62e76326 1011
d620ae0e
CT
1012 case 4:
1013 debugs(83, 5, "Using TLSv1.");
1014 return TLSv1_client_method();
1015 break;
1016
1017 case 5:
1018#if OPENSSL_VERSION_NUMBER >= 0x10001000L // NP: not sure exactly which sub-version yet.
1019 debugs(83, 5, "Using TLSv1.1.");
1020 return TLSv1_1_client_method();
1021#else
1022 debugs(83, DBG_IMPORTANT, "TLSv1.1 is not available in this Proxy.");
1023 return NULL;
1024#endif
1025 break;
1026
1027 case 6:
1028#if OPENSSL_VERSION_NUMBER >= 0x10001000L // NP: not sure exactly which sub-version yet.
1029 debugs(83, 5, "Using TLSv1.2");
1030 return TLSv1_2_client_method();
1031#else
1032 debugs(83, DBG_IMPORTANT, "TLSv1.2 is not available in this Proxy.");
1033 return NULL;
1034#endif
1035 break;
a7ad6e4e 1036
d620ae0e
CT
1037 case 1:
1038
1039 default:
1040 debugs(83, 5, "Using SSLv2/SSLv3.");
1041 return SSLv23_client_method();
1042 break;
1043 }
1044
1045 //Not reached
1046 return NULL;
1047}
1048
1049const SSL_METHOD *
1050Ssl::serverMethod(int version)
1051{
a7ad6e4e 1052 switch (version) {
62e76326 1053
a7ad6e4e 1054 case 2:
48e7baac 1055 debugs(83, DBG_IMPORTANT, "SSLv2 is not available in this Proxy.");
50b4c080 1056 return NULL;
62e76326 1057 break;
1058
a7ad6e4e 1059 case 3:
bf8fe701 1060 debugs(83, 5, "Using SSLv3.");
d620ae0e 1061 return SSLv3_server_method();
62e76326 1062 break;
1063
a7ad6e4e 1064 case 4:
bf8fe701 1065 debugs(83, 5, "Using TLSv1.");
d620ae0e 1066 return TLSv1_server_method();
62e76326 1067 break;
1068
3d96b0e8
AJ
1069 case 5:
1070#if OPENSSL_VERSION_NUMBER >= 0x10001000L // NP: not sure exactly which sub-version yet.
1071 debugs(83, 5, "Using TLSv1.1.");
d620ae0e 1072 return TLSv1_1_server_method();
3d96b0e8
AJ
1073#else
1074 debugs(83, DBG_IMPORTANT, "TLSv1.1 is not available in this Proxy.");
1075 return NULL;
1076#endif
1077 break;
1078
1079 case 6:
1080#if OPENSSL_VERSION_NUMBER >= 0x10001000L // NP: not sure exactly which sub-version yet.
1081 debugs(83, 5, "Using TLSv1.2");
d620ae0e 1082 return TLSv1_2_server_method();
3d96b0e8
AJ
1083#else
1084 debugs(83, DBG_IMPORTANT, "TLSv1.2 is not available in this Proxy.");
1085 return NULL;
1086#endif
1087 break;
1088
a7ad6e4e 1089 case 1:
62e76326 1090
a7ad6e4e 1091 default:
bf8fe701 1092 debugs(83, 5, "Using SSLv2/SSLv3.");
d620ae0e 1093 return SSLv23_server_method();
62e76326 1094 break;
a7ad6e4e 1095 }
1096
d620ae0e
CT
1097 //Not reached
1098 return NULL;
1099}
1100
1101SSL_CTX *
1102sslCreateClientContext(const char *certfile, const char *keyfile, int version, const char *cipher, const char *options, const char *flags, const char *CAfile, const char *CApath, const char *CRLfile)
1103{
1104 int ssl_error;
31855516
CT
1105 Ssl::ContextMethod method;
1106 SSL_CTX * sslContext;
d620ae0e
CT
1107 long fl = Ssl::parse_flags(flags);
1108
1109 ssl_initialize();
1110
1111 if (!keyfile)
1112 keyfile = certfile;
1113
1114 if (!certfile)
1115 certfile = keyfile;
1116
1117 if (!(method = Ssl::method(version)))
1118 return NULL;
e1f72a8b 1119
a7ad6e4e 1120 sslContext = SSL_CTX_new(method);
62e76326 1121
a7ad6e4e 1122 if (sslContext == NULL) {
62e76326 1123 ssl_error = ERR_get_error();
1124 fatalf("Failed to allocate SSL context: %s\n",
1125 ERR_error_string(ssl_error, NULL));
a7ad6e4e 1126 }
62e76326 1127
86660d64 1128 SSL_CTX_set_options(sslContext, Ssl::parse_options(options));
a7ad6e4e 1129
1130 if (cipher) {
bf8fe701 1131 debugs(83, 5, "Using chiper suite " << cipher << ".");
62e76326 1132
1133 if (!SSL_CTX_set_cipher_list(sslContext, cipher)) {
1134 ssl_error = ERR_get_error();
1135 fatalf("Failed to set SSL cipher suite '%s': %s\n",
1136 cipher, ERR_error_string(ssl_error, NULL));
1137 }
a7ad6e4e 1138 }
62e76326 1139
a7ad6e4e 1140 if (certfile) {
e0236918 1141 debugs(83, DBG_IMPORTANT, "Using certificate in " << certfile);
62e76326 1142
1143 if (!SSL_CTX_use_certificate_chain_file(sslContext, certfile)) {
1144 ssl_error = ERR_get_error();
1145 fatalf("Failed to acquire SSL certificate '%s': %s\n",
1146 certfile, ERR_error_string(ssl_error, NULL));
1147 }
1148
e0236918 1149 debugs(83, DBG_IMPORTANT, "Using private key in " << keyfile);
307b83b7 1150 ssl_ask_password(sslContext, keyfile);
62e76326 1151
1152 if (!SSL_CTX_use_PrivateKey_file(sslContext, keyfile, SSL_FILETYPE_PEM)) {
1153 ssl_error = ERR_get_error();
1154 fatalf("Failed to acquire SSL private key '%s': %s\n",
1155 keyfile, ERR_error_string(ssl_error, NULL));
1156 }
1157
bf8fe701 1158 debugs(83, 5, "Comparing private and public SSL keys.");
62e76326 1159
1160 if (!SSL_CTX_check_private_key(sslContext)) {
1161 ssl_error = ERR_get_error();
1162 fatalf("SSL private key '%s' does not match public key '%s': %s\n",
1163 certfile, keyfile, ERR_error_string(ssl_error, NULL));
1164 }
a7ad6e4e 1165 }
62e76326 1166
bf8fe701 1167 debugs(83, 9, "Setting RSA key generation callback.");
f484cdf5 1168 SSL_CTX_set_tmp_rsa_callback(sslContext, ssl_temp_rsa_cb);
1169
a7ad6e4e 1170 if (fl & SSL_FLAG_DONT_VERIFY_PEER) {
48e7baac 1171 debugs(83, 2, "NOTICE: Peer certificates are not verified for validity!");
62e76326 1172 SSL_CTX_set_verify(sslContext, SSL_VERIFY_NONE, NULL);
a7ad6e4e 1173 } else {
bf8fe701 1174 debugs(83, 9, "Setting certificate verification callback.");
62e76326 1175 SSL_CTX_set_verify(sslContext, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, ssl_verify_cb);
a7ad6e4e 1176 }
f484cdf5 1177
bf8fe701 1178 debugs(83, 9, "Setting CA certificate locations.");
62e76326 1179
a82a4fe4 1180 if ((CAfile || CApath) && !SSL_CTX_load_verify_locations(sslContext, CAfile, CApath)) {
1181 ssl_error = ERR_get_error();
48e7baac 1182 debugs(83, DBG_IMPORTANT, "WARNING: Ignoring error setting CA certificate locations: " << ERR_error_string(ssl_error, NULL));
a82a4fe4 1183 }
1184
1185 if (CRLfile) {
1186 ssl_load_crl(sslContext, CRLfile);
1187 fl |= SSL_FLAG_VERIFY_CRL;
1188 }
1189
32d002cb 1190#if X509_V_FLAG_CRL_CHECK
a82a4fe4 1191 if (fl & SSL_FLAG_VERIFY_CRL_ALL)
1192 X509_STORE_set_flags(SSL_CTX_get_cert_store(sslContext), X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
1193 else if (fl & SSL_FLAG_VERIFY_CRL)
1194 X509_STORE_set_flags(SSL_CTX_get_cert_store(sslContext), X509_V_FLAG_CRL_CHECK);
1195
1196#endif
62e76326 1197
a7ad6e4e 1198 if (!(fl & SSL_FLAG_NO_DEFAULT_CA) &&
62e76326 1199 !SSL_CTX_set_default_verify_paths(sslContext)) {
1200 ssl_error = ERR_get_error();
48e7baac 1201 debugs(83, DBG_IMPORTANT, "WARNING: Ignoring error setting default CA certificate location: " << ERR_error_string(ssl_error, NULL));
f484cdf5 1202 }
62e76326 1203
d193a436 1204 return sslContext;
f484cdf5 1205}
1206
63be0a78 1207/// \ingroup ServerProtocolSSLInternal
d193a436 1208int
e6ccf245 1209ssl_read_method(int fd, char *buf, int len)
f484cdf5 1210{
6de9e64b 1211 SSL *ssl = fd_table[fd].ssl;
79d4ccdf 1212 int i;
1213
6de9e64b 1214#if DONT_DO_THIS
1215
1216 if (!SSL_is_init_finished(ssl)) {
1217 errno = ENOTCONN;
1218 return -1;
1219 }
79d4ccdf 1220
6de9e64b 1221#endif
1222
1223 i = SSL_read(ssl, buf, len);
1224
1225 if (i > 0 && SSL_pending(ssl) > 0) {
bf8fe701 1226 debugs(83, 2, "SSL FD " << fd << " is pending");
be4d35dc 1227 fd_table[fd].flags.read_pending = true;
79d4ccdf 1228 } else
be4d35dc 1229 fd_table[fd].flags.read_pending = false;
79d4ccdf 1230
1231 return i;
f484cdf5 1232}
1233
63be0a78 1234/// \ingroup ServerProtocolSSLInternal
d193a436 1235int
e6ccf245 1236ssl_write_method(int fd, const char *buf, int len)
f484cdf5 1237{
6de9e64b 1238 SSL *ssl = fd_table[fd].ssl;
1239 int i;
1240
1241 if (!SSL_is_init_finished(ssl)) {
1242 errno = ENOTCONN;
1243 return -1;
1244 }
1245
1246 i = SSL_write(ssl, buf, len);
1247
1248 return i;
f484cdf5 1249}
79d4ccdf 1250
1251void
575d05c4 1252ssl_shutdown_method(SSL *ssl)
79d4ccdf 1253{
79d4ccdf 1254 SSL_shutdown(ssl);
1255}
a7ad6e4e 1256
63be0a78 1257/// \ingroup ServerProtocolSSLInternal
a7ad6e4e 1258static const char *
1259ssl_get_attribute(X509_NAME * name, const char *attribute_name)
1260{
1261 static char buffer[1024];
1262 int nid;
1263
1264 buffer[0] = '\0';
1265
1266 if (strcmp(attribute_name, "DN") == 0) {
62e76326 1267 X509_NAME_oneline(name, buffer, sizeof(buffer));
1268 goto done;
a7ad6e4e 1269 }
62e76326 1270
a7ad6e4e 1271 nid = OBJ_txt2nid((char *) attribute_name);
62e76326 1272
a7ad6e4e 1273 if (nid == 0) {
e0236918 1274 debugs(83, DBG_IMPORTANT, "WARNING: Unknown SSL attribute name '" << attribute_name << "'");
62e76326 1275 return NULL;
a7ad6e4e 1276 }
62e76326 1277
a7ad6e4e 1278 X509_NAME_get_text_by_NID(name, nid, buffer, sizeof(buffer));
62e76326 1279
1280done:
a7ad6e4e 1281 return *buffer ? buffer : NULL;
1282}
1283
63be0a78 1284/// \ingroup ServerProtocolSSLInternal
a7ad6e4e 1285const char *
00352183 1286Ssl::GetX509UserAttribute(X509 * cert, const char *attribute_name)
a7ad6e4e 1287{
a7ad6e4e 1288 X509_NAME *name;
23e6c4ae 1289 const char *ret;
a7ad6e4e 1290
a7ad6e4e 1291 if (!cert)
62e76326 1292 return NULL;
a7ad6e4e 1293
5a4684b6 1294 name = X509_get_subject_name(cert);
a7ad6e4e 1295
23e6c4ae 1296 ret = ssl_get_attribute(name, attribute_name);
1297
23e6c4ae 1298 return ret;
a7ad6e4e 1299}
1300
00352183
AR
1301const char *
1302Ssl::GetX509Fingerprint(X509 * cert, const char *)
1303{
1304 static char buf[1024];
1305 if (!cert)
1306 return NULL;
960e100b 1307
00352183
AR
1308 unsigned int n;
1309 unsigned char md[EVP_MAX_MD_SIZE];
1310 if (!X509_digest(cert, EVP_sha1(), md, &n))
1311 return NULL;
1312
1313 assert(3 * n + 1 < sizeof(buf));
1314
1315 char *s = buf;
1316 for (unsigned int i=0; i < n; ++i, s += 3) {
1317 const char term = (i + 1 < n) ? ':' : '\0';
1318 snprintf(s, 4, "%02X%c", md[i], term);
1319 }
1320
1321 return buf;
1322}
1323
63be0a78 1324/// \ingroup ServerProtocolSSLInternal
a7ad6e4e 1325const char *
00352183 1326Ssl::GetX509CAAttribute(X509 * cert, const char *attribute_name)
a7ad6e4e 1327{
00352183 1328
a7ad6e4e 1329 X509_NAME *name;
23e6c4ae 1330 const char *ret;
a7ad6e4e 1331
a7ad6e4e 1332 if (!cert)
62e76326 1333 return NULL;
a7ad6e4e 1334
5a4684b6 1335 name = X509_get_issuer_name(cert);
a7ad6e4e 1336
23e6c4ae 1337 ret = ssl_get_attribute(name, attribute_name);
1338
00352183
AR
1339 return ret;
1340}
1341
1342const char *sslGetUserAttribute(SSL *ssl, const char *attribute_name)
1343{
1344 if (!ssl)
1345 return NULL;
1346
1347 X509 *cert = SSL_get_peer_certificate(ssl);
1348
1349 const char *attr = Ssl::GetX509UserAttribute(cert, attribute_name);
1350
23e6c4ae 1351 X509_free(cert);
00352183
AR
1352 return attr;
1353}
23e6c4ae 1354
00352183
AR
1355const char *sslGetCAAttribute(SSL *ssl, const char *attribute_name)
1356{
1357 if (!ssl)
1358 return NULL;
1359
1360 X509 *cert = SSL_get_peer_certificate(ssl);
1361
1362 const char *attr = Ssl::GetX509CAAttribute(cert, attribute_name);
1363
1364 X509_free(cert);
1365 return attr;
a7ad6e4e 1366}
1367
a7ad6e4e 1368const char *
1369sslGetUserEmail(SSL * ssl)
1370{
e6ceef10 1371 return sslGetUserAttribute(ssl, "emailAddress");
a7ad6e4e 1372}
4ac9968f 1373
1374const char *
1375sslGetUserCertificatePEM(SSL *ssl)
1376{
1377 X509 *cert;
1378 BIO *mem;
1379 static char *str = NULL;
1380 char *ptr;
1381 long len;
1382
1383 safe_free(str);
1384
1385 if (!ssl)
1386 return NULL;
1387
1388 cert = SSL_get_peer_certificate(ssl);
1389
1390 if (!cert)
1391 return NULL;
1392
1393 mem = BIO_new(BIO_s_mem());
1394
1395 PEM_write_bio_X509(mem, cert);
1396
4ac9968f 1397 len = BIO_get_mem_data(mem, &ptr);
1398
1399 str = (char *)xmalloc(len + 1);
1400
1401 memcpy(str, ptr, len);
1402
1403 str[len] = '\0';
1404
1405 X509_free(cert);
1406
1407 BIO_free(mem);
1408
1409 return str;
1410}
3d61c476 1411
1412const char *
1413sslGetUserCertificateChainPEM(SSL *ssl)
1414{
1415 STACK_OF(X509) *chain;
1416 BIO *mem;
1417 static char *str = NULL;
1418 char *ptr;
1419 long len;
1420 int i;
1421
1422 safe_free(str);
1423
1424 if (!ssl)
1425 return NULL;
1426
1427 chain = SSL_get_peer_cert_chain(ssl);
1428
1429 if (!chain)
1430 return sslGetUserCertificatePEM(ssl);
1431
1432 mem = BIO_new(BIO_s_mem());
1433
d7ae3534 1434 for (i = 0; i < sk_X509_num(chain); ++i) {
3d61c476 1435 X509 *cert = sk_X509_value(chain, i);
1436 PEM_write_bio_X509(mem, cert);
1437 }
1438
1439 len = BIO_get_mem_data(mem, &ptr);
1440
1441 str = (char *)xmalloc(len + 1);
1442 memcpy(str, ptr, len);
1443 str[len] = '\0';
1444
1445 BIO_free(mem);
1446
1447 return str;
1448}
454e8283 1449
86660d64
CT
1450Ssl::ContextMethod
1451Ssl::contextMethod(int version)
1452{
1453 Ssl::ContextMethod method;
1454
1455 switch (version) {
1456
1457 case 2:
86660d64
CT
1458 debugs(83, DBG_IMPORTANT, "SSLv2 is not available in this Proxy.");
1459 return NULL;
86660d64
CT
1460 break;
1461
1462 case 3:
1463 debugs(83, 5, "Using SSLv3.");
1464 method = SSLv3_server_method();
1465 break;
1466
1467 case 4:
1468 debugs(83, 5, "Using TLSv1.");
1469 method = TLSv1_server_method();
1470 break;
1471
1472 case 5:
1473#if OPENSSL_VERSION_NUMBER >= 0x10001000L // NP: not sure exactly which sub-version yet.
1474 debugs(83, 5, "Using TLSv1.1.");
1475 method = TLSv1_1_server_method();
1476#else
1477 debugs(83, DBG_IMPORTANT, "TLSv1.1 is not available in this Proxy.");
1478 return NULL;
1479#endif
1480 break;
1481
1482 case 6:
1483#if OPENSSL_VERSION_NUMBER >= 0x10001000L // NP: not sure exactly which sub-version yet.
1484 debugs(83, 5, "Using TLSv1.2");
1485 method = TLSv1_2_server_method();
1486#else
1487 debugs(83, DBG_IMPORTANT, "TLSv1.2 is not available in this Proxy.");
1488 return NULL;
1489#endif
1490 break;
1491
1492 case 1:
1493
1494 default:
1495 debugs(83, 5, "Using SSLv2/SSLv3.");
1496 method = SSLv23_server_method();
1497 break;
1498 }
1499 return method;
1500}
1501
95d2589c
CT
1502/// \ingroup ServerProtocolSSLInternal
1503/// Create SSL context and apply ssl certificate and private key to it.
d620ae0e
CT
1504SSL_CTX *
1505Ssl::createSSLContext(Ssl::X509_Pointer & x509, Ssl::EVP_PKEY_Pointer & pkey, AnyP::PortCfg &port)
95d2589c 1506{
86660d64 1507 Ssl::SSL_CTX_Pointer sslContext(SSL_CTX_new(port.contextMethod));
95d2589c
CT
1508
1509 if (!SSL_CTX_use_certificate(sslContext.get(), x509.get()))
1510 return NULL;
1511
1512 if (!SSL_CTX_use_PrivateKey(sslContext.get(), pkey.get()))
1513 return NULL;
86660d64
CT
1514
1515 if (!configureSslContext(sslContext.get(), port))
1516 return NULL;
1517
95d2589c
CT
1518 return sslContext.release();
1519}
1520
86660d64
CT
1521SSL_CTX *
1522Ssl::generateSslContextUsingPkeyAndCertFromMemory(const char * data, AnyP::PortCfg &port)
95d2589c
CT
1523{
1524 Ssl::X509_Pointer cert;
1525 Ssl::EVP_PKEY_Pointer pkey;
1526 if (!readCertAndPrivateKeyFromMemory(cert, pkey, data))
1527 return NULL;
1528
1529 if (!cert || !pkey)
1530 return NULL;
1531
86660d64 1532 return createSSLContext(cert, pkey, port);
95d2589c
CT
1533}
1534
86660d64
CT
1535SSL_CTX *
1536Ssl::generateSslContext(CertificateProperties const &properties, AnyP::PortCfg &port)
95d2589c
CT
1537{
1538 Ssl::X509_Pointer cert;
1539 Ssl::EVP_PKEY_Pointer pkey;
aebe6888 1540 if (!generateSslCertificate(cert, pkey, properties))
95d2589c 1541 return NULL;
9a90aace 1542
95d2589c
CT
1543 if (!cert)
1544 return NULL;
1545
1546 if (!pkey)
1547 return NULL;
1548
86660d64 1549 return createSSLContext(cert, pkey, port);
95d2589c
CT
1550}
1551
d620ae0e
CT
1552bool
1553Ssl::configureSSL(SSL *ssl, CertificateProperties const &properties, AnyP::PortCfg &port)
1554{
1555 Ssl::X509_Pointer cert;
1556 Ssl::EVP_PKEY_Pointer pkey;
1557 if (!generateSslCertificate(cert, pkey, properties))
1558 return false;
1559
1560 if (!cert)
1561 return false;
1562
1563 if (!pkey)
1564 return false;
1565
1566 if (!SSL_use_certificate(ssl, cert.get()))
1567 return false;
1568
1569 if (!SSL_use_PrivateKey(ssl, pkey.get()))
1570 return false;
1571
1572 return true;
1573}
1574
1575bool
1576Ssl::configureSSLUsingPkeyAndCertFromMemory(SSL *ssl, const char *data, AnyP::PortCfg &port)
1577{
1578 Ssl::X509_Pointer cert;
1579 Ssl::EVP_PKEY_Pointer pkey;
1580 if (!readCertAndPrivateKeyFromMemory(cert, pkey, data))
1581 return false;
1582
1583 if (!cert || !pkey)
1584 return false;
1585
1586 if (!SSL_use_certificate(ssl, cert.get()))
1587 return false;
1588
1589 if (!SSL_use_PrivateKey(ssl, pkey.get()))
1590 return false;
1591
1592 return true;
1593}
1594
4ece76b2 1595bool Ssl::verifySslCertificate(SSL_CTX * sslContext, CertificateProperties const &properties)
95d2589c 1596{
b8658552
CT
1597 // SSL_get_certificate is buggy in openssl versions 1.0.1d and 1.0.1e
1598 // Try to retrieve certificate directly from SSL_CTX object
fc321c30 1599#if SQUID_USE_SSLGETCERTIFICATE_HACK
b8658552
CT
1600 X509 ***pCert = (X509 ***)sslContext->cert;
1601 X509 * cert = pCert && *pCert ? **pCert : NULL;
fc321c30
CT
1602#elif SQUID_SSLGETCERTIFICATE_BUGGY
1603 X509 * cert = NULL;
1604 assert(0);
b8658552 1605#else
95d2589c
CT
1606 // Temporary ssl for getting X509 certificate from SSL_CTX.
1607 Ssl::SSL_Pointer ssl(SSL_new(sslContext));
1608 X509 * cert = SSL_get_certificate(ssl.get());
b8658552
CT
1609#endif
1610 if (!cert)
1611 return false;
95d2589c
CT
1612 ASN1_TIME * time_notBefore = X509_get_notBefore(cert);
1613 ASN1_TIME * time_notAfter = X509_get_notAfter(cert);
1614 bool ret = (X509_cmp_current_time(time_notBefore) < 0 && X509_cmp_current_time(time_notAfter) > 0);
e7bcc25f
CT
1615 if (!ret)
1616 return false;
1617
4ece76b2 1618 return certificateMatchesProperties(cert, properties);
95d2589c
CT
1619}
1620
253749a8
CT
1621bool
1622Ssl::setClientSNI(SSL *ssl, const char *fqdn)
1623{
1624 //The SSL_CTRL_SET_TLSEXT_HOSTNAME is a openssl macro which indicates
1625 // if the TLS servername extension (SNI) is enabled in openssl library.
1626#if defined(SSL_CTRL_SET_TLSEXT_HOSTNAME)
1627 if (!SSL_set_tlsext_host_name(ssl, fqdn)) {
1628 const int ssl_error = ERR_get_error();
1629 debugs(83, 3, "WARNING: unable to set TLS servername extension (SNI): " <<
1630 ERR_error_string(ssl_error, NULL) << "\n");
1631 return false;
1632 }
1633 return true;
1634#else
1635 debugs(83, 7, "no support for TLS servername extension (SNI)\n");
1636 return false;
1637#endif
1638}
1639
a594dbfa
CT
1640void Ssl::addChainToSslContext(SSL_CTX *sslContext, STACK_OF(X509) *chain)
1641{
1642 if (!chain)
1643 return;
1644
d7ae3534 1645 for (int i = 0; i < sk_X509_num(chain); ++i) {
a594dbfa
CT
1646 X509 *cert = sk_X509_value(chain, i);
1647 if (SSL_CTX_add_extra_chain_cert(sslContext, cert)) {
1648 // increase the certificate lock
1649 CRYPTO_add(&(cert->references),1,CRYPTO_LOCK_X509);
1650 } else {
1651 const int ssl_error = ERR_get_error();
1652 debugs(83, DBG_IMPORTANT, "WARNING: can not add certificate to SSL context chain: " << ERR_error_string(ssl_error, NULL));
1653 }
1654 }
1655}
1656
1657/**
1658 \ingroup ServerProtocolSSLInternal
1659 * Read certificate from file.
1660 * See also: static readSslX509Certificate function, gadgets.cc file
1661 */
1662static X509 * readSslX509CertificatesChain(char const * certFilename, STACK_OF(X509)* chain)
1663{
1664 if (!certFilename)
1665 return NULL;
1666 Ssl::BIO_Pointer bio(BIO_new(BIO_s_file_internal()));
1667 if (!bio)
1668 return NULL;
1669 if (!BIO_read_filename(bio.get(), certFilename))
1670 return NULL;
1671 X509 *certificate = PEM_read_bio_X509(bio.get(), NULL, NULL, NULL);
1672
1673 if (certificate && chain) {
1674
c11211d9 1675 if (X509_check_issued(certificate, certificate) == X509_V_OK)
a594dbfa
CT
1676 debugs(83, 5, "Certificate is self-signed, will not be chained");
1677 else {
a411d213 1678 // and add to the chain any other certificate exist in the file
a594dbfa
CT
1679 while (X509 *ca = PEM_read_bio_X509(bio.get(), NULL, NULL, NULL)) {
1680 if (!sk_X509_push(chain, ca))
1681 debugs(83, DBG_IMPORTANT, "WARNING: unable to add CA certificate to cert chain");
1682 }
1683 }
1684 }
c11211d9 1685
a594dbfa
CT
1686 return certificate;
1687}
1688
1689void Ssl::readCertChainAndPrivateKeyFromFiles(X509_Pointer & cert, EVP_PKEY_Pointer & pkey, X509_STACK_Pointer & chain, char const * certFilename, char const * keyFilename)
1690{
1691 if (keyFilename == NULL)
1692 keyFilename = certFilename;
86660d64
CT
1693
1694 if (certFilename == NULL)
1695 certFilename = keyFilename;
1696
1697 debugs(83, DBG_IMPORTANT, "Using certificate in " << certFilename);
1698
a594dbfa
CT
1699 if (!chain)
1700 chain.reset(sk_X509_new_null());
1701 if (!chain)
1702 debugs(83, DBG_IMPORTANT, "WARNING: unable to allocate memory for cert chain");
37144aca
AR
1703 // XXX: ssl_ask_password_cb needs SSL_CTX_set_default_passwd_cb_userdata()
1704 // so this may not fully work iff Config.Program.ssl_password is set.
1705 pem_password_cb *cb = ::Config.Program.ssl_password ? &ssl_ask_password_cb : NULL;
1706 pkey.reset(readSslPrivateKey(keyFilename, cb));
a594dbfa
CT
1707 cert.reset(readSslX509CertificatesChain(certFilename, chain.get()));
1708 if (!pkey || !cert || !X509_check_private_key(cert.get(), pkey.get())) {
1709 pkey.reset(NULL);
1710 cert.reset(NULL);
1711 }
1712}
1713
95588170
CT
1714bool Ssl::generateUntrustedCert(X509_Pointer &untrustedCert, EVP_PKEY_Pointer &untrustedPkey, X509_Pointer const &cert, EVP_PKEY_Pointer const & pkey)
1715{
1716 // Generate the self-signed certificate, using a hard-coded subject prefix
1717 Ssl::CertificateProperties certProperties;
1718 if (const char *cn = CommonHostName(cert.get())) {
1719 certProperties.commonName = "Not trusted by \"";
1720 certProperties.commonName += cn;
1721 certProperties.commonName += "\"";
87f237a9 1722 } else if (const char *org = getOrganization(cert.get())) {
95588170
CT
1723 certProperties.commonName = "Not trusted by \"";
1724 certProperties.commonName += org;
1725 certProperties.commonName += "\"";
87f237a9 1726 } else
95588170
CT
1727 certProperties.commonName = "Not trusted";
1728 certProperties.setCommonName = true;
1729 // O, OU, and other CA subject fields will be mimicked
1730 // Expiration date and other common properties will be mimicked
1731 certProperties.signAlgorithm = Ssl::algSignSelf;
1732 certProperties.signWithPkey.resetAndLock(pkey.get());
1733 certProperties.mimicCert.resetAndLock(cert.get());
1734 return Ssl::generateSslCertificate(untrustedCert, untrustedPkey, certProperties);
1735}
1736
b3a8ae1b 1737SSL *
d620ae0e 1738SslCreate(SSL_CTX *sslContext, const int fd, Ssl::Bio::Type type, const char *squidCtx)
b3a8ae1b
AR
1739{
1740 const char *errAction = NULL;
1741 int errCode = 0;
1742 if (SSL *ssl = SSL_new(sslContext)) {
1743 // without BIO, we would call SSL_set_fd(ssl, fd) instead
d620ae0e 1744 if (BIO *bio = Ssl::Bio::Create(fd, type)) {
b3a8ae1b
AR
1745 Ssl::Bio::Link(ssl, bio); // cannot fail
1746
1747 fd_table[fd].ssl = ssl;
1748 fd_table[fd].read_method = &ssl_read_method;
1749 fd_table[fd].write_method = &ssl_write_method;
1750 fd_note(fd, squidCtx);
1751
1752 return ssl;
1753 }
1754 errCode = ERR_get_error();
1755 errAction = "failed to initialize I/O";
1756 SSL_free(ssl);
1757 } else {
1758 errCode = ERR_get_error();
1759 errAction = "failed to allocate handle";
1760 }
1761
1762 debugs(83, DBG_IMPORTANT, "ERROR: " << squidCtx << ' ' << errAction <<
1763 ": " << ERR_error_string(errCode, NULL));
1764 return NULL;
1765}
1766
d620ae0e
CT
1767SSL *
1768Ssl::CreateClient(SSL_CTX *sslContext, const int fd, const char *squidCtx)
1769{
1770 return SslCreate(sslContext, fd, Ssl::Bio::BIO_TO_SERVER, squidCtx);
1771}
1772
1773SSL *
1774Ssl::CreateServer(SSL_CTX *sslContext, const int fd, const char *squidCtx)
1775{
1776 return SslCreate(sslContext, fd, Ssl::Bio::BIO_TO_CLIENT, squidCtx);
1777}
1778
62a7607e 1779Ssl::CertError::CertError(ssl_error_t anErr, X509 *aCert): code(anErr)
170cb017 1780{
62a7607e
CT
1781 cert.resetAndLock(aCert);
1782}
1783
1784Ssl::CertError::CertError(CertError const &err): code(err.code)
1785{
1786 cert.resetAndLock(err.cert.get());
1787}
1788
1789Ssl::CertError &
170cb017 1790Ssl::CertError::operator = (const CertError &old)
62a7607e 1791{
170cb017 1792 code = old.code;
62a7607e
CT
1793 cert.resetAndLock(old.cert.get());
1794 return *this;
1795}
1796
1797bool
1798Ssl::CertError::operator == (const CertError &ce) const
1799{
1800 return code == ce.code && cert.get() == ce.cert.get();
1801}
1802
1803bool
1804Ssl::CertError::operator != (const CertError &ce) const
1805{
1806 return code != ce.code || cert.get() != ce.cert.get();
1807}
1808
10a69fc0
CT
1809static int
1810store_session_cb(SSL *ssl, SSL_SESSION *session)
1811{
1812 if (!SslSessionCache)
1813 return 0;
1814
1815 debugs(83, 5, "Request to store SSL Session ");
1816
1817 SSL_SESSION_set_timeout(session, Config.SSL.session_ttl);
1818
1819 unsigned char *id = session->session_id;
1820 unsigned int idlen = session->session_id_length;
1821 unsigned char key[MEMMAP_SLOT_KEY_SIZE];
1822 // Session ids are of size 32bytes. They should always fit to a
86c63190 1823 // MemMap::Slot::key
10a69fc0
CT
1824 assert(idlen <= MEMMAP_SLOT_KEY_SIZE);
1825 memset(key, 0, sizeof(key));
1826 memcpy(key, id, idlen);
1827 int pos;
1828 Ipc::MemMap::Slot *slotW = SslSessionCache->openForWriting((const cache_key*)key, pos);
1829 if (slotW) {
1830 int lenRequired = i2d_SSL_SESSION(session, NULL);
1831 if (lenRequired < MEMMAP_SLOT_DATA_SIZE) {
1832 unsigned char *p = (unsigned char *)slotW->p;
1833 lenRequired = i2d_SSL_SESSION(session, &p);
1834 slotW->set(key, NULL, lenRequired, squid_curtime + Config.SSL.session_ttl);
1835 }
1836 SslSessionCache->closeForWriting(pos);
1837 debugs(83, 5, "wrote an ssl session entry of size " << lenRequired << " at pos " << pos);
1838 }
1839 return 0;
1840}
1841
1842static void
1843remove_session_cb(SSL_CTX *, SSL_SESSION *sessionID)
1844{
1845 if (!SslSessionCache)
1846 return ;
1847
1848 debugs(83, 5, "Request to remove corrupted or not valid SSL Session ");
1849 int pos;
1850 Ipc::MemMap::Slot const *slot = SslSessionCache->openForReading((const cache_key*)sessionID, pos);
1851 if (slot == NULL)
1852 return;
1853 SslSessionCache->closeForReading(pos);
1854 // TODO:
1855 // What if we are not able to remove the session?
1856 // Maybe schedule a job to remove it later?
1857 // For now we just have an invalid entry in cache until will be expired
1858 // The openSSL will reject it when we try to use it
1859 SslSessionCache->free(pos);
1860}
1861
1862static SSL_SESSION *
1863get_session_cb(SSL *, unsigned char *sessionID, int len, int *copy)
1864{
1865 if (!SslSessionCache)
1866 return NULL;
1867
1868 SSL_SESSION *session = NULL;
1869 const unsigned int *p;
1870 p = (unsigned int *)sessionID;
1871 debugs(83, 5, "Request to search for SSL Session of len:" <<
1872 len << p[0] << ":" << p[1]);
1873
1874 int pos;
1875 Ipc::MemMap::Slot const *slot = SslSessionCache->openForReading((const cache_key*)sessionID, pos);
1876 if (slot != NULL) {
1877 if (slot->expire > squid_curtime) {
1878 const unsigned char *ptr = slot->p;
1879 session = d2i_SSL_SESSION(NULL, &ptr, slot->pSize);
1880 debugs(83, 5, "Session retrieved from cache at pos " << pos);
1881 } else
1882 debugs(83, 5, "Session in cache expired");
1883 SslSessionCache->closeForReading(pos);
1884 }
1885
1886 if (!session)
1887 debugs(83, 5, "Failed to retrieved from cache\n");
1888
1889 // With the parameter copy the callback can require the SSL engine
1890 // to increment the reference count of the SSL_SESSION object, Normally
1891 // the reference count is not incremented and therefore the session must
1892 // not be explicitly freed with SSL_SESSION_free(3).
1893 *copy = 0;
1894 return session;
1895}
1896
1897static void
1898setSessionCallbacks(SSL_CTX *ctx)
1899{
1900 if (SslSessionCache) {
1901 SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_SERVER|SSL_SESS_CACHE_NO_INTERNAL);
1902 SSL_CTX_sess_set_new_cb(ctx, store_session_cb);
1903 SSL_CTX_sess_set_remove_cb(ctx, remove_session_cb);
1904 SSL_CTX_sess_set_get_cb(ctx, get_session_cb);
1905 }
1906}
1907
1908static bool
1909isSslServer()
1910{
d00790b2 1911 if (HttpsPortList != NULL)
10a69fc0
CT
1912 return true;
1913
fa720bfb 1914 for (AnyP::PortCfgPointer s = HttpPortList; s != NULL; s = s->next) {
10a69fc0
CT
1915 if (s->flags.tunnelSslBumping)
1916 return true;
1917 }
1918
1919 return false;
1920}
1921
1922#define SSL_SESSION_ID_SIZE 32
1923#define SSL_SESSION_MAX_SIZE 10*1024
1924
1925void
1926Ssl::initialize_session_cache()
1927{
1928
1929 if (!isSslServer()) //no need to configure ssl session cache.
1930 return;
1931
86c63190 1932 // Check if the MemMap keys and data are enough big to hold
10a69fc0
CT
1933 // session ids and session data
1934 assert(SSL_SESSION_ID_SIZE >= MEMMAP_SLOT_KEY_SIZE);
1935 assert(SSL_SESSION_MAX_SIZE >= MEMMAP_SLOT_DATA_SIZE);
1936
1937 int configuredItems = ::Config.SSL.sessionCacheSize / sizeof(Ipc::MemMap::Slot);
1938 if (IamWorkerProcess() && configuredItems)
1939 SslSessionCache = new Ipc::MemMap(SslSessionCacheName);
1940 else {
1941 SslSessionCache = NULL;
1942 return;
1943 }
1944
fa720bfb 1945 for (AnyP::PortCfgPointer s = HttpsPortList; s != NULL; s = s->next) {
10a69fc0
CT
1946 if (s->staticSslContext.get() != NULL)
1947 setSessionCallbacks(s->staticSslContext.get());
1948 }
1949
fa720bfb 1950 for (AnyP::PortCfgPointer s = HttpPortList; s != NULL; s = s->next) {
10a69fc0
CT
1951 if (s->staticSslContext.get() != NULL)
1952 setSessionCallbacks(s->staticSslContext.get());
1953 }
1954}
1955
1956void
1957destruct_session_cache()
1958{
1959 delete SslSessionCache;
1960}
1961
1962/// initializes shared memory segments used by MemStore
1963class SharedSessionCacheRr: public Ipc::Mem::RegisteredRunner
1964{
1965public:
1966 /* RegisteredRunner API */
1967 SharedSessionCacheRr(): owner(NULL) {}
21b7990f 1968 virtual void useConfig();
10a69fc0
CT
1969 virtual ~SharedSessionCacheRr();
1970
1971protected:
21b7990f 1972 virtual void create();
10a69fc0
CT
1973
1974private:
1975 Ipc::MemMap::Owner *owner;
1976};
1977
21b7990f 1978RunnerRegistrationEntry(SharedSessionCacheRr);
10a69fc0
CT
1979
1980void
21b7990f 1981SharedSessionCacheRr::useConfig()
10a69fc0 1982{
21b7990f 1983 Ipc::Mem::RegisteredRunner::useConfig();
10a69fc0
CT
1984}
1985
1986void
21b7990f 1987SharedSessionCacheRr::create()
10a69fc0
CT
1988{
1989 if (!isSslServer()) //no need to configure ssl session cache.
1990 return;
1991
1992 int items;
1993 items = Config.SSL.sessionCacheSize / sizeof(Ipc::MemMap::Slot);
1994 if (items)
1995 owner = Ipc::MemMap::Init(SslSessionCacheName, items);
1996}
1997
1998SharedSessionCacheRr::~SharedSessionCacheRr()
1999{
2000 delete owner;
2001}
d620ae0e 2002
cb4f4424 2003#endif /* USE_OPENSSL */
f53969cc 2004