Debian Codegraph @

WWW/Library/Implementation/HTTLS.c

raw
1 /*
2 * $LynxId: HTTLS.c,v 1.21 2025/07/25 19:34:13 tom Exp $
3 *
4 * TRANSPORT LAYER SECURITY
5 *
6 * This file provides some utilities to create a reasonably simple TLS API,
7 * without having to manage all of the different versions and forks of libssl.
8 * */
9
10 #include <HTTLS.h>
11 #include <HTAlert.h>
12 #include <HTParse.h>
13
14 #include <LYUtils.h>
15 #include <LYGlobalDefs.h>
16
17 #ifdef USE_SSL
18
19 #ifdef USE_OPENSSL_INCL
20 #include <openssl/x509v3.h>
21 #endif
22
23 #ifdef USE_GNUTLS_INCL
24 #include <gnutls/x509.h>
25 #endif
26
27 #if defined(LIBRESSL_VERSION_NUMBER)
28 /* OpenSSL and LibreSSL version numbers do not correspond */
29
30 #if LIBRESSL_VERSION_NUMBER >= 0x2060100fL
31 #define SSL_set_no_TLSV1() SSL_set_min_proto_version(handle, TLS1_1_VERSION)
32 #endif
33
34 #elif defined(OPENSSL_VERSION_NUMBER) && (OPENSSL_VERSION_NUMBER >= 0x10100000L)
35
36 #define SSLEAY_VERSION_NUMBER OPENSSL_VERSION_NUMBER
37 #undef SSL_load_error_strings
38 #undef SSLeay_add_ssl_algorithms
39 #define ASN1_STRING_data ASN1_STRING_get0_data
40 #define TLS_client_method() SSLv23_client_method()
41 #define SSL_load_error_strings() /* nothing */
42 #define SSLeay_add_ssl_algorithms() /* nothing */
43 #define SSL_set_no_TLSV1() SSL_set_min_proto_version(handle, TLS1_1_VERSION)
44
45 #elif defined(SSLEAY_VERSION_NUMBER)
46
47 #define TLS_client_method() SSLv23_client_method()
48
49 #endif
50
51 #ifndef SSL_set_no_TLSV1
52 #define SSL_set_no_TLSV1() SSL_set_options(handle, SSL_OP_NO_TLSv1)
53 #endif
54
55 #ifndef SSL_OP_NO_SSLv3
56 #define SSL_OP_NO_SSLv3 -1
57 #endif
58
59 #ifndef SSL_OP_NO_TLSv1
60 #define SSL_OP_NO_TLSv1 -2
61 #endif
62
63 #ifndef SSL_OP_NO_TLSv1_1
64 #define SSL_OP_NO_TLSv1_1 -3
65 #endif
66
67 #ifndef SSL_OP_NO_TLSv1_2
68 #define SSL_OP_NO_TLSv1_2 -4
69 #endif
70
71 #ifndef SSL_OP_NO_TLSv1_3
72 #define SSL_OP_NO_TLSv1_3 -5
73 #endif
74
75 #ifndef MAX
76 #define MAX(x, y) ((x) > (y) ? (x) : (y))
77 #endif
78
79 SSL_CTX *ssl_ctx = NULL; /* SSL ctx */
80 static int ssl_okay;
81
82 #if SSLEAY_VERSION_NUMBER < 0x101000000
83 /* *INDENT-OFF* */
84 static const struct {
85 int version;
86
87 /* The name is used to get gnutls_protocol_t values for each of these
88 * protocols. It's kind of ugly that we're doing a runtime string search
89 * on something that could easily be determined at compile time, but I
90 * think that this is still cleaner than preprocessor hell.
91 */
92 const char *name;
93
94 /* This is used with SSL_set_options */
95 long opt;
96 } tls_versions[] = {
97 { SSL3_VERSION, "SSL3.0", SSL_OP_NO_SSLv3 },
98 { TLS1_VERSION, "TLS1.0", SSL_OP_NO_TLSv1 },
99 { TLS1_1_VERSION, "TLS1.1", SSL_OP_NO_TLSv1_1 },
100 { TLS1_2_VERSION, "TLS1.2", SSL_OP_NO_TLSv1_2 },
101 { TLS1_3_VERSION, "TLS1.3", SSL_OP_NO_TLSv1_3 },
102 };
103 /* *INDENT-ON* */
104 #endif /* older libssl */
105
106 static void free_ssl_ctx(void)
107 {
108 if (ssl_ctx != NULL)
109 SSL_CTX_free(ssl_ctx);
110 }
111
112 static BOOL needs_limit(const char *actual)
113 {
114 return ((int) strlen(actual) > LYcols - 7) ? TRUE : FALSE;
115 }
116
117 static char *limited_string(const char *source, const char *actual)
118 {
119 int limit = ((int) strlen(source)
120 - ((int) strlen(actual) - (LYcols - 10)));
121 char *temp = NULL;
122
123 StrAllocCopy(temp, source);
124 if (limit < 0)
125 limit = 0;
126 strcpy(temp + limit, "...");
127 return temp;
128 }
129
130 /*
131 * If the error message is too long to fit in the line, truncate that to fit
132 * within the limits for prompting.
133 */
134 static void SSL_single_prompt(char **target, const char *source)
135 {
136 HTSprintf0(target, SSL_FORCED_PROMPT, source);
137 if (needs_limit(*target)) {
138 char *temp = limited_string(source, *target);
139
140 *target = NULL;
141 HTSprintf0(target, SSL_FORCED_PROMPT, temp);
142 free(temp);
143 }
144 }
145
146 static void SSL_double_prompt(char **target, const char *format, const char
147 *arg1, const char *arg2)
148 {
149 (void) format;
150 HTSprintf0(target, HT_FMT("%s%s", format), arg1, arg2);
151 if (needs_limit(*target)) {
152 char *parg2 = limited_string(arg2, *target);
153
154 *target = NULL;
155 HTSprintf0(target, HT_FMT("%s%s", format), arg1, parg2);
156 if (needs_limit(*target)) {
157 char *parg1 = limited_string(arg1, *target);
158
159 *target = NULL;
160 HTSprintf0(target, HT_FMT("%s%s", format), parg1, parg2);
161 free(parg1);
162 }
163 free(parg2);
164 }
165 }
166
167 static int HTSSLCallback(int preverify_ok, X509_STORE_CTX * x509_ctx GCC_UNUSED)
168 {
169 char *msg = NULL;
170 int result = 1;
171
172 #ifdef USE_X509_SUPPORT
173 HTSprintf0(&msg,
174 LY_MSG("SSL callback:%s, preverify_ok=%d, ssl_okay=%d"),
175 X509_verify_cert_error_string((long) X509_STORE_CTX_get_error(x509_ctx)),
176 preverify_ok, ssl_okay);
177 _HTProgress(msg);
178 FREE(msg);
179 #endif
180
181 if (!(preverify_ok || ssl_okay || ssl_noprompt)) {
182 #ifdef USE_X509_SUPPORT
183 SSL_single_prompt(&msg,
184 X509_verify_cert_error_string((long)
185 X509_STORE_CTX_get_error(x509_ctx)));
186 if (HTForcedPrompt(ssl_noprompt, msg, NO))
187 ssl_okay = 1;
188 else
189 result = 0;
190 #endif
191
192 FREE(msg);
193 }
194 return result;
195 }
196
197 SSL *HTGetSSLHandle(void)
198 {
199 #ifdef USE_GNUTLS_INCL
200 static char *certfile = NULL;
201 #endif
202 static char *client_keyfile = NULL;
203 static char *client_certfile = NULL;
204
205 if (ssl_ctx == NULL) {
206 /*
207 * First time only.
208 */
209 #if SSLEAY_VERSION_NUMBER < 0x0800
210 if ((ssl_ctx = SSL_CTX_new()) != NULL) {
211 X509_set_default_verify_paths(ssl_ctx->cert);
212 }
213 #else
214 SSLeay_add_ssl_algorithms();
215 if ((ssl_ctx = SSL_CTX_new(TLS_client_method())) != NULL) {
216 #ifdef SSL_OP_NO_SSLv2
217 SSL_CTX_set_options(ssl_ctx, SSL_OP_ALL | SSL_OP_NO_SSLv2);
218 #else
219 SSL_CTX_set_options(ssl_ctx, SSL_OP_ALL);
220 #endif
221 #ifdef SSL_OP_NO_COMPRESSION
222 SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_COMPRESSION);
223 #endif
224 #ifdef SSL_MODE_AUTO_RETRY
225 SSL_CTX_set_mode(ssl_ctx, SSL_MODE_AUTO_RETRY);
226 #endif
227 #ifdef SSL_MODE_RELEASE_BUFFERS
228 SSL_CTX_set_mode(ssl_ctx, SSL_MODE_RELEASE_BUFFERS);
229 #endif
230 SSL_CTX_set_default_verify_paths(ssl_ctx);
231 SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, HTSSLCallback);
232 }
233 #endif /* SSLEAY_VERSION_NUMBER < 0x0800 */
234 #if defined(USE_PROGRAM_DIR) & !defined(USE_GNUTLS_INCL)
235 if (ssl_ctx != NULL) {
236 X509_LOOKUP *lookup;
237
238 lookup = X509_STORE_add_lookup(ssl_ctx->cert_store,
239 X509_LOOKUP_file());
240 if (lookup != NULL) {
241 char *certfile = NULL;
242
243 HTSprintf0(&certfile, "%s\\cert.pem", program_dir);
244 X509_LOOKUP_load_file(lookup, certfile, X509_FILETYPE_PEM);
245 FREE(certfile);
246 }
247 }
248 #endif
249 #ifdef USE_GNUTLS_INCL
250 if ((certfile = LYGetEnv("SSL_CERT_FILE")) != NULL) {
251 CTRACE((tfp,
252 "HTGetSSLHandle: certfile is set to %s by SSL_CERT_FILE\n",
253 certfile));
254 } else {
255 if (non_empty(SSL_cert_file)) {
256 certfile = SSL_cert_file;
257 CTRACE((tfp,
258 "HTGetSSLHandle: certfile is set to %s by config SSL_CERT_FILE\n",
259 certfile));
260 }
261 #if defined(USE_PROGRAM_DIR)
262 else {
263 HTSprintf0(&(certfile), "%s\\cert.pem", program_dir);
264 CTRACE((tfp,
265 "HTGetSSLHandle: certfile is set to %s by installed directory\n", certfile));
266 }
267 #endif
268 }
269 #endif
270 atexit(free_ssl_ctx);
271 }
272
273 if (non_empty(SSL_client_key_file)) {
274 client_keyfile = SSL_client_key_file;
275 CTRACE((tfp,
276 "HTGetSSLHandle: client key file is set to %s by config SSL_CLIENT_KEY_FILE\n",
277 client_keyfile));
278 }
279
280 if (non_empty(SSL_client_cert_file)) {
281 client_certfile = SSL_client_cert_file;
282 CTRACE((tfp,
283 "HTGetSSLHandle: client cert file is set to %s by config SSL_CLIENT_CERT_FILE\n",
284 client_certfile));
285 }
286 #ifdef USE_GNUTLS_INCL
287 ssl_ctx->certfile = certfile;
288 ssl_ctx->certfile_type = GNUTLS_X509_FMT_PEM;
289 ssl_ctx->client_keyfile = client_keyfile;
290 ssl_ctx->client_keyfile_type = GNUTLS_X509_FMT_PEM;
291 ssl_ctx->client_certfile = client_certfile;
292 ssl_ctx->client_certfile_type = GNUTLS_X509_FMT_PEM;
293 #elif SSLEAY_VERSION_NUMBER >= 0x0930
294 if (client_certfile != NULL) {
295 if (client_keyfile == NULL) {
296 client_keyfile = client_certfile;
297 }
298 SSL_CTX_use_certificate_chain_file(ssl_ctx, client_certfile);
299 SSL_CTX_use_PrivateKey_file(ssl_ctx, client_keyfile, SSL_FILETYPE_PEM);
300 }
301 #endif
302 ssl_okay = 0;
303 return (SSL_new(ssl_ctx));
304 }
305
306 void HTSSLInitPRNG(void)
307 {
308 #if SSLEAY_VERSION_NUMBER >= 0x00905100
309 if (RAND_status() == 0) {
310 char rand_file[256];
311 time_t t;
312 long l, seed;
313
314 #ifndef _WINDOWS
315 pid_t pid;
316
317 #else
318 DWORD pid;
319 #endif
320
321 t = time(NULL);
322
323 #ifndef _WINDOWS
324 pid = getpid();
325 #else
326 pid = GetCurrentThreadId();
327 #endif
328
329 RAND_file_name(rand_file, 256L);
330 CTRACE((tfp, "HTTP: Seeding PRNG\n"));
331 /* Seed as much as 1024 bytes from RAND_file_name */
332 RAND_load_file(rand_file, 1024L);
333 /* Seed in time (mod_ssl does this) */
334 RAND_seed((unsigned char *) &t, (int) sizeof(time_t));
335
336 /* Seed in pid (mod_ssl does this) */
337 RAND_seed((unsigned char *) &pid, (int) sizeof(pid));
338 /* Initialize system's random number generator */
339 RAND_bytes((unsigned char *) &seed, (int) sizeof(long));
340
341 lynx_srand((unsigned) seed);
342 while (RAND_status() == 0) {
343 /* Repeatedly seed the PRNG using the system's random number generator until it has been seeded with enough data */
344 l = (long) lynx_rand();
345 RAND_seed((unsigned char *) &l, (int) sizeof(long));
346 }
347 /* Write a rand_file */
348 RAND_write_file(rand_file);
349 }
350 #endif /* SSLEAY_VERSION_NUMBER >= 0x00905100 */
351 return;
352 }
353
354 static void show_cert_issuer(X509 * peer_cert GCC_UNUSED)
355 {
356 #if defined(USE_OPENSSL_INCL) || defined(USE_GNUTLS_INCL)
357 char ssl_dn[1024];
358 char *msg = NULL;
359
360 X509_NAME_oneline(X509_get_issuer_name(peer_cert), ssl_dn, (int) sizeof(ssl_dn));
361 HTSprintf0(&msg, LY_MSG("Certificate issued by: %s"), ssl_dn);
362 _HTProgress(msg);
363 FREE(msg);
364 #endif
365 }
366
367 /*
368 * Remove user/password, if any, from the given host-string.
369 */
370 static char *StripUserAuthents(char *host)
371 {
372 char *p = strchr(host, '@');
373
374 if (p != NULL) {
375 char *q = host;
376
377 while ((*q++ = *++p) != '\0') ;
378 }
379 return host;
380 }
381
382 /*
383 * Remove IPv6 brackets (and any port-number) from the given host-string.
384 */
385 static char *StripIpv6Brackets(char *host)
386 {
387 int port_number;
388 char *p;
389
390 if ((p = HTParsePort(host, &port_number)) != NULL)
391 *p = '\0';
392
393 if (*host == '[') {
394 p = host + strlen(host) - 1;
395 if (*p == ']') {
396 *p = '\0';
397 for (p = host; (p[0] = p[1]) != '\0'; ++p) {
398 ; /* EMPTY */
399 }
400 }
401 }
402 return host;
403 }
404
405 /* Extracts the host name from a URL. */
406 static char *get_host(const char *url)
407 {
408 char *host;
409
410 host = HTParse(url, "", PARSE_HOST);
411 host = StripIpv6Brackets(host);
412 host = StripUserAuthents(host);
413 return host;
414 }
415
416 /* Configures various options on an SSL handle */
417 static void configure_handle(SSL * handle, char *host,
418 int min_version, int max_version)
419 {
420 unsigned i;
421 int ret, state;
422 unsigned long opts, optm, retl;
423
424 /* Silence compiler warnings about unused variables */
425 (void) i;
426 (void) ret;
427 (void) state;
428 (void) opts;
429 (void) optm;
430 (void) retl;
431
432 (void) handle;
433 (void) host;
434 (void) min_version;
435 (void) max_version;
436
437 #if defined(USE_GNUTLS_INCL)
438 /* gnutls */
439
440 ret = SSL_set_tlsext_host_name(handle, host);
441 CTRACE((tfp, "...called SSL_set_tlsext_host_name(%s) ->%d\n", host, ret));
442
443 /* If we're in state 0, that means that we haven't hit `min_version` yet.
444 * If we're in state 1, we've seen `min_version` and are waiting for
445 * `max_version`
446 * If we're in state 2, we've seen `max_version` and are disabling
447 * everything else.
448 *
449 * This code is kind of gross, sorry. - Nate Choe
450 * */
451 state = (min_version == HTTLS_ANY_VERSION) ? 1 : 0;
452 for (i = 0; i < TABLESIZE(tls_versions); ++i) {
453 gnutls_protocol_t proto;
454 unsigned int v;
455
456 proto = gnutls_protocol_get_id(tls_versions[i].name);
457 CTRACE((tfp, "...called gnutls_protocol_get_id(%s) ->%d\n",
458 tls_versions[i].name, (int) proto));
459
460 #if defined(HAVE_GNUTLS_PROTOCOL_SET_ENABLED)
461 if (state == 0) {
462 if (tls_versions[i].version == min_version) {
463 state = 1;
464 } else {
465 v = 0;
466 goto set_version;
467 }
468 }
469
470 if (state == 2) {
471 v = 0;
472 goto set_version;
473 }
474
475 if (tls_versions[i].version == max_version)
476 state = 2;
477
478 if (proto != GNUTLS_VERSION_UNKNOWN)
479 v = 1;
480
481 set_version:
482 if (proto != GNUTLS_VERSION_UNKNOWN) {
483 ret = gnutls_protocol_set_enabled(proto, v);
484 CTRACE((tfp,
485 "...called gnutls_protocol_set_enabled(%d, %u) ->%d\n",
486 (int) proto, v, ret));
487 }
488 #endif
489 }
490
491 #elif SSLEAY_VERSION_NUMBER >= 0x0900
492 /* Set host name */
493 #if OPENSSL_VERSION_NUMBER >= 0x0090806fL && !defined(OPENSSL_NO_TLSEXT)
494 ret = (int) SSL_set_tlsext_host_name(handle, host);
495 CTRACE((tfp, "...called SSL_set_tlsext_host_name(%s) ->%d\n", host, ret));
496 #endif
497
498 /* Set allowed version numbers */
499 #if SSLEAY_VERSION_NUMBER < 0x101000000
500 /* We don't have access to SSL_set_*_proto_version, so we have to handroll
501 * it. */
502
503 /* See the GnuTLS code for the explanation of state */
504 state = (min_version == HTTLS_ANY_VERSION) ? 0 : 1;
505 opts = optm = 0;
506 for (i = 0; i < TABLESIZE(tls_versions); ++i) {
507 if (tls_versions[i].opt >= 0) {
508 optm |= (unsigned long) tls_versions[i].opt;
509 }
510 switch (state) {
511 case 0:
512 if (tls_versions[i].version == min_version)
513 state = 1;
514 else
515 break;
516 /* fallthrough */
517 case 1:
518 if (tls_versions[i].version == max_version)
519 state = 2;
520 if (tls_versions[i].opt >= 0)
521 opts |= (unsigned long) tls_versions[i].opt;
522 break;
523 }
524 }
525
526 #if defined(SSL_clear_options) || defined(HAVE_SSL_CLEAR_OPTIONS)
527 retl = (unsigned long) SSL_clear_options(handle, optm);
528 CTRACE((tfp, "...called SSL_clear_options(%ld) ->%ld\n", optm, retl));
529 #endif
530 retl = (unsigned long) SSL_set_options(handle, opts);
531 CTRACE((tfp, "...called SSL_set_options(%ld) ->%ld\n", opts, retl));
532
533 #else
534 min_version = MAX(min_version, 0);
535 max_version = MAX(max_version, 0);
536 ret = SSL_set_min_proto_version(handle, min_version);
537 CTRACE((tfp, "...called SSL_set_min_proto_version(%d) ->%d\n",
538 min_version, ret));
539 ret = SSL_set_max_proto_version(handle, max_version);
540 CTRACE((tfp, "...called SSL_set_max_proto_version(%d) ->%d\n",
541 max_version, ret));
542 #endif
543 #endif
544 }
545
546 static void print_ssl_connect_error(const char *url, int status)
547 {
548 unsigned long SSLerror;
549
550 CTRACE((tfp,
551 "HTTP: Unable to complete SSL handshake for '%s', SSL_connect=%d, SSL error stack dump follows\n",
552 url, status));
553 SSL_load_error_strings();
554 while ((SSLerror = ERR_get_error()) != 0) {
555 CTRACE((tfp, "HTTP: SSL: %s\n", ERR_error_string(SSLerror, NULL)));
556 }
557 HTAlert("Unable to make secure connection to remote host.");
558 }
559
560 #ifdef USE_GNUTLS_INCL
561 /* Checks if a handle's certificate is signed, but doesn't check that the
562 * hostname is valid. */
563 static BOOL cert_signed_gnutls(SSL * handle)
564 {
565 int ret;
566 unsigned int tls_status;
567
568 gnutls_certificate_set_verify_flags(handle->gnutls_cred,
569 GNUTLS_VERIFY_DO_NOT_ALLOW_SAME |
570 GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT);
571 ret = gnutls_certificate_verify_peers2(handle->gnutls_state, &tls_status);
572
573 /* GnuTLS verify has failed print an error message and potentially ask the
574 * user to trust the certificate anyways */
575 if (ret < 0 || tls_status != 0) {
576 int flag_continue = 1;
577 char *msg = NULL;
578
579 /* Print an error message */
580 #if GNUTLS_VERSION_NUMBER >= 0x030104
581 int type;
582 gnutls_datum_t out;
583
584 if (ret < 0) {
585 SSL_single_prompt(&msg,
586 gettext("GnuTLS error when trying to verify certificate."));
587 } else {
588 type = gnutls_certificate_type_get(handle->gnutls_state);
589 (void) gnutls_certificate_verification_status_print(tls_status,
590 type, &out, 0);
591 SSL_single_prompt(&msg, (const char *) out.data);
592 gnutls_free(out.data);
593 }
594 #else
595 char *msg2;
596
597 if (ret == 0 && tls_status & GNUTLS_CERT_SIGNER_NOT_FOUND) {
598 msg2 = gettext("the certificate has no known issuer");
599 } else if (tls_status & GNUTLS_CERT_SIGNER_NOT_FOUND) {
600 msg2 = gettext("no issuer was found");
601 } else if (tls_status & GNUTLS_CERT_SIGNER_NOT_CA) {
602 msg2 = gettext("issuer is not a CA");
603 } else if (tls_status & GNUTLS_CERT_REVOKED) {
604 msg2 = gettext("the certificate has been revoked");
605 } else {
606 msg2 = gettext("the certificate is not trusted");
607 }
608 SSL_single_prompt(&msg, msg2);
609 #endif
610
611 /* At this point, we know that the certificate is invalid and have
612 * printed an error message to the user. Now, the user has the option of
613 * trusting the certificate anyways. */
614 CTRACE((tfp, "HTLoadHTTP: %s\n", msg));
615 if (!ssl_noprompt) {
616 if (!HTForcedPrompt(ssl_noprompt, msg, NO)) {
617 flag_continue = 0;
618 }
619 } else if (ssl_noprompt == FORCE_PROMPT_NO) {
620 flag_continue = 0;
621 }
622 FREE(msg);
623 if (flag_continue == 0) {
624 return FALSE;
625 }
626 }
627 return TRUE;
628 }
629 #endif /* USE_GNUTLS_INCL */
630
631 /* Parses TLS canonical names from a DN string generated by X509_NAME_ONELINE
632 *
633 * I'm pretty sure OpenSSL and the GnuTLS polyfill defined in tidy_tls.c are
634 * basically equivalent, but ssl_dn generally looks something like this:
635 *
636 * /CN=example.com/CN=www.example.com/C=US/L=TX/[email protected]
637 *
638 * We're looking for every instance of /CN=* and checking to see if any of them
639 * match the hostname we're looking for.
640 *
641 * Return values:
642 * 0 - No CN found
643 * 1 - CN found but no match
644 * 2 - CN found which matches
645 *
646 * - Nate Choe
647 * */
648 static int parse_cns(char *ssl_dn, char *host, char **all_cns)
649 {
650 int status_sslcertcheck;
651 char *cert_host, *p, *msg;
652
653 /*
654 * X.509 DN validation taking ALL CN fields into account
655 * (c) 2006 Thorsten Glaser <[email protected]>
656 */
657
658 /* initialise status information */
659 status_sslcertcheck = 0; /* 0 = no CN found in DN */
660
661 msg = NULL;
662
663 /* validate all CNs found in DN */
664 CTRACE((tfp, "Validating CNs in '%s'\n", ssl_dn));
665 while ((cert_host = strstr(ssl_dn, "/CN=")) != NULL) {
666 status_sslcertcheck = 1; /* 1 = could not verify CN */
667 /* start of CommonName */
668 cert_host += 4;
669 /* find next part of DistinguishedName */
670 if ((p = StrChr(cert_host, '/')) != NULL) {
671 *p = '\0';
672 ssl_dn = p; /* yes this points to the NUL byte */
673 } else
674 ssl_dn = NULL;
675 cert_host = StripIpv6Brackets(cert_host);
676
677 /* verify this CN */
678 CTRACE((tfp, "Matching\n\tssl_host '%s'\n\tcert_host '%s'\n",
679 host, cert_host));
680 if (!strcasecomp_asterisk(host, cert_host)) {
681 status_sslcertcheck = 2; /* 2 = verified peer */
682 /* I think this is cool to have in the logs -TG */
683 HTSprintf0(&msg,
684 LY_MSG("Verified connection to %s (cert=%s)"),
685 host, cert_host);
686 _HTProgress(msg);
687 FREE(msg);
688 /* no need to continue the verification loop */
689
690 /* Actually, we might want to continue filling in all_cns.
691 * - Nate Choe */
692 break;
693 }
694
695 /* add this CN to list of failed CNs */
696 if (*all_cns == NULL)
697 HTSACopy(all_cns, "CN<");
698 else
699 HTSACopy(all_cns, ":CN<");
700 HTSACopy(all_cns, cert_host);
701 HTSACopy(all_cns, ">");
702 /* if we cannot retry, don't try it */
703 if (ssl_dn == NULL)
704 break;
705 /* now retry next CN found in DN */
706 *ssl_dn = '/'; /* formerly NUL byte */
707 }
708 return status_sslcertcheck;
709 }
710
711 /* Checks X.509v3 Subject Alternative Name
712 *
713 * Return values are the same as parse_cns.
714 * */
715 static int altname_valid(X509 * peer_cert, char *host, char **all_cns)
716 {
717 #if defined(USE_GNUTLS_INCL)
718 unsigned int i;
719 int ret;
720 size_t size;
721 gnutls_x509_crt_t cert;
722 char buf[2048], *msg;
723
724 /* import the certificate to the x509_crt format */
725 if (gnutls_x509_crt_init(&cert) != 0) {
726 return 0;
727 }
728
729 if (gnutls_x509_crt_import(cert, peer_cert, GNUTLS_X509_FMT_DER) < 0) {
730 gnutls_x509_crt_deinit(cert);
731 return 0;
732 }
733
734 ret = 0;
735 for (i = 0; ret >= 0; ++i) {
736 size = sizeof(buf);
737 ret = gnutls_x509_crt_get_subject_alt_name(cert, i, buf, &size, NULL);
738 if (strcasecomp_asterisk(host, buf) != 0) {
739 continue;
740 }
741 msg = NULL;
742 HTSprintf0(&msg,
743 LY_MSG("Verified connection to %s (subj=%s)"),
744 host, buf);
745 _HTProgress(msg);
746 FREE(msg);
747 return 2;
748 }
749 return 0;
750 #elif defined(USE_OPENSSL_INCL)
751 STACK_OF(GENERAL_NAME) * gens;
752 int i, numalts, result;
753 const GENERAL_NAME *gn;
754 char *cert_host, *msg;
755
756 gens = (STACK_OF(GENERAL_NAME) *)
757 X509_get_ext_d2i(peer_cert, NID_subject_alt_name, NULL, NULL);
758 if (gens == NULL) {
759 return FALSE;
760 }
761
762 result = 0;
763
764 numalts = sk_GENERAL_NAME_num(gens);
765 for (i = 0; i < numalts; ++i) {
766 gn = sk_GENERAL_NAME_value(gens, i);
767 if (gn->type == GEN_DNS) {
768 cert_host = (char *) ASN1_STRING_data(gn->d.ia5);
769 } else if (gn->type == GEN_IPADD) {
770 /* XXX untested -TG */
771 size_t j = (size_t) ASN1_STRING_length(gn->d.ia5);
772
773 cert_host = (char *) malloc(j + 1);
774 MemCpy(cert_host, ASN1_STRING_data(gn->d.ia5), j);
775 cert_host[j] = '\0';
776 } else {
777 continue;
778 }
779 result = 1; /* got at least one */
780 /* verify this SubjectAltName (see parse_cns) */
781 cert_host = StripIpv6Brackets(cert_host);
782 if (!(gn->type == GEN_IPADD ? strcasecomp :
783 strcasecomp_asterisk) (host, cert_host)) {
784 result = 2;
785 msg = NULL;
786 HTSprintf0(&msg,
787 LY_MSG("Verified connection to %s (subj=%s)"),
788 host, cert_host);
789 _HTProgress(msg);
790 FREE(msg);
791 if (gn->type == GEN_IPADD)
792 free(cert_host);
793 break;
794 }
795 /* add to list of failed CNs */
796 if (*all_cns == NULL)
797 HTSACopy(all_cns, "SAN<");
798 else
799 HTSACopy(all_cns, ":SAN<");
800 if (gn->type == GEN_DNS)
801 HTSACopy(all_cns, "DNS=");
802 else if (gn->type == GEN_IPADD)
803 HTSACopy(all_cns, "IP=");
804 HTSACopy(all_cns, cert_host);
805 HTSACopy(all_cns, ">");
806 if (gn->type == GEN_IPADD)
807 free(cert_host);
808 }
809 sk_GENERAL_NAME_free(gens);
810
811 return result;
812 #else
813 return 0;
814 #endif
815
816 /* Silence compiler warnings about unused arguments */
817 (void) peer_cert;
818 (void) host;
819 (void) all_cns;
820 }
821
822 static BOOL cert_valid(SSL * handle, char *host)
823 {
824 X509 *peer_cert; /* The peer certificate */
825 char ssl_dn[1024], *msg;
826 char *all_cns = NULL;
827 int status;
828
829 /* OpenSSL certificate verification is handled by HTSSLCallback. */
830 #ifdef USE_GNUTLS_INCL
831 if (!cert_signed_gnutls(handle)) {
832 return FALSE;
833 }
834 #endif
835
836 peer_cert = (X509 *) SSL_get_peer_certificate(handle);
837 X509_NAME_oneline(X509_get_subject_name(peer_cert),
838 ssl_dn, (int) sizeof(ssl_dn));
839
840 status = parse_cns(ssl_dn, host, &all_cns);
841 if (status < 2) {
842 int s2;
843
844 s2 = altname_valid(peer_cert, host, &all_cns);
845 status = MAX(status, s2);
846 }
847
848 msg = NULL;
849 switch (status) {
850 case 0:
851 SSL_single_prompt(&msg,
852 gettext("Can't find common name in certificate"));
853 break;
854 case 1:
855 SSL_double_prompt(&msg,
856 LY_MSG("SSL error:host(%s)!=cert(%s)-Continue?"),
857 host, all_cns);
858 break;
859 case 2:
860 goto success;
861 default:
862 msg = NULL;
863 break;
864 }
865
866 /* If we reach this point then we've failed to notify the certificate, we
867 * notified the user, and we're asking if we should trust this
868 * certificate anyways. */
869
870 if (msg == NULL)
871 StrAllocCopy(msg, gettext("SSL error"));
872 if (!HTForcedPrompt(ssl_noprompt, msg, NO)) {
873 FREE(msg);
874 FREE(all_cns);
875 return FALSE;
876 }
877
878 SSL_double_prompt(&msg,
879 LY_MSG("UNVERIFIED connection to %s (cert=%s)"),
880 host, all_cns ? all_cns : "NONE");
881 _HTProgress(msg);
882 FREE(msg);
883 success:
884 show_cert_issuer(peer_cert);
885 FREE(all_cns);
886 return TRUE;
887 }
888
889 SSL *HTSSLConnect(int fd, const char *url, int min_version, int max_version)
890 {
891 SSL *handle;
892 char *host;
893 int status;
894
895 handle = HTGetSSLHandle();
896 SSL_set_fd(handle, fd);
897 host = get_host(url);
898 configure_handle(handle, host, min_version, max_version);
899 HTSSLInitPRNG();
900 status = SSL_connect(handle);
901 if (status <= 0) {
902 print_ssl_connect_error(url, status);
903 goto error;
904 }
905 if (!cert_valid(handle, host)) {
906 goto error;
907 }
908
909 return handle;
910 error:
911 SSL_free(handle);
912 return NULL;
913 }
914
915 #endif /* USE_SSL */