2 * Copyright (C) 1996-2020 The Squid Software Foundation and contributors
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.
9 /* DEBUG: section 83 SSL accelerator support */
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.
18 #include "acl/FilledChecklist.h"
19 #include "anyp/PortCfg.h"
25 #include "ipc/MemMap.h"
26 #include "security/CertError.h"
27 #include "security/ErrorDetail.h"
28 #include "security/Session.h"
29 #include "SquidConfig.h"
30 #include "SquidTime.h"
32 #include "ssl/Config.h"
33 #include "ssl/ErrorDetail.h"
34 #include "ssl/gadgets.h"
35 #include "ssl/support.h"
39 // TODO: Move ssl_ex_index_* global variables from global.cc here.
40 static int ssl_ex_index_verify_callback_parameters
= -1;
42 static Ssl::CertsIndexedList SquidUntrustedCerts
;
44 const EVP_MD
*Ssl::DefaultSignHash
= NULL
;
46 std::vector
<const char *> Ssl::BumpModeStr
= {
59 \defgroup ServerProtocolSSLInternal Server-Side SSL Internals
60 \ingroup ServerProtocolSSLAPI
64 Ssl::AskPasswordCb(char *buf
, int size
, int rwflag
, void *userdata
)
70 snprintf(cmdline
, sizeof(cmdline
), "\"%s\" \"%s\"", ::Config
.Program
.ssl_password
, (const char *)userdata
);
71 in
= popen(cmdline
, "r");
73 if (fgets(buf
, size
, in
))
77 while (len
> 0 && (buf
[len
- 1] == '\n' || buf
[len
- 1] == '\r'))
87 /// \ingroup ServerProtocolSSLInternal
89 ssl_ask_password(SSL_CTX
* context
, const char * prompt
)
91 if (Config
.Program
.ssl_password
) {
92 SSL_CTX_set_default_passwd_cb(context
, Ssl::AskPasswordCb
);
93 SSL_CTX_set_default_passwd_cb_userdata(context
, (void *)prompt
);
97 #if HAVE_LIBSSL_SSL_CTX_SET_TMP_RSA_CALLBACK
99 ssl_temp_rsa_cb(SSL
* ssl
, int anInt
, int keylen
)
101 static RSA
*rsa_512
= nullptr;
102 static RSA
*rsa_1024
= nullptr;
103 static BIGNUM
*e
= nullptr;
109 if (!e
|| !BN_set_word(e
, RSA_F4
)) {
110 debugs(83, DBG_IMPORTANT
, "ssl_temp_rsa_cb: Failed to set exponent for key " << keylen
);
123 if (rsa_512
&& RSA_generate_key_ex(rsa_512
, 512, e
, nullptr)) {
137 rsa_1024
= RSA_new();
138 if (rsa_1024
&& RSA_generate_key_ex(rsa_1024
, 1024, e
, nullptr)) {
150 debugs(83, DBG_IMPORTANT
, "ssl_temp_rsa_cb: Unexpected key length " << keylen
);
155 debugs(83, DBG_IMPORTANT
, "ssl_temp_rsa_cb: Failed to generate key " << keylen
);
160 if (Debug::Enabled(83, 5))
161 PEM_write_RSAPrivateKey(debug_log
, rsa
, NULL
, NULL
, 0, NULL
, NULL
);
163 debugs(83, DBG_IMPORTANT
, "Generated ephemeral RSA key of length " << keylen
);
171 Ssl::MaybeSetupRsaCallback(Security::ContextPointer
&ctx
)
173 #if HAVE_LIBSSL_SSL_CTX_SET_TMP_RSA_CALLBACK
174 debugs(83, 9, "Setting RSA key generation callback.");
175 SSL_CTX_set_tmp_rsa_callback(ctx
.get(), ssl_temp_rsa_cb
);
179 int Ssl::asn1timeToString(ASN1_TIME
*tm
, char *buf
, int len
)
183 bio
= BIO_new(BIO_s_mem());
185 if (ASN1_TIME_print(bio
, tm
))
186 write
= BIO_read(bio
, buf
, len
-1);
193 int Ssl::matchX509CommonNames(X509
*peer_cert
, void *check_data
, int (*check_func
)(void *check_data
, ASN1_STRING
*cn_data
))
197 X509_NAME
*name
= X509_get_subject_name(peer_cert
);
199 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
)) {
201 ASN1_STRING
*cn_data
= X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name
, i
));
203 if ( (*check_func
)(check_data
, cn_data
) == 0)
207 STACK_OF(GENERAL_NAME
) * altnames
;
208 altnames
= (STACK_OF(GENERAL_NAME
)*)X509_get_ext_d2i(peer_cert
, NID_subject_alt_name
, NULL
, NULL
);
211 int numalts
= sk_GENERAL_NAME_num(altnames
);
212 for (int i
= 0; i
< numalts
; ++i
) {
213 const GENERAL_NAME
*check
= sk_GENERAL_NAME_value(altnames
, i
);
214 if (check
->type
!= GEN_DNS
) {
217 ASN1_STRING
*cn_data
= check
->d
.dNSName
;
219 if ( (*check_func
)(check_data
, cn_data
) == 0) {
220 sk_GENERAL_NAME_pop_free(altnames
, GENERAL_NAME_free
);
224 sk_GENERAL_NAME_pop_free(altnames
, GENERAL_NAME_free
);
229 static int check_domain( void *check_data
, ASN1_STRING
*cn_data
)
232 const char *server
= (const char *)check_data
;
234 if (cn_data
->length
== 0)
235 return 1; // zero length cn, ignore
237 if (cn_data
->length
> (int)sizeof(cn
) - 1)
238 return 1; //if does not fit our buffer just ignore
240 char *s
= reinterpret_cast<char*>(cn_data
->data
);
242 for (int i
= 0; i
< cn_data
->length
; ++i
, ++d
, ++s
) {
244 return 1; // always a domain mismatch. contains 0x00
247 cn
[cn_data
->length
] = '\0';
248 debugs(83, 4, "Verifying server domain " << server
<< " to certificate name/subjectAltName " << cn
);
249 return matchDomainName(server
, (cn
[0] == '*' ? cn
+ 1 : cn
), mdnRejectSubsubDomains
);
252 bool Ssl::checkX509ServerValidity(X509
*cert
, const char *server
)
254 return matchX509CommonNames(cert
, (void *)server
, check_domain
);
257 /// adjusts OpenSSL validation results for each verified certificate in ctx
258 /// OpenSSL "verify_callback function" (\ref OpenSSL_vcb_disambiguation)
260 ssl_verify_cb(int ok
, X509_STORE_CTX
* ctx
)
262 // preserve original ctx->error before SSL_ calls can overwrite it
263 Security::ErrorCode error_no
= ok
? SSL_ERROR_NONE
: X509_STORE_CTX_get_error(ctx
);
265 char buffer
[256] = "";
266 SSL
*ssl
= (SSL
*)X509_STORE_CTX_get_ex_data(ctx
, SSL_get_ex_data_X509_STORE_CTX_idx());
267 SSL_CTX
*sslctx
= SSL_get_SSL_CTX(ssl
);
268 SBuf
*server
= (SBuf
*)SSL_get_ex_data(ssl
, ssl_ex_index_server
);
269 void *dont_verify_domain
= SSL_CTX_get_ex_data(sslctx
, ssl_ctx_ex_index_dont_verify_domain
);
270 ACLChecklist
*check
= (ACLChecklist
*)SSL_get_ex_data(ssl
, ssl_ex_index_cert_error_check
);
271 X509
*peeked_cert
= (X509
*)SSL_get_ex_data(ssl
, ssl_ex_index_ssl_peeked_cert
);
272 Security::CertPointer peer_cert
;
273 peer_cert
.resetAndLock(X509_STORE_CTX_get0_cert(ctx
));
275 X509_NAME_oneline(X509_get_subject_name(peer_cert
.get()), buffer
, sizeof(buffer
));
277 // detect infinite loops
278 uint32_t *validationCounter
= static_cast<uint32_t *>(SSL_get_ex_data(ssl
, ssl_ex_index_ssl_validation_counter
));
279 if (!validationCounter
) {
280 validationCounter
= new uint32_t(1);
281 SSL_set_ex_data(ssl
, ssl_ex_index_ssl_validation_counter
, validationCounter
);
283 // overflows allowed if SQUID_CERT_VALIDATION_ITERATION_MAX >= UINT32_MAX
284 (*validationCounter
)++;
287 if ((*validationCounter
) >= SQUID_CERT_VALIDATION_ITERATION_MAX
) {
288 ok
= 0; // or the validation loop will never stop
289 error_no
= SQUID_X509_V_ERR_INFINITE_VALIDATION
;
290 debugs(83, 2, "SQUID_X509_V_ERR_INFINITE_VALIDATION: " <<
291 *validationCounter
<< " iterations while checking " << buffer
);
295 debugs(83, 5, "SSL Certificate signature OK: " << buffer
);
297 // Check for domain mismatch only if the current certificate is the peer certificate.
298 if (!dont_verify_domain
&& server
&& peer_cert
.get() == X509_STORE_CTX_get_current_cert(ctx
)) {
299 if (!Ssl::checkX509ServerValidity(peer_cert
.get(), server
->c_str())) {
300 debugs(83, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " << buffer
<< " does not match domainname " << server
);
302 error_no
= SQUID_X509_V_ERR_DOMAIN_MISMATCH
;
307 if (ok
&& peeked_cert
) {
308 // Check whether the already peeked certificate matches the new one.
309 if (X509_cmp(peer_cert
.get(), peeked_cert
) != 0) {
310 debugs(83, 2, "SQUID_X509_V_ERR_CERT_CHANGE: Certificate " << buffer
<< " does not match peeked certificate");
312 error_no
= SQUID_X509_V_ERR_CERT_CHANGE
;
316 if (!ok
&& error_no
== X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY
) {
317 if (const auto params
= Ssl::VerifyCallbackParameters::Find(*ssl
)) {
318 if (params
->callerHandlesMissingCertificates
) {
319 debugs(83, 3, "hiding X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY");
320 params
->hidMissingIssuer
= true;
327 Security::CertPointer broken_cert
;
328 broken_cert
.resetAndLock(X509_STORE_CTX_get_current_cert(ctx
));
330 broken_cert
= peer_cert
;
332 Security::CertErrors
*errs
= static_cast<Security::CertErrors
*>(SSL_get_ex_data(ssl
, ssl_ex_index_ssl_errors
));
333 const int depth
= X509_STORE_CTX_get_error_depth(ctx
);
335 errs
= new Security::CertErrors(Security::CertError(error_no
, broken_cert
, depth
));
336 if (!SSL_set_ex_data(ssl
, ssl_ex_index_ssl_errors
, (void *)errs
)) {
337 debugs(83, 2, "Failed to set ssl error_no in ssl_verify_cb: Certificate " << buffer
);
341 } else // remember another error number
342 errs
->push_back_unique(Security::CertError(error_no
, broken_cert
, depth
));
344 if (const char *err_descr
= Ssl::GetErrorDescr(error_no
))
345 debugs(83, 5, err_descr
<< ": " << buffer
);
347 debugs(83, DBG_IMPORTANT
, "SSL unknown certificate error " << error_no
<< " in " << buffer
);
349 // Check if the certificate error can be bypassed.
350 // Infinity validation loop errors can not bypassed.
351 if (error_no
!= SQUID_X509_V_ERR_INFINITE_VALIDATION
) {
353 ACLFilledChecklist
*filledCheck
= Filled(check
);
354 assert(!filledCheck
->sslErrors
);
355 filledCheck
->sslErrors
= new Security::CertErrors(Security::CertError(error_no
, broken_cert
));
356 filledCheck
->serverCert
= peer_cert
;
357 if (check
->fastCheck().allowed()) {
358 debugs(83, 3, "bypassing SSL error " << error_no
<< " in " << buffer
);
361 debugs(83, 5, "confirming SSL error " << error_no
);
363 delete filledCheck
->sslErrors
;
364 filledCheck
->sslErrors
= NULL
;
365 filledCheck
->serverCert
.reset();
367 // If the certificate validator is used then we need to allow all errors and
368 // pass them to certificate validator for more processing
369 else if (Ssl::TheConfig
.ssl_crt_validator
) {
375 if (Ssl::TheConfig
.ssl_crt_validator
) {
376 // Check if we have stored certificates chain. Store if not.
377 if (!SSL_get_ex_data(ssl
, ssl_ex_index_ssl_cert_chain
)) {
378 STACK_OF(X509
) *certStack
= X509_STORE_CTX_get1_chain(ctx
);
379 if (certStack
&& !SSL_set_ex_data(ssl
, ssl_ex_index_ssl_cert_chain
, certStack
))
380 sk_X509_pop_free(certStack
, X509_free
);
384 if (!ok
&& !SSL_get_ex_data(ssl
, ssl_ex_index_ssl_error_detail
) ) {
386 // Find the broken certificate. It may be intermediate.
387 Security::CertPointer
broken_cert(peer_cert
); // reasonable default if search fails
388 // Our SQUID_X509_V_ERR_DOMAIN_MISMATCH implies peer_cert is at fault.
389 if (error_no
!= SQUID_X509_V_ERR_DOMAIN_MISMATCH
) {
390 if (auto *last_used_cert
= X509_STORE_CTX_get_current_cert(ctx
))
391 broken_cert
.resetAndLock(last_used_cert
);
394 std::unique_ptr
<Security::ErrorDetail::Pointer
> edp(new Security::ErrorDetail::Pointer(
395 new Security::ErrorDetail(error_no
, peer_cert
, broken_cert
)));
396 if (SSL_set_ex_data(ssl
, ssl_ex_index_ssl_error_detail
, edp
.get()))
399 debugs(83, 2, "failed to store a " << buffer
<< " error detail: " << *edp
);
406 Ssl::ConfigurePeerVerification(Security::ContextPointer
&ctx
, const Security::ParsedPortFlags flags
)
410 // assume each flag is exclusive; flags creator must check this assumption
411 if (flags
& SSL_FLAG_DONT_VERIFY_PEER
) {
412 debugs(83, DBG_IMPORTANT
, "SECURITY WARNING: Peer certificates are not verified for validity!");
413 debugs(83, DBG_IMPORTANT
, "UPGRADE NOTICE: The DONT_VERIFY_PEER flag is deprecated. Remove the clientca= option to disable client certificates.");
414 mode
= SSL_VERIFY_NONE
;
416 else if (flags
& SSL_FLAG_DELAYED_AUTH
) {
417 debugs(83, DBG_PARSE_NOTE(3), "not requesting client certificates until ACL processing requires one");
418 mode
= SSL_VERIFY_NONE
;
420 else if (flags
& SSL_FLAG_CONDITIONAL_AUTH
) {
421 debugs(83, DBG_PARSE_NOTE(3), "will request the client certificate but ignore its absense");
422 mode
= SSL_VERIFY_PEER
;
425 debugs(83, DBG_PARSE_NOTE(3), "Requiring client certificates.");
426 mode
= SSL_VERIFY_PEER
|SSL_VERIFY_FAIL_IF_NO_PEER_CERT
;
429 SSL_CTX_set_verify(ctx
.get(), mode
, (mode
!= SSL_VERIFY_NONE
) ? ssl_verify_cb
: nullptr);
433 Ssl::DisablePeerVerification(Security::ContextPointer
&ctx
)
435 debugs(83, DBG_PARSE_NOTE(3), "Not requiring any client certificates");
436 SSL_CTX_set_verify(ctx
.get(),SSL_VERIFY_NONE
,nullptr);
439 static int VerifyCtxCertificates(X509_STORE_CTX
*ctx
, STACK_OF(X509
) *extraCerts
);
442 Ssl::VerifyConnCertificates(Security::Connection
&sconn
, const Ssl::X509_STACK_Pointer
&extraCerts
)
444 const auto peerCertificatesChain
= SSL_get_peer_cert_chain(&sconn
);
446 // TODO: Replace debugs/return false with returning ErrorDetail::Pointer.
447 // Using Security::ErrorDetail terminology, errors in _this_ function are
448 // "non-validation errors", but VerifyCtxCertificates() errors may be
449 // "certificate validation errors". Callers detail SQUID_TLS_ERR_CONNECT.
450 // Some details should be created right here. Others extracted from OpenSSL.
451 // Why not throw? Most of the reasons detailed in the following commit apply
452 // here as well: https://github.com/measurement-factory/squid/commit/e862d33
454 if (!peerCertificatesChain
|| sk_X509_num(peerCertificatesChain
) == 0) {
455 debugs(83, 2, "no server certificates");
459 const auto verificationStore
= SSL_CTX_get_cert_store(SSL_get_SSL_CTX(&sconn
));
460 if (!verificationStore
) {
461 debugs(83, 2, "no certificate store");
465 const X509_STORE_CTX_Pointer
storeCtx(X509_STORE_CTX_new());
467 debugs(83, 2, "cannot create X509_STORE_CTX; likely OOM");
471 const auto peerCert
= sk_X509_value(peerCertificatesChain
, 0);
472 if (!X509_STORE_CTX_init(storeCtx
.get(), verificationStore
, peerCert
, peerCertificatesChain
)) {
473 debugs(83, 2, "cannot initialize X509_STORE_CTX");
477 #if defined(SSL_CERT_FLAG_SUITEB_128_LOS)
478 // overwrite context Suite B (RFC 5759) flags with connection non-defaults
479 // SSL_set_cert_flags() return type is long, but its implementation actually
480 // returns an unsigned long flags value expected by X509_STORE_CTX_set_flags
481 const unsigned long certFlags
= SSL_set_cert_flags(&sconn
, 0);
482 if (const auto suiteBflags
= certFlags
& SSL_CERT_FLAG_SUITEB_128_LOS
)
483 X509_STORE_CTX_set_flags(storeCtx
.get(), suiteBflags
);
486 if (!X509_STORE_CTX_set_ex_data(storeCtx
.get(), SSL_get_ex_data_X509_STORE_CTX_idx(), &sconn
)) {
487 debugs(83, 2, "cannot attach SSL object to X509_STORE_CTX");
491 // If we ever add DANE support to Squid, we will supply DANE details here:
492 // X509_STORE_CTX_set0_dane(storeCtx.get(), SSL_get0_dane(&sconn));
494 // tell OpenSSL we are verifying a server certificate
495 if (!X509_STORE_CTX_set_default(storeCtx
.get(), "ssl_server")) {
496 debugs(83, 2, "cannot set default verification method to ssl_server");
500 // overwrite context "verification parameters" with connection non-defaults
501 const auto param
= X509_STORE_CTX_get0_param(storeCtx
.get());
503 debugs(83, 2, "no context verification parameters");
506 #if defined(HAVE_X509_VERIFY_PARAM_SET_AUTH_LEVEL)
507 X509_VERIFY_PARAM_set_auth_level(param
, SSL_get_security_level(&sconn
));
509 if (!X509_VERIFY_PARAM_set1(param
, SSL_get0_param(&sconn
))) {
510 debugs(83, 2, "cannot overwrite context verification parameters");
514 // copy any connection "verify_callback function" to the validation context
515 // (\ref OpenSSL_vcb_disambiguation)
516 if (const auto cb
= SSL_get_verify_callback(&sconn
))
517 X509_STORE_CTX_set_verify_cb(storeCtx
.get(), cb
);
519 // verify the server certificate chain in the prepared validation context
520 if (VerifyCtxCertificates(storeCtx
.get(), extraCerts
.get()) <= 0) {
521 // see also: ssl_verify_cb() details errors via ssl_ex_index_ssl_errors
522 const auto verifyResult
= X509_STORE_CTX_get_error(storeCtx
.get());
523 debugs(83, 3, "verification failure: " << verifyResult
<< ' ' << X509_verify_cert_error_string(verifyResult
));
527 debugs(83, 7, "success");
531 /* Ssl::VerifyCallbackParameters */
533 Ssl::VerifyCallbackParameters
*
534 Ssl::VerifyCallbackParameters::Find(Security::Connection
&sconn
)
536 return static_cast<VerifyCallbackParameters
*>(SSL_get_ex_data(&sconn
, ssl_ex_index_verify_callback_parameters
));
539 Ssl::VerifyCallbackParameters
*
540 Ssl::VerifyCallbackParameters::New(Security::Connection
&sconn
)
543 const auto parameters
= new VerifyCallbackParameters();
544 if (!SSL_set_ex_data(&sconn
, ssl_ex_index_verify_callback_parameters
, parameters
)) {
546 throw TextException("SSL_set_ex_data() failed; likely OOM", Here());
551 Ssl::VerifyCallbackParameters
&
552 Ssl::VerifyCallbackParameters::At(Security::Connection
&sconn
)
554 const auto parameters
= Find(sconn
);
559 // "dup" function for SSL_get_ex_new_index("cert_err_check")
560 #if SQUID_USE_CONST_CRYPTO_EX_DATA_DUP
562 ssl_dupAclChecklist(CRYPTO_EX_DATA
*, const CRYPTO_EX_DATA
*, void *,
566 ssl_dupAclChecklist(CRYPTO_EX_DATA
*, CRYPTO_EX_DATA
*, void *,
570 // We do not support duplication of ACLCheckLists.
571 // If duplication is needed, we can count copies with cbdata.
576 // "free" function for SSL_get_ex_new_index("cert_err_check")
578 ssl_freeAclChecklist(void *, void *ptr
, CRYPTO_EX_DATA
*,
581 delete static_cast<ACLChecklist
*>(ptr
); // may be NULL
584 // "free" function for SSL_get_ex_new_index("ssl_error_detail")
586 ssl_free_ErrorDetail(void *, void *ptr
, CRYPTO_EX_DATA
*,
589 const auto errDetail
= static_cast<Security::ErrorDetail::Pointer
*>(ptr
);
594 ssl_free_SslErrors(void *, void *ptr
, CRYPTO_EX_DATA
*,
597 Security::CertErrors
*errs
= static_cast <Security::CertErrors
*>(ptr
);
601 // "free" function for SSL_get_ex_new_index("ssl_ex_index_ssl_validation_counter")
603 ssl_free_int(void *, void *ptr
, CRYPTO_EX_DATA
*,
606 uint32_t *counter
= static_cast <uint32_t *>(ptr
);
610 /// \ingroup ServerProtocolSSLInternal
611 /// Callback handler function to release STACK_OF(X509) "ex" data stored
612 /// in an SSL object.
614 ssl_free_CertChain(void *, void *ptr
, CRYPTO_EX_DATA
*,
617 STACK_OF(X509
) *certsChain
= static_cast <STACK_OF(X509
) *>(ptr
);
618 sk_X509_pop_free(certsChain
,X509_free
);
621 // "free" function for X509 certificates
623 ssl_free_X509(void *, void *ptr
, CRYPTO_EX_DATA
*,
626 X509
*cert
= static_cast <X509
*>(ptr
);
630 // "free" function for SBuf
632 ssl_free_SBuf(void *, void *ptr
, CRYPTO_EX_DATA
*,
635 SBuf
*buf
= static_cast <SBuf
*>(ptr
);
639 /// "free" function for the ssl_ex_index_verify_callback_parameters entry
641 ssl_free_VerifyCallbackParameters(void *, void *ptr
, CRYPTO_EX_DATA
*,
644 delete static_cast<Ssl::VerifyCallbackParameters
*>(ptr
);
648 Ssl::Initialize(void)
650 static bool initialized
= false;
655 SQUID_OPENSSL_init_ssl();
657 #if !defined(OPENSSL_NO_ENGINE)
658 if (::Config
.SSL
.ssl_engine
) {
659 ENGINE_load_builtin_engines();
661 if (!(e
= ENGINE_by_id(::Config
.SSL
.ssl_engine
)))
662 fatalf("Unable to find SSL engine '%s'\n", ::Config
.SSL
.ssl_engine
);
664 if (!ENGINE_set_default(e
, ENGINE_METHOD_ALL
)) {
665 const auto ssl_error
= ERR_get_error();
666 fatalf("Failed to initialise SSL engine: %s\n", Security::ErrorString(ssl_error
));
670 if (::Config
.SSL
.ssl_engine
)
671 fatalf("Your OpenSSL has no SSL engine support\n");
674 const char *defName
= ::Config
.SSL
.certSignHash
? ::Config
.SSL
.certSignHash
: SQUID_SSL_SIGN_HASH_IF_NONE
;
675 Ssl::DefaultSignHash
= EVP_get_digestbyname(defName
);
676 if (!Ssl::DefaultSignHash
)
677 fatalf("Sign hash '%s' is not supported\n", defName
);
679 ssl_ex_index_server
= SSL_get_ex_new_index(0, (void *) "server", NULL
, NULL
, ssl_free_SBuf
);
680 ssl_ctx_ex_index_dont_verify_domain
= SSL_CTX_get_ex_new_index(0, (void *) "dont_verify_domain", NULL
, NULL
, NULL
);
681 ssl_ex_index_cert_error_check
= SSL_get_ex_new_index(0, (void *) "cert_error_check", NULL
, &ssl_dupAclChecklist
, &ssl_freeAclChecklist
);
682 ssl_ex_index_ssl_error_detail
= SSL_get_ex_new_index(0, (void *) "ssl_error_detail", NULL
, NULL
, &ssl_free_ErrorDetail
);
683 ssl_ex_index_ssl_peeked_cert
= SSL_get_ex_new_index(0, (void *) "ssl_peeked_cert", NULL
, NULL
, &ssl_free_X509
);
684 ssl_ex_index_ssl_errors
= SSL_get_ex_new_index(0, (void *) "ssl_errors", NULL
, NULL
, &ssl_free_SslErrors
);
685 ssl_ex_index_ssl_cert_chain
= SSL_get_ex_new_index(0, (void *) "ssl_cert_chain", NULL
, NULL
, &ssl_free_CertChain
);
686 ssl_ex_index_ssl_validation_counter
= SSL_get_ex_new_index(0, (void *) "ssl_validation_counter", NULL
, NULL
, &ssl_free_int
);
687 ssl_ex_index_verify_callback_parameters
= SSL_get_ex_new_index(0, (void *) "verify_callback_parameters", nullptr, nullptr, &ssl_free_VerifyCallbackParameters
);
691 Ssl::InitServerContext(Security::ContextPointer
&ctx
, AnyP::PortCfg
&port
)
700 Ssl::InitClientContext(Security::ContextPointer
&ctx
, Security::PeerOptions
&peer
, Security::ParsedPortFlags fl
)
705 if (!peer
.sslCipher
.isEmpty()) {
706 debugs(83, 5, "Using chiper suite " << peer
.sslCipher
<< ".");
708 const char *cipher
= peer
.sslCipher
.c_str();
709 if (!SSL_CTX_set_cipher_list(ctx
.get(), cipher
)) {
710 const auto ssl_error
= ERR_get_error();
711 fatalf("Failed to set SSL cipher suite '%s': %s\n",
712 cipher
, Security::ErrorString(ssl_error
));
716 if (!peer
.certs
.empty()) {
717 // TODO: support loading multiple cert/key pairs
718 auto &keys
= peer
.certs
.front();
719 if (!keys
.certFile
.isEmpty()) {
720 debugs(83, DBG_IMPORTANT
, "Using certificate in " << keys
.certFile
);
722 const char *certfile
= keys
.certFile
.c_str();
723 if (!SSL_CTX_use_certificate_chain_file(ctx
.get(), certfile
)) {
724 const auto ssl_error
= ERR_get_error();
725 fatalf("Failed to acquire SSL certificate '%s': %s\n",
726 certfile
, Security::ErrorString(ssl_error
));
729 debugs(83, DBG_IMPORTANT
, "Using private key in " << keys
.privateKeyFile
);
730 const char *keyfile
= keys
.privateKeyFile
.c_str();
731 ssl_ask_password(ctx
.get(), keyfile
);
733 if (!SSL_CTX_use_PrivateKey_file(ctx
.get(), keyfile
, SSL_FILETYPE_PEM
)) {
734 const auto ssl_error
= ERR_get_error();
735 fatalf("Failed to acquire SSL private key '%s': %s\n",
736 keyfile
, Security::ErrorString(ssl_error
));
739 debugs(83, 5, "Comparing private and public SSL keys.");
741 if (!SSL_CTX_check_private_key(ctx
.get())) {
742 const auto ssl_error
= ERR_get_error();
743 fatalf("SSL private key '%s' does not match public key '%s': %s\n",
744 certfile
, keyfile
, Security::ErrorString(ssl_error
));
749 MaybeSetupRsaCallback(ctx
);
751 Ssl::ConfigurePeerVerification(ctx
, fl
);
756 /// \ingroup ServerProtocolSSLInternal
758 ssl_get_attribute(X509_NAME
* name
, const char *attribute_name
)
760 static char buffer
[1024];
763 if (strcmp(attribute_name
, "DN") == 0) {
764 X509_NAME_oneline(name
, buffer
, sizeof(buffer
));
766 int nid
= OBJ_txt2nid(const_cast<char *>(attribute_name
));
768 debugs(83, DBG_IMPORTANT
, "WARNING: Unknown SSL attribute name '" << attribute_name
<< "'");
771 X509_NAME_get_text_by_NID(name
, nid
, buffer
, sizeof(buffer
));
774 return *buffer
? buffer
: nullptr;
777 /// \ingroup ServerProtocolSSLInternal
779 Ssl::GetX509UserAttribute(X509
* cert
, const char *attribute_name
)
787 name
= X509_get_subject_name(cert
);
789 ret
= ssl_get_attribute(name
, attribute_name
);
795 Ssl::GetX509Fingerprint(X509
* cert
, const char *)
797 static char buf
[1024];
802 unsigned char md
[EVP_MAX_MD_SIZE
];
803 if (!X509_digest(cert
, EVP_sha1(), md
, &n
))
806 assert(3 * n
+ 1 < sizeof(buf
));
809 for (unsigned int i
=0; i
< n
; ++i
, s
+= 3) {
810 const char term
= (i
+ 1 < n
) ? ':' : '\0';
811 snprintf(s
, 4, "%02X%c", md
[i
], term
);
818 Ssl::GetX509PEM(X509
* cert
)
822 Ssl::BIO_Pointer
bio(BIO_new(BIO_s_mem()));
823 PEM_write_bio_X509(bio
.get(), cert
);
826 const auto len
= BIO_get_mem_data(bio
.get(), &ptr
);
827 return SBuf(ptr
, len
);
830 /// \ingroup ServerProtocolSSLInternal
832 Ssl::GetX509CAAttribute(X509
* cert
, const char *attribute_name
)
841 name
= X509_get_issuer_name(cert
);
843 ret
= ssl_get_attribute(name
, attribute_name
);
848 const char *sslGetUserAttribute(SSL
*ssl
, const char *attribute_name
)
853 X509
*cert
= SSL_get_peer_certificate(ssl
);
855 const char *attr
= Ssl::GetX509UserAttribute(cert
, attribute_name
);
861 const char *sslGetCAAttribute(SSL
*ssl
, const char *attribute_name
)
866 X509
*cert
= SSL_get_peer_certificate(ssl
);
868 const char *attr
= Ssl::GetX509CAAttribute(cert
, attribute_name
);
875 sslGetUserEmail(SSL
* ssl
)
877 return sslGetUserAttribute(ssl
, "emailAddress");
881 sslGetUserCertificatePEM(SSL
*ssl
)
885 if (const auto cert
= SSL_get_peer_certificate(ssl
))
886 return Ssl::GetX509PEM(cert
);
892 sslGetUserCertificateChainPEM(SSL
*ssl
)
896 auto chain
= SSL_get_peer_cert_chain(ssl
);
899 return sslGetUserCertificatePEM(ssl
);
901 Ssl::BIO_Pointer
bio(BIO_new(BIO_s_mem()));
903 for (int i
= 0; i
< sk_X509_num(chain
); ++i
) {
904 X509
*cert
= sk_X509_value(chain
, i
);
905 PEM_write_bio_X509(bio
.get(), cert
);
909 const auto len
= BIO_get_mem_data(bio
.get(), &ptr
);
910 return SBuf(ptr
, len
);
913 /// Create SSL context and apply ssl certificate and private key to it.
914 Security::ContextPointer
915 Ssl::createSSLContext(Security::CertPointer
& x509
, Security::PrivateKeyPointer
& pkey
, Security::ServerOptions
&options
)
917 Security::ContextPointer
ctx(options
.createBlankContext());
919 if (!SSL_CTX_use_certificate(ctx
.get(), x509
.get()))
920 return Security::ContextPointer();
922 if (!SSL_CTX_use_PrivateKey(ctx
.get(), pkey
.get()))
923 return Security::ContextPointer();
925 if (!options
.updateContextConfig(ctx
))
926 return Security::ContextPointer();
931 Security::ContextPointer
932 Ssl::GenerateSslContextUsingPkeyAndCertFromMemory(const char * data
, Security::ServerOptions
&options
, bool trusted
)
934 Security::CertPointer cert
;
935 Security::PrivateKeyPointer pkey
;
936 if (!readCertAndPrivateKeyFromMemory(cert
, pkey
, data
) || !cert
|| !pkey
)
937 return Security::ContextPointer();
939 Security::ContextPointer
ctx(createSSLContext(cert
, pkey
, options
));
941 Ssl::chainCertificatesToSSLContext(ctx
, options
);
945 Security::ContextPointer
946 Ssl::GenerateSslContext(CertificateProperties
const &properties
, Security::ServerOptions
&options
, bool trusted
)
948 Security::CertPointer cert
;
949 Security::PrivateKeyPointer pkey
;
950 if (!generateSslCertificate(cert
, pkey
, properties
) || !cert
|| !pkey
)
951 return Security::ContextPointer();
953 Security::ContextPointer
ctx(createSSLContext(cert
, pkey
, options
));
955 Ssl::chainCertificatesToSSLContext(ctx
, options
);
960 Ssl::chainCertificatesToSSLContext(Security::ContextPointer
&ctx
, Security::ServerOptions
&options
)
963 // Add signing certificate to the certificates chain
964 X509
*signingCert
= options
.signingCa
.cert
.get();
965 if (SSL_CTX_add_extra_chain_cert(ctx
.get(), signingCert
)) {
966 // increase the certificate lock
967 X509_up_ref(signingCert
);
969 const auto ssl_error
= ERR_get_error();
970 debugs(33, DBG_IMPORTANT
, "WARNING: can not add signing certificate to SSL context chain: " << Security::ErrorString(ssl_error
));
973 for (auto cert
: options
.signingCa
.chain
) {
974 if (SSL_CTX_add_extra_chain_cert(ctx
.get(), cert
.get())) {
975 // increase the certificate lock
976 X509_up_ref(cert
.get());
978 const auto error
= ERR_get_error();
979 debugs(83, DBG_IMPORTANT
, "WARNING: can not add certificate to SSL dynamic context chain: " << Security::ErrorString(error
));
985 Ssl::configureUnconfiguredSslContext(Security::ContextPointer
&ctx
, Ssl::CertSignAlgorithm signAlgorithm
,AnyP::PortCfg
&port
)
987 if (ctx
&& signAlgorithm
== Ssl::algSignTrusted
)
988 Ssl::chainCertificatesToSSLContext(ctx
, port
.secure
);
992 Ssl::configureSSL(SSL
*ssl
, CertificateProperties
const &properties
, AnyP::PortCfg
&port
)
994 Security::CertPointer cert
;
995 Security::PrivateKeyPointer pkey
;
996 if (!generateSslCertificate(cert
, pkey
, properties
))
1005 if (!SSL_use_certificate(ssl
, cert
.get()))
1008 if (!SSL_use_PrivateKey(ssl
, pkey
.get()))
1015 Ssl::configureSSLUsingPkeyAndCertFromMemory(SSL
*ssl
, const char *data
, AnyP::PortCfg
&port
)
1017 Security::CertPointer cert
;
1018 Security::PrivateKeyPointer pkey
;
1019 if (!readCertAndPrivateKeyFromMemory(cert
, pkey
, data
))
1025 if (!SSL_use_certificate(ssl
, cert
.get()))
1028 if (!SSL_use_PrivateKey(ssl
, pkey
.get()))
1035 Ssl::verifySslCertificate(const Security::ContextPointer
&ctx
, CertificateProperties
const &properties
)
1037 #if HAVE_SSL_CTX_GET0_CERTIFICATE
1038 X509
* cert
= SSL_CTX_get0_certificate(ctx
.get());
1039 #elif SQUID_USE_SSLGETCERTIFICATE_HACK
1040 // SSL_get_certificate is buggy in openssl versions 1.0.1d and 1.0.1e
1041 // Try to retrieve certificate directly from Security::ContextPointer object
1042 X509
***pCert
= (X509
***)ctx
->cert
;
1043 X509
* cert
= pCert
&& *pCert
? **pCert
: NULL
;
1044 #elif SQUID_SSLGETCERTIFICATE_BUGGY
1048 // Temporary ssl for getting X509 certificate from SSL_CTX.
1049 Security::SessionPointer
ssl(Security::NewSessionObject(ctx
));
1050 X509
* cert
= SSL_get_certificate(ssl
.get());
1054 const auto time_notBefore
= X509_getm_notBefore(cert
);
1055 const auto time_notAfter
= X509_getm_notAfter(cert
);
1056 return (X509_cmp_current_time(time_notBefore
) < 0 && X509_cmp_current_time(time_notAfter
) > 0);
1060 Ssl::setClientSNI(SSL
*ssl
, const char *fqdn
)
1062 const Ip::Address
test(fqdn
);
1063 if (!test
.isAnyAddr())
1064 return; // raw IP is inappropriate for SNI
1066 //The SSL_CTRL_SET_TLSEXT_HOSTNAME is a openssl macro which indicates
1067 // if the TLS servername extension (SNI) is enabled in openssl library.
1068 #if defined(SSL_CTRL_SET_TLSEXT_HOSTNAME)
1069 if (!SSL_set_tlsext_host_name(ssl
, fqdn
)) {
1070 const auto ssl_error
= ERR_get_error();
1071 debugs(83, 3, "WARNING: unable to set TLS servername extension (SNI): " <<
1072 Security::ErrorString(ssl_error
) << "\n");
1075 debugs(83, 7, "no support for TLS servername extension (SNI)");
1080 Ssl::findIssuerUri(X509
*cert
)
1082 AUTHORITY_INFO_ACCESS
*info
;
1085 info
= static_cast<AUTHORITY_INFO_ACCESS
*>(X509_get_ext_d2i(cert
, NID_info_access
, NULL
, NULL
));
1089 static char uri
[MAX_URL
];
1092 for (int i
= 0; i
< sk_ACCESS_DESCRIPTION_num(info
); i
++) {
1093 ACCESS_DESCRIPTION
*ad
= sk_ACCESS_DESCRIPTION_value(info
, i
);
1094 if (OBJ_obj2nid(ad
->method
) == NID_ad_ca_issuers
) {
1095 if (ad
->location
->type
== GEN_URI
) {
1097 reinterpret_cast<const char *>(
1098 ASN1_STRING_get0_data(ad
->location
->d
.uniformResourceIdentifier
)
1105 AUTHORITY_INFO_ACCESS_free(info
);
1106 return uri
[0] != '\0' ? uri
: nullptr;
1110 Ssl::loadCerts(const char *certsFile
, Ssl::CertsIndexedList
&list
)
1112 BIO
*in
= BIO_new_file(certsFile
, "r");
1114 debugs(83, DBG_IMPORTANT
, "Failed to open '" << certsFile
<< "' to load certificates");
1119 while((aCert
= PEM_read_bio_X509(in
, NULL
, NULL
, NULL
))) {
1120 static char buffer
[2048];
1121 X509_NAME_oneline(X509_get_subject_name(aCert
), buffer
, sizeof(buffer
));
1122 list
.insert(std::pair
<SBuf
, X509
*>(SBuf(buffer
), aCert
));
1124 debugs(83, 4, "Loaded " << list
.size() << " certificates from file: '" << certsFile
<< "'");
1129 /// quickly find the issuer certificate of a certificate cert in the
1130 /// Ssl::CertsIndexedList list
1132 findCertIssuerFast(Ssl::CertsIndexedList
&list
, X509
*cert
)
1134 static char buffer
[2048];
1136 if (X509_NAME
*issuerName
= X509_get_issuer_name(cert
))
1137 X509_NAME_oneline(issuerName
, buffer
, sizeof(buffer
));
1141 const auto ret
= list
.equal_range(SBuf(buffer
));
1142 for (Ssl::CertsIndexedList::iterator it
= ret
.first
; it
!= ret
.second
; ++it
) {
1143 X509
*issuer
= it
->second
;
1144 if (X509_check_issued(issuer
, cert
) == X509_V_OK
) {
1151 /// slowly find the issuer certificate of a given cert using linear search
1153 sk_x509_findIssuer(const STACK_OF(X509
) *sk
, X509
*cert
)
1158 const auto certCount
= sk_X509_num(sk
);
1159 for (int i
= 0; i
< certCount
; ++i
) {
1160 const auto issuer
= sk_X509_value(sk
, i
);
1161 if (X509_check_issued(issuer
, cert
) == X509_V_OK
)
1167 /// finds issuer of a given certificate in CA store of the given connContext
1168 /// \returns the cert issuer (after increasing its reference count) or nil
1170 findIssuerInCaDb(X509
*cert
, const Security::ContextPointer
&connContext
)
1175 X509_STORE_CTX
*storeCtx
= X509_STORE_CTX_new();
1177 debugs(83, DBG_IMPORTANT
, "Failed to allocate STORE_CTX object");
1181 X509
*issuer
= nullptr;
1182 X509_STORE
*store
= SSL_CTX_get_cert_store(connContext
.get());
1183 if (X509_STORE_CTX_init(storeCtx
, store
, nullptr, nullptr)) {
1184 const auto ret
= X509_STORE_CTX_get1_issuer(&issuer
, storeCtx
, cert
);
1188 debugs(83, 5, "found " << X509_NAME_oneline(X509_get_subject_name(issuer
), buffer
, sizeof(buffer
)));
1190 debugs(83, ret
< 0 ? 2 : 3, "not found or failure: " << ret
);
1194 const auto ssl_error
= ERR_get_error();
1195 debugs(83, DBG_IMPORTANT
, "Failed to initialize STORE_CTX object: " << Security::ErrorString(ssl_error
));
1198 X509_STORE_CTX_free(storeCtx
);
1203 Security::CertPointer
1204 Ssl::findIssuerCertificate(X509
*cert
, const STACK_OF(X509
) *serverCertificates
, const Security::ContextPointer
&context
)
1208 // check certificate chain, if any
1209 if (const auto issuer
= serverCertificates
? sk_x509_findIssuer(serverCertificates
, cert
) : nullptr) {
1210 X509_up_ref(issuer
);
1211 return Security::CertPointer(issuer
);
1214 // check untrusted certificates
1215 if (const auto issuer
= findCertIssuerFast(SquidUntrustedCerts
, cert
)) {
1216 X509_up_ref(issuer
);
1217 return Security::CertPointer(issuer
);
1220 // check trusted CA certificates
1221 if (const auto issuer
= findIssuerInCaDb(cert
, context
)) {
1222 // no X509_up_ref(issuer) because findIssuerInCaDb() ups reference count
1223 return Security::CertPointer(issuer
);
1226 return Security::CertPointer(nullptr);
1230 Ssl::missingChainCertificatesUrls(std::queue
<SBuf
> &URIs
, const STACK_OF(X509
) &serverCertificates
, const Security::ContextPointer
&context
)
1232 for (int i
= 0; i
< sk_X509_num(&serverCertificates
); ++i
) {
1233 const auto cert
= sk_X509_value(&serverCertificates
, i
);
1235 if (findIssuerCertificate(cert
, &serverCertificates
, context
))
1238 if (const auto issuerUri
= findIssuerUri(cert
)) {
1239 URIs
.push(SBuf(issuerUri
));
1241 static char name
[2048];
1242 debugs(83, 3, "Issuer certificate for " <<
1243 X509_NAME_oneline(X509_get_subject_name(cert
), name
, sizeof(name
)) <<
1244 " is missing and its URI is not provided");
1248 debugs(83, (URIs
.empty() ? 3 : 5), "found: " << URIs
.size());
1249 return !URIs
.empty();
1252 /// add missing issuer certificates to untrustedCerts
1254 completeIssuers(X509_STORE_CTX
*ctx
, STACK_OF(X509
) &untrustedCerts
)
1256 debugs(83, 2, "completing " << sk_X509_num(&untrustedCerts
) <<
1257 " OpenSSL untrusted certs using " << SquidUntrustedCerts
.size() <<
1258 " configured untrusted certificates");
1260 const X509_VERIFY_PARAM
*param
= X509_STORE_CTX_get0_param(ctx
);
1261 int depth
= X509_VERIFY_PARAM_get_depth(param
);
1262 Security::CertPointer current
;
1263 current
.resetAndLock(X509_STORE_CTX_get0_cert(ctx
));
1265 for (i
= 0; current
&& (i
< depth
); ++i
) {
1266 if (X509_check_issued(current
.get(), current
.get()) == X509_V_OK
) {
1267 // either ctx->cert is itself self-signed or untrustedCerts
1268 // already contain the self-signed current certificate
1272 // untrustedCerts is short, not worth indexing
1273 const Security::ContextPointer nullCtx
;
1274 auto issuer
= Ssl::findIssuerCertificate(current
.get(), &untrustedCerts
, nullCtx
);
1277 sk_X509_push(&untrustedCerts
, issuer
.release());
1281 debugs(83, 2, "exceeded the maximum certificate chain length: " << depth
);
1284 /// Validates certificates while consulting sslproxy_foreign_intermediate_certs
1285 /// and, optionally, the given extra certificates.
1286 /// \returns whatever OpenSSL X509_verify_cert() returns
1288 VerifyCtxCertificates(X509_STORE_CTX
*ctx
, STACK_OF(X509
) *extraCerts
)
1290 // OpenSSL already maintains ctx->untrusted but we cannot modify
1291 // internal OpenSSL list directly. We have to give OpenSSL our own
1292 // list, but it must include certificates on the OpenSSL ctx->untrusted
1293 STACK_OF(X509
) *oldUntrusted
= X509_STORE_CTX_get0_untrusted(ctx
);
1294 // X509_chain_up_ref() increments cert references _and_ dupes the stack
1295 Ssl::X509_STACK_Pointer
untrustedCerts(oldUntrusted
? X509_chain_up_ref(oldUntrusted
) : sk_X509_new_null());
1298 for (int i
= 0; i
< sk_X509_num(extraCerts
); ++i
) {
1299 const auto cert
= sk_X509_value(extraCerts
, i
);
1301 sk_X509_push(untrustedCerts
.get(), cert
);
1305 // If the local untrusted certificates internal database is used
1306 // run completeIssuers to add missing certificates if possible.
1307 if (SquidUntrustedCerts
.size() > 0)
1308 completeIssuers(ctx
, *untrustedCerts
);
1310 X509_STORE_CTX_set0_untrusted(ctx
, untrustedCerts
.get()); // No locking/unlocking, just sets ctx->untrusted
1311 int ret
= X509_verify_cert(ctx
);
1312 X509_STORE_CTX_set0_untrusted(ctx
, oldUntrusted
); // Set back the old untrusted list
1316 /// \interface OpenSSL_vcb_disambiguation
1318 /// OpenSSL has two very different concepts with nearly identical names:
1320 /// a) A (replaceable) certificate verification function -- X509_verify_cert():
1321 /// This function drives the entire certificate verification algorithm.
1322 /// It can be called directly, but is usually called during SSL_connect().
1323 /// OpenSSL calls this function a "verification callback function".
1324 /// SSL_CTX_set_cert_verify_callback(3) replaces X509_verify_cert() default.
1326 /// b) An (optional) certificate verification adjustment callback:
1327 /// This function, if set, is called at the end of (a) to adjust (a) results.
1328 /// It is never called directly, only from (a).
1329 /// OpenSSL calls this function a "verify_callback function".
1330 /// The SSL_CTX_set_verify(3) family of functions sets this function.
1332 /// Validates certificates while consulting sslproxy_foreign_intermediate_certs
1333 /// but without using any dynamically downloaded intermediate certificates.
1334 /// OpenSSL "verification callback function" (\ref OpenSSL_vcb_disambiguation)
1336 untrustedToStoreCtx_cb(X509_STORE_CTX
*ctx
, void *)
1338 debugs(83, 4, "Try to use pre-downloaded intermediate certificates");
1339 return VerifyCtxCertificates(ctx
, nullptr);
1343 Ssl::useSquidUntrusted(SSL_CTX
*sslContext
)
1345 SSL_CTX_set_cert_verify_callback(sslContext
, untrustedToStoreCtx_cb
, NULL
);
1349 Ssl::loadSquidUntrusted(const char *path
)
1351 return Ssl::loadCerts(path
, SquidUntrustedCerts
);
1355 Ssl::unloadSquidUntrusted()
1357 if (SquidUntrustedCerts
.size()) {
1358 for (Ssl::CertsIndexedList::iterator it
= SquidUntrustedCerts
.begin(); it
!= SquidUntrustedCerts
.end(); ++it
) {
1359 X509_free(it
->second
);
1361 SquidUntrustedCerts
.clear();
1365 bool Ssl::generateUntrustedCert(Security::CertPointer
&untrustedCert
, Security::PrivateKeyPointer
&untrustedPkey
, Security::CertPointer
const &cert
, Security::PrivateKeyPointer
const & pkey
)
1367 // Generate the self-signed certificate, using a hard-coded subject prefix
1368 Ssl::CertificateProperties certProperties
;
1369 if (const char *cn
= CommonHostName(cert
.get())) {
1370 certProperties
.commonName
= "Not trusted by \"";
1371 certProperties
.commonName
+= cn
;
1372 certProperties
.commonName
+= "\"";
1373 } else if (const char *org
= getOrganization(cert
.get())) {
1374 certProperties
.commonName
= "Not trusted by \"";
1375 certProperties
.commonName
+= org
;
1376 certProperties
.commonName
+= "\"";
1378 certProperties
.commonName
= "Not trusted";
1379 certProperties
.setCommonName
= true;
1380 // O, OU, and other CA subject fields will be mimicked
1381 // Expiration date and other common properties will be mimicked
1382 certProperties
.signAlgorithm
= Ssl::algSignSelf
;
1383 certProperties
.signWithPkey
.resetAndLock(pkey
.get());
1384 certProperties
.mimicCert
.resetAndLock(cert
.get());
1385 return Ssl::generateSslCertificate(untrustedCert
, untrustedPkey
, certProperties
);
1388 void Ssl::InRamCertificateDbKey(const Ssl::CertificateProperties
&certProperties
, SBuf
&key
)
1390 bool origSignatureAsKey
= false;
1391 if (certProperties
.mimicCert
) {
1392 if (auto *sig
= Ssl::X509_get_signature(certProperties
.mimicCert
)) {
1393 origSignatureAsKey
= true;
1394 key
.append((const char *)sig
->data
, sig
->length
);
1398 if (!origSignatureAsKey
|| certProperties
.setCommonName
) {
1399 // Use common name instead
1400 key
.append(certProperties
.commonName
.c_str());
1402 key
.append(certProperties
.setCommonName
? '1' : '0');
1403 key
.append(certProperties
.setValidAfter
? '1' : '0');
1404 key
.append(certProperties
.setValidBefore
? '1' : '0');
1405 key
.append(certProperties
.signAlgorithm
!= Ssl:: algSignEnd
? certSignAlgorithm(certProperties
.signAlgorithm
) : "-");
1406 key
.append(certProperties
.signHash
? EVP_MD_name(certProperties
.signHash
) : "-");
1408 if (certProperties
.mimicCert
) {
1409 Ssl::BIO_Pointer
bio(BIO_new_SBuf(&key
));
1410 ASN1_item_i2d_bio(ASN1_ITEM_rptr(X509
), bio
.get(), (ASN1_VALUE
*)certProperties
.mimicCert
.get());
1415 bio_sbuf_create(BIO
* bio
)
1417 BIO_set_init(bio
, 0);
1418 BIO_set_data(bio
, NULL
);
1423 bio_sbuf_destroy(BIO
* bio
)
1431 bio_sbuf_write(BIO
* bio
, const char* data
, int len
)
1433 SBuf
*buf
= static_cast<SBuf
*>(BIO_get_data(bio
));
1434 // TODO: Convert exceptions into BIO errors
1435 buf
->append(data
, len
);
1440 bio_sbuf_puts(BIO
* bio
, const char* data
)
1442 // TODO: use bio_sbuf_write() instead
1443 SBuf
*buf
= static_cast<SBuf
*>(BIO_get_data(bio
));
1444 size_t oldLen
= buf
->length();
1446 return buf
->length() - oldLen
;
1450 bio_sbuf_ctrl(BIO
* bio
, int cmd
, long num
, void* ptr
) {
1451 SBuf
*buf
= static_cast<SBuf
*>(BIO_get_data(bio
));
1453 case BIO_CTRL_RESET
:
1454 // TODO: Convert exceptions into BIO errors
1457 case BIO_CTRL_FLUSH
:
1464 BIO
*Ssl::BIO_new_SBuf(SBuf
*buf
)
1466 #if HAVE_LIBCRYPTO_BIO_METH_NEW
1467 static BIO_METHOD
*BioSBufMethods
= nullptr;
1468 if (!BioSBufMethods
) {
1469 BioSBufMethods
= BIO_meth_new(BIO_TYPE_MEM
, "Squid-SBuf");
1470 BIO_meth_set_write(BioSBufMethods
, bio_sbuf_write
);
1471 BIO_meth_set_read(BioSBufMethods
, nullptr);
1472 BIO_meth_set_puts(BioSBufMethods
, bio_sbuf_puts
);
1473 BIO_meth_set_gets(BioSBufMethods
, nullptr);
1474 BIO_meth_set_ctrl(BioSBufMethods
, bio_sbuf_ctrl
);
1475 BIO_meth_set_create(BioSBufMethods
, bio_sbuf_create
);
1476 BIO_meth_set_destroy(BioSBufMethods
, bio_sbuf_destroy
);
1479 static BIO_METHOD
*BioSBufMethods
= new BIO_METHOD({
1492 BIO
*bio
= BIO_new(BioSBufMethods
);
1494 BIO_set_data(bio
, buf
);
1495 BIO_set_init(bio
, 1);
1499 #endif /* USE_OPENSSL */