]> git.ipfire.org Git - thirdparty/squid.git/blob - src/ssl/support.cc
SourceFormat Enforcement
[thirdparty/squid.git] / src / ssl / support.cc
1
2 /*
3 * $Id$
4 *
5 * AUTHOR: Benno Rice
6 * DEBUG: section 83 SSL accelerator support
7 *
8 * SQUID Internet Object Cache http://squid.nlanr.net/Squid/
9 * ----------------------------------------------------------
10 *
11 * Squid is the result of efforts by numerous individuals from the
12 * Internet community. Development is led by Duane Wessels of the
13 * National Laboratory for Applied Network Research and funded by the
14 * National Science Foundation. Squid is Copyrighted (C) 1998 by
15 * Duane Wessels and the University of California San Diego. Please
16 * see the COPYRIGHT file for full details. Squid incorporates
17 * software developed and/or copyrighted by other sources. Please see
18 * the CREDITS file for full details.
19 *
20 * This program is free software; you can redistribute it and/or modify
21 * it under the terms of the GNU General Public License as published by
22 * the Free Software Foundation; either version 2 of the License, or
23 * (at your option) any later version.
24 *
25 * This program is distributed in the hope that it will be useful,
26 * but WITHOUT ANY WARRANTY; without even the implied warranty of
27 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
28 * GNU General Public License for more details.
29 *
30 * You should have received a copy of the GNU General Public License
31 * along with this program; if not, write to the Free Software
32 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
33 *
34 */
35
36 #include "squid-old.h"
37
38 /* MS Visual Studio Projects are monolithic, so we need the following
39 * #if to exclude the SSL code from compile process when not needed.
40 */
41 #if USE_SSL
42
43 #include "fde.h"
44 #include "acl/FilledChecklist.h"
45 #include "ssl/ErrorDetail.h"
46 #include "ssl/support.h"
47 #include "ssl/gadgets.h"
48
49 const char *Ssl::BumpModeStr[] = {
50 "none",
51 "client-first",
52 "server-first",
53 NULL
54 };
55
56 /**
57 \defgroup ServerProtocolSSLInternal Server-Side SSL Internals
58 \ingroup ServerProtocolSSLAPI
59 */
60
61 /// \ingroup ServerProtocolSSLInternal
62 static int
63 ssl_ask_password_cb(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
78 len--;
79
80 buf[len] = '\0';
81
82 pclose(in);
83
84 return len;
85 }
86
87 /// \ingroup ServerProtocolSSLInternal
88 static void
89 ssl_ask_password(SSL_CTX * context, const char * prompt)
90 {
91 if (Config.Program.ssl_password) {
92 SSL_CTX_set_default_passwd_cb(context, ssl_ask_password_cb);
93 SSL_CTX_set_default_passwd_cb_userdata(context, (void *)prompt);
94 }
95 }
96
97 /// \ingroup ServerProtocolSSLInternal
98 static RSA *
99 ssl_temp_rsa_cb(SSL * ssl, int anInt, int keylen)
100 {
101 static RSA *rsa_512 = NULL;
102 static RSA *rsa_1024 = NULL;
103 RSA *rsa = NULL;
104 int newkey = 0;
105
106 switch (keylen) {
107
108 case 512:
109
110 if (!rsa_512) {
111 rsa_512 = RSA_generate_key(512, RSA_F4, NULL, NULL);
112 newkey = 1;
113 }
114
115 rsa = rsa_512;
116 break;
117
118 case 1024:
119
120 if (!rsa_1024) {
121 rsa_1024 = RSA_generate_key(1024, RSA_F4, NULL, NULL);
122 newkey = 1;
123 }
124
125 rsa = rsa_1024;
126 break;
127
128 default:
129 debugs(83, 1, "ssl_temp_rsa_cb: Unexpected key length " << keylen);
130 return NULL;
131 }
132
133 if (rsa == NULL) {
134 debugs(83, 1, "ssl_temp_rsa_cb: Failed to generate key " << keylen);
135 return NULL;
136 }
137
138 if (newkey) {
139 if (do_debug(83, 5))
140 PEM_write_RSAPrivateKey(debug_log, rsa, NULL, NULL, 0, NULL, NULL);
141
142 debugs(83, 1, "Generated ephemeral RSA key of length " << keylen);
143 }
144
145 return rsa;
146 }
147
148 int Ssl::asn1timeToString(ASN1_TIME *tm, char *buf, int len)
149 {
150 BIO *bio;
151 int write = 0;
152 bio = BIO_new(BIO_s_mem());
153 if (bio) {
154 if (ASN1_TIME_print(bio, tm))
155 write = BIO_read(bio, buf, len-1);
156 BIO_free(bio);
157 }
158 buf[write]='\0';
159 return write;
160 }
161
162 int Ssl::matchX509CommonNames(X509 *peer_cert, void *check_data, int (*check_func)(void *check_data, ASN1_STRING *cn_data))
163 {
164 assert(peer_cert);
165
166 X509_NAME *name = X509_get_subject_name(peer_cert);
167
168 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)) {
169
170 ASN1_STRING *cn_data = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, i));
171
172 if ( (*check_func)(check_data, cn_data) == 0)
173 return 1;
174 }
175
176 STACK_OF(GENERAL_NAME) * altnames;
177 altnames = (STACK_OF(GENERAL_NAME)*)X509_get_ext_d2i(peer_cert, NID_subject_alt_name, NULL, NULL);
178
179 if (altnames) {
180 int numalts = sk_GENERAL_NAME_num(altnames);
181 for (int i = 0; i < numalts; i++) {
182 const GENERAL_NAME *check = sk_GENERAL_NAME_value(altnames, i);
183 if (check->type != GEN_DNS) {
184 continue;
185 }
186 ASN1_STRING *cn_data = check->d.dNSName;
187
188 if ( (*check_func)(check_data, cn_data) == 0)
189 return 1;
190 }
191 sk_GENERAL_NAME_pop_free(altnames, GENERAL_NAME_free);
192 }
193 return 0;
194 }
195
196 static int check_domain( void *check_data, ASN1_STRING *cn_data)
197 {
198 char cn[1024];
199 const char *server = (const char *)check_data;
200
201 if (cn_data->length > (int)sizeof(cn) - 1) {
202 return 1; //if does not fit our buffer just ignore
203 }
204 memcpy(cn, cn_data->data, cn_data->length);
205 cn[cn_data->length] = '\0';
206 debugs(83, 4, "Verifying server domain " << server << " to certificate name/subjectAltName " << cn);
207 return matchDomainName(server, cn[0] == '*' ? cn + 1 : cn);
208 }
209
210 bool Ssl::checkX509ServerValidity(X509 *cert, const char *server)
211 {
212 return matchX509CommonNames(cert, (void *)server, check_domain);
213 }
214
215 /// \ingroup ServerProtocolSSLInternal
216 static int
217 ssl_verify_cb(int ok, X509_STORE_CTX * ctx)
218 {
219 // preserve original ctx->error before SSL_ calls can overwrite it
220 Ssl::ssl_error_t error_no = ok ? SSL_ERROR_NONE : ctx->error;
221
222 char buffer[256] = "";
223 SSL *ssl = (SSL *)X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
224 SSL_CTX *sslctx = SSL_get_SSL_CTX(ssl);
225 const char *server = (const char *)SSL_get_ex_data(ssl, ssl_ex_index_server);
226 void *dont_verify_domain = SSL_CTX_get_ex_data(sslctx, ssl_ctx_ex_index_dont_verify_domain);
227 ACLChecklist *check = (ACLChecklist*)SSL_get_ex_data(ssl, ssl_ex_index_cert_error_check);
228 X509 *peeked_cert = (X509 *)SSL_get_ex_data(ssl, ssl_ex_index_ssl_peeked_cert);
229 X509 *peer_cert = ctx->cert;
230
231 X509_NAME_oneline(X509_get_subject_name(peer_cert), buffer,
232 sizeof(buffer));
233
234 if (ok) {
235 debugs(83, 5, "SSL Certificate signature OK: " << buffer);
236
237 if (server) {
238 if (!Ssl::checkX509ServerValidity(peer_cert, server)) {
239 debugs(83, 2, "SQUID_X509_V_ERR_DOMAIN_MISMATCH: Certificate " << buffer << " does not match domainname " << server);
240 ok = 0;
241 error_no = SQUID_X509_V_ERR_DOMAIN_MISMATCH;
242 }
243 }
244 }
245
246 if (ok && peeked_cert) {
247 // Check whether the already peeked certificate matches the new one.
248 if (X509_cmp(peer_cert, peeked_cert) != 0) {
249 debugs(83, 2, "SQUID_X509_V_ERR_CERT_CHANGE: Certificate " << buffer << " does not match peeked certificate");
250 ok = 0;
251 error_no = SQUID_X509_V_ERR_CERT_CHANGE;
252 }
253 }
254
255 if (!ok) {
256 Ssl::Errors *errs = static_cast<Ssl::Errors *>(SSL_get_ex_data(ssl, ssl_ex_index_ssl_errors));
257 if (!errs) {
258 errs = new Ssl::Errors(error_no);
259 if (!SSL_set_ex_data(ssl, ssl_ex_index_ssl_errors, (void *)errs)) {
260 debugs(83, 2, "Failed to set ssl error_no in ssl_verify_cb: Certificate " << buffer);
261 delete errs;
262 errs = NULL;
263 }
264 } else // remember another error number
265 errs->push_back_unique(error_no);
266
267 if (const char *err_descr = Ssl::GetErrorDescr(error_no))
268 debugs(83, 5, err_descr << ": " << buffer);
269 else
270 debugs(83, DBG_IMPORTANT, "SSL unknown certificate error " << error_no << " in " << buffer);
271
272 if (check) {
273 ACLFilledChecklist *filledCheck = Filled(check);
274 assert(!filledCheck->sslErrors);
275 filledCheck->sslErrors = new Ssl::Errors(error_no);
276 if (check->fastCheck() == ACCESS_ALLOWED) {
277 debugs(83, 3, "bypassing SSL error " << error_no << " in " << buffer);
278 ok = 1;
279 } else {
280 debugs(83, 5, "confirming SSL error " << error_no);
281 }
282 delete filledCheck->sslErrors;
283 filledCheck->sslErrors = NULL;
284 }
285 }
286
287 if (!dont_verify_domain && server) {}
288
289 if (!ok && !SSL_get_ex_data(ssl, ssl_ex_index_ssl_error_detail) ) {
290
291 // Find the broken certificate. It may be intermediate.
292 X509 *broken_cert = peer_cert; // reasonable default if search fails
293 // Our SQUID_X509_V_ERR_DOMAIN_MISMATCH implies peer_cert is at fault.
294 if (error_no != SQUID_X509_V_ERR_DOMAIN_MISMATCH) {
295 if (X509 *last_used_cert = X509_STORE_CTX_get_current_cert(ctx))
296 broken_cert = last_used_cert;
297 }
298
299 Ssl::ErrorDetail *errDetail =
300 new Ssl::ErrorDetail(error_no, peer_cert, broken_cert);
301
302 if (!SSL_set_ex_data(ssl, ssl_ex_index_ssl_error_detail, errDetail)) {
303 debugs(83, 2, "Failed to set Ssl::ErrorDetail in ssl_verify_cb: Certificate " << buffer);
304 delete errDetail;
305 }
306 }
307
308 return ok;
309 }
310
311 /// \ingroup ServerProtocolSSLInternal
312 static struct ssl_option {
313 const char *name;
314 long value;
315 }
316
317 ssl_options[] = {
318
319 #if SSL_OP_MICROSOFT_SESS_ID_BUG
320 {
321 "MICROSOFT_SESS_ID_BUG", SSL_OP_MICROSOFT_SESS_ID_BUG
322 },
323 #endif
324 #if SSL_OP_NETSCAPE_CHALLENGE_BUG
325 {
326 "NETSCAPE_CHALLENGE_BUG", SSL_OP_NETSCAPE_CHALLENGE_BUG
327 },
328 #endif
329 #if SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
330 {
331 "NETSCAPE_REUSE_CIPHER_CHANGE_BUG", SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
332 },
333 #endif
334 #if SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
335 {
336 "SSLREF2_REUSE_CERT_TYPE_BUG", SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
337 },
338 #endif
339 #if SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
340 {
341 "MICROSOFT_BIG_SSLV3_BUFFER", SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
342 },
343 #endif
344 #if SSL_OP_MSIE_SSLV2_RSA_PADDING
345 {
346 "MSIE_SSLV2_RSA_PADDING", SSL_OP_MSIE_SSLV2_RSA_PADDING
347 },
348 #endif
349 #if SSL_OP_SSLEAY_080_CLIENT_DH_BUG
350 {
351 "SSLEAY_080_CLIENT_DH_BUG", SSL_OP_SSLEAY_080_CLIENT_DH_BUG
352 },
353 #endif
354 #if SSL_OP_TLS_D5_BUG
355 {
356 "TLS_D5_BUG", SSL_OP_TLS_D5_BUG
357 },
358 #endif
359 #if SSL_OP_TLS_BLOCK_PADDING_BUG
360 {
361 "TLS_BLOCK_PADDING_BUG", SSL_OP_TLS_BLOCK_PADDING_BUG
362 },
363 #endif
364 #if SSL_OP_TLS_ROLLBACK_BUG
365 {
366 "TLS_ROLLBACK_BUG", SSL_OP_TLS_ROLLBACK_BUG
367 },
368 #endif
369 #if SSL_OP_ALL
370 {
371 "ALL", (long)SSL_OP_ALL
372 },
373 #endif
374 #if SSL_OP_SINGLE_DH_USE
375 {
376 "SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE
377 },
378 #endif
379 #if SSL_OP_EPHEMERAL_RSA
380 {
381 "EPHEMERAL_RSA", SSL_OP_EPHEMERAL_RSA
382 },
383 #endif
384 #if SSL_OP_PKCS1_CHECK_1
385 {
386 "PKCS1_CHECK_1", SSL_OP_PKCS1_CHECK_1
387 },
388 #endif
389 #if SSL_OP_PKCS1_CHECK_2
390 {
391 "PKCS1_CHECK_2", SSL_OP_PKCS1_CHECK_2
392 },
393 #endif
394 #if SSL_OP_NETSCAPE_CA_DN_BUG
395 {
396 "NETSCAPE_CA_DN_BUG", SSL_OP_NETSCAPE_CA_DN_BUG
397 },
398 #endif
399 #if SSL_OP_NON_EXPORT_FIRST
400 {
401 "NON_EXPORT_FIRST", SSL_OP_NON_EXPORT_FIRST
402 },
403 #endif
404 #if SSL_OP_CIPHER_SERVER_PREFERENCE
405 {
406 "CIPHER_SERVER_PREFERENCE", SSL_OP_CIPHER_SERVER_PREFERENCE
407 },
408 #endif
409 #if SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
410 {
411 "NETSCAPE_DEMO_CIPHER_CHANGE_BUG", SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
412 },
413 #endif
414 #if SSL_OP_NO_SSLv2
415 {
416 "NO_SSLv2", SSL_OP_NO_SSLv2
417 },
418 #endif
419 #if SSL_OP_NO_SSLv3
420 {
421 "NO_SSLv3", SSL_OP_NO_SSLv3
422 },
423 #endif
424 #if SSL_OP_NO_TLSv1
425 {
426 "NO_TLSv1", SSL_OP_NO_TLSv1
427 },
428 #endif
429 #if SSL_OP_NO_TLSv1_1
430 {
431 "NO_TLSv1_1", SSL_OP_NO_TLSv1_1
432 },
433 #endif
434 #if SSL_OP_NO_TLSv1_2
435 {
436 "NO_TLSv1_2", SSL_OP_NO_TLSv1_2
437 },
438 #endif
439 {
440 "", 0
441 },
442 {
443 NULL, 0
444 }
445 };
446
447 /// \ingroup ServerProtocolSSLInternal
448 static long
449 ssl_parse_options(const char *options)
450 {
451 long op = 0;
452 char *tmp;
453 char *option;
454
455 if (!options)
456 goto no_options;
457
458 tmp = xstrdup(options);
459
460 option = strtok(tmp, ":,");
461
462 while (option) {
463
464 struct ssl_option *opt = NULL, *opttmp;
465 long value = 0;
466 enum {
467 MODE_ADD, MODE_REMOVE
468 } mode;
469
470 switch (*option) {
471
472 case '!':
473
474 case '-':
475 mode = MODE_REMOVE;
476 option++;
477 break;
478
479 case '+':
480 mode = MODE_ADD;
481 option++;
482 break;
483
484 default:
485 mode = MODE_ADD;
486 break;
487 }
488
489 for (opttmp = ssl_options; opttmp->name; opttmp++) {
490 if (strcmp(opttmp->name, option) == 0) {
491 opt = opttmp;
492 break;
493 }
494 }
495
496 if (opt)
497 value = opt->value;
498 else if (strncmp(option, "0x", 2) == 0) {
499 /* Special case.. hex specification */
500 value = strtol(option + 2, NULL, 16);
501 } else {
502 fatalf("Unknown SSL option '%s'", option);
503 value = 0; /* Keep GCC happy */
504 }
505
506 switch (mode) {
507
508 case MODE_ADD:
509 op |= value;
510 break;
511
512 case MODE_REMOVE:
513 op &= ~value;
514 break;
515 }
516
517 option = strtok(NULL, ":,");
518 }
519
520 safe_free(tmp);
521
522 no_options:
523 return op;
524 }
525
526 /// \ingroup ServerProtocolSSLInternal
527 #define SSL_FLAG_NO_DEFAULT_CA (1<<0)
528 /// \ingroup ServerProtocolSSLInternal
529 #define SSL_FLAG_DELAYED_AUTH (1<<1)
530 /// \ingroup ServerProtocolSSLInternal
531 #define SSL_FLAG_DONT_VERIFY_PEER (1<<2)
532 /// \ingroup ServerProtocolSSLInternal
533 #define SSL_FLAG_DONT_VERIFY_DOMAIN (1<<3)
534 /// \ingroup ServerProtocolSSLInternal
535 #define SSL_FLAG_NO_SESSION_REUSE (1<<4)
536 /// \ingroup ServerProtocolSSLInternal
537 #define SSL_FLAG_VERIFY_CRL (1<<5)
538 /// \ingroup ServerProtocolSSLInternal
539 #define SSL_FLAG_VERIFY_CRL_ALL (1<<6)
540
541 /// \ingroup ServerProtocolSSLInternal
542 static long
543 ssl_parse_flags(const char *flags)
544 {
545 long fl = 0;
546 char *tmp;
547 char *flag;
548
549 if (!flags)
550 return 0;
551
552 tmp = xstrdup(flags);
553
554 flag = strtok(tmp, ":,");
555
556 while (flag) {
557 if (strcmp(flag, "NO_DEFAULT_CA") == 0)
558 fl |= SSL_FLAG_NO_DEFAULT_CA;
559 else if (strcmp(flag, "DELAYED_AUTH") == 0)
560 fl |= SSL_FLAG_DELAYED_AUTH;
561 else if (strcmp(flag, "DONT_VERIFY_PEER") == 0)
562 fl |= SSL_FLAG_DONT_VERIFY_PEER;
563 else if (strcmp(flag, "DONT_VERIFY_DOMAIN") == 0)
564 fl |= SSL_FLAG_DONT_VERIFY_DOMAIN;
565 else if (strcmp(flag, "NO_SESSION_REUSE") == 0)
566 fl |= SSL_FLAG_NO_SESSION_REUSE;
567
568 #if X509_V_FLAG_CRL_CHECK
569
570 else if (strcmp(flag, "VERIFY_CRL") == 0)
571 fl |= SSL_FLAG_VERIFY_CRL;
572 else if (strcmp(flag, "VERIFY_CRL_ALL") == 0)
573 fl |= SSL_FLAG_VERIFY_CRL_ALL;
574
575 #endif
576
577 else
578 fatalf("Unknown ssl flag '%s'", flag);
579
580 flag = strtok(NULL, ":,");
581 }
582
583 safe_free(tmp);
584 return fl;
585 }
586
587 // "dup" function for SSL_get_ex_new_index("cert_err_check")
588 static int
589 ssl_dupAclChecklist(CRYPTO_EX_DATA *, CRYPTO_EX_DATA *, void *,
590 int, long, void *)
591 {
592 // We do not support duplication of ACLCheckLists.
593 // If duplication is needed, we can count copies with cbdata.
594 assert(false);
595 return 0;
596 }
597
598 // "free" function for SSL_get_ex_new_index("cert_err_check")
599 static void
600 ssl_freeAclChecklist(void *, void *ptr, CRYPTO_EX_DATA *,
601 int, long, void *)
602 {
603 delete static_cast<ACLChecklist *>(ptr); // may be NULL
604 }
605
606 // "free" function for SSL_get_ex_new_index("ssl_error_detail")
607 static void
608 ssl_free_ErrorDetail(void *, void *ptr, CRYPTO_EX_DATA *,
609 int, long, void *)
610 {
611 Ssl::ErrorDetail *errDetail = static_cast <Ssl::ErrorDetail *>(ptr);
612 delete errDetail;
613 }
614
615 static void
616 ssl_free_SslErrors(void *, void *ptr, CRYPTO_EX_DATA *,
617 int, long, void *)
618 {
619 Ssl::Errors *errs = static_cast <Ssl::Errors*>(ptr);
620 delete errs;
621 }
622
623 // "free" function for X509 certificates
624 static void
625 ssl_free_X509(void *, void *ptr, CRYPTO_EX_DATA *,
626 int, long, void *)
627 {
628 X509 *cert = static_cast <X509 *>(ptr);
629 X509_free(cert);
630 }
631
632 /// \ingroup ServerProtocolSSLInternal
633 static void
634 ssl_initialize(void)
635 {
636 static int ssl_initialized = 0;
637
638 if (!ssl_initialized) {
639 ssl_initialized = 1;
640 SSL_load_error_strings();
641 SSLeay_add_ssl_algorithms();
642 #if HAVE_OPENSSL_ENGINE_H
643
644 if (Config.SSL.ssl_engine) {
645 ENGINE *e;
646
647 if (!(e = ENGINE_by_id(Config.SSL.ssl_engine))) {
648 fatalf("Unable to find SSL engine '%s'\n", Config.SSL.ssl_engine);
649 }
650
651 if (!ENGINE_set_default(e, ENGINE_METHOD_ALL)) {
652 int ssl_error = ERR_get_error();
653 fatalf("Failed to initialise SSL engine: %s\n",
654 ERR_error_string(ssl_error, NULL));
655 }
656 }
657
658 #else
659 if (Config.SSL.ssl_engine) {
660 fatalf("Your OpenSSL has no SSL engine support\n");
661 }
662
663 #endif
664
665 }
666
667 ssl_ex_index_server = SSL_get_ex_new_index(0, (void *) "server", NULL, NULL, NULL);
668 ssl_ctx_ex_index_dont_verify_domain = SSL_CTX_get_ex_new_index(0, (void *) "dont_verify_domain", NULL, NULL, NULL);
669 ssl_ex_index_cert_error_check = SSL_get_ex_new_index(0, (void *) "cert_error_check", NULL, &ssl_dupAclChecklist, &ssl_freeAclChecklist);
670 ssl_ex_index_ssl_error_detail = SSL_get_ex_new_index(0, (void *) "ssl_error_detail", NULL, NULL, &ssl_free_ErrorDetail);
671 ssl_ex_index_ssl_peeked_cert = SSL_get_ex_new_index(0, (void *) "ssl_peeked_cert", NULL, NULL, &ssl_free_X509);
672 ssl_ex_index_ssl_errors = SSL_get_ex_new_index(0, (void *) "ssl_errors", NULL, NULL, &ssl_free_SslErrors);
673 }
674
675 /// \ingroup ServerProtocolSSLInternal
676 static int
677 ssl_load_crl(SSL_CTX *sslContext, const char *CRLfile)
678 {
679 X509_STORE *st = SSL_CTX_get_cert_store(sslContext);
680 X509_CRL *crl;
681 BIO *in = BIO_new_file(CRLfile, "r");
682 int count = 0;
683
684 if (!in) {
685 debugs(83, 2, "WARNING: Failed to open CRL file '" << CRLfile << "'");
686 return 0;
687 }
688
689 while ((crl = PEM_read_bio_X509_CRL(in,NULL,NULL,NULL))) {
690 if (!X509_STORE_add_crl(st, crl))
691 debugs(83, 2, "WARNING: Failed to add CRL from file '" << CRLfile << "'");
692 else
693 count++;
694
695 X509_CRL_free(crl);
696 }
697
698 BIO_free(in);
699 return count;
700 }
701
702 SSL_CTX *
703 sslCreateServerContext(const char *certfile, const char *keyfile, int version, const char *cipher, const char *options, const char *flags, const char *clientCA, const char *CAfile, const char *CApath, const char *CRLfile, const char *dhfile, const char *context)
704 {
705 int ssl_error;
706 #if OPENSSL_VERSION_NUMBER < 0x00909000L
707 SSL_METHOD *method;
708 #else
709 const SSL_METHOD *method;
710 #endif
711 SSL_CTX *sslContext;
712 long fl = ssl_parse_flags(flags);
713
714 ssl_initialize();
715
716 if (!keyfile)
717 keyfile = certfile;
718
719 if (!certfile)
720 certfile = keyfile;
721
722 if (!CAfile)
723 CAfile = clientCA;
724
725 if (!certfile) {
726 debugs(83, DBG_CRITICAL, "ERROR: No certificate file");
727 return NULL;
728 }
729
730 switch (version) {
731
732 case 2:
733 #ifndef OPENSSL_NO_SSL2
734 debugs(83, 5, "Using SSLv2.");
735 method = SSLv2_server_method();
736 #else
737 debugs(83, DBG_IMPORTANT, "SSLv2 is not available in this Proxy.");
738 return NULL;
739 #endif
740 break;
741
742 case 3:
743 debugs(83, 5, "Using SSLv3.");
744 method = SSLv3_server_method();
745 break;
746
747 case 4:
748 debugs(83, 5, "Using TLSv1.");
749 method = TLSv1_server_method();
750 break;
751
752 case 5:
753 #if OPENSSL_VERSION_NUMBER >= 0x10001000L // NP: not sure exactly which sub-version yet.
754 debugs(83, 5, "Using TLSv1.1.");
755 method = TLSv1_1_server_method();
756 #else
757 debugs(83, DBG_IMPORTANT, "TLSv1.1 is not available in this Proxy.");
758 return NULL;
759 #endif
760 break;
761
762 case 6:
763 #if OPENSSL_VERSION_NUMBER >= 0x10001000L // NP: not sure exactly which sub-version yet.
764 debugs(83, 5, "Using TLSv1.2");
765 method = TLSv1_2_server_method();
766 #else
767 debugs(83, DBG_IMPORTANT, "TLSv1.2 is not available in this Proxy.");
768 return NULL;
769 #endif
770 break;
771
772 case 1:
773
774 default:
775 debugs(83, 5, "Using SSLv2/SSLv3.");
776 method = SSLv23_server_method();
777 break;
778 }
779
780 sslContext = SSL_CTX_new(method);
781
782 if (sslContext == NULL) {
783 ssl_error = ERR_get_error();
784 debugs(83, DBG_CRITICAL, "ERROR: Failed to allocate SSL context: " << ERR_error_string(ssl_error, NULL));
785 return NULL;
786 }
787
788 SSL_CTX_set_options(sslContext, ssl_parse_options(options));
789
790 if (context && *context) {
791 SSL_CTX_set_session_id_context(sslContext, (const unsigned char *)context, strlen(context));
792 }
793
794 if (fl & SSL_FLAG_NO_SESSION_REUSE) {
795 SSL_CTX_set_session_cache_mode(sslContext, SSL_SESS_CACHE_OFF);
796 }
797
798 if (Config.SSL.unclean_shutdown) {
799 debugs(83, 5, "Enabling quiet SSL shutdowns (RFC violation).");
800
801 SSL_CTX_set_quiet_shutdown(sslContext, 1);
802 }
803
804 if (cipher) {
805 debugs(83, 5, "Using chiper suite " << cipher << ".");
806
807 if (!SSL_CTX_set_cipher_list(sslContext, cipher)) {
808 ssl_error = ERR_get_error();
809 debugs(83, DBG_CRITICAL, "ERROR: Failed to set SSL cipher suite '" << cipher << "': " << ERR_error_string(ssl_error, NULL));
810 SSL_CTX_free(sslContext);
811 return NULL;
812 }
813 }
814
815 debugs(83, DBG_IMPORTANT, "Using certificate in " << certfile);
816
817 if (!SSL_CTX_use_certificate_chain_file(sslContext, certfile)) {
818 ssl_error = ERR_get_error();
819 debugs(83, DBG_CRITICAL, "ERROR: Failed to acquire SSL certificate '" << certfile << "': " << ERR_error_string(ssl_error, NULL));
820 SSL_CTX_free(sslContext);
821 return NULL;
822 }
823
824 debugs(83, DBG_IMPORTANT, "Using private key in " << keyfile);
825 ssl_ask_password(sslContext, keyfile);
826
827 if (!SSL_CTX_use_PrivateKey_file(sslContext, keyfile, SSL_FILETYPE_PEM)) {
828 ssl_error = ERR_get_error();
829 debugs(83, DBG_CRITICAL, "ERROR: Failed to acquire SSL private key '" << keyfile << "': " << ERR_error_string(ssl_error, NULL));
830 SSL_CTX_free(sslContext);
831 return NULL;
832 }
833
834 debugs(83, 5, "Comparing private and public SSL keys.");
835
836 if (!SSL_CTX_check_private_key(sslContext)) {
837 ssl_error = ERR_get_error();
838 debugs(83, DBG_CRITICAL, "ERROR: SSL private key '" << certfile << "' does not match public key '" <<
839 keyfile << "': " << ERR_error_string(ssl_error, NULL));
840 SSL_CTX_free(sslContext);
841 return NULL;
842 }
843
844 debugs(83, 9, "Setting RSA key generation callback.");
845 SSL_CTX_set_tmp_rsa_callback(sslContext, ssl_temp_rsa_cb);
846
847 debugs(83, 9, "Setting CA certificate locations.");
848
849 if ((CAfile || CApath) && !SSL_CTX_load_verify_locations(sslContext, CAfile, CApath)) {
850 ssl_error = ERR_get_error();
851 debugs(83, DBG_IMPORTANT, "WARNING: Ignoring error setting CA certificate locations: " << ERR_error_string(ssl_error, NULL));
852 }
853
854 if (!(fl & SSL_FLAG_NO_DEFAULT_CA) &&
855 !SSL_CTX_set_default_verify_paths(sslContext)) {
856 ssl_error = ERR_get_error();
857 debugs(83, DBG_IMPORTANT, "WARNING: Ignoring error setting default CA certificate location: " << ERR_error_string(ssl_error, NULL));
858 }
859
860 if (clientCA) {
861 STACK_OF(X509_NAME) *cert_names;
862 debugs(83, 9, "Set client certifying authority list.");
863 cert_names = SSL_load_client_CA_file(clientCA);
864
865 if (cert_names == NULL) {
866 debugs(83, DBG_IMPORTANT, "ERROR: loading the client CA certificates from '" << clientCA << "\': " << ERR_error_string(ERR_get_error(),NULL));
867 SSL_CTX_free(sslContext);
868 return NULL;
869 }
870
871 ERR_clear_error();
872 SSL_CTX_set_client_CA_list(sslContext, cert_names);
873
874 if (fl & SSL_FLAG_DELAYED_AUTH) {
875 debugs(83, 9, "Not requesting client certificates until acl processing requires one");
876 SSL_CTX_set_verify(sslContext, SSL_VERIFY_NONE, NULL);
877 } else {
878 debugs(83, 9, "Requiring client certificates.");
879 SSL_CTX_set_verify(sslContext, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, ssl_verify_cb);
880 }
881
882 if (CRLfile) {
883 ssl_load_crl(sslContext, CRLfile);
884 fl |= SSL_FLAG_VERIFY_CRL;
885 }
886
887 #if X509_V_FLAG_CRL_CHECK
888 if (fl & SSL_FLAG_VERIFY_CRL_ALL)
889 X509_STORE_set_flags(SSL_CTX_get_cert_store(sslContext), X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
890 else if (fl & SSL_FLAG_VERIFY_CRL)
891 X509_STORE_set_flags(SSL_CTX_get_cert_store(sslContext), X509_V_FLAG_CRL_CHECK);
892
893 #endif
894
895 } else {
896 debugs(83, 9, "Not requiring any client certificates");
897 SSL_CTX_set_verify(sslContext, SSL_VERIFY_NONE, NULL);
898 }
899
900 if (dhfile) {
901 FILE *in = fopen(dhfile, "r");
902 DH *dh = NULL;
903 int codes;
904
905 if (in) {
906 dh = PEM_read_DHparams(in, NULL, NULL, NULL);
907 fclose(in);
908 }
909
910 if (!dh)
911 debugs(83, DBG_IMPORTANT, "WARNING: Failed to read DH parameters '" << dhfile << "'");
912 else if (dh && DH_check(dh, &codes) == 0) {
913 if (codes) {
914 debugs(83, DBG_IMPORTANT, "WARNING: Failed to verify DH parameters '" << dhfile << "' (" << std::hex << codes << ")");
915 DH_free(dh);
916 dh = NULL;
917 }
918 }
919
920 if (dh)
921 SSL_CTX_set_tmp_dh(sslContext, dh);
922 }
923
924 if (fl & SSL_FLAG_DONT_VERIFY_DOMAIN)
925 SSL_CTX_set_ex_data(sslContext, ssl_ctx_ex_index_dont_verify_domain, (void *) -1);
926
927 return sslContext;
928 }
929
930 SSL_CTX *
931 sslCreateClientContext(const char *certfile, const char *keyfile, int version, const char *cipher, const char *options, const char *flags, const char *CAfile, const char *CApath, const char *CRLfile)
932 {
933 int ssl_error;
934 #if OPENSSL_VERSION_NUMBER < 0x00909000L
935 SSL_METHOD *method;
936 #else
937 const SSL_METHOD *method;
938 #endif
939 SSL_CTX *sslContext;
940 long fl = ssl_parse_flags(flags);
941
942 ssl_initialize();
943
944 if (!keyfile)
945 keyfile = certfile;
946
947 if (!certfile)
948 certfile = keyfile;
949
950 switch (version) {
951
952 case 2:
953 #ifndef OPENSSL_NO_SSL2
954 debugs(83, 5, "Using SSLv2.");
955 method = SSLv2_client_method();
956 #else
957 debugs(83, DBG_IMPORTANT, "SSLv2 is not available in this Proxy.");
958 return NULL;
959 #endif
960 break;
961
962 case 3:
963 debugs(83, 5, "Using SSLv3.");
964 method = SSLv3_client_method();
965 break;
966
967 case 4:
968 debugs(83, 5, "Using TLSv1.");
969 method = TLSv1_client_method();
970 break;
971
972 case 5:
973 #if OPENSSL_VERSION_NUMBER >= 0x10001000L // NP: not sure exactly which sub-version yet.
974 debugs(83, 5, "Using TLSv1.1.");
975 method = TLSv1_1_client_method();
976 #else
977 debugs(83, DBG_IMPORTANT, "TLSv1.1 is not available in this Proxy.");
978 return NULL;
979 #endif
980 break;
981
982 case 6:
983 #if OPENSSL_VERSION_NUMBER >= 0x10001000L // NP: not sure exactly which sub-version yet.
984 debugs(83, 5, "Using TLSv1.2");
985 method = TLSv1_2_client_method();
986 #else
987 debugs(83, DBG_IMPORTANT, "TLSv1.2 is not available in this Proxy.");
988 return NULL;
989 #endif
990 break;
991
992 case 1:
993
994 default:
995 debugs(83, 5, "Using SSLv2/SSLv3.");
996 method = SSLv23_client_method();
997 break;
998 }
999
1000 sslContext = SSL_CTX_new(method);
1001
1002 if (sslContext == NULL) {
1003 ssl_error = ERR_get_error();
1004 fatalf("Failed to allocate SSL context: %s\n",
1005 ERR_error_string(ssl_error, NULL));
1006 }
1007
1008 SSL_CTX_set_options(sslContext, ssl_parse_options(options));
1009
1010 if (cipher) {
1011 debugs(83, 5, "Using chiper suite " << cipher << ".");
1012
1013 if (!SSL_CTX_set_cipher_list(sslContext, cipher)) {
1014 ssl_error = ERR_get_error();
1015 fatalf("Failed to set SSL cipher suite '%s': %s\n",
1016 cipher, ERR_error_string(ssl_error, NULL));
1017 }
1018 }
1019
1020 if (certfile) {
1021 debugs(83, 1, "Using certificate in " << certfile);
1022
1023 if (!SSL_CTX_use_certificate_chain_file(sslContext, certfile)) {
1024 ssl_error = ERR_get_error();
1025 fatalf("Failed to acquire SSL certificate '%s': %s\n",
1026 certfile, ERR_error_string(ssl_error, NULL));
1027 }
1028
1029 debugs(83, 1, "Using private key in " << keyfile);
1030 ssl_ask_password(sslContext, keyfile);
1031
1032 if (!SSL_CTX_use_PrivateKey_file(sslContext, keyfile, SSL_FILETYPE_PEM)) {
1033 ssl_error = ERR_get_error();
1034 fatalf("Failed to acquire SSL private key '%s': %s\n",
1035 keyfile, ERR_error_string(ssl_error, NULL));
1036 }
1037
1038 debugs(83, 5, "Comparing private and public SSL keys.");
1039
1040 if (!SSL_CTX_check_private_key(sslContext)) {
1041 ssl_error = ERR_get_error();
1042 fatalf("SSL private key '%s' does not match public key '%s': %s\n",
1043 certfile, keyfile, ERR_error_string(ssl_error, NULL));
1044 }
1045 }
1046
1047 debugs(83, 9, "Setting RSA key generation callback.");
1048 SSL_CTX_set_tmp_rsa_callback(sslContext, ssl_temp_rsa_cb);
1049
1050 if (fl & SSL_FLAG_DONT_VERIFY_PEER) {
1051 debugs(83, 2, "NOTICE: Peer certificates are not verified for validity!");
1052 SSL_CTX_set_verify(sslContext, SSL_VERIFY_NONE, NULL);
1053 } else {
1054 debugs(83, 9, "Setting certificate verification callback.");
1055 SSL_CTX_set_verify(sslContext, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, ssl_verify_cb);
1056 }
1057
1058 debugs(83, 9, "Setting CA certificate locations.");
1059
1060 if ((CAfile || CApath) && !SSL_CTX_load_verify_locations(sslContext, CAfile, CApath)) {
1061 ssl_error = ERR_get_error();
1062 debugs(83, DBG_IMPORTANT, "WARNING: Ignoring error setting CA certificate locations: " << ERR_error_string(ssl_error, NULL));
1063 }
1064
1065 if (CRLfile) {
1066 ssl_load_crl(sslContext, CRLfile);
1067 fl |= SSL_FLAG_VERIFY_CRL;
1068 }
1069
1070 #if X509_V_FLAG_CRL_CHECK
1071 if (fl & SSL_FLAG_VERIFY_CRL_ALL)
1072 X509_STORE_set_flags(SSL_CTX_get_cert_store(sslContext), X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
1073 else if (fl & SSL_FLAG_VERIFY_CRL)
1074 X509_STORE_set_flags(SSL_CTX_get_cert_store(sslContext), X509_V_FLAG_CRL_CHECK);
1075
1076 #endif
1077
1078 if (!(fl & SSL_FLAG_NO_DEFAULT_CA) &&
1079 !SSL_CTX_set_default_verify_paths(sslContext)) {
1080 ssl_error = ERR_get_error();
1081 debugs(83, DBG_IMPORTANT, "WARNING: Ignoring error setting default CA certificate location: " << ERR_error_string(ssl_error, NULL));
1082 }
1083
1084 return sslContext;
1085 }
1086
1087 /// \ingroup ServerProtocolSSLInternal
1088 int
1089 ssl_read_method(int fd, char *buf, int len)
1090 {
1091 SSL *ssl = fd_table[fd].ssl;
1092 int i;
1093
1094 #if DONT_DO_THIS
1095
1096 if (!SSL_is_init_finished(ssl)) {
1097 errno = ENOTCONN;
1098 return -1;
1099 }
1100
1101 #endif
1102
1103 i = SSL_read(ssl, buf, len);
1104
1105 if (i > 0 && SSL_pending(ssl) > 0) {
1106 debugs(83, 2, "SSL FD " << fd << " is pending");
1107 fd_table[fd].flags.read_pending = 1;
1108 } else
1109 fd_table[fd].flags.read_pending = 0;
1110
1111 return i;
1112 }
1113
1114 /// \ingroup ServerProtocolSSLInternal
1115 int
1116 ssl_write_method(int fd, const char *buf, int len)
1117 {
1118 SSL *ssl = fd_table[fd].ssl;
1119 int i;
1120
1121 if (!SSL_is_init_finished(ssl)) {
1122 errno = ENOTCONN;
1123 return -1;
1124 }
1125
1126 i = SSL_write(ssl, buf, len);
1127
1128 return i;
1129 }
1130
1131 void
1132 ssl_shutdown_method(SSL *ssl)
1133 {
1134 SSL_shutdown(ssl);
1135 }
1136
1137 /// \ingroup ServerProtocolSSLInternal
1138 static const char *
1139 ssl_get_attribute(X509_NAME * name, const char *attribute_name)
1140 {
1141 static char buffer[1024];
1142 int nid;
1143
1144 buffer[0] = '\0';
1145
1146 if (strcmp(attribute_name, "DN") == 0) {
1147 X509_NAME_oneline(name, buffer, sizeof(buffer));
1148 goto done;
1149 }
1150
1151 nid = OBJ_txt2nid((char *) attribute_name);
1152
1153 if (nid == 0) {
1154 debugs(83, 1, "WARNING: Unknown SSL attribute name '" << attribute_name << "'");
1155 return NULL;
1156 }
1157
1158 X509_NAME_get_text_by_NID(name, nid, buffer, sizeof(buffer));
1159
1160 done:
1161 return *buffer ? buffer : NULL;
1162 }
1163
1164 /// \ingroup ServerProtocolSSLInternal
1165 const char *
1166 sslGetUserAttribute(SSL * ssl, const char *attribute_name)
1167 {
1168 X509 *cert;
1169 X509_NAME *name;
1170 const char *ret;
1171
1172 if (!ssl)
1173 return NULL;
1174
1175 cert = SSL_get_peer_certificate(ssl);
1176
1177 if (!cert)
1178 return NULL;
1179
1180 name = X509_get_subject_name(cert);
1181
1182 ret = ssl_get_attribute(name, attribute_name);
1183
1184 X509_free(cert);
1185
1186 return ret;
1187 }
1188
1189 /// \ingroup ServerProtocolSSLInternal
1190 const char *
1191 sslGetCAAttribute(SSL * ssl, const char *attribute_name)
1192 {
1193 X509 *cert;
1194 X509_NAME *name;
1195 const char *ret;
1196
1197 if (!ssl)
1198 return NULL;
1199
1200 cert = SSL_get_peer_certificate(ssl);
1201
1202 if (!cert)
1203 return NULL;
1204
1205 name = X509_get_issuer_name(cert);
1206
1207 ret = ssl_get_attribute(name, attribute_name);
1208
1209 X509_free(cert);
1210
1211 return ret;
1212 }
1213
1214 const char *
1215 sslGetUserEmail(SSL * ssl)
1216 {
1217 return sslGetUserAttribute(ssl, "emailAddress");
1218 }
1219
1220 const char *
1221 sslGetUserCertificatePEM(SSL *ssl)
1222 {
1223 X509 *cert;
1224 BIO *mem;
1225 static char *str = NULL;
1226 char *ptr;
1227 long len;
1228
1229 safe_free(str);
1230
1231 if (!ssl)
1232 return NULL;
1233
1234 cert = SSL_get_peer_certificate(ssl);
1235
1236 if (!cert)
1237 return NULL;
1238
1239 mem = BIO_new(BIO_s_mem());
1240
1241 PEM_write_bio_X509(mem, cert);
1242
1243
1244 len = BIO_get_mem_data(mem, &ptr);
1245
1246 str = (char *)xmalloc(len + 1);
1247
1248 memcpy(str, ptr, len);
1249
1250 str[len] = '\0';
1251
1252 X509_free(cert);
1253
1254 BIO_free(mem);
1255
1256 return str;
1257 }
1258
1259 const char *
1260 sslGetUserCertificateChainPEM(SSL *ssl)
1261 {
1262 STACK_OF(X509) *chain;
1263 BIO *mem;
1264 static char *str = NULL;
1265 char *ptr;
1266 long len;
1267 int i;
1268
1269 safe_free(str);
1270
1271 if (!ssl)
1272 return NULL;
1273
1274 chain = SSL_get_peer_cert_chain(ssl);
1275
1276 if (!chain)
1277 return sslGetUserCertificatePEM(ssl);
1278
1279 mem = BIO_new(BIO_s_mem());
1280
1281 for (i = 0; i < sk_X509_num(chain); i++) {
1282 X509 *cert = sk_X509_value(chain, i);
1283 PEM_write_bio_X509(mem, cert);
1284 }
1285
1286 len = BIO_get_mem_data(mem, &ptr);
1287
1288 str = (char *)xmalloc(len + 1);
1289 memcpy(str, ptr, len);
1290 str[len] = '\0';
1291
1292 BIO_free(mem);
1293
1294 return str;
1295 }
1296
1297 /// \ingroup ServerProtocolSSLInternal
1298 /// Create SSL context and apply ssl certificate and private key to it.
1299 static SSL_CTX * createSSLContext(Ssl::X509_Pointer & x509, Ssl::EVP_PKEY_Pointer & pkey)
1300 {
1301 Ssl::SSL_CTX_Pointer sslContext(SSL_CTX_new(SSLv23_server_method()));
1302
1303 if (!SSL_CTX_use_certificate(sslContext.get(), x509.get()))
1304 return NULL;
1305
1306 if (!SSL_CTX_use_PrivateKey(sslContext.get(), pkey.get()))
1307 return NULL;
1308 return sslContext.release();
1309 }
1310
1311 SSL_CTX * Ssl::generateSslContextUsingPkeyAndCertFromMemory(const char * data)
1312 {
1313 Ssl::X509_Pointer cert;
1314 Ssl::EVP_PKEY_Pointer pkey;
1315 if (!readCertAndPrivateKeyFromMemory(cert, pkey, data))
1316 return NULL;
1317
1318 if (!cert || !pkey)
1319 return NULL;
1320
1321 return createSSLContext(cert, pkey);
1322 }
1323
1324 SSL_CTX * Ssl::generateSslContext(CertificateProperties const &properties)
1325 {
1326 Ssl::X509_Pointer cert;
1327 Ssl::EVP_PKEY_Pointer pkey;
1328 if (!generateSslCertificate(cert, pkey, properties))
1329 return NULL;
1330
1331 if (!cert)
1332 return NULL;
1333
1334 if (!pkey)
1335 return NULL;
1336
1337 return createSSLContext(cert, pkey);
1338 }
1339
1340 bool Ssl::verifySslCertificate(SSL_CTX * sslContext, CertificateProperties const &properties)
1341 {
1342 // Temporary ssl for getting X509 certificate from SSL_CTX.
1343 Ssl::SSL_Pointer ssl(SSL_new(sslContext));
1344 X509 * cert = SSL_get_certificate(ssl.get());
1345 ASN1_TIME * time_notBefore = X509_get_notBefore(cert);
1346 ASN1_TIME * time_notAfter = X509_get_notAfter(cert);
1347 bool ret = (X509_cmp_current_time(time_notBefore) < 0 && X509_cmp_current_time(time_notAfter) > 0);
1348 if (!ret)
1349 return false;
1350
1351 return certificateMatchesProperties(cert, properties);
1352 }
1353
1354 bool
1355 Ssl::setClientSNI(SSL *ssl, const char *fqdn)
1356 {
1357 //The SSL_CTRL_SET_TLSEXT_HOSTNAME is a openssl macro which indicates
1358 // if the TLS servername extension (SNI) is enabled in openssl library.
1359 #if defined(SSL_CTRL_SET_TLSEXT_HOSTNAME)
1360 if (!SSL_set_tlsext_host_name(ssl, fqdn)) {
1361 const int ssl_error = ERR_get_error();
1362 debugs(83, 3, "WARNING: unable to set TLS servername extension (SNI): " <<
1363 ERR_error_string(ssl_error, NULL) << "\n");
1364 return false;
1365 }
1366 return true;
1367 #else
1368 debugs(83, 7, "no support for TLS servername extension (SNI)\n");
1369 return false;
1370 #endif
1371 }
1372
1373 void Ssl::addChainToSslContext(SSL_CTX *sslContext, STACK_OF(X509) *chain)
1374 {
1375 if (!chain)
1376 return;
1377
1378 for (int i = 0; i < sk_X509_num(chain); i++) {
1379 X509 *cert = sk_X509_value(chain, i);
1380 if (SSL_CTX_add_extra_chain_cert(sslContext, cert)) {
1381 // increase the certificate lock
1382 CRYPTO_add(&(cert->references),1,CRYPTO_LOCK_X509);
1383 } else {
1384 const int ssl_error = ERR_get_error();
1385 debugs(83, DBG_IMPORTANT, "WARNING: can not add certificate to SSL context chain: " << ERR_error_string(ssl_error, NULL));
1386 }
1387 }
1388 }
1389
1390 /**
1391 \ingroup ServerProtocolSSLInternal
1392 * Read certificate from file.
1393 * See also: static readSslX509Certificate function, gadgets.cc file
1394 */
1395 static X509 * readSslX509CertificatesChain(char const * certFilename, STACK_OF(X509)* chain)
1396 {
1397 if (!certFilename)
1398 return NULL;
1399 Ssl::BIO_Pointer bio(BIO_new(BIO_s_file_internal()));
1400 if (!bio)
1401 return NULL;
1402 if (!BIO_read_filename(bio.get(), certFilename))
1403 return NULL;
1404 X509 *certificate = PEM_read_bio_X509(bio.get(), NULL, NULL, NULL);
1405
1406 if (certificate && chain) {
1407
1408 if (X509_check_issued(certificate, certificate) == X509_V_OK)
1409 debugs(83, 5, "Certificate is self-signed, will not be chained");
1410 else {
1411 if (sk_X509_push(chain, certificate))
1412 CRYPTO_add(&(certificate->references), 1, CRYPTO_LOCK_X509);
1413 else
1414 debugs(83, DBG_IMPORTANT, "WARNING: unable to add signing certificate to cert chain");
1415 // and add to the chain any certificate loaded from the file
1416 while (X509 *ca = PEM_read_bio_X509(bio.get(), NULL, NULL, NULL)) {
1417 if (!sk_X509_push(chain, ca))
1418 debugs(83, DBG_IMPORTANT, "WARNING: unable to add CA certificate to cert chain");
1419 }
1420 }
1421 }
1422
1423 return certificate;
1424 }
1425
1426 void Ssl::readCertChainAndPrivateKeyFromFiles(X509_Pointer & cert, EVP_PKEY_Pointer & pkey, X509_STACK_Pointer & chain, char const * certFilename, char const * keyFilename)
1427 {
1428 if (keyFilename == NULL)
1429 keyFilename = certFilename;
1430 if (!chain)
1431 chain.reset(sk_X509_new_null());
1432 if (!chain)
1433 debugs(83, DBG_IMPORTANT, "WARNING: unable to allocate memory for cert chain");
1434 pkey.reset(readSslPrivateKey(keyFilename, ssl_ask_password_cb));
1435 cert.reset(readSslX509CertificatesChain(certFilename, chain.get()));
1436 if (!pkey || !cert || !X509_check_private_key(cert.get(), pkey.get())) {
1437 pkey.reset(NULL);
1438 cert.reset(NULL);
1439 }
1440 }
1441
1442 bool Ssl::generateUntrustedCert(X509_Pointer &untrustedCert, EVP_PKEY_Pointer &untrustedPkey, X509_Pointer const &cert, EVP_PKEY_Pointer const & pkey)
1443 {
1444 // Generate the self-signed certificate, using a hard-coded subject prefix
1445 Ssl::CertificateProperties certProperties;
1446 if (const char *cn = CommonHostName(cert.get())) {
1447 certProperties.commonName = "Not trusted by \"";
1448 certProperties.commonName += cn;
1449 certProperties.commonName += "\"";
1450 } else if (const char *org = getOrganization(cert.get())) {
1451 certProperties.commonName = "Not trusted by \"";
1452 certProperties.commonName += org;
1453 certProperties.commonName += "\"";
1454 } else
1455 certProperties.commonName = "Not trusted";
1456 certProperties.setCommonName = true;
1457 // O, OU, and other CA subject fields will be mimicked
1458 // Expiration date and other common properties will be mimicked
1459 certProperties.signAlgorithm = Ssl::algSignSelf;
1460 certProperties.signWithPkey.resetAndLock(pkey.get());
1461 certProperties.mimicCert.resetAndLock(cert.get());
1462 return Ssl::generateSslCertificate(untrustedCert, untrustedPkey, certProperties);
1463 }
1464
1465 #endif /* USE_SSL */