support.cc
Go to the documentation of this file.
1 /*
2  * Copyright (C) 1996-2018 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 SSL accelerator support */
10 
11 #include "squid.h"
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  */
16 #if USE_OPENSSL
17 
18 #include "acl/FilledChecklist.h"
19 #include "anyp/PortCfg.h"
20 #include "anyp/Uri.h"
21 #include "fatal.h"
22 #include "fd.h"
23 #include "fde.h"
24 #include "globals.h"
25 #include "ipc/MemMap.h"
26 #include "security/CertError.h"
27 #include "security/Session.h"
28 #include "SquidConfig.h"
29 #include "SquidTime.h"
30 #include "ssl/bio.h"
31 #include "ssl/Config.h"
32 #include "ssl/ErrorDetail.h"
33 #include "ssl/gadgets.h"
34 #include "ssl/support.h"
35 
36 #include <cerrno>
37 
38 // TODO: Move ssl_ex_index_* global variables from global.cc here.
40 
42 
43 const EVP_MD *Ssl::DefaultSignHash = NULL;
44 
45 std::vector<const char *> Ssl::BumpModeStr = {
46  "none",
47  "client-first",
48  "server-first",
49  "peek",
50  "stare",
51  "bump",
52  "splice",
53  "terminate"
54  /*,"err"*/
55 };
56 
62 int
63 Ssl::AskPasswordCb(char *buf, int size, int rwflag, void *userdata)
64 {
65  FILE *in;
66  int len = 0;
67  char cmdline[1024];
68 
69  snprintf(cmdline, sizeof(cmdline), "\"%s\" \"%s\"", ::Config.Program.ssl_password, (const char *)userdata);
70  in = popen(cmdline, "r");
71 
72  if (fgets(buf, size, in))
73 
74  len = strlen(buf);
75 
76  while (len > 0 && (buf[len - 1] == '\n' || buf[len - 1] == '\r'))
77  --len;
78 
79  buf[len] = '\0';
80 
81  pclose(in);
82 
83  return len;
84 }
85 
87 static void
88 ssl_ask_password(SSL_CTX * context, const char * prompt)
89 {
91  SSL_CTX_set_default_passwd_cb(context, Ssl::AskPasswordCb);
92  SSL_CTX_set_default_passwd_cb_userdata(context, (void *)prompt);
93  }
94 }
95 
96 #if HAVE_LIBSSL_SSL_CTX_SET_TMP_RSA_CALLBACK
97 static RSA *
98 ssl_temp_rsa_cb(SSL * ssl, int anInt, int keylen)
99 {
100  static RSA *rsa_512 = nullptr;
101  static RSA *rsa_1024 = nullptr;
102  static BIGNUM *e = nullptr;
103  RSA *rsa = nullptr;
104  int newkey = 0;
105 
106  if (!e) {
107  e = BN_new();
108  if (!e || !BN_set_word(e, RSA_F4)) {
109  debugs(83, DBG_IMPORTANT, "ssl_temp_rsa_cb: Failed to set exponent for key " << keylen);
110  BN_free(e);
111  e = nullptr;
112  return nullptr;
113  }
114  }
115 
116  switch (keylen) {
117 
118  case 512:
119 
120  if (!rsa_512) {
121  rsa_512 = RSA_new();
122  if (rsa_512 && RSA_generate_key_ex(rsa_512, 512, e, nullptr)) {
123  newkey = 1;
124  } else {
125  RSA_free(rsa_512);
126  rsa_512 = nullptr;
127  }
128  }
129 
130  rsa = rsa_512;
131  break;
132 
133  case 1024:
134 
135  if (!rsa_1024) {
136  rsa_1024 = RSA_new();
137  if (rsa_1024 && RSA_generate_key_ex(rsa_1024, 1024, e, nullptr)) {
138  newkey = 1;
139  } else {
140  RSA_free(rsa_1024);
141  rsa_1024 = nullptr;
142  }
143  }
144 
145  rsa = rsa_1024;
146  break;
147 
148  default:
149  debugs(83, DBG_IMPORTANT, "ssl_temp_rsa_cb: Unexpected key length " << keylen);
150  return NULL;
151  }
152 
153  if (rsa == NULL) {
154  debugs(83, DBG_IMPORTANT, "ssl_temp_rsa_cb: Failed to generate key " << keylen);
155  return NULL;
156  }
157 
158  if (newkey) {
159  if (Debug::Enabled(83, 5))
160  PEM_write_RSAPrivateKey(debug_log, rsa, NULL, NULL, 0, NULL, NULL);
161 
162  debugs(83, DBG_IMPORTANT, "Generated ephemeral RSA key of length " << keylen);
163  }
164 
165  return rsa;
166 }
167 #endif
168 
169 void
171 {
172 #if HAVE_LIBSSL_SSL_CTX_SET_TMP_RSA_CALLBACK
173  debugs(83, 9, "Setting RSA key generation callback.");
174  SSL_CTX_set_tmp_rsa_callback(ctx.get(), ssl_temp_rsa_cb);
175 #endif
176 }
177 
178 int Ssl::asn1timeToString(ASN1_TIME *tm, char *buf, int len)
179 {
180  BIO *bio;
181  int write = 0;
182  bio = BIO_new(BIO_s_mem());
183  if (bio) {
184  if (ASN1_TIME_print(bio, tm))
185  write = BIO_read(bio, buf, len-1);
186  BIO_free(bio);
187  }
188  buf[write]='\0';
189  return write;
190 }
191 
192 int Ssl::matchX509CommonNames(X509 *peer_cert, void *check_data, int (*check_func)(void *check_data, ASN1_STRING *cn_data))
193 {
194  assert(peer_cert);
195 
196  X509_NAME *name = X509_get_subject_name(peer_cert);
197 
198  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)) {
199 
200  ASN1_STRING *cn_data = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, i));
201 
202  if ( (*check_func)(check_data, cn_data) == 0)
203  return 1;
204  }
205 
206  STACK_OF(GENERAL_NAME) * altnames;
207  altnames = (STACK_OF(GENERAL_NAME)*)X509_get_ext_d2i(peer_cert, NID_subject_alt_name, NULL, NULL);
208 
209  if (altnames) {
210  int numalts = sk_GENERAL_NAME_num(altnames);
211  for (int i = 0; i < numalts; ++i) {
212  const GENERAL_NAME *check = sk_GENERAL_NAME_value(altnames, i);
213  if (check->type != GEN_DNS) {
214  continue;
215  }
216  ASN1_STRING *cn_data = check->d.dNSName;
217 
218  if ( (*check_func)(check_data, cn_data) == 0) {
219  sk_GENERAL_NAME_pop_free(altnames, GENERAL_NAME_free);
220  return 1;
221  }
222  }
223  sk_GENERAL_NAME_pop_free(altnames, GENERAL_NAME_free);
224  }
225  return 0;
226 }
227 
228 static int check_domain( void *check_data, ASN1_STRING *cn_data)
229 {
230  char cn[1024];
231  const char *server = (const char *)check_data;
232 
233  if (cn_data->length == 0)
234  return 1; // zero length cn, ignore
235 
236  if (cn_data->length > (int)sizeof(cn) - 1)
237  return 1; //if does not fit our buffer just ignore
238 
239  char *s = reinterpret_cast<char*>(cn_data->data);
240  char *d = cn;
241  for (int i = 0; i < cn_data->length; ++i, ++d, ++s) {
242  if (*s == '\0')
243  return 1; // always a domain mismatch. contains 0x00
244  *d = *s;
245  }
246  cn[cn_data->length] = '\0';
247  debugs(83, 4, "Verifying server domain " << server << " to certificate name/subjectAltName " << cn);
248  return matchDomainName(server, (cn[0] == '*' ? cn + 1 : cn), mdnRejectSubsubDomains);
249 }
250 
251 bool Ssl::checkX509ServerValidity(X509 *cert, const char *server)
252 {
253  return matchX509CommonNames(cert, (void *)server, check_domain);
254 }
255 
257 static int
258 ssl_verify_cb(int ok, X509_STORE_CTX * ctx)
259 {
260  // preserve original ctx->error before SSL_ calls can overwrite it
261  Security::ErrorCode error_no = ok ? SSL_ERROR_NONE : X509_STORE_CTX_get_error(ctx);
262 
263  char buffer[256] = "";
264  SSL *ssl = (SSL *)X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
265  SSL_CTX *sslctx = SSL_get_SSL_CTX(ssl);
266  SBuf *server = (SBuf *)SSL_get_ex_data(ssl, ssl_ex_index_server);
267  void *dont_verify_domain = SSL_CTX_get_ex_data(sslctx, ssl_ctx_ex_index_dont_verify_domain);
268  ACLChecklist *check = (ACLChecklist*)SSL_get_ex_data(ssl, ssl_ex_index_cert_error_check);
269  X509 *peeked_cert = (X509 *)SSL_get_ex_data(ssl, ssl_ex_index_ssl_peeked_cert);
270  Security::CertPointer peer_cert;
271  peer_cert.resetAndLock(X509_STORE_CTX_get0_cert(ctx));
272 
273  X509_NAME_oneline(X509_get_subject_name(peer_cert.get()), buffer, sizeof(buffer));
274 
275  // detect infinite loops
276  uint32_t *validationCounter = static_cast<uint32_t *>(SSL_get_ex_data(ssl, ssl_ex_index_ssl_validation_counter));
277  if (!validationCounter) {
278  validationCounter = new uint32_t(1);
279  SSL_set_ex_data(ssl, ssl_ex_index_ssl_validation_counter, validationCounter);
280  } else {
281  // overflows allowed if SQUID_CERT_VALIDATION_ITERATION_MAX >= UINT32_MAX
282  (*validationCounter)++;
283  }
284 
285  if ((*validationCounter) >= SQUID_CERT_VALIDATION_ITERATION_MAX) {
286  ok = 0; // or the validation loop will never stop
288  debugs(83, 2, "SQUID_X509_V_ERR_INFINITE_VALIDATION: " <<
289  *validationCounter << " iterations while checking " << buffer);
290  }
291 
292  if (ok) {
293  debugs(83, 5, "SSL Certificate signature OK: " << buffer);
294 
295  // Check for domain mismatch only if the current certificate is the peer certificate.
296  if (!dont_verify_domain && server && peer_cert.get() == X509_STORE_CTX_get_current_cert(ctx)) {
297  if (!Ssl::checkX509ServerValidity(peer_cert.get(), server->c_str())) {
298  debugs(83, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " << buffer << " does not match domainname " << server);
299  ok = 0;
301  }
302  }
303  }
304 
305  if (ok && peeked_cert) {
306  // Check whether the already peeked certificate matches the new one.
307  if (X509_cmp(peer_cert.get(), peeked_cert) != 0) {
308  debugs(83, 2, "SQUID_X509_V_ERR_CERT_CHANGE: Certificate " << buffer << " does not match peeked certificate");
309  ok = 0;
310  error_no = SQUID_X509_V_ERR_CERT_CHANGE;
311  }
312  }
313 
314  if (!ok) {
315  Security::CertPointer broken_cert;
316  broken_cert.resetAndLock(X509_STORE_CTX_get_current_cert(ctx));
317  if (!broken_cert)
318  broken_cert = peer_cert;
319 
320  Security::CertErrors *errs = static_cast<Security::CertErrors *>(SSL_get_ex_data(ssl, ssl_ex_index_ssl_errors));
321  const int depth = X509_STORE_CTX_get_error_depth(ctx);
322  if (!errs) {
323  errs = new Security::CertErrors(Security::CertError(error_no, broken_cert, depth));
324  if (!SSL_set_ex_data(ssl, ssl_ex_index_ssl_errors, (void *)errs)) {
325  debugs(83, 2, "Failed to set ssl error_no in ssl_verify_cb: Certificate " << buffer);
326  delete errs;
327  errs = NULL;
328  }
329  } else // remember another error number
330  errs->push_back_unique(Security::CertError(error_no, broken_cert, depth));
331 
332  if (const char *err_descr = Ssl::GetErrorDescr(error_no))
333  debugs(83, 5, err_descr << ": " << buffer);
334  else
335  debugs(83, DBG_IMPORTANT, "SSL unknown certificate error " << error_no << " in " << buffer);
336 
337  // Check if the certificate error can be bypassed.
338  // Infinity validation loop errors can not bypassed.
339  if (error_no != SQUID_X509_V_ERR_INFINITE_VALIDATION) {
340  if (check) {
341  ACLFilledChecklist *filledCheck = Filled(check);
342  assert(!filledCheck->sslErrors);
343  filledCheck->sslErrors = new Security::CertErrors(Security::CertError(error_no, broken_cert));
344  filledCheck->serverCert = peer_cert;
345  if (check->fastCheck().allowed()) {
346  debugs(83, 3, "bypassing SSL error " << error_no << " in " << buffer);
347  ok = 1;
348  } else {
349  debugs(83, 5, "confirming SSL error " << error_no);
350  }
351  delete filledCheck->sslErrors;
352  filledCheck->sslErrors = NULL;
353  filledCheck->serverCert.reset();
354  }
355  // If the certificate validator is used then we need to allow all errors and
356  // pass them to certficate validator for more processing
357  else if (Ssl::TheConfig.ssl_crt_validator) {
358  ok = 1;
359  }
360  }
361  }
362 
363  if (Ssl::TheConfig.ssl_crt_validator) {
364  // Check if we have stored certificates chain. Store if not.
365  if (!SSL_get_ex_data(ssl, ssl_ex_index_ssl_cert_chain)) {
366  STACK_OF(X509) *certStack = X509_STORE_CTX_get1_chain(ctx);
367  if (certStack && !SSL_set_ex_data(ssl, ssl_ex_index_ssl_cert_chain, certStack))
368  sk_X509_pop_free(certStack, X509_free);
369  }
370  }
371 
372  if (!ok && !SSL_get_ex_data(ssl, ssl_ex_index_ssl_error_detail) ) {
373 
374  // Find the broken certificate. It may be intermediate.
375  Security::CertPointer broken_cert(peer_cert); // reasonable default if search fails
376  // Our SQUID_X509_V_ERR_DOMAIN_MISMATCH implies peer_cert is at fault.
377  if (error_no != SQUID_X509_V_ERR_DOMAIN_MISMATCH) {
378  if (auto *last_used_cert = X509_STORE_CTX_get_current_cert(ctx))
379  broken_cert.resetAndLock(last_used_cert);
380  }
381 
382  auto *errDetail = new Ssl::ErrorDetail(error_no, peer_cert.get(), broken_cert.get());
383  if (!SSL_set_ex_data(ssl, ssl_ex_index_ssl_error_detail, errDetail)) {
384  debugs(83, 2, "Failed to set Ssl::ErrorDetail in ssl_verify_cb: Certificate " << buffer);
385  delete errDetail;
386  }
387  }
388 
389  return ok;
390 }
391 
392 void
394 {
395  SSL_CTX_set_verify(ctx.get(), SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, ssl_verify_cb);
396 }
397 
398 // "dup" function for SSL_get_ex_new_index("cert_err_check")
399 #if SQUID_USE_CONST_CRYPTO_EX_DATA_DUP
400 static int
401 ssl_dupAclChecklist(CRYPTO_EX_DATA *, const CRYPTO_EX_DATA *, void *,
402  int, long, void *)
403 #else
404 static int
405 ssl_dupAclChecklist(CRYPTO_EX_DATA *, CRYPTO_EX_DATA *, void *,
406  int, long, void *)
407 #endif
408 {
409  // We do not support duplication of ACLCheckLists.
410  // If duplication is needed, we can count copies with cbdata.
411  assert(false);
412  return 0;
413 }
414 
415 // "free" function for SSL_get_ex_new_index("cert_err_check")
416 static void
417 ssl_freeAclChecklist(void *, void *ptr, CRYPTO_EX_DATA *,
418  int, long, void *)
419 {
420  delete static_cast<ACLChecklist *>(ptr); // may be NULL
421 }
422 
423 // "free" function for SSL_get_ex_new_index("ssl_error_detail")
424 static void
425 ssl_free_ErrorDetail(void *, void *ptr, CRYPTO_EX_DATA *,
426  int, long, void *)
427 {
428  Ssl::ErrorDetail *errDetail = static_cast <Ssl::ErrorDetail *>(ptr);
429  delete errDetail;
430 }
431 
432 static void
433 ssl_free_SslErrors(void *, void *ptr, CRYPTO_EX_DATA *,
434  int, long, void *)
435 {
436  Security::CertErrors *errs = static_cast <Security::CertErrors*>(ptr);
437  delete errs;
438 }
439 
440 // "free" function for SSL_get_ex_new_index("ssl_ex_index_ssl_validation_counter")
441 static void
442 ssl_free_int(void *, void *ptr, CRYPTO_EX_DATA *,
443  int, long, void *)
444 {
445  uint32_t *counter = static_cast <uint32_t *>(ptr);
446  delete counter;
447 }
448 
452 static void
453 ssl_free_CertChain(void *, void *ptr, CRYPTO_EX_DATA *,
454  int, long, void *)
455 {
456  STACK_OF(X509) *certsChain = static_cast <STACK_OF(X509) *>(ptr);
457  sk_X509_pop_free(certsChain,X509_free);
458 }
459 
460 // "free" function for X509 certificates
461 static void
462 ssl_free_X509(void *, void *ptr, CRYPTO_EX_DATA *,
463  int, long, void *)
464 {
465  X509 *cert = static_cast <X509 *>(ptr);
466  X509_free(cert);
467 }
468 
469 // "free" function for SBuf
470 static void
471 ssl_free_SBuf(void *, void *ptr, CRYPTO_EX_DATA *,
472  int, long, void *)
473 {
474  SBuf *buf = static_cast <SBuf *>(ptr);
475  delete buf;
476 }
477 
478 void
480 {
481  static bool initialized = false;
482  if (initialized)
483  return;
484  initialized = true;
485 
487 
488 #if HAVE_OPENSSL_ENGINE_H
489  if (::Config.SSL.ssl_engine) {
490  ENGINE_load_builtin_engines();
491  ENGINE *e;
492  if (!(e = ENGINE_by_id(::Config.SSL.ssl_engine)))
493  fatalf("Unable to find SSL engine '%s'\n", ::Config.SSL.ssl_engine);
494 
495  if (!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
496  const int ssl_error = ERR_get_error();
497  fatalf("Failed to initialise SSL engine: %s\n", Security::ErrorString(ssl_error));
498  }
499  }
500 #else
501  if (::Config.SSL.ssl_engine)
502  fatalf("Your OpenSSL has no SSL engine support\n");
503 #endif
504 
505  const char *defName = ::Config.SSL.certSignHash ? ::Config.SSL.certSignHash : SQUID_SSL_SIGN_HASH_IF_NONE;
506  Ssl::DefaultSignHash = EVP_get_digestbyname(defName);
508  fatalf("Sign hash '%s' is not supported\n", defName);
509 
510  ssl_ex_index_server = SSL_get_ex_new_index(0, (void *) "server", NULL, NULL, ssl_free_SBuf);
511  ssl_ctx_ex_index_dont_verify_domain = SSL_CTX_get_ex_new_index(0, (void *) "dont_verify_domain", NULL, NULL, NULL);
512  ssl_ex_index_cert_error_check = SSL_get_ex_new_index(0, (void *) "cert_error_check", NULL, &ssl_dupAclChecklist, &ssl_freeAclChecklist);
513  ssl_ex_index_ssl_error_detail = SSL_get_ex_new_index(0, (void *) "ssl_error_detail", NULL, NULL, &ssl_free_ErrorDetail);
514  ssl_ex_index_ssl_peeked_cert = SSL_get_ex_new_index(0, (void *) "ssl_peeked_cert", NULL, NULL, &ssl_free_X509);
515  ssl_ex_index_ssl_errors = SSL_get_ex_new_index(0, (void *) "ssl_errors", NULL, NULL, &ssl_free_SslErrors);
516  ssl_ex_index_ssl_cert_chain = SSL_get_ex_new_index(0, (void *) "ssl_cert_chain", NULL, NULL, &ssl_free_CertChain);
517  ssl_ex_index_ssl_validation_counter = SSL_get_ex_new_index(0, (void *) "ssl_validation_counter", NULL, NULL, &ssl_free_int);
518  ssl_ex_index_ssl_untrusted_chain = SSL_get_ex_new_index(0, (void *) "ssl_untrusted_chain", NULL, NULL, &ssl_free_CertChain);
519 }
520 
521 bool
523 {
524  if (!ctx)
525  return false;
526 
527  return true;
528 }
529 
530 bool
532 {
533  if (!ctx)
534  return false;
535 
536  if (!peer.sslCipher.isEmpty()) {
537  debugs(83, 5, "Using chiper suite " << peer.sslCipher << ".");
538 
539  const char *cipher = peer.sslCipher.c_str();
540  if (!SSL_CTX_set_cipher_list(ctx.get(), cipher)) {
541  const int ssl_error = ERR_get_error();
542  fatalf("Failed to set SSL cipher suite '%s': %s\n",
543  cipher, Security::ErrorString(ssl_error));
544  }
545  }
546 
547  if (!peer.certs.empty()) {
548  // TODO: support loading multiple cert/key pairs
549  auto &keys = peer.certs.front();
550  if (!keys.certFile.isEmpty()) {
551  debugs(83, DBG_IMPORTANT, "Using certificate in " << keys.certFile);
552 
553  const char *certfile = keys.certFile.c_str();
554  if (!SSL_CTX_use_certificate_chain_file(ctx.get(), certfile)) {
555  const int ssl_error = ERR_get_error();
556  fatalf("Failed to acquire SSL certificate '%s': %s\n",
557  certfile, Security::ErrorString(ssl_error));
558  }
559 
560  debugs(83, DBG_IMPORTANT, "Using private key in " << keys.privateKeyFile);
561  const char *keyfile = keys.privateKeyFile.c_str();
562  ssl_ask_password(ctx.get(), keyfile);
563 
564  if (!SSL_CTX_use_PrivateKey_file(ctx.get(), keyfile, SSL_FILETYPE_PEM)) {
565  const int ssl_error = ERR_get_error();
566  fatalf("Failed to acquire SSL private key '%s': %s\n",
567  keyfile, Security::ErrorString(ssl_error));
568  }
569 
570  debugs(83, 5, "Comparing private and public SSL keys.");
571 
572  if (!SSL_CTX_check_private_key(ctx.get())) {
573  const int ssl_error = ERR_get_error();
574  fatalf("SSL private key '%s' does not match public key '%s': %s\n",
575  certfile, keyfile, Security::ErrorString(ssl_error));
576  }
577  }
578  }
579 
581 
582  if (fl & SSL_FLAG_DONT_VERIFY_PEER) {
583  debugs(83, 2, "SECURITY WARNING: Peer certificates are not verified for validity!");
584  SSL_CTX_set_verify(ctx.get(), SSL_VERIFY_NONE, NULL);
585  } else {
586  debugs(83, 9, "Setting certificate verification callback.");
588  }
589 
590  return true;
591 }
592 
594 static const char *
595 ssl_get_attribute(X509_NAME * name, const char *attribute_name)
596 {
597  static char buffer[1024];
598  buffer[0] = '\0';
599 
600  if (strcmp(attribute_name, "DN") == 0) {
601  X509_NAME_oneline(name, buffer, sizeof(buffer));
602  } else {
603  int nid = OBJ_txt2nid(const_cast<char *>(attribute_name));
604  if (nid == 0) {
605  debugs(83, DBG_IMPORTANT, "WARNING: Unknown SSL attribute name '" << attribute_name << "'");
606  return nullptr;
607  }
608  X509_NAME_get_text_by_NID(name, nid, buffer, sizeof(buffer));
609  }
610 
611  return *buffer ? buffer : nullptr;
612 }
613 
615 const char *
616 Ssl::GetX509UserAttribute(X509 * cert, const char *attribute_name)
617 {
618  X509_NAME *name;
619  const char *ret;
620 
621  if (!cert)
622  return NULL;
623 
624  name = X509_get_subject_name(cert);
625 
626  ret = ssl_get_attribute(name, attribute_name);
627 
628  return ret;
629 }
630 
631 const char *
632 Ssl::GetX509Fingerprint(X509 * cert, const char *)
633 {
634  static char buf[1024];
635  if (!cert)
636  return NULL;
637 
638  unsigned int n;
639  unsigned char md[EVP_MAX_MD_SIZE];
640  if (!X509_digest(cert, EVP_sha1(), md, &n))
641  return NULL;
642 
643  assert(3 * n + 1 < sizeof(buf));
644 
645  char *s = buf;
646  for (unsigned int i=0; i < n; ++i, s += 3) {
647  const char term = (i + 1 < n) ? ':' : '\0';
648  snprintf(s, 4, "%02X%c", md[i], term);
649  }
650 
651  return buf;
652 }
653 
655 const char *
656 Ssl::GetX509CAAttribute(X509 * cert, const char *attribute_name)
657 {
658 
659  X509_NAME *name;
660  const char *ret;
661 
662  if (!cert)
663  return NULL;
664 
665  name = X509_get_issuer_name(cert);
666 
667  ret = ssl_get_attribute(name, attribute_name);
668 
669  return ret;
670 }
671 
672 const char *sslGetUserAttribute(SSL *ssl, const char *attribute_name)
673 {
674  if (!ssl)
675  return NULL;
676 
677  X509 *cert = SSL_get_peer_certificate(ssl);
678 
679  const char *attr = Ssl::GetX509UserAttribute(cert, attribute_name);
680 
681  X509_free(cert);
682  return attr;
683 }
684 
685 const char *sslGetCAAttribute(SSL *ssl, const char *attribute_name)
686 {
687  if (!ssl)
688  return NULL;
689 
690  X509 *cert = SSL_get_peer_certificate(ssl);
691 
692  const char *attr = Ssl::GetX509CAAttribute(cert, attribute_name);
693 
694  X509_free(cert);
695  return attr;
696 }
697 
698 const char *
699 sslGetUserEmail(SSL * ssl)
700 {
701  return sslGetUserAttribute(ssl, "emailAddress");
702 }
703 
704 const char *
706 {
707  X509 *cert;
708  BIO *mem;
709  static char *str = NULL;
710  char *ptr;
711  long len;
712 
713  safe_free(str);
714 
715  if (!ssl)
716  return NULL;
717 
718  cert = SSL_get_peer_certificate(ssl);
719 
720  if (!cert)
721  return NULL;
722 
723  mem = BIO_new(BIO_s_mem());
724 
725  PEM_write_bio_X509(mem, cert);
726 
727  len = BIO_get_mem_data(mem, &ptr);
728 
729  str = (char *)xmalloc(len + 1);
730 
731  memcpy(str, ptr, len);
732 
733  str[len] = '\0';
734 
735  X509_free(cert);
736 
737  BIO_free(mem);
738 
739  return str;
740 }
741 
742 const char *
744 {
745  STACK_OF(X509) *chain;
746  BIO *mem;
747  static char *str = NULL;
748  char *ptr;
749  long len;
750  int i;
751 
752  safe_free(str);
753 
754  if (!ssl)
755  return NULL;
756 
757  chain = SSL_get_peer_cert_chain(ssl);
758 
759  if (!chain)
760  return sslGetUserCertificatePEM(ssl);
761 
762  mem = BIO_new(BIO_s_mem());
763 
764  for (i = 0; i < sk_X509_num(chain); ++i) {
765  X509 *cert = sk_X509_value(chain, i);
766  PEM_write_bio_X509(mem, cert);
767  }
768 
769  len = BIO_get_mem_data(mem, &ptr);
770 
771  str = (char *)xmalloc(len + 1);
772  memcpy(str, ptr, len);
773  str[len] = '\0';
774 
775  BIO_free(mem);
776 
777  return str;
778 }
779 
782 Ssl::createSSLContext(Security::CertPointer & x509, Security::PrivateKeyPointer & pkey, Security::ServerOptions &options)
783 {
785 
786  if (!SSL_CTX_use_certificate(ctx.get(), x509.get()))
787  return Security::ContextPointer();
788 
789  if (!SSL_CTX_use_PrivateKey(ctx.get(), pkey.get()))
790  return Security::ContextPointer();
791 
792  if (!options.updateContextConfig(ctx))
793  return Security::ContextPointer();
794 
795  return ctx;
796 }
797 
800 {
802  Security::PrivateKeyPointer pkey;
803  if (!readCertAndPrivateKeyFromMemory(cert, pkey, data) || !cert || !pkey)
804  return Security::ContextPointer();
805 
806  Security::ContextPointer ctx(createSSLContext(cert, pkey, options));
807  if (ctx && trusted)
809  return ctx;
810 }
811 
814 {
816  Security::PrivateKeyPointer pkey;
817  if (!generateSslCertificate(cert, pkey, properties) || !cert || !pkey)
818  return Security::ContextPointer();
819 
820  Security::ContextPointer ctx(createSSLContext(cert, pkey, options));
821  if (ctx && trusted)
823  return ctx;
824 }
825 
826 void
828 {
829  assert(ctx);
830  // Add signing certificate to the certificates chain
831  X509 *signingCert = options.signingCa.cert.get();
832  if (SSL_CTX_add_extra_chain_cert(ctx.get(), signingCert)) {
833  // increase the certificate lock
834  X509_up_ref(signingCert);
835  } else {
836  const int ssl_error = ERR_get_error();
837  debugs(33, DBG_IMPORTANT, "WARNING: can not add signing certificate to SSL context chain: " << Security::ErrorString(ssl_error));
838  }
839 
840  for (auto cert : options.signingCa.chain) {
841  if (SSL_CTX_add_extra_chain_cert(ctx.get(), cert.get())) {
842  // increase the certificate lock
843  X509_up_ref(cert.get());
844  } else {
845  const auto error = ERR_get_error();
846  debugs(83, DBG_IMPORTANT, "WARNING: can not add certificate to SSL dynamic context chain: " << Security::ErrorString(error));
847  }
848  }
849 }
850 
851 void
853 {
854  if (ctx && signAlgorithm == Ssl::algSignTrusted)
856 }
857 
858 bool
860 {
862  Security::PrivateKeyPointer pkey;
863  if (!generateSslCertificate(cert, pkey, properties))
864  return false;
865 
866  if (!cert)
867  return false;
868 
869  if (!pkey)
870  return false;
871 
872  if (!SSL_use_certificate(ssl, cert.get()))
873  return false;
874 
875  if (!SSL_use_PrivateKey(ssl, pkey.get()))
876  return false;
877 
878  return true;
879 }
880 
881 bool
883 {
885  Security::PrivateKeyPointer pkey;
886  if (!readCertAndPrivateKeyFromMemory(cert, pkey, data))
887  return false;
888 
889  if (!cert || !pkey)
890  return false;
891 
892  if (!SSL_use_certificate(ssl, cert.get()))
893  return false;
894 
895  if (!SSL_use_PrivateKey(ssl, pkey.get()))
896  return false;
897 
898  return true;
899 }
900 
901 bool
903 {
904 #if HAVE_SSL_CTX_GET0_CERTIFICATE
905  X509 * cert = SSL_CTX_get0_certificate(ctx.get());
906 #elif SQUID_USE_SSLGETCERTIFICATE_HACK
907  // SSL_get_certificate is buggy in openssl versions 1.0.1d and 1.0.1e
908  // Try to retrieve certificate directly from Security::ContextPointer object
909  X509 ***pCert = (X509 ***)ctx->cert;
910  X509 * cert = pCert && *pCert ? **pCert : NULL;
911 #elif SQUID_SSLGETCERTIFICATE_BUGGY
912  X509 * cert = NULL;
913  assert(0);
914 #else
915  // Temporary ssl for getting X509 certificate from SSL_CTX.
917  X509 * cert = SSL_get_certificate(ssl.get());
918 #endif
919  if (!cert)
920  return false;
921  const auto time_notBefore = X509_getm_notBefore(cert);
922  const auto time_notAfter = X509_getm_notAfter(cert);
923  return (X509_cmp_current_time(time_notBefore) < 0 && X509_cmp_current_time(time_notAfter) > 0);
924 }
925 
926 void
927 Ssl::setClientSNI(SSL *ssl, const char *fqdn)
928 {
929  const Ip::Address test(fqdn);
930  if (!test.isAnyAddr())
931  return; // raw IP is inappropriate for SNI
932 
933  //The SSL_CTRL_SET_TLSEXT_HOSTNAME is a openssl macro which indicates
934  // if the TLS servername extension (SNI) is enabled in openssl library.
935 #if defined(SSL_CTRL_SET_TLSEXT_HOSTNAME)
936  if (!SSL_set_tlsext_host_name(ssl, fqdn)) {
937  const int ssl_error = ERR_get_error();
938  debugs(83, 3, "WARNING: unable to set TLS servername extension (SNI): " <<
939  Security::ErrorString(ssl_error) << "\n");
940  }
941 #else
942  debugs(83, 7, "no support for TLS servername extension (SNI)");
943 #endif
944 }
945 
946 static const char *
948 {
949  AUTHORITY_INFO_ACCESS *info;
950  if (!cert)
951  return nullptr;
952  info = static_cast<AUTHORITY_INFO_ACCESS *>(X509_get_ext_d2i(cert, NID_info_access, NULL, NULL));
953  if (!info)
954  return nullptr;
955 
956  static char uri[MAX_URL];
957  uri[0] = '\0';
958 
959  for (int i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
960  ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
961  if (OBJ_obj2nid(ad->method) == NID_ad_ca_issuers) {
962  if (ad->location->type == GEN_URI) {
963  xstrncpy(uri,
964  reinterpret_cast<const char *>(
965  ASN1_STRING_get0_data(ad->location->d.uniformResourceIdentifier)
966  ),
967  sizeof(uri));
968  }
969  break;
970  }
971  }
972  AUTHORITY_INFO_ACCESS_free(info);
973  return uri[0] != '\0' ? uri : nullptr;
974 }
975 
976 bool
977 Ssl::loadCerts(const char *certsFile, Ssl::CertsIndexedList &list)
978 {
979  BIO *in = BIO_new_file(certsFile, "r");
980  if (!in) {
981  debugs(83, DBG_IMPORTANT, "Failed to open '" << certsFile << "' to load certificates");
982  return false;
983  }
984 
985  X509 *aCert;
986  while((aCert = PEM_read_bio_X509(in, NULL, NULL, NULL))) {
987  static char buffer[2048];
988  X509_NAME_oneline(X509_get_subject_name(aCert), buffer, sizeof(buffer));
989  list.insert(std::pair<SBuf, X509 *>(SBuf(buffer), aCert));
990  }
991  debugs(83, 4, "Loaded " << list.size() << " certificates from file: '" << certsFile << "'");
992  BIO_free(in);
993  return true;
994 }
995 
998 static X509 *
1000 {
1001  static char buffer[2048];
1002 
1003  if (X509_NAME *issuerName = X509_get_issuer_name(cert))
1004  X509_NAME_oneline(issuerName, buffer, sizeof(buffer));
1005  else
1006  return NULL;
1007 
1008  const auto ret = list.equal_range(SBuf(buffer));
1009  for (Ssl::CertsIndexedList::iterator it = ret.first; it != ret.second; ++it) {
1010  X509 *issuer = it->second;
1011  if (X509_check_issued(issuer, cert) == X509_V_OK) {
1012  return issuer;
1013  }
1014  }
1015  return NULL;
1016 }
1017 
1019 static bool
1020 findCertIssuer(Security::CertList const &list, X509 *cert)
1021 {
1022  for (Security::CertList::const_iterator it = list.begin(); it != list.end(); ++it) {
1023  if (X509_check_issued(it->get(), cert) == X509_V_OK)
1024  return true;
1025  }
1026  return false;
1027 }
1028 
1030 static bool
1031 issuerExistInCaDb(X509 *cert, const Security::ContextPointer &connContext)
1032 {
1033  if (!connContext)
1034  return false;
1035 
1036  X509_STORE_CTX *storeCtx = X509_STORE_CTX_new();
1037  if (!storeCtx) {
1038  debugs(83, DBG_IMPORTANT, "Failed to allocate STORE_CTX object");
1039  return false;
1040  }
1041 
1042  bool gotIssuer = false;
1043  X509_STORE *store = SSL_CTX_get_cert_store(connContext.get());
1044  if (X509_STORE_CTX_init(storeCtx, store, nullptr, nullptr)) {
1045  X509 *issuer = nullptr;
1046  gotIssuer = (X509_STORE_CTX_get1_issuer(&issuer, storeCtx, cert) > 0);
1047  if (issuer)
1048  X509_free(issuer);
1049  } else {
1050  const int ssl_error = ERR_get_error();
1051  debugs(83, DBG_IMPORTANT, "Failed to initialize STORE_CTX object: " << Security::ErrorString(ssl_error));
1052  }
1053  X509_STORE_CTX_free(storeCtx);
1054 
1055  return gotIssuer;
1056 }
1057 
1058 const char *
1059 Ssl::uriOfIssuerIfMissing(X509 *cert, Security::CertList const &serverCertificates, const Security::ContextPointer &context)
1060 {
1061  if (!cert || !serverCertificates.size())
1062  return nullptr;
1063 
1064  if (!findCertIssuer(serverCertificates, cert)) {
1065  //if issuer is missing
1066  if (const char *issuerUri = hasAuthorityInfoAccessCaIssuers(cert)) {
1067  // There is a URI where we can download a certificate.
1069  !issuerExistInCaDb(cert, context)) {
1070  // and issuer not found in local databases containing
1071  // untrusted certificates and trusted CA certificates
1072  return issuerUri;
1073  }
1074  }
1075  }
1076  return nullptr;
1077 }
1078 
1079 void
1080 Ssl::missingChainCertificatesUrls(std::queue<SBuf> &URIs, Security::CertList const &serverCertificates, const Security::ContextPointer &context)
1081 {
1082  if (!serverCertificates.size())
1083  return;
1084 
1085  for (const auto &i : serverCertificates) {
1086  if (const char *issuerUri = uriOfIssuerIfMissing(i.get(), serverCertificates, context))
1087  URIs.push(SBuf(issuerUri));
1088  }
1089 }
1090 
1091 void
1092 Ssl::SSL_add_untrusted_cert(SSL *ssl, X509 *cert)
1093 {
1094  STACK_OF(X509) *untrustedStack = static_cast <STACK_OF(X509) *>(SSL_get_ex_data(ssl, ssl_ex_index_ssl_untrusted_chain));
1095  if (!untrustedStack) {
1096  untrustedStack = sk_X509_new_null();
1097  if (!SSL_set_ex_data(ssl, ssl_ex_index_ssl_untrusted_chain, untrustedStack)) {
1098  sk_X509_pop_free(untrustedStack, X509_free);
1099  throw TextException("Failed to attach untrusted certificates chain", Here());
1100  }
1101  }
1102  sk_X509_push(untrustedStack, cert);
1103 }
1104 
1106 static X509 *
1107 sk_x509_findIssuer(STACK_OF(X509) *sk, X509 *cert)
1108 {
1109  if (!sk)
1110  return NULL;
1111 
1112  const int skItemsNum = sk_X509_num(sk);
1113  for (int i = 0; i < skItemsNum; ++i) {
1114  X509 *issuer = sk_X509_value(sk, i);
1115  if (X509_check_issued(issuer, cert) == X509_V_OK)
1116  return issuer;
1117  }
1118  return NULL;
1119 }
1120 
1122 static void
1123 completeIssuers(X509_STORE_CTX *ctx, STACK_OF(X509) *untrustedCerts)
1124 {
1125  debugs(83, 2, "completing " << sk_X509_num(untrustedCerts) << " OpenSSL untrusted certs using " << SquidUntrustedCerts.size() << " configured untrusted certificates");
1126 
1127  const X509_VERIFY_PARAM *param = X509_STORE_CTX_get0_param(ctx);
1128  int depth = X509_VERIFY_PARAM_get_depth(param);
1129  X509 *current = X509_STORE_CTX_get0_cert(ctx);
1130  int i = 0;
1131  for (i = 0; current && (i < depth); ++i) {
1132  if (X509_check_issued(current, current) == X509_V_OK) {
1133  // either ctx->cert is itself self-signed or untrustedCerts
1134  // aready contain the self-signed current certificate
1135  break;
1136  }
1137 
1138  // untrustedCerts is short, not worth indexing
1139  X509 *issuer = sk_x509_findIssuer(untrustedCerts, current);
1140  if (!issuer) {
1141  if ((issuer = findCertIssuerFast(SquidUntrustedCerts, current)))
1142  sk_X509_push(untrustedCerts, issuer);
1143  }
1144  current = issuer;
1145  }
1146 
1147  if (i >= depth)
1148  debugs(83, 2, "exceeded the maximum certificate chain length: " << depth);
1149 }
1150 
1152 static int
1153 untrustedToStoreCtx_cb(X509_STORE_CTX *ctx,void *data)
1154 {
1155  debugs(83, 4, "Try to use pre-downloaded intermediate certificates");
1156 
1157  SSL *ssl = static_cast<SSL *>(X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx()));
1158  STACK_OF(X509) *sslUntrustedStack = static_cast <STACK_OF(X509) *>(SSL_get_ex_data(ssl, ssl_ex_index_ssl_untrusted_chain));
1159 
1160  // OpenSSL already maintains ctx->untrusted but we cannot modify
1161  // internal OpenSSL list directly. We have to give OpenSSL our own
1162  // list, but it must include certificates on the OpenSSL ctx->untrusted
1163  STACK_OF(X509) *oldUntrusted = X509_STORE_CTX_get0_untrusted(ctx);
1164  STACK_OF(X509) *sk = sk_X509_dup(oldUntrusted); // oldUntrusted is always not NULL
1165 
1166  for (int i = 0; i < sk_X509_num(sslUntrustedStack); ++i) {
1167  X509 *cert = sk_X509_value(sslUntrustedStack, i);
1168  sk_X509_push(sk, cert);
1169  }
1170 
1171  // If the local untrusted certificates internal database is used
1172  // run completeIssuers to add missing certificates if possible.
1173  if (SquidUntrustedCerts.size() > 0)
1174  completeIssuers(ctx, sk);
1175 
1176  X509_STORE_CTX_set0_untrusted(ctx, sk); // No locking/unlocking, just sets ctx->untrusted
1177  int ret = X509_verify_cert(ctx);
1178  X509_STORE_CTX_set0_untrusted(ctx, oldUntrusted); // Set back the old untrusted list
1179  sk_X509_free(sk); // Release sk list
1180  return ret;
1181 }
1182 
1183 void
1184 Ssl::useSquidUntrusted(SSL_CTX *sslContext)
1185 {
1186  SSL_CTX_set_cert_verify_callback(sslContext, untrustedToStoreCtx_cb, NULL);
1187 }
1188 
1189 bool
1190 Ssl::loadSquidUntrusted(const char *path)
1191 {
1192  return Ssl::loadCerts(path, SquidUntrustedCerts);
1193 }
1194 
1195 void
1197 {
1198  if (SquidUntrustedCerts.size()) {
1199  for (Ssl::CertsIndexedList::iterator it = SquidUntrustedCerts.begin(); it != SquidUntrustedCerts.end(); ++it) {
1200  X509_free(it->second);
1201  }
1202  SquidUntrustedCerts.clear();
1203  }
1204 }
1205 
1206 bool Ssl::generateUntrustedCert(Security::CertPointer &untrustedCert, Security::PrivateKeyPointer &untrustedPkey, Security::CertPointer const &cert, Security::PrivateKeyPointer const & pkey)
1207 {
1208  // Generate the self-signed certificate, using a hard-coded subject prefix
1209  Ssl::CertificateProperties certProperties;
1210  if (const char *cn = CommonHostName(cert.get())) {
1211  certProperties.commonName = "Not trusted by \"";
1212  certProperties.commonName += cn;
1213  certProperties.commonName += "\"";
1214  } else if (const char *org = getOrganization(cert.get())) {
1215  certProperties.commonName = "Not trusted by \"";
1216  certProperties.commonName += org;
1217  certProperties.commonName += "\"";
1218  } else
1219  certProperties.commonName = "Not trusted";
1220  certProperties.setCommonName = true;
1221  // O, OU, and other CA subject fields will be mimicked
1222  // Expiration date and other common properties will be mimicked
1223  certProperties.signAlgorithm = Ssl::algSignSelf;
1224  certProperties.signWithPkey.resetAndLock(pkey.get());
1225  certProperties.mimicCert.resetAndLock(cert.get());
1226  return Ssl::generateSslCertificate(untrustedCert, untrustedPkey, certProperties);
1227 }
1228 
1230 {
1231  bool origSignatureAsKey = false;
1232  if (certProperties.mimicCert) {
1233  if (auto *sig = Ssl::X509_get_signature(certProperties.mimicCert)) {
1234  origSignatureAsKey = true;
1235  key.append((const char *)sig->data, sig->length);
1236  }
1237  }
1238 
1239  if (!origSignatureAsKey || certProperties.setCommonName) {
1240  // Use common name instead
1241  key.append(certProperties.commonName.c_str());
1242  }
1243  key.append(certProperties.setCommonName ? '1' : '0');
1244  key.append(certProperties.setValidAfter ? '1' : '0');
1245  key.append(certProperties.setValidBefore ? '1' : '0');
1246  key.append(certProperties.signAlgorithm != Ssl:: algSignEnd ? certSignAlgorithm(certProperties.signAlgorithm) : "-");
1247  key.append(certProperties.signHash ? EVP_MD_name(certProperties.signHash) : "-");
1248 
1249  if (certProperties.mimicCert) {
1250  Ssl::BIO_Pointer bio(BIO_new_SBuf(&key));
1251  ASN1_item_i2d_bio(ASN1_ITEM_rptr(X509), bio.get(), (ASN1_VALUE *)certProperties.mimicCert.get());
1252  }
1253 }
1254 
1255 static int
1257 {
1258  BIO_set_init(bio, 0);
1259  BIO_set_data(bio, NULL);
1260  return 1;
1261 }
1262 
1263 static int
1265 {
1266  if (!bio)
1267  return 0;
1268  return 1;
1269 }
1270 
1271 int
1272 bio_sbuf_write(BIO* bio, const char* data, int len)
1273 {
1274  SBuf *buf = static_cast<SBuf *>(BIO_get_data(bio));
1275  // TODO: Convert exceptions into BIO errors
1276  buf->append(data, len);
1277  return len;
1278 }
1279 
1280 int
1281 bio_sbuf_puts(BIO* bio, const char* data)
1282 {
1283  // TODO: use bio_sbuf_write() instead
1284  SBuf *buf = static_cast<SBuf *>(BIO_get_data(bio));
1285  size_t oldLen = buf->length();
1286  buf->append(data);
1287  return buf->length() - oldLen;
1288 }
1289 
1290 long
1291 bio_sbuf_ctrl(BIO* bio, int cmd, long num, void* ptr) {
1292  SBuf *buf = static_cast<SBuf *>(BIO_get_data(bio));
1293  switch (cmd) {
1294  case BIO_CTRL_RESET:
1295  // TODO: Convert exceptions into BIO errors
1296  buf->clear();
1297  return 1;
1298  case BIO_CTRL_FLUSH:
1299  return 1;
1300  default:
1301  return 0;
1302  }
1303 }
1304 
1306 {
1307 #if HAVE_LIBCRYPTO_BIO_METH_NEW
1308  static BIO_METHOD *BioSBufMethods = nullptr;
1309  if (!BioSBufMethods) {
1310  BioSBufMethods = BIO_meth_new(BIO_TYPE_MEM, "Squid-SBuf");
1311  BIO_meth_set_write(BioSBufMethods, bio_sbuf_write);
1312  BIO_meth_set_read(BioSBufMethods, nullptr);
1313  BIO_meth_set_puts(BioSBufMethods, bio_sbuf_puts);
1314  BIO_meth_set_gets(BioSBufMethods, nullptr);
1315  BIO_meth_set_ctrl(BioSBufMethods, bio_sbuf_ctrl);
1316  BIO_meth_set_create(BioSBufMethods, bio_sbuf_create);
1317  BIO_meth_set_destroy(BioSBufMethods, bio_sbuf_destroy);
1318  }
1319 #else
1320  static BIO_METHOD *BioSBufMethods = new BIO_METHOD({
1321  BIO_TYPE_MEM,
1322  "Squid SBuf",
1324  nullptr,
1325  bio_sbuf_puts,
1326  nullptr,
1327  bio_sbuf_ctrl,
1330  NULL
1331  });
1332 #endif
1333  BIO *bio = BIO_new(BioSBufMethods);
1334  Must(bio);
1335  BIO_set_data(bio, buf);
1336  BIO_set_init(bio, 1);
1337  return bio;
1338 }
1339 
1340 #endif /* USE_OPENSSL */
1341 
int X509_VERIFY_PARAM_get_depth(const X509_VERIFY_PARAM *param)
Definition: openssl.h:227
int ssl_ex_index_ssl_peeked_cert
bool setCommonName
Replace the CN field of the mimicing subject with the given.
Definition: gadgets.h:221
STACK_OF(X509)*X509_STORE_CTX_get0_untrusted(X509_STORE_CTX *ctx)
Definition: openssl.h:195
std::multimap< SBuf, X509 * > CertsIndexedList
certificates indexed by issuer name
Definition: support.h:151
#define debug_log
change-avoidance macro; new code should call DebugStream() instead
Definition: Debug.h:110
GETX509ATTRIBUTE GetX509UserAttribute
Definition: support.h:117
std::vector< const char * > BumpModeStr
Definition: support.cc:45
static bool findCertIssuer(Security::CertList const &list, X509 *cert)
slowly find the issuer certificate of a given cert using linear search
Definition: support.cc:1020
long bio_sbuf_ctrl(BIO *bio, int cmd, long num, void *ptr)
Definition: support.cc:1291
bool setValidAfter
Do not mimic &quot;Not Valid After&quot; field.
Definition: gadgets.h:219
static bool issuerExistInCaDb(X509 *cert, const Security::ContextPointer &connContext)
Definition: support.cc:1031
#define assert(EX)
Definition: assert.h:17
static void ssl_free_SBuf(void *, void *ptr, CRYPTO_EX_DATA *, int, long, void *)
Definition: support.cc:471
bool setValidBefore
Do not mimic &quot;Not Valid Before&quot; field.
Definition: gadgets.h:220
bool verifySslCertificate(Security::ContextPointer &, CertificateProperties const &)
Definition: support.cc:902
int ssl_ex_index_server
Security::CertPointer cert
public X.509 certificate from certFile
Definition: KeyData.h:31
X509 * X509_STORE_CTX_get0_cert(X509_STORE_CTX *ctx)
Definition: openssl.h:188
Definition: SBuf.h:86
static const char * hasAuthorityInfoAccessCaIssuers(X509 *cert)
Definition: support.cc:947
void configureUnconfiguredSslContext(Security::ContextPointer &, Ssl::CertSignAlgorithm signAlgorithm, AnyP::PortCfg &)
Definition: support.cc:852
bool updateContextConfig(Security::ContextPointer &)
update the given TLS security context using squid.conf settings
const char * GetErrorDescr(Security::ErrorCode value)
A short description of the TLS error &quot;value&quot;.
Definition: ErrorDetail.cc:416
ACLFilledChecklist * Filled(ACLChecklist *checklist)
convenience and safety wrapper for dynamic_cast&lt;ACLFilledChecklist*&gt;
int AskPasswordCb(char *buf, int size, int rwflag, void *userdata)
Definition: support.cc:63
void error(char *format,...)
int i
Definition: membanger.c:49
SBuf & append(const SBuf &S)
Definition: SBuf.cc:195
static X509 * findCertIssuerFast(Ssl::CertsIndexedList &list, X509 *cert)
Definition: support.cc:999
#define SQUID_X509_V_ERR_DOMAIN_MISMATCH
Definition: support.h:44
std::list< Security::CertPointer > CertList
Definition: forward.h:80
#define SQUID_X509_V_ERR_CERT_CHANGE
Definition: support.h:42
#define safe_free(x)
Definition: xalloc.h:73
static void completeIssuers(X509_STORE_CTX *ctx, STACK_OF(X509)*untrustedCerts)
add missing issuer certificates to untrustedCerts
Definition: support.cc:1123
bool loadSquidUntrusted(const char *path)
Definition: support.cc:1190
bool loadCerts(const char *certsFile, Ssl::CertsIndexedList &list)
Definition: support.cc:977
int ssl_ex_index_cert_error_check
std::string commonName
A CN to use for the generated certificate.
Definition: gadgets.h:222
void clear()
Definition: SBuf.cc:178
#define Must(condition)
Like assert() but throws an exception instead of aborting the process.
Definition: TextException.h:69
bool isEmpty() const
Definition: SBuf.h:420
int ssl_ex_index_ssl_validation_counter
void BIO_set_init(BIO *table, int init)
Definition: openssl.h:72
const char * sslGetUserAttribute(SSL *ssl, const char *attribute_name)
Definition: support.cc:672
static void ssl_free_CertChain(void *, void *ptr, CRYPTO_EX_DATA *, int, long, void *)
Definition: support.cc:453
#define SSL_FLAG_DONT_VERIFY_PEER
Definition: forward.h:47
Security::CertList chain
any certificates which must be chained from cert
Definition: KeyData.h:35
Security::ServerOptions secure
TLS configuration options for this listening port.
Definition: PortCfg.h:65
TLS squid.conf settings for a remote server peer.
Definition: PeerOptions.h:22
bool isAnyAddr() const
Definition: Address.cc:163
Security::ContextPointer GenerateSslContextUsingPkeyAndCertFromMemory(const char *data, Security::ServerOptions &, bool trusted)
Definition: support.cc:799
#define X509_getm_notBefore
Definition: openssl.h:206
static int untrustedToStoreCtx_cb(X509_STORE_CTX *ctx, void *data)
OpenSSL certificate validation callback.
Definition: support.cc:1153
char * ssl_password
Definition: SquidConfig.h:204
#define X509_STORE_CTX_set0_untrusted
Definition: openssl.h:204
void chainCertificatesToSSLContext(Security::ContextPointer &, Security::ServerOptions &)
Definition: support.cc:827
void * BIO_get_data(BIO *table)
Definition: openssl.h:60
bool generateSslCertificate(Security::CertPointer &cert, Security::PrivateKeyPointer &pkey, CertificateProperties const &properties)
Definition: gadgets.cc:675
void fatalf(const char *fmt,...)
Definition: fatal.cc:68
static void ssl_ask_password(SSL_CTX *context, const char *prompt)
Definition: support.cc:88
const char * sslGetCAAttribute(SSL *ssl, const char *attribute_name)
Definition: support.cc:685
Security::ContextPointer GenerateSslContext(CertificateProperties const &, Security::ServerOptions &, bool trusted)
Definition: support.cc:813
void useSquidUntrusted(SSL_CTX *sslContext)
Definition: support.cc:1184
Security::PrivateKeyPointer signWithPkey
The key of the signing certificate.
Definition: gadgets.h:218
bool InitServerContext(Security::ContextPointer &, AnyP::PortCfg &)
initialize a TLS server context with OpenSSL specific settings
Definition: support.cc:522
void const char HLPCB void * data
Definition: stub_helper.cc:16
const unsigned char * ASN1_STRING_get0_data(const ASN1_STRING *x)
Definition: openssl.h:52
bool configureSSLUsingPkeyAndCertFromMemory(SSL *ssl, const char *data, AnyP::PortCfg &port)
Definition: support.cc:882
CbDataList< Security::CertError > CertErrors
Holds a list of X.509 certificate errors.
Definition: forward.h:57
size_type length() const
Returns the number of bytes stored in SBuf.
Definition: SBuf.h:404
int ssl_ctx_ex_index_dont_verify_domain
static void ssl_free_ErrorDetail(void *, void *ptr, CRYPTO_EX_DATA *, int, long, void *)
Definition: support.cc:425
#define debugs(SECTION, LEVEL, CONTENT)
Definition: Debug.h:124
#define DBG_IMPORTANT
Definition: Debug.h:46
static void ssl_freeAclChecklist(void *, void *ptr, CRYPTO_EX_DATA *, int, long, void *)
Definition: support.cc:417
int ssl_ex_index_ssl_error_detail
bool push_back_unique(C const &element)
Definition: CbDataList.h:87
Security::CertPointer mimicCert
Certificate to mimic.
Definition: gadgets.h:216
const char * certSignAlgorithm(int sg)
Definition: gadgets.h:163
const char * CommonHostName(X509 *x509)
Definition: gadgets.cc:903
const char * sslGetUserCertificateChainPEM(SSL *ssl)
Definition: support.cc:743
void missingChainCertificatesUrls(std::queue< SBuf > &URIs, Security::CertList const &serverCertificates, const Security::ContextPointer &context)
Definition: support.cc:1080
CertSignAlgorithm
Definition: gadgets.h:150
Security::KeyData signingCa
x509 certificate and key for signing generated certificates
Definition: ServerOptions.h:87
Security::CertPointer serverCert
The peer certificate.
static int check_domain(void *check_data, ASN1_STRING *cn_data)
Definition: support.cc:228
static X509 * sk_x509_findIssuer(STACK_OF(X509)*sk, X509 *cert)
Search for the issuer certificate of cert in sk list.
Definition: support.cc:1107
int ErrorCode
Squid defined error code (&lt;0), an error code returned by X.509 API, or SSL_ERROR_NONE.
Definition: forward.h:91
static int ssl_verify_cb(int ok, X509_STORE_CTX *ctx)
Definition: support.cc:258
void reset()
Forget the raw pointer - unlock if any value was set. Become a nil pointer.
GETX509ATTRIBUTE GetX509CAAttribute
Definition: support.h:120
bool InitClientContext(Security::ContextPointer &, Security::PeerOptions &, long flags)
initialize a TLS client context with OpenSSL specific settings
Definition: support.cc:531
char * xstrncpy(char *dst, const char *src, size_t n)
Definition: xstring.cc:37
std::shared_ptr< SSL_CTX > ContextPointer
Definition: Context.h:29
Security::ContextPointer createSSLContext(Security::CertPointer &x509, Security::PrivateKeyPointer &pkey, Security::ServerOptions &)
Create SSL context and apply ssl certificate and private key to it.
Definition: support.cc:782
void MaybeSetupRsaCallback(Security::ContextPointer &)
if required, setup callback for generating ephemeral RSA keys
Definition: support.cc:170
bool allowed() const
Definition: Acl.h:141
void BIO_set_data(BIO *table, void *data)
Definition: openssl.h:66
static const char * ssl_get_attribute(X509_NAME *name, const char *attribute_name)
Definition: support.cc:595
static int ssl_dupAclChecklist(CRYPTO_EX_DATA *, CRYPTO_EX_DATA *, void *, int, long, void *)
Definition: support.cc:405
const char * c_str()
Definition: SBuf.cc:526
std::unique_ptr< BIO, HardFun< void, BIO *,&BIO_vfree > > BIO_Pointer
Definition: gadgets.h:50
void SSL_add_untrusted_cert(SSL *ssl, X509 *cert)
Definition: support.cc:1092
int ssl_ex_index_ssl_errors
static int port
Definition: ldap_backend.cc:69
static int bio_sbuf_create(BIO *bio)
Definition: support.cc:1256
int unsigned int const char *desc STUB void int len
Definition: stub_fd.cc:20
T * get() const
Returns raw and possibly nullptr pointer.
int bio_sbuf_write(BIO *bio, const char *data, int len)
Definition: support.cc:1272
void const char * buf
Definition: stub_helper.cc:16
const char * uriOfIssuerIfMissing(X509 *cert, Security::CertList const &serverCertificates, const Security::ContextPointer &context)
Definition: support.cc:1059
an std::runtime_error with thrower location info
Definition: TextException.h:19
static char * keys[]
Definition: WinSvc.cc:84
CertSignAlgorithm signAlgorithm
The signing algorithm to use.
Definition: gadgets.h:223
void Initialize()
Definition: support.cc:479
struct SquidConfig::@104 Program
bool configureSSL(SSL *ssl, CertificateProperties const &properties, AnyP::PortCfg &port)
Definition: support.cc:859
static Ssl::CertsIndexedList SquidUntrustedCerts
Definition: support.cc:41
bool checkX509ServerValidity(X509 *cert, const char *server)
Definition: support.cc:251
virtual Security::ContextPointer createBlankContext() const
generate an unset security context object
#define X509_getm_notAfter
Definition: openssl.h:205
#define SQUID_X509_V_ERR_INFINITE_VALIDATION
Definition: support.h:41
allow_t const & fastCheck()
Definition: Checklist.cc:336
void SQUID_OPENSSL_init_ssl(void)
Definition: openssl.h:236
void InRamCertificateDbKey(const Ssl::CertificateProperties &certProperties, SBuf &key)
Definition: support.cc:1229
int ssl_ex_index_ssl_untrusted_chain
Definition: support.cc:39
#define xmalloc
static char server[MAXLINE]
void setClientSNI(SSL *ssl, const char *fqdn)
Definition: support.cc:927
#define SQUID_SSL_SIGN_HASH_IF_NONE
Definition: gadgets.h:39
int bio_sbuf_puts(BIO *bio, const char *data)
Definition: support.cc:1281
bool generateUntrustedCert(Security::CertPointer &untrustedCert, Security::PrivateKeyPointer &untrustedPkey, Security::CertPointer const &cert, Security::PrivateKeyPointer const &pkey)
Definition: support.cc:1206
static int bio_sbuf_destroy(BIO *bio)
Definition: support.cc:1264
static void ssl_free_int(void *, void *ptr, CRYPTO_EX_DATA *, int, long, void *)
Definition: support.cc:442
int asn1timeToString(ASN1_TIME *tm, char *buf, int len)
Definition: support.cc:178
const char * getOrganization(X509 *x509)
Definition: gadgets.cc:908
const Security::CertErrors * sslErrors
SSL [certificate validation] errors, in undefined order.
TLS squid.conf settings for a listening port.
Definition: ServerOptions.h:25
const char * sslGetUserCertificatePEM(SSL *ssl)
Definition: support.cc:705
bool readCertAndPrivateKeyFromMemory(Security::CertPointer &cert, Security::PrivateKeyPointer &pkey, char const *bufferToRead)
Definition: gadgets.cc:116
static void ssl_free_SslErrors(void *, void *ptr, CRYPTO_EX_DATA *, int, long, void *)
Definition: support.cc:433
static void ssl_free_X509(void *, void *ptr, CRYPTO_EX_DATA *, int, long, void *)
Definition: support.cc:462
std::list< Security::KeyData > certs
details from the cert= and file= config parameters
Definition: PeerOptions.h:85
const EVP_MD * signHash
The signing hash to use.
Definition: gadgets.h:224
int matchX509CommonNames(X509 *peer_cert, void *check_data, int(*check_func)(void *check_data, ASN1_STRING *cn_data))
Definition: support.cc:192
#define MAX_URL
Definition: defines.h:118
const EVP_MD * DefaultSignHash
Definition: support.cc:43
int ssl_ex_index_ssl_cert_chain
Security::SessionPointer NewSessionObject(const Security::ContextPointer &)
Definition: Session.cc:97
GETX509ATTRIBUTE GetX509Fingerprint
Definition: support.h:123
static bool Enabled(const int section, const int level)
whether debugging the given section and the given level produces output
Definition: Debug.h:75
void SetupVerifyCallback(Security::ContextPointer &)
set the certificate verify callback for a context
Definition: support.cc:393
void unloadSquidUntrusted()
Definition: support.cc:1196
int matchDomainName(const char *h, const char *d, uint8_t flags)
Definition: Uri.cc:660
#define SQUID_CERT_VALIDATION_ITERATION_MAX
Definition: support.h:54
const char * sslGetUserEmail(SSL *ssl)
Definition: support.cc:699
BIO * BIO_new_SBuf(SBuf *buf)
Definition: support.cc:1305
Config TheConfig
Definition: Config.cc:12
#define Here()
source code location of the caller
Definition: Here.h:15
const char * ErrorString(const ErrorCode code)
Definition: forward.h:96
const ASN1_BIT_STRING * X509_get_signature(const Security::CertPointer &)
Definition: gadgets.cc:939
class SquidConfig Config
Definition: SquidConfig.cc:12
#define NULL
Definition: types.h:166
int size
Definition: ModDevPoll.cc:77
std::shared_ptr< SSL > SessionPointer
Definition: Session.h:42

 

Introduction

Documentation

Support

Miscellaneous

Web Site Translations

Mirrors