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