]> sjero.net Git - wget/blob - src/openssl.c
[svn] Only allocate an error string on actual error.
[wget] / src / openssl.c
1 /* SSL support via OpenSSL library.
2    Copyright (C) 2000-2005 Free Software Foundation, Inc.
3    Originally contributed by Christian Fraenkel.
4
5 This file is part of GNU Wget.
6
7 GNU Wget is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 GNU Wget is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with Wget; if not, write to the Free Software Foundation, Inc.,
19 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20
21 In addition, as a special exception, the Free Software Foundation
22 gives permission to link the code of its release of Wget with the
23 OpenSSL project's "OpenSSL" library (or with modified versions of it
24 that use the same license as the "OpenSSL" library), and distribute
25 the linked executables.  You must obey the GNU General Public License
26 in all respects for all of the code used other than "OpenSSL".  If you
27 modify this file, you may extend this exception to your version of the
28 file, but you are not obligated to do so.  If you do not wish to do
29 so, delete this exception statement from your version.  */
30
31 #include <config.h>
32
33 #include <assert.h>
34 #include <errno.h>
35 #ifdef HAVE_UNISTD_H
36 # include <unistd.h>
37 #endif
38 #include <string.h>
39
40 #include <openssl/ssl.h>
41 #include <openssl/x509.h>
42 #include <openssl/err.h>
43 #include <openssl/rand.h>
44
45 #include "wget.h"
46 #include "utils.h"
47 #include "connect.h"
48 #include "url.h"
49 #include "ssl.h"
50
51 /* Application-wide SSL context.  This is common to all SSL
52    connections.  */
53 static SSL_CTX *ssl_ctx;
54
55 /* Initialize the SSL's PRNG using various methods. */
56
57 static void
58 init_prng (void)
59 {
60   char namebuf[256];
61   const char *random_file;
62
63   if (RAND_status ())
64     /* The PRNG has been seeded; no further action is necessary. */
65     return;
66
67   /* Seed from a file specified by the user.  This will be the file
68      specified with --random-file, $RANDFILE, if set, or ~/.rnd, if it
69      exists.  */
70   if (opt.random_file)
71     random_file = opt.random_file;
72   else
73     {
74       /* Get the random file name using RAND_file_name. */
75       namebuf[0] = '\0';
76       random_file = RAND_file_name (namebuf, sizeof (namebuf));
77     }
78
79   if (random_file && *random_file)
80     /* Seed at most 16k (apparently arbitrary value borrowed from
81        curl) from random file. */
82     RAND_load_file (random_file, 16384);
83
84   if (RAND_status ())
85     return;
86
87   /* Get random data from EGD if opt.egd_file was used.  */
88   if (opt.egd_file && *opt.egd_file)
89     RAND_egd (opt.egd_file);
90
91   if (RAND_status ())
92     return;
93
94 #ifdef WINDOWS
95   /* Under Windows, we can try to seed the PRNG using screen content.
96      This may or may not work, depending on whether we'll calling Wget
97      interactively.  */
98
99   RAND_screen ();
100   if (RAND_status ())
101     return;
102 #endif
103
104 #if 0 /* don't do this by default */
105   {
106     int maxrand = 500;
107
108     /* Still not random enough, presumably because neither /dev/random
109        nor EGD were available.  Try to seed OpenSSL's PRNG with libc
110        PRNG.  This is cryptographically weak and defeats the purpose
111        of using OpenSSL, which is why it is highly discouraged.  */
112
113     logprintf (LOG_NOTQUIET, _("WARNING: using a weak random seed.\n"));
114
115     while (RAND_status () == 0 && maxrand-- > 0)
116       {
117         unsigned char rnd = random_number (256);
118         RAND_seed (&rnd, sizeof (rnd));
119       }
120   }
121 #endif
122 }
123
124 /* Print errors in the OpenSSL error stack. */
125
126 static void
127 print_errors (void) 
128 {
129   unsigned long err;
130   while ((err = ERR_get_error ()) != 0)
131     logprintf (LOG_NOTQUIET, "OpenSSL: %s\n", ERR_error_string (err, NULL));
132 }
133
134 /* Convert keyfile type as used by options.h to a type as accepted by
135    SSL_CTX_use_certificate_file and SSL_CTX_use_PrivateKey_file.
136
137    (options.h intentionally doesn't use values from openssl/ssl.h so
138    it doesn't depend specifically on OpenSSL for SSL functionality.)  */
139
140 static int
141 key_type_to_ssl_type (enum keyfile_type type)
142 {
143   switch (type)
144     {
145     case keyfile_pem:
146       return SSL_FILETYPE_PEM;
147     case keyfile_asn1:
148       return SSL_FILETYPE_ASN1;
149     default:
150       abort ();
151     }
152 }
153
154 /* Create an SSL Context and set default paths etc.  Called the first
155    time an HTTP download is attempted.
156
157    Returns true on success, false otherwise.  */
158
159 bool
160 ssl_init ()
161 {
162   SSL_METHOD *meth;
163
164   if (ssl_ctx)
165     /* The SSL has already been initialized. */
166     return true;
167
168   /* Init the PRNG.  If that fails, bail out.  */
169   init_prng ();
170   if (RAND_status () != 1)
171     {
172       logprintf (LOG_NOTQUIET,
173                  _("Could not seed PRNG; consider using --random-file.\n"));
174       goto error;
175     }
176
177   SSL_library_init ();
178   SSL_load_error_strings ();
179   SSLeay_add_all_algorithms ();
180   SSLeay_add_ssl_algorithms ();
181
182   switch (opt.secure_protocol)
183     {
184     case secure_protocol_auto:
185       meth = SSLv23_client_method ();
186       break;
187     case secure_protocol_sslv2:
188       meth = SSLv2_client_method ();
189       break;
190     case secure_protocol_sslv3:
191       meth = SSLv3_client_method ();
192       break;
193     case secure_protocol_tlsv1:
194       meth = TLSv1_client_method ();
195       break;
196     default:
197       abort ();
198     }
199
200   ssl_ctx = SSL_CTX_new (meth);
201   if (!ssl_ctx)
202     goto error;
203
204   SSL_CTX_set_default_verify_paths (ssl_ctx);
205   SSL_CTX_load_verify_locations (ssl_ctx, opt.ca_cert, opt.ca_directory);
206
207   /* SSL_VERIFY_NONE instructs OpenSSL not to abort SSL_connect if the
208      certificate is invalid.  We verify the certificate separately in
209      ssl_check_certificate, which provides much better diagnostics
210      than examining the error stack after a failed SSL_connect.  */
211   SSL_CTX_set_verify (ssl_ctx, SSL_VERIFY_NONE, NULL);
212
213   if (opt.cert_file)
214     if (SSL_CTX_use_certificate_file (ssl_ctx, opt.cert_file,
215                                       key_type_to_ssl_type (opt.cert_type))
216         != 1)
217       goto error;
218   if (opt.private_key)
219     if (SSL_CTX_use_PrivateKey_file (ssl_ctx, opt.private_key,
220                                      key_type_to_ssl_type (opt.private_key_type))
221         != 1)
222       goto error;
223
224   /* Since fd_write unconditionally assumes partial writes (and
225      handles them correctly), allow them in OpenSSL.  */
226   SSL_CTX_set_mode (ssl_ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
227
228   return true;
229
230  error:
231   if (ssl_ctx)
232     SSL_CTX_free (ssl_ctx);
233   print_errors ();
234   return false;
235 }
236
237 struct openssl_transport_context {
238   SSL *conn;                    /* SSL connection handle */
239   char *last_error;             /* last error printed with openssl_errstr */
240 };
241
242 static int
243 openssl_read (int fd, char *buf, int bufsize, void *arg)
244 {
245   int ret;
246   struct openssl_transport_context *ctx = arg;
247   SSL *conn = ctx->conn;
248   do
249     ret = SSL_read (conn, buf, bufsize);
250   while (ret == -1
251          && SSL_get_error (conn, ret) == SSL_ERROR_SYSCALL
252          && errno == EINTR);
253   return ret;
254 }
255
256 static int
257 openssl_write (int fd, char *buf, int bufsize, void *arg)
258 {
259   int ret = 0;
260   struct openssl_transport_context *ctx = arg;
261   SSL *conn = ctx->conn;
262   do
263     ret = SSL_write (conn, buf, bufsize);
264   while (ret == -1
265          && SSL_get_error (conn, ret) == SSL_ERROR_SYSCALL
266          && errno == EINTR);
267   return ret;
268 }
269
270 static int
271 openssl_poll (int fd, double timeout, int wait_for, void *arg)
272 {
273   struct openssl_transport_context *ctx = arg;
274   SSL *conn = ctx->conn;
275   if (timeout == 0)
276     return 1;
277   if (SSL_pending (conn))
278     return 1;
279   return select_fd (fd, timeout, wait_for);
280 }
281
282 static int
283 openssl_peek (int fd, char *buf, int bufsize, void *arg)
284 {
285   int ret;
286   struct openssl_transport_context *ctx = arg;
287   SSL *conn = ctx->conn;
288   do
289     ret = SSL_peek (conn, buf, bufsize);
290   while (ret == -1
291          && SSL_get_error (conn, ret) == SSL_ERROR_SYSCALL
292          && errno == EINTR);
293   return ret;
294 }
295
296 static const char *
297 openssl_errstr (int fd, void *arg)
298 {
299   struct openssl_transport_context *ctx = arg;
300   unsigned long errcode;
301   char *errmsg = NULL;
302   int msglen = 0;
303
304   /* If there are no SSL-specific errors, just return NULL. */
305   if ((errcode = ERR_get_error ()) == 0)
306     return NULL;
307
308   /* Get rid of previous contents of ctx->last_error, if any.  */
309   xfree_null (ctx->last_error);
310
311   /* Iterate over OpenSSL's error stack and accumulate errors in the
312      last_error buffer, separated by "; ".  This is better than using
313      a static buffer, which *always* takes up space (and has to be
314      large, to fit more than one error message), whereas these
315      allocations are only performed when there is an actual error.  */
316
317   for (;;)
318     {
319       const char *str = ERR_error_string (errcode, NULL);
320       int len = strlen (str);
321
322       /* Allocate space for the existing message, plus two more chars
323          for the "; " separator and one for the terminating \0.  */
324       errmsg = xrealloc (errmsg, msglen + len + 2 + 1);
325       memcpy (errmsg + msglen, str, len);
326       msglen += len;
327
328       /* Get next error and bail out if there are no more. */
329       errcode = ERR_get_error ();
330       if (errcode == 0)
331         break;
332
333       errmsg[msglen++] = ';';
334       errmsg[msglen++] = ' ';
335     }
336   errmsg[msglen] = '\0';
337
338   /* Store the error in ctx->last_error where openssl_close will
339      eventually find it and free it.  */
340   ctx->last_error = errmsg;
341
342   return errmsg;
343 }
344
345 static void
346 openssl_close (int fd, void *arg)
347 {
348   struct openssl_transport_context *ctx = arg;
349   SSL *conn = ctx->conn;
350
351   SSL_shutdown (conn);
352   SSL_free (conn);
353   xfree_null (ctx->last_error);
354   xfree (ctx);
355
356 #ifdef WINDOWS
357   closesocket (fd);
358 #else
359   close (fd);
360 #endif
361
362   DEBUGP (("Closed %d/SSL 0x%0*lx\n", fd, PTR_FORMAT (conn)));
363 }
364
365 /* openssl_transport is the singleton that describes the SSL transport
366    methods provided by this file.  */
367
368 static struct transport_implementation openssl_transport = {
369   openssl_read, openssl_write, openssl_poll,
370   openssl_peek, openssl_errstr, openssl_close
371 };
372
373 /* Perform the SSL handshake on file descriptor FD, which is assumed
374    to be connected to an SSL server.  The SSL handle provided by
375    OpenSSL is registered with the file descriptor FD using
376    fd_register_transport, so that subsequent calls to fd_read,
377    fd_write, etc., will use the corresponding SSL functions.
378
379    Returns true on success, false on failure.  */
380
381 bool
382 ssl_connect (int fd) 
383 {
384   SSL *conn;
385   struct openssl_transport_context *ctx;
386
387   DEBUGP (("Initiating SSL handshake.\n"));
388
389   assert (ssl_ctx != NULL);
390   conn = SSL_new (ssl_ctx);
391   if (!conn)
392     goto error;
393   if (!SSL_set_fd (conn, fd))
394     goto error;
395   SSL_set_connect_state (conn);
396   if (SSL_connect (conn) <= 0 || conn->state != SSL_ST_OK)
397     goto error;
398
399   ctx = xnew0 (struct openssl_transport_context);
400   ctx->conn = conn;
401
402   /* Register FD with Wget's transport layer, i.e. arrange that our
403      functions are used for reading, writing, and polling.  */
404   fd_register_transport (fd, &openssl_transport, ctx);
405   DEBUGP (("Handshake successful; connected socket %d to SSL handle 0x%0*lx\n",
406            fd, PTR_FORMAT (conn)));
407   return true;
408
409  error:
410   DEBUGP (("SSL handshake failed.\n"));
411   print_errors ();
412   if (conn)
413     SSL_free (conn);
414   return false;
415 }
416
417 #define ASTERISK_EXCLUDES_DOT   /* mandated by rfc2818 */
418
419 /* Return true is STRING (case-insensitively) matches PATTERN, false
420    otherwise.  The recognized wildcard character is "*", which matches
421    any character in STRING except ".".  Any number of the "*" wildcard
422    may be present in the pattern.
423
424    This is used to match of hosts as indicated in rfc2818: "Names may
425    contain the wildcard character * which is considered to match any
426    single domain name component or component fragment. E.g., *.a.com
427    matches foo.a.com but not bar.foo.a.com. f*.com matches foo.com but
428    not bar.com [or foo.bar.com]."
429
430    If the pattern contain no wildcards, pattern_match(a, b) is
431    equivalent to !strcasecmp(a, b).  */
432
433 static bool
434 pattern_match (const char *pattern, const char *string)
435 {
436   const char *p = pattern, *n = string;
437   char c;
438   for (; (c = TOLOWER (*p++)) != '\0'; n++)
439     if (c == '*')
440       {
441         for (c = TOLOWER (*p); c == '*'; c = TOLOWER (*++p))
442           ;
443         for (; *n != '\0'; n++)
444           if (TOLOWER (*n) == c && pattern_match (p, n))
445             return true;
446 #ifdef ASTERISK_EXCLUDES_DOT
447           else if (*n == '.')
448             return false;
449 #endif
450         return c == '\0';
451       }
452     else
453       {
454         if (c != TOLOWER (*n))
455           return false;
456       }
457   return *n == '\0';
458 }
459
460 /* Verify the validity of the certificate presented by the server.
461    Also check that the "common name" of the server, as presented by
462    its certificate, corresponds to HOST.  (HOST typically comes from
463    the URL and is what the user thinks he's connecting to.)
464
465    This assumes that ssl_connect has successfully finished, i.e. that
466    the SSL handshake has been performed and that FD is connected to an
467    SSL handle.
468
469    If opt.check_cert is true (the default), this returns 1 if the
470    certificate is valid, 0 otherwise.  If opt.check_cert is 0, the
471    function always returns 1, but should still be called because it
472    warns the user about any problems with the certificate.  */
473
474 bool
475 ssl_check_certificate (int fd, const char *host)
476 {
477   X509 *cert;
478   char common_name[256];
479   long vresult;
480   bool success = true;
481
482   /* If the user has specified --no-check-cert, we still want to warn
483      him about problems with the server's certificate.  */
484   const char *severity = opt.check_cert ? _("ERROR") : _("WARNING");
485
486   struct openssl_transport_context *ctx = fd_transport_context (fd);
487   SSL *conn = ctx->conn;
488   assert (conn != NULL);
489
490   cert = SSL_get_peer_certificate (conn);
491   if (!cert)
492     {
493       logprintf (LOG_NOTQUIET, _("%s: No certificate presented by %s.\n"),
494                  severity, escnonprint (host));
495       success = false;
496       goto no_cert;             /* must bail out since CERT is NULL */
497     }
498
499   IF_DEBUG
500     {
501       char *subject = X509_NAME_oneline (X509_get_subject_name (cert), 0, 0);
502       char *issuer = X509_NAME_oneline (X509_get_issuer_name (cert), 0, 0);
503       DEBUGP (("certificate:\n  subject: %s\n  issuer:  %s\n",
504                escnonprint (subject), escnonprint (issuer)));
505       OPENSSL_free (subject);
506       OPENSSL_free (issuer);
507     }
508
509   vresult = SSL_get_verify_result (conn);
510   if (vresult != X509_V_OK)
511     {
512       /* #### We might want to print saner (and translatable) error
513          messages for several frequently encountered errors.  The
514          candidates would include
515          X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY,
516          X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN,
517          X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT,
518          X509_V_ERR_CERT_NOT_YET_VALID, X509_V_ERR_CERT_HAS_EXPIRED,
519          and possibly others.  The current approach would still be
520          used for the less frequent failure cases.  */
521       logprintf (LOG_NOTQUIET,
522                  _("%s: Certificate verification error for %s: %s\n"),
523                  severity, escnonprint (host),
524                  X509_verify_cert_error_string (vresult));
525       success = false;
526       /* Fall through, so that the user is warned about *all* issues
527          with the cert (important with --no-check-certificate.)  */
528     }
529
530   /* Check that HOST matches the common name in the certificate.
531      #### The following remains to be done:
532
533      - It should use dNSName/ipAddress subjectAltName extensions if
534        available; according to rfc2818: "If a subjectAltName extension
535        of type dNSName is present, that MUST be used as the identity."
536
537      - When matching against common names, it should loop over all
538        common names and choose the most specific one, i.e. the last
539        one, not the first one, which the current code picks.
540
541      - Ensure that ASN1 strings from the certificate are encoded as
542        UTF-8 which can be meaningfully compared to HOST.  */
543
544   common_name[0] = '\0';
545   X509_NAME_get_text_by_NID (X509_get_subject_name (cert),
546                              NID_commonName, common_name, sizeof (common_name));
547   if (!pattern_match (common_name, host))
548     {
549       logprintf (LOG_NOTQUIET, _("\
550 %s: certificate common name `%s' doesn't match requested host name `%s'.\n"),
551                  severity, escnonprint (common_name), escnonprint (host));
552       success = false;
553     }
554
555   if (success)
556     DEBUGP (("X509 certificate successfully verified and matches host %s\n",
557              escnonprint (host)));
558   X509_free (cert);
559
560  no_cert:
561   if (opt.check_cert && !success)
562     logprintf (LOG_NOTQUIET, _("\
563 To connect to %s insecurely, use `--no-check-certificate'.\n"),
564                escnonprint (host));
565
566   /* Allow --no-check-cert to disable certificate checking. */
567   return opt.check_cert ? success : true;
568 }