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