]> sjero.net Git - wget/blobdiff - src/openssl.c
[svn] *** empty log message ***
[wget] / src / openssl.c
index 920f5a50384db4a5a50d6578355dc462d4c00ad6..46e100dcc661d0cf69d86a9bb44beb8a7298d47f 100644 (file)
@@ -41,12 +41,9 @@ so, delete this exception statement from your version.  */
 # include <strings.h>
 #endif
 
-#include <openssl/bio.h>
-#include <openssl/crypto.h>
-#include <openssl/x509.h>
 #include <openssl/ssl.h>
+#include <openssl/x509.h>
 #include <openssl/err.h>
-#include <openssl/pem.h>
 #include <openssl/rand.h>
 
 #include "wget.h"
@@ -59,29 +56,43 @@ so, delete this exception statement from your version.  */
 extern int errno;
 #endif
 
+/* Application-wide SSL context.  This is common to all SSL
+   connections.  */
 SSL_CTX *ssl_ctx;
 
+/* Initialize the SSL's PRNG using various methods. */
+
 static void
-ssl_init_prng (void)
+init_prng (void)
 {
-  /* It is likely that older versions of OpenSSL will fail on
-     non-Linux machines because this code is unable to seed the PRNG
-     on older versions of the library.  */
+  char namebuf[256];
+  const char *random_file;
 
-#if SSLEAY_VERSION_NUMBER >= 0x00905100
-  char rand_file[256];
+  if (RAND_status ())
+    /* The PRNG has been seeded; no further action is necessary. */
+    return;
 
-  /* First, seed from a file specified by the user.  This will be
-     $RANDFILE, if set, or ~/.rnd.  */
-  RAND_file_name (rand_file, sizeof (rand_file));
-  if (rand_file)
-    /* Seed at most 16k (value borrowed from curl) from random file. */
-    RAND_load_file (rand_file, 16384);
+  /* Seed from a file specified by the user.  This will be the file
+     specified with --random-file, $RANDFILE, if set, or ~/.rnd, if it
+     exists.  */
+  if (opt.random_file)
+    random_file = opt.random_file;
+  else
+    {
+      /* Get the random file name using RAND_file_name. */
+      namebuf[0] = '\0';
+      random_file = RAND_file_name (namebuf, sizeof (namebuf));
+    }
+
+  if (random_file && *random_file)
+    /* Seed at most 16k (apparently arbitrary value borrowed from
+       curl) from random file. */
+    RAND_load_file (random_file, 16384);
 
   if (RAND_status ())
     return;
 
-  /* Get random data from EGD if opt.egd_file was set.  */
+  /* Get random data from EGD if opt.egd_file was used.  */
   if (opt.egd_file && *opt.egd_file)
     RAND_egd (opt.egd_file);
 
@@ -107,7 +118,7 @@ ssl_init_prng (void)
        PRNG.  This is cryptographically weak and defeats the purpose
        of using OpenSSL, which is why it is highly discouraged.  */
 
-    logprintf (LOG_VERBOSE, _("WARNING: using a weak random seed.\n"));
+    logprintf (LOG_NOTQUIET, _("WARNING: using a weak random seed.\n"));
 
     while (RAND_status () == 0 && maxrand-- > 0)
       {
@@ -116,38 +127,12 @@ ssl_init_prng (void)
       }
   }
 #endif
-
-#endif /* SSLEAY_VERSION_NUMBER >= 0x00905100 */
 }
 
-static int
-verify_callback (int ok, X509_STORE_CTX *ctx)
-{
-  char *s, buf[256];
-  s = X509_NAME_oneline (X509_get_subject_name (ctx->current_cert),
-                        buf, sizeof (buf));
-  if (ok == 0)
-    {
-      switch (ctx->error)
-       {
-       case X509_V_ERR_CERT_NOT_YET_VALID:
-       case X509_V_ERR_CERT_HAS_EXPIRED:
-         /* This mean the CERT is not valid !!! */
-         ok = 0;
-         break;
-       case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
-         /* Unsure if we should handle that this way */
-         ok = 1;
-         break;
-       }
-    }
-  return ok;
-}
-
-/* Print SSL errors. */
+/* Print errors in the OpenSSL error stack. */
 
 static void
-ssl_print_errors (void) 
+print_errors (void) 
 {
   unsigned long curerr = 0;
   while ((curerr = ERR_get_error ()) != 0)
@@ -174,29 +159,34 @@ key_type_to_ssl_type (enum keyfile_type type)
     }
 }
 
-/* Creates a SSL Context and sets some defaults for it */
-uerr_t
+/* Create an SSL Context and set default paths etc.  Called the first
+   time an HTTP download is attempted.
+
+   Returns 1 on success, 0 otherwise.  */
+
+int
 ssl_init ()
 {
-  SSL_METHOD *meth = NULL;
+  SSL_METHOD *meth;
 
   if (ssl_ctx)
-    return 0;
+    /* The SSL has already been initialized. */
+    return 1;
 
   /* Init the PRNG.  If that fails, bail out.  */
-  ssl_init_prng ();
-  if (RAND_status () == 0)
+  init_prng ();
+  if (RAND_status () != 1)
     {
       logprintf (LOG_NOTQUIET,
-                _("Could not seed OpenSSL PRNG; disabling SSL.\n"));
-      scheme_disable (SCHEME_HTTPS);
-      return SSLERRCTXCREATE;
+                _("Could not seed PRNG; consider using --random-file.\n"));
+      goto error;
     }
 
   SSL_library_init ();
   SSL_load_error_strings ();
   SSLeay_add_all_algorithms ();
   SSLeay_add_ssl_algorithms ();
+
   switch (opt.secure_protocol)
     {
     case secure_protocol_auto:
@@ -216,34 +206,43 @@ ssl_init ()
     }
 
   ssl_ctx = SSL_CTX_new (meth);
+  if (!ssl_ctx)
+    goto error;
+
   SSL_CTX_set_default_verify_paths (ssl_ctx);
   SSL_CTX_load_verify_locations (ssl_ctx, opt.ca_cert, opt.ca_directory);
+
+  /* Specify whether the connect should fail if the verification of
+     the peer fails or if it should go ahead.  */
   SSL_CTX_set_verify (ssl_ctx,
-                     opt.check_cert ? SSL_VERIFY_PEER : SSL_VERIFY_NONE,
-                     verify_callback);
+                     opt.check_cert ? SSL_VERIFY_PEER : SSL_VERIFY_NONE, NULL);
 
   if (opt.cert_file)
     if (SSL_CTX_use_certificate_file (ssl_ctx, opt.cert_file,
                                      key_type_to_ssl_type (opt.cert_type))
        != 1)
-      {
-       ssl_print_errors ();
-       return SSLERRCERTFILE;
-      }
+      goto error;
   if (opt.private_key)
     if (SSL_CTX_use_PrivateKey_file (ssl_ctx, opt.private_key,
                                     key_type_to_ssl_type (opt.private_key_type))
        != 1)
-      {
-       ssl_print_errors ();
-       return SSLERRCERTKEY;
-      }
+      goto error;
+
+  /* Since fd_write unconditionally assumes partial writes (and
+     handles them correctly), allow them in OpenSSL.  */
+  SSL_CTX_set_mode (ssl_ctx, SSL_MODE_ENABLE_PARTIAL_WRITE);
 
-  return 0; /* Succeded */
+  return 1;
+
+ error:
+  if (ssl_ctx)
+    SSL_CTX_free (ssl_ctx);
+  print_errors ();
+  return 0;
 }
 
 static int
-ssl_read (int fd, char *buf, int bufsize, void *ctx)
+openssl_read (int fd, char *buf, int bufsize, void *ctx)
 {
   int ret;
   SSL *ssl = (SSL *) ctx;
@@ -256,7 +255,7 @@ ssl_read (int fd, char *buf, int bufsize, void *ctx)
 }
 
 static int
-ssl_write (int fd, char *buf, int bufsize, void *ctx)
+openssl_write (int fd, char *buf, int bufsize, void *ctx)
 {
   int ret = 0;
   SSL *ssl = (SSL *) ctx;
@@ -269,7 +268,7 @@ ssl_write (int fd, char *buf, int bufsize, void *ctx)
 }
 
 static int
-ssl_poll (int fd, double timeout, int wait_for, void *ctx)
+openssl_poll (int fd, double timeout, int wait_for, void *ctx)
 {
   SSL *ssl = (SSL *) ctx;
   if (timeout == 0)
@@ -280,7 +279,7 @@ ssl_poll (int fd, double timeout, int wait_for, void *ctx)
 }
 
 static int
-ssl_peek (int fd, char *buf, int bufsize, void *ctx)
+openssl_peek (int fd, char *buf, int bufsize, void *ctx)
 {
   int ret;
   SSL *ssl = (SSL *) ctx;
@@ -293,7 +292,7 @@ ssl_peek (int fd, char *buf, int bufsize, void *ctx)
 }
 
 static void
-ssl_close (int fd, void *ctx)
+openssl_close (int fd, void *ctx)
 {
   SSL *ssl = (SSL *) ctx;
   SSL_shutdown (ssl);
@@ -323,26 +322,152 @@ ssl_connect (int fd)
   assert (ssl_ctx != NULL);
   ssl = SSL_new (ssl_ctx);
   if (!ssl)
-    goto err;
+    goto error;
   if (!SSL_set_fd (ssl, fd))
-    goto err;
+    goto error;
   SSL_set_connect_state (ssl);
   if (SSL_connect (ssl) <= 0 || ssl->state != SSL_ST_OK)
-    goto err;
+    goto error;
 
   /* Register FD with Wget's transport layer, i.e. arrange that
      SSL-enabled functions are used for reading, writing, and polling.
-     That way the rest of Wget can keep using xread, xwrite, and
+     That way the rest of Wget can keep using fd_read, fd_write, and
      friends and not care what happens underneath.  */
-  fd_register_transport (fd, ssl_read, ssl_write, ssl_poll, ssl_peek,
-                        ssl_close, ssl);
+  fd_register_transport (fd, openssl_read, openssl_write, openssl_poll,
+                        openssl_peek, openssl_close, ssl);
   DEBUGP (("Connected %d to SSL 0x%0*lx\n", fd, 2 * sizeof (void *),
           (unsigned long) ssl));
   return 1;
 
- err:
-  ssl_print_errors ();
+ error:
+  print_errors ();
   if (ssl)
     SSL_free (ssl);
   return 0;
 }
+
+/* Return 1 is STRING (case-insensitively) matches PATTERN, 0
+   otherwise.  The recognized wildcard character is "*", which matches
+   any character in STRING except ".".  Any number of the "*" wildcard
+   may be present in the pattern.
+
+   This is used to match of hosts as indicated in rfc2818: "Names may
+   contain the wildcard character * which is considered to match any
+   single domain name component or component fragment. E.g., *.a.com
+   matches foo.a.com but not bar.foo.a.com. f*.com matches foo.com but
+   not bar.com."  */
+
+static int
+pattern_match (const char *pattern, const char *string)
+{
+  const char *p = pattern, *n = string;
+  char c;
+  for (; (c = TOLOWER (*p++)) != '\0'; n++)
+    if (c == '*')
+      {
+       for (c = TOLOWER (*p); c == '*'; c = TOLOWER (*++p))
+         ;
+       for (; *n != '\0'; n++)
+         if (TOLOWER (*n) == c && pattern_match (p, n))
+           return 1;
+         else if (*n == '.')
+           return 0;
+       return c == '\0';
+      }
+    else
+      {
+       if (c != TOLOWER (*n))
+         return 0;
+      }
+  return *n == '\0';
+}
+
+/* Check that the identity of the remote host, as presented by its
+   server certificate, corresponds to HOST, which is the host name the
+   user thinks he's connecting to.  This assumes that FD has been
+   connected to an SSL context using ssl_connect.  Return 1 if the
+   identity checks out, 0 otherwise.
+
+   If opt.check_cert is 0, this always returns 1, but still warns the
+   user about the mismatches, if any.  */
+
+int
+ssl_check_server_identity (int fd, const char *host)
+{
+  X509 *peer_cert = NULL;
+  char peer_CN[256];
+  long vresult;
+  int retval;
+
+  /* If the user has specified --no-check-cert, we still want to warn
+     him about problems with the server's certificate.  */
+  const char *severity = opt.check_cert ? _("ERROR") : _("WARNING");
+
+  SSL *ssl = (SSL *) fd_transport_context (fd);
+  assert (ssl != NULL);
+
+  peer_cert = SSL_get_peer_certificate (ssl);
+  if (!peer_cert)
+    {
+      logprintf (LOG_NOTQUIET, _("%s: No certificate presented by %s.\n"),
+                severity, escnonprint (host));
+      retval = 0;
+      goto out;
+    }
+
+#ifdef ENABLE_DEBUG
+  if (opt.debug)
+    {
+      char *subject = X509_NAME_oneline (X509_get_subject_name (peer_cert), 0, 0);
+      char *issuer = X509_NAME_oneline (X509_get_issuer_name (peer_cert), 0, 0);
+      DEBUGP (("certificate:\n  subject: %s\n  issuer:  %s\n",
+              escnonprint (subject), escnonprint (issuer)));
+      OPENSSL_free (subject);
+      OPENSSL_free (issuer);
+    }
+#endif
+
+  vresult = SSL_get_verify_result (ssl);
+  if (vresult != X509_V_OK)
+    {
+      logprintf (LOG_NOTQUIET,
+                _("%s: Certificate verification error for %s: %s\n"),
+                severity, escnonprint (host),
+                X509_verify_cert_error_string (vresult));
+      retval = 0;
+      goto out;
+    }
+
+  /* Check that the common name in the presented certificate matches
+     HOST.  This should be improved in the following ways:
+
+     - It should use dNSName/ipAddress subjectAltName extensions if
+       available; according to rfc2818: "If a subjectAltName extension
+       of type dNSName is present, that MUST be used as the identity."
+
+     - When matching against common names, it should loop over all
+       common names and choose the most specific one, i.e. the last
+       one, not the first one, which the current code picks.  */
+
+  peer_CN[0] = '\0';
+  X509_NAME_get_text_by_NID (X509_get_subject_name (peer_cert),
+                            NID_commonName, peer_CN, sizeof (peer_CN));
+  if (!pattern_match (peer_CN, host))
+    {
+      logprintf (LOG_NOTQUIET, _("\
+%s: certificate common name `%s' doesn't match requested host name `%s'.\n"),
+                severity, escnonprint (peer_CN), escnonprint (host));
+      retval = 0;
+      goto out;
+    }
+
+  /* The certificate was found, verified, and matched HOST. */
+  retval = 1;
+
+ out:
+  if (peer_cert)
+    X509_free (peer_cert);
+
+  /* Allow --no-check-cert to disable certificate checking. */
+  return opt.check_cert ? retval : 1;
+}