]> git.ipfire.org Git - thirdparty/squid.git/blob - src/security/PeerConnector.cc
C++11: Remove GnuRegex and all -lregex related code
[thirdparty/squid.git] / src / security / PeerConnector.cc
1 /*
2 * Copyright (C) 1996-2016 The Squid Software Foundation and contributors
3 *
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.
7 */
8
9 /* DEBUG: section 83 TLS Server/Peer negotiation */
10
11 #include "squid.h"
12 #include "acl/FilledChecklist.h"
13 #include "comm/Loops.h"
14 #include "Downloader.h"
15 #include "errorpage.h"
16 #include "fde.h"
17 #include "http/Stream.h"
18 #include "HttpRequest.h"
19 #include "security/NegotiationHistory.h"
20 #include "security/PeerConnector.h"
21 #include "SquidConfig.h"
22 #if USE_OPENSSL
23 #include "ssl/bio.h"
24 #include "ssl/cert_validate_message.h"
25 #include "ssl/Config.h"
26 #include "ssl/helper.h"
27 #endif
28
29 CBDATA_NAMESPACED_CLASS_INIT(Security, PeerConnector);
30
31 Security::PeerConnector::PeerConnector(const Comm::ConnectionPointer &aServerConn, AsyncCall::Pointer &aCallback, const AccessLogEntryPointer &alp, const time_t timeout) :
32 AsyncJob("Security::PeerConnector"),
33 serverConn(aServerConn),
34 al(alp),
35 callback(aCallback),
36 negotiationTimeout(timeout),
37 startTime(squid_curtime),
38 useCertValidator_(true),
39 certsDownloads(0)
40 {
41 debugs(83, 5, "Security::PeerConnector constructed, this=" << (void*)this);
42 // if this throws, the caller's cb dialer is not our CbDialer
43 Must(dynamic_cast<CbDialer*>(callback->getDialer()));
44 }
45
46 Security::PeerConnector::~PeerConnector()
47 {
48 debugs(83, 5, "Security::PeerConnector destructed, this=" << (void*)this);
49 }
50
51 bool Security::PeerConnector::doneAll() const
52 {
53 return (!callback || callback->canceled()) && AsyncJob::doneAll();
54 }
55
56 /// Preps connection and SSL state. Calls negotiate().
57 void
58 Security::PeerConnector::start()
59 {
60 AsyncJob::start();
61
62 Security::SessionPointer tmp;
63 if (prepareSocket() && initialize(tmp))
64 negotiate();
65 else
66 mustStop("Security::PeerConnector TLS socket initialize failed");
67 }
68
69 void
70 Security::PeerConnector::commCloseHandler(const CommCloseCbParams &params)
71 {
72 debugs(83, 5, "FD " << params.fd << ", Security::PeerConnector=" << params.data);
73 connectionClosed("Security::PeerConnector::commCloseHandler");
74 }
75
76 void
77 Security::PeerConnector::connectionClosed(const char *reason)
78 {
79 mustStop(reason);
80 callback = NULL;
81 }
82
83 bool
84 Security::PeerConnector::prepareSocket()
85 {
86 const int fd = serverConnection()->fd;
87 if (!Comm::IsConnOpen(serverConn) || fd_table[serverConn->fd].closing()) {
88 connectionClosed("Security::PeerConnector::prepareSocket");
89 return false;
90 }
91
92 // watch for external connection closures
93 typedef CommCbMemFunT<Security::PeerConnector, CommCloseCbParams> Dialer;
94 closeHandler = JobCallback(9, 5, Dialer, this, Security::PeerConnector::commCloseHandler);
95 comm_add_close_handler(fd, closeHandler);
96 return true;
97 }
98
99 bool
100 Security::PeerConnector::initialize(Security::SessionPointer &serverSession)
101 {
102 #if USE_OPENSSL
103 Security::ContextPointer ctx(getTlsContext());
104 assert(ctx);
105
106 if (!Ssl::CreateClient(ctx, serverConnection(), "server https start")) {
107 const auto xerrno = errno;
108 const auto ssl_error = ERR_get_error();
109 ErrorState *anErr = new ErrorState(ERR_SOCKET_FAILURE, Http::scInternalServerError, request.getRaw());
110 anErr->xerrno = xerrno;
111 debugs(83, DBG_IMPORTANT, "Error allocating TLS handle: " << Security::ErrorString(ssl_error));
112 noteNegotiationDone(anErr);
113 bail(anErr);
114 return false;
115 }
116
117 // A TLS/SSL session has now been created for the connection and stored in fd_table
118 serverSession = fd_table[serverConnection()->fd].ssl;
119
120 // If CertValidation Helper used do not lookup checklist for errors,
121 // but keep a list of errors to send it to CertValidator
122 if (!Ssl::TheConfig.ssl_crt_validator) {
123 // Create the ACL check list now, while we have access to more info.
124 // The list is used in ssl_verify_cb() and is freed in ssl_free().
125 if (acl_access *acl = ::Config.ssl_client.cert_error) {
126 ACLFilledChecklist *check = new ACLFilledChecklist(acl, request.getRaw(), dash_str);
127 check->al = al;
128 // check->fd(fd); XXX: need client FD here
129 SSL_set_ex_data(serverSession.get(), ssl_ex_index_cert_error_check, check);
130 }
131 }
132
133 return true;
134 #else
135 return false;
136 #endif
137 }
138
139 void
140 Security::PeerConnector::setReadTimeout()
141 {
142 int timeToRead;
143 if (negotiationTimeout) {
144 const int timeUsed = squid_curtime - startTime;
145 const int timeLeft = max(0, static_cast<int>(negotiationTimeout - timeUsed));
146 timeToRead = min(static_cast<int>(::Config.Timeout.read), timeLeft);
147 } else
148 timeToRead = ::Config.Timeout.read;
149 AsyncCall::Pointer nil;
150 commSetConnTimeout(serverConnection(), timeToRead, nil);
151 }
152
153 void
154 Security::PeerConnector::recordNegotiationDetails()
155 {
156 const int fd = serverConnection()->fd;
157 Security::SessionPointer session(fd_table[fd].ssl);
158
159 // retrieve TLS server negotiated information if any
160 serverConnection()->tlsNegotiations()->retrieveNegotiatedInfo(session);
161
162 #if USE_OPENSSL
163 // retrieve TLS parsed extra info
164 BIO *b = SSL_get_rbio(session.get());
165 Ssl::ServerBio *bio = static_cast<Ssl::ServerBio *>(b->ptr);
166 if (const Security::TlsDetails::Pointer &details = bio->receivedHelloDetails())
167 serverConnection()->tlsNegotiations()->retrieveParsedInfo(details);
168 #endif
169 }
170
171 void
172 Security::PeerConnector::negotiate()
173 {
174 if (!Comm::IsConnOpen(serverConnection()))
175 return;
176
177 const int fd = serverConnection()->fd;
178 if (fd_table[fd].closing())
179 return;
180
181 #if USE_OPENSSL
182 const int result = SSL_connect(fd_table[fd].ssl.get());
183 #else
184 const int result = -1;
185 #endif
186 if (result <= 0) {
187 handleNegotiateError(result);
188 return; // we might be gone by now
189 }
190
191 recordNegotiationDetails();
192
193 if (!sslFinalized())
194 return;
195
196 callBack();
197 }
198
199 bool
200 Security::PeerConnector::sslFinalized()
201 {
202 #if USE_OPENSSL
203 if (Ssl::TheConfig.ssl_crt_validator && useCertValidator_) {
204 const int fd = serverConnection()->fd;
205 Security::SessionPointer session(fd_table[fd].ssl);
206
207 Ssl::CertValidationRequest validationRequest;
208 // WARNING: Currently we do not use any locking for any of the
209 // members of the Ssl::CertValidationRequest class. In this code the
210 // Ssl::CertValidationRequest object used only to pass data to
211 // Ssl::CertValidationHelper::submit method.
212 validationRequest.ssl = session.get();
213 if (SBuf *dName = (SBuf *)SSL_get_ex_data(session.get(), ssl_ex_index_server))
214 validationRequest.domainName = dName->c_str();
215 if (Security::CertErrors *errs = static_cast<Security::CertErrors *>(SSL_get_ex_data(session.get(), ssl_ex_index_ssl_errors)))
216 // validationRequest disappears on return so no need to cbdataReference
217 validationRequest.errors = errs;
218 try {
219 debugs(83, 5, "Sending SSL certificate for validation to ssl_crtvd.");
220 AsyncCall::Pointer call = asyncCall(83,5, "Security::PeerConnector::sslCrtvdHandleReply", Ssl::CertValidationHelper::CbDialer(this, &Security::PeerConnector::sslCrtvdHandleReply, nullptr));
221 Ssl::CertValidationHelper::GetInstance()->sslSubmit(validationRequest, call);
222 return false;
223 } catch (const std::exception &e) {
224 debugs(83, DBG_IMPORTANT, "ERROR: Failed to compose ssl_crtvd " <<
225 "request for " << validationRequest.domainName <<
226 " certificate: " << e.what() << "; will now block to " <<
227 "validate that certificate.");
228 // fall through to do blocking in-process generation.
229 ErrorState *anErr = new ErrorState(ERR_GATEWAY_FAILURE, Http::scInternalServerError, request.getRaw());
230
231 noteNegotiationDone(anErr);
232 bail(anErr);
233 serverConn->close();
234 return true;
235 }
236 }
237 #endif
238
239 noteNegotiationDone(NULL);
240 return true;
241 }
242
243 #if USE_OPENSSL
244 void
245 Security::PeerConnector::sslCrtvdHandleReply(Ssl::CertValidationResponse::Pointer validationResponse)
246 {
247 Must(validationResponse != NULL);
248
249 Ssl::ErrorDetail *errDetails = NULL;
250 bool validatorFailed = false;
251 if (!Comm::IsConnOpen(serverConnection())) {
252 return;
253 }
254
255 if (Debug::Enabled(83, 5)) {
256 Security::SessionPointer ssl(fd_table[serverConnection()->fd].ssl);
257 SBuf *server = static_cast<SBuf *>(SSL_get_ex_data(ssl.get(), ssl_ex_index_server));
258 debugs(83,5, RawPointer("host", server) << " cert validation result: " << validationResponse->resultCode);
259 }
260
261 if (validationResponse->resultCode == ::Helper::Error) {
262 if (Security::CertErrors *errs = sslCrtvdCheckForErrors(*validationResponse, errDetails)) {
263 Security::SessionPointer session(fd_table[serverConnection()->fd].ssl);
264 Security::CertErrors *oldErrs = static_cast<Security::CertErrors*>(SSL_get_ex_data(session.get(), ssl_ex_index_ssl_errors));
265 SSL_set_ex_data(session.get(), ssl_ex_index_ssl_errors, (void *)errs);
266 delete oldErrs;
267 }
268 } else if (validationResponse->resultCode != ::Helper::Okay)
269 validatorFailed = true;
270
271 if (!errDetails && !validatorFailed) {
272 noteNegotiationDone(NULL);
273 callBack();
274 return;
275 }
276
277 ErrorState *anErr = NULL;
278 if (validatorFailed) {
279 anErr = new ErrorState(ERR_GATEWAY_FAILURE, Http::scInternalServerError, request.getRaw());
280 } else {
281 anErr = new ErrorState(ERR_SECURE_CONNECT_FAIL, Http::scServiceUnavailable, request.getRaw());
282 anErr->detail = errDetails;
283 /*anErr->xerrno= Should preserved*/
284 }
285
286 noteNegotiationDone(anErr);
287 bail(anErr);
288 serverConn->close();
289 return;
290 }
291 #endif
292
293 #if USE_OPENSSL
294 /// Checks errors in the cert. validator response against sslproxy_cert_error.
295 /// The first honored error, if any, is returned via errDetails parameter.
296 /// The method returns all seen errors except SSL_ERROR_NONE as Security::CertErrors.
297 Security::CertErrors *
298 Security::PeerConnector::sslCrtvdCheckForErrors(Ssl::CertValidationResponse const &resp, Ssl::ErrorDetail *& errDetails)
299 {
300 ACLFilledChecklist *check = NULL;
301 if (acl_access *acl = ::Config.ssl_client.cert_error) {
302 check = new ACLFilledChecklist(acl, request.getRaw(), dash_str);
303 check->al = al;
304 }
305
306 Security::CertErrors *errs = nullptr;
307 Security::SessionPointer session(fd_table[serverConnection()->fd].ssl);
308 typedef Ssl::CertValidationResponse::RecvdErrors::const_iterator SVCRECI;
309 for (SVCRECI i = resp.errors.begin(); i != resp.errors.end(); ++i) {
310 debugs(83, 7, "Error item: " << i->error_no << " " << i->error_reason);
311
312 assert(i->error_no != SSL_ERROR_NONE);
313
314 if (!errDetails) {
315 bool allowed = false;
316 if (check) {
317 check->sslErrors = new Security::CertErrors(Security::CertError(i->error_no, i->cert, i->error_depth));
318 if (check->fastCheck() == ACCESS_ALLOWED)
319 allowed = true;
320 }
321 // else the Config.ssl_client.cert_error access list is not defined
322 // and the first error will cause the error page
323
324 if (allowed) {
325 debugs(83, 3, "bypassing SSL error " << i->error_no << " in " << "buffer");
326 } else {
327 debugs(83, 5, "confirming SSL error " << i->error_no);
328 X509 *brokenCert = i->cert.get();
329 Security::CertPointer peerCert(SSL_get_peer_certificate(session.get()));
330 const char *aReason = i->error_reason.empty() ? NULL : i->error_reason.c_str();
331 errDetails = new Ssl::ErrorDetail(i->error_no, peerCert.get(), brokenCert, aReason);
332 }
333 if (check) {
334 delete check->sslErrors;
335 check->sslErrors = NULL;
336 }
337 }
338
339 if (!errs)
340 errs = new Security::CertErrors(Security::CertError(i->error_no, i->cert, i->error_depth));
341 else
342 errs->push_back_unique(Security::CertError(i->error_no, i->cert, i->error_depth));
343 }
344 if (check)
345 delete check;
346
347 return errs;
348 }
349 #endif
350
351 /// A wrapper for Comm::SetSelect() notifications.
352 void
353 Security::PeerConnector::NegotiateSsl(int, void *data)
354 {
355 PeerConnector *pc = static_cast<Security::PeerConnector *>(data);
356 // Use job calls to add done() checks and other job logic/protections.
357 CallJobHere(83, 7, pc, Security::PeerConnector, negotiate);
358 }
359
360 void
361 Security::PeerConnector::handleNegotiateError(const int ret)
362 {
363 #if USE_OPENSSL
364 const int fd = serverConnection()->fd;
365 unsigned long ssl_lib_error = SSL_ERROR_NONE;
366 Security::SessionPointer session(fd_table[fd].ssl);
367 const int ssl_error = SSL_get_error(session.get(), ret);
368
369 switch (ssl_error) {
370 case SSL_ERROR_WANT_READ:
371 noteWantRead();
372 return;
373
374 case SSL_ERROR_WANT_WRITE:
375 noteWantWrite();
376 return;
377
378 case SSL_ERROR_SSL:
379 case SSL_ERROR_SYSCALL:
380 ssl_lib_error = ERR_get_error();
381 // proceed to the general error handling code
382 break;
383 default:
384 // no special error handling for all other errors
385 break;
386 }
387
388 // Log connection details, if any
389 recordNegotiationDetails();
390 noteNegotiationError(ret, ssl_error, ssl_lib_error);
391 #endif
392 }
393
394 void
395 Security::PeerConnector::noteWantRead()
396 {
397 const int fd = serverConnection()->fd;
398 #if USE_OPENSSL
399 Security::SessionPointer session(fd_table[fd].ssl);
400 BIO *b = SSL_get_rbio(session.get());
401 Ssl::ServerBio *srvBio = static_cast<Ssl::ServerBio *>(b->ptr);
402 if (srvBio->holdRead()) {
403 if (srvBio->gotHello()) {
404 if (checkForMissingCertificates())
405 return; // Wait to download certificates before proceed.
406
407 srvBio->holdRead(false);
408 // schedule a negotiateSSl to allow openSSL parse received data
409 Security::PeerConnector::NegotiateSsl(fd, this);
410 return;
411 } else if (srvBio->gotHelloFailed()) {
412 srvBio->holdRead(false);
413 debugs(83, DBG_IMPORTANT, "Error parsing SSL Server Hello Message on FD " << fd);
414 // schedule a negotiateSSl to allow openSSL parse received data
415 Security::PeerConnector::NegotiateSsl(fd, this);
416 return;
417 }
418 }
419 #endif
420 setReadTimeout();
421 Comm::SetSelect(fd, COMM_SELECT_READ, &NegotiateSsl, this, 0);
422 }
423
424 void
425 Security::PeerConnector::noteWantWrite()
426 {
427 const int fd = serverConnection()->fd;
428 Comm::SetSelect(fd, COMM_SELECT_WRITE, &NegotiateSsl, this, 0);
429 return;
430 }
431
432 void
433 Security::PeerConnector::noteNegotiationError(const int ret, const int ssl_error, const int ssl_lib_error)
434 {
435 #if USE_OPENSSL // not used unless OpenSSL enabled.
436 #if defined(EPROTO)
437 int sysErrNo = EPROTO;
438 #else
439 int sysErrNo = EACCES;
440 #endif
441
442 // store/report errno when ssl_error is SSL_ERROR_SYSCALL, ssl_lib_error is 0, and ret is -1
443 if (ssl_error == SSL_ERROR_SYSCALL && ret == -1 && ssl_lib_error == 0)
444 sysErrNo = errno;
445
446 const int fd = serverConnection()->fd;
447 debugs(83, DBG_IMPORTANT, "Error negotiating SSL on FD " << fd <<
448 ": " << Security::ErrorString(ssl_lib_error) << " (" <<
449 ssl_error << "/" << ret << "/" << errno << ")");
450
451 ErrorState *anErr = NULL;
452 if (request != NULL)
453 anErr = ErrorState::NewForwarding(ERR_SECURE_CONNECT_FAIL, request.getRaw());
454 else
455 anErr = new ErrorState(ERR_SECURE_CONNECT_FAIL, Http::scServiceUnavailable, NULL);
456 anErr->xerrno = sysErrNo;
457
458 Security::SessionPointer session(fd_table[fd].ssl);
459 Ssl::ErrorDetail *errFromFailure = static_cast<Ssl::ErrorDetail *>(SSL_get_ex_data(session.get(), ssl_ex_index_ssl_error_detail));
460 if (errFromFailure != NULL) {
461 // The errFromFailure is attached to the ssl object
462 // and will be released when ssl object destroyed.
463 // Copy errFromFailure to a new Ssl::ErrorDetail object
464 anErr->detail = new Ssl::ErrorDetail(*errFromFailure);
465 } else {
466 // server_cert can be NULL here
467 X509 *server_cert = SSL_get_peer_certificate(session.get());
468 anErr->detail = new Ssl::ErrorDetail(SQUID_ERR_SSL_HANDSHAKE, server_cert, NULL);
469 X509_free(server_cert);
470 }
471
472 if (ssl_lib_error != SSL_ERROR_NONE)
473 anErr->detail->setLibError(ssl_lib_error);
474
475 noteNegotiationDone(anErr);
476 bail(anErr);
477 #endif
478 }
479
480 void
481 Security::PeerConnector::bail(ErrorState *error)
482 {
483 Must(error); // or the recepient will not know there was a problem
484 Must(callback != NULL);
485 CbDialer *dialer = dynamic_cast<CbDialer*>(callback->getDialer());
486 Must(dialer);
487 dialer->answer().error = error;
488
489 callBack();
490 // Our job is done. The callabck recepient will probably close the failed
491 // peer connection and try another peer or go direct (if possible). We
492 // can close the connection ourselves (our error notification would reach
493 // the recepient before the fd-closure notification), but we would rather
494 // minimize the number of fd-closure notifications and let the recepient
495 // manage the TCP state of the connection.
496 }
497
498 void
499 Security::PeerConnector::callBack()
500 {
501 AsyncCall::Pointer cb = callback;
502 // Do this now so that if we throw below, swanSong() assert that we _tried_
503 // to call back holds.
504 callback = NULL; // this should make done() true
505
506 // remove close handler
507 comm_remove_close_handler(serverConnection()->fd, closeHandler);
508
509 CbDialer *dialer = dynamic_cast<CbDialer*>(cb->getDialer());
510 Must(dialer);
511 dialer->answer().conn = serverConnection();
512 ScheduleCallHere(cb);
513 }
514
515 void
516 Security::PeerConnector::swanSong()
517 {
518 // XXX: unregister fd-closure monitoring and CommSetSelect interest, if any
519 AsyncJob::swanSong();
520 if (callback != NULL) { // paranoid: we have left the caller waiting
521 debugs(83, DBG_IMPORTANT, "BUG: Unexpected state while connecting to a cache_peer or origin server");
522 ErrorState *anErr = new ErrorState(ERR_GATEWAY_FAILURE, Http::scInternalServerError, request.getRaw());
523 bail(anErr);
524 assert(!callback);
525 return;
526 }
527 }
528
529 const char *
530 Security::PeerConnector::status() const
531 {
532 static MemBuf buf;
533 buf.reset();
534
535 // TODO: redesign AsyncJob::status() API to avoid this
536 // id and stop reason reporting duplication.
537 buf.append(" [", 2);
538 if (stopReason != NULL) {
539 buf.append("Stopped, reason:", 16);
540 buf.appendf("%s",stopReason);
541 }
542 if (serverConn != NULL)
543 buf.appendf(" FD %d", serverConn->fd);
544 buf.appendf(" %s%u]", id.prefix(), id.value);
545 buf.terminate();
546
547 return buf.content();
548 }
549
550 #if USE_OPENSSL
551 /// CallDialer to allow use Downloader objects within PeerConnector class.
552 class PeerConnectorCertDownloaderDialer: public Downloader::CbDialer
553 {
554 public:
555 typedef void (Security::PeerConnector::*Method)(SBuf &object, int status);
556
557 PeerConnectorCertDownloaderDialer(Method method, Security::PeerConnector *pc):
558 method_(method),
559 peerConnector_(pc) {}
560
561 /* CallDialer API */
562 virtual bool canDial(AsyncCall &call) { return peerConnector_.valid(); }
563 virtual void dial(AsyncCall &call) { ((&(*peerConnector_))->*method_)(object, status); }
564 Method method_; ///< The Security::PeerConnector method to dial
565 CbcPointer<Security::PeerConnector> peerConnector_; ///< The Security::PeerConnector object
566 };
567
568 void
569 Security::PeerConnector::startCertDownloading(SBuf &url)
570 {
571 AsyncCall::Pointer certCallback = asyncCall(81, 4,
572 "Security::PeerConnector::certDownloadingDone",
573 PeerConnectorCertDownloaderDialer(&Security::PeerConnector::certDownloadingDone, this));
574
575 const Downloader *csd = (request ? dynamic_cast<const Downloader*>(request->downloader.valid()) : nullptr);
576 Downloader *dl = new Downloader(url, certCallback, csd ? csd->nestedLevel() + 1 : 1);
577 AsyncJob::Start(dl);
578 }
579
580 void
581 Security::PeerConnector::certDownloadingDone(SBuf &obj, int downloadStatus)
582 {
583 ++certsDownloads;
584 debugs(81, 5, "Certificate downloading status: " << downloadStatus << " certificate size: " << obj.length());
585
586 // get ServerBio from SSL object
587 const int fd = serverConnection()->fd;
588 Security::SessionPointer session(fd_table[fd].ssl);
589 BIO *b = SSL_get_rbio(session.get());
590 Ssl::ServerBio *srvBio = static_cast<Ssl::ServerBio *>(b->ptr);
591
592 // Parse Certificate. Assume that it is in DER format.
593 // According to RFC 4325:
594 // The server must provide a DER encoded certificate or a collection
595 // collection of certificates in a "certs-only" CMS message.
596 // The applications MUST accept DER encoded certificates and SHOULD
597 // be able to accept collection of certificates.
598 // TODO: support collection of certificates
599 const unsigned char *raw = (const unsigned char*)obj.rawContent();
600 if (X509 *cert = d2i_X509(NULL, &raw, obj.length())) {
601 char buffer[1024];
602 debugs(81, 5, "Retrieved certificate: " << X509_NAME_oneline(X509_get_subject_name(cert), buffer, 1024));
603 const Security::CertList &certsList = srvBio->serverCertificatesIfAny();
604 if (const char *issuerUri = Ssl::uriOfIssuerIfMissing(cert, certsList)) {
605 urlsOfMissingCerts.push(SBuf(issuerUri));
606 }
607 Ssl::SSL_add_untrusted_cert(session.get(), cert);
608 }
609
610 // Check if there are URIs to download from and if yes start downloading
611 // the first in queue.
612 if (urlsOfMissingCerts.size() && certsDownloads <= MaxCertsDownloads) {
613 startCertDownloading(urlsOfMissingCerts.front());
614 urlsOfMissingCerts.pop();
615 return;
616 }
617
618 srvBio->holdRead(false);
619 Security::PeerConnector::NegotiateSsl(serverConnection()->fd, this);
620 }
621
622 bool
623 Security::PeerConnector::checkForMissingCertificates()
624 {
625 // Check for nested SSL certificates downloads. For example when the
626 // certificate located in an SSL site which requires to download a
627 // a missing certificate (... from an SSL site which requires to ...).
628
629 const Downloader *csd = (request ? request->downloader.get() : nullptr);
630 if (csd && csd->nestedLevel() >= MaxNestedDownloads)
631 return false;
632
633 const int fd = serverConnection()->fd;
634 Security::SessionPointer session(fd_table[fd].ssl);
635 BIO *b = SSL_get_rbio(session.get());
636 Ssl::ServerBio *srvBio = static_cast<Ssl::ServerBio *>(b->ptr);
637 const Security::CertList &certs = srvBio->serverCertificatesIfAny();
638
639 if (certs.size()) {
640 debugs(83, 5, "SSL server sent " << certs.size() << " certificates");
641 Ssl::missingChainCertificatesUrls(urlsOfMissingCerts, certs);
642 if (urlsOfMissingCerts.size()) {
643 startCertDownloading(urlsOfMissingCerts.front());
644 urlsOfMissingCerts.pop();
645 return true;
646 }
647 }
648
649 return false;
650 }
651 #endif //USE_OPENSSL
652