mutt_ssl.c 12.8 KB
Newer Older
1
/*
2
 * Copyright (C) 1999-2000 Tommi Komulainen <Tommi.Komulainen@iki.fi>
3 4 5 6 7 8 9 10 11 12 13 14 15
 * 
 *     This program is free software; you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation; either version 2 of the License, or
 *     (at your option) any later version.
 * 
 *     This program is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 * 
 *     You should have received a copy of the GNU General Public License
 *     along with this program; if not, write to the Free Software
16
 *     Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
17
 */
18 19 20 21

/* for SSL NO_* defines */
#include "config.h"

22 23 24
#include <openssl/ssl.h>
#include <openssl/x509.h>
#include <openssl/err.h>
25
#include <openssl/rand.h>
26 27 28 29 30 31

#undef _

#include <string.h>

#include "mutt.h"
32
#include "mutt_socket.h"
33 34
#include "mutt_menu.h"
#include "mutt_curses.h"
35
#include "mutt_ssl.h"
36

37 38 39 40 41
#if OPENSSL_VERSION_NUMBER >= 0x00904000L
#define READ_X509_KEY(fp, key)	PEM_read_X509(fp, key, NULL, NULL)
#else
#define READ_X509_KEY(fp, key)	PEM_read_X509(fp, key, NULL)
#endif
42

43 44 45 46 47
/* Just in case OpenSSL doesn't define DEVRANDOM */
#ifndef DEVRANDOM
#define DEVRANDOM "/dev/urandom"
#endif

48 49 50 51 52 53 54
/* This is ugly, but as RAND_status came in on OpenSSL version 0.9.5
 * and the code has to support older versions too, this is seemed to
 * be cleaner way compared to having even uglier #ifdefs all around.
 */
#ifdef HAVE_RAND_STATUS
#define HAVE_ENTROPY()	(RAND_status() == 1)
#else
55
static int entropy_byte_count = 0;
56
/* OpenSSL fills the entropy pool from /dev/urandom if it exists */
57
#define HAVE_ENTROPY()	(!access(DEVRANDOM, R_OK) || entropy_byte_count >= 16)
58 59
#endif

60
char *SslCertFile = NULL;
61
char *SslEntropyFile = NULL;
62 63 64 65 66 67 68 69 70

typedef struct _sslsockdata
{
  SSL_CTX *ctx;
  SSL *ssl;
  X509 *cert;
}
sslsockdata;

71
static int add_entropy (const char *file);
72 73 74 75 76 77 78 79 80 81 82 83
/* 
 * OpenSSL library needs to be fed with sufficient entropy. On systems
 * with /dev/urandom, this is done transparently by the library itself,
 * on other systems we need to fill the entropy pool ourselves.
 *
 * Even though only OpenSSL 0.9.5 and later will complain about the
 * lack of entropy, we try to our best and fill the pool with older
 * versions also. (That's the reason for the ugly #ifdefs and macros,
 * otherwise I could have simply #ifdef'd the whole ssl_init funcion)
 */
int ssl_init (void)
{
84
  char path[_POSIX_PATH_MAX];
85 86 87

  if (HAVE_ENTROPY()) return 0;
  
88 89 90
 /* load entropy from files */
  add_entropy (SslEntropyFile);
  add_entropy (RAND_file_name (path, sizeof (path)));
91
  
92
   /* load entropy from egd sockets */
93
#ifdef HAVE_RAND_EGD
94
  add_entropy (getenv ("EGDSOCKET"));
95
  snprintf (path, sizeof(path), "%s/.entropy", NONULL(Homedir));
96 97
  add_entropy (path);
  add_entropy ("/tmp/entropy");
98 99
#endif

100 101 102
  /* shuffle $RANDFILE (or ~/.rnd if unset) */
  RAND_write_file (RAND_file_name (path, sizeof (path)));
  mutt_clear_error ();
103 104 105 106 107 108 109
  if (HAVE_ENTROPY()) return 0;

  mutt_error (_("Failed to find enough entropy on your system"));
  sleep (2);
  return -1;
}

110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
static int add_entropy (const char *file)
{
  struct stat st;
  int n = -1;

  if (!file) return 0;

  if (stat (file, &st) == -1)
    return errno == ENOENT ? 0 : -1;

  mutt_message (_("Filling entropy pool: %s...\n"),
		file);
  
  /* check that the file permissions are secure */
  if (st.st_uid != getuid () || 
      ((st.st_mode & (S_IWGRP | S_IRGRP)) != 0) ||
      ((st.st_mode & (S_IWOTH | S_IROTH)) != 0))
  {
    mutt_error (_("%s has insecure permissions!"), file);
    sleep (2);
    return -1;
  }

#ifdef HAVE_RAND_EGD
  n = RAND_egd (file);
#endif
  if (n <= 0)
    n = RAND_load_file (file, -1);

#ifndef HAVE_RAND_STATUS
  if (n > 0) entropy_byte_count += n;
#endif
  return n;
}

145 146 147 148 149 150
static int ssl_socket_open_err (CONNECTION *conn)
{
  mutt_error (_("SSL disabled due the lack of entropy"));
  sleep (2);
  return -1;
}
151 152 153

static int ssl_check_certificate (sslsockdata * data);

154
static int ssl_socket_read (CONNECTION * conn);
155
static int ssl_socket_write (CONNECTION* conn, const char* buf, size_t len);
156 157 158 159 160
static int ssl_socket_open (CONNECTION * conn);
static int ssl_socket_close (CONNECTION * conn);

int ssl_socket_setup (CONNECTION * conn)
{
161 162
  if (ssl_init() < 0)
  {
163 164 165 166 167 168 169 170 171 172 173
    conn->open = ssl_socket_open_err;
    return -1;
  }

  conn->open	= ssl_socket_open;
  conn->read	= ssl_socket_read;
  conn->write	= ssl_socket_write;
  conn->close	= ssl_socket_close;

  return 0;
}
174 175 176 177 178 179 180

int ssl_socket_read (CONNECTION * conn)
{
  sslsockdata *data = conn->sockdata;
  return SSL_read (data->ssl, conn->inbuf, LONG_STRING);
}

181
int ssl_socket_write (CONNECTION* conn, const char* buf, size_t len)
182 183
{
  sslsockdata *data = conn->sockdata;
184
  return SSL_write (data->ssl, buf, len);
185 186 187 188 189 190 191 192 193 194 195 196 197
}

int ssl_socket_open (CONNECTION * conn)
{
  sslsockdata *data;
  int err;

  if (raw_socket_open (conn) < 0)
    return -1;

  data = (sslsockdata *) safe_calloc (1, sizeof (sslsockdata));
  conn->sockdata = data;

198
  SSL_library_init();
199 200
  data->ctx = SSL_CTX_new (SSLv23_client_method ());

201 202 203 204 205 206 207 208 209 210 211 212 213 214
  /* disable SSL protocols as needed */
  if (!option(OPTTLSV1)) 
  {
    SSL_CTX_set_options(data->ctx, SSL_OP_NO_TLSv1);
  }
  if (!option(OPTSSLV2)) 
  {
    SSL_CTX_set_options(data->ctx, SSL_OP_NO_SSLv2);
  }
  if (!option(OPTSSLV3)) 
  {
    SSL_CTX_set_options(data->ctx, SSL_OP_NO_SSLv3);
  }

215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
  data->ssl = SSL_new (data->ctx);
  SSL_set_fd (data->ssl, conn->fd);

  if ((err = SSL_connect (data->ssl)) < 0)
  {
    ssl_socket_close (conn);
    return -1;
  }

  data->cert = SSL_get_peer_certificate (data->ssl);
  if (!data->cert)
  {
    mutt_error (_("Unable to get certificate from peer"));
    sleep (1);
    return -1;
  }

  if (!ssl_check_certificate (data))
  {
    ssl_socket_close (conn);
    return -1;
  }

  mutt_message (_("SSL connection using %s"), SSL_get_cipher (data->ssl));
  sleep (1);

  return 0;
}

int ssl_socket_close (CONNECTION * conn)
{
  sslsockdata *data = conn->sockdata;
247 248
  if (data)
  {
249
    SSL_shutdown (data->ssl);
250

251 252 253 254 255
    X509_free (data->cert);
    SSL_free (data->ssl);
    SSL_CTX_free (data->ctx);
    safe_free ((void **) &conn->sockdata);
  }
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304

  return raw_socket_close (conn);
}



static char *x509_get_part (char *line, const char *ndx)
{
  static char ret[SHORT_STRING];
  char *c, *c2;

  strncpy (ret, _("Unknown"), sizeof (ret));

  c = strstr (line, ndx);
  if (c)
  {
    c += strlen (ndx);
    c2 = strchr (c, '/');
    if (c2)
      *c2 = '\0';
    strncpy (ret, c, sizeof (ret));
    if (c2)
      *c2 = '/';
  }

  return ret;
}

static void x509_fingerprint (char *s, int l, X509 * cert)
{
  unsigned char md[EVP_MAX_MD_SIZE];
  unsigned int n;
  int j;

  if (!X509_digest (cert, EVP_md5 (), md, &n))
  {
    snprintf (s, l, _("[unable to calculate]"));
  }
  else
  {
    for (j = 0; j < (int) n; j++)
    {
      char ch[8];
      snprintf (ch, 8, "%02X%s", md[j], (j % 2 ? " " : ""));
      strncat (s, ch, l);
    }
  }
}

305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
static char *asn1time_to_string (ASN1_UTCTIME *tm)
{
  static char buf[64];
  BIO *bio;

  strncpy (buf, _("[invalid date]"), sizeof (buf));
  
  bio = BIO_new (BIO_s_mem());
  if (bio)
  {
    if (ASN1_TIME_print (bio, tm))
      (void) BIO_read (bio, buf, sizeof (buf));
    BIO_free (bio);
  }

  return buf;
}

static int check_certificate_by_signer (X509 *peercert)
{
  X509_STORE_CTX xsc;
  X509_STORE *ctx;
Thomas Roessler's avatar
Thomas Roessler committed
327
  int pass = 0;
328 329 330 331

  ctx = X509_STORE_new ();
  if (ctx == NULL) return 0;

Thomas Roessler's avatar
Thomas Roessler committed
332
  if (option (OPTSSLSYSTEMCERTS))
333
  {
Thomas Roessler's avatar
Thomas Roessler committed
334 335 336 337
    if (X509_STORE_set_default_paths (ctx))
      pass++;
    else
      dprint (2, (debugfile, "X509_STORE_set_default_paths failed\n"));
338 339
  }

Thomas Roessler's avatar
Thomas Roessler committed
340 341 342 343 344 345
  if (X509_STORE_load_locations (ctx, SslCertFile, NULL))
    pass++;
  else
    dprint (2, (debugfile, "X509_STORE_load_locations_failed\n"));

  if (pass == 0)
346
  {
Thomas Roessler's avatar
Thomas Roessler committed
347
    /* nothing to do */
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
    X509_STORE_free (ctx);
    return 0;
  }

  X509_STORE_CTX_init (&xsc, ctx, peercert, NULL);

  pass = (X509_verify_cert (&xsc) > 0);
#ifdef DEBUG
  if (! pass)
  {
    char buf[SHORT_STRING];
    int err;

    err = X509_STORE_CTX_get_error (&xsc);
    snprintf (buf, sizeof (buf), "%s (%d)", 
	X509_verify_cert_error_string(err), err);
    dprint (2, (debugfile, "X509_verify_cert: %s\n", buf));
  }
#endif
  X509_STORE_CTX_cleanup (&xsc);
  X509_STORE_free (ctx);

  return pass;
}

static int check_certificate_by_digest (X509 *peercert)
374 375 376 377 378 379 380
{
  unsigned char peermd[EVP_MAX_MD_SIZE];
  unsigned int peermdlen;
  X509 *cert = NULL;
  int pass = 0;
  FILE *fp;

381 382 383 384 385 386
  /* expiration check */
  if (X509_cmp_current_time (X509_get_notBefore (peercert)) >= 0)
  {
    dprint (2, (debugfile, "Server certificate is not yet valid\n"));
    mutt_error (_("Server certificate is not yet valid"));
    sleep (2);
387
    return 0;
388 389 390 391 392 393 394 395 396
  }
  if (X509_cmp_current_time (X509_get_notAfter (peercert)) <= 0)
  {
    dprint (2, (debugfile, "Server certificate has expired"));
    mutt_error (_("Server certificate has expired"));
    sleep (2);
    return 0;
  }

397 398 399
  if ((fp = fopen (SslCertFile, "rt")) == NULL)
    return 0;

400 401 402 403 404 405
  if (!X509_digest (peercert, EVP_sha1(), peermd, &peermdlen))
  {
    fclose (fp);
    return 0;
  }
  
406 407 408 409 410
  while ((cert = READ_X509_KEY (fp, &cert)) != NULL)
  {
    unsigned char md[EVP_MAX_MD_SIZE];
    unsigned int mdlen;

411 412 413 414 415 416 417
    /* Avoid CPU-intensive digest calculation if the certificates are
     * not even remotely equal.
     */
    if (X509_subject_name_cmp (cert, peercert) != 0 ||
	X509_issuer_name_cmp (cert, peercert) != 0)
      continue;

418 419 420
    if (!X509_digest (cert, EVP_sha1(), md, &mdlen) || peermdlen != mdlen)
      continue;
    
421 422 423 424 425
    if (memcmp(peermd, md, mdlen) != 0)
      continue;

    pass = 1;
    break;
426
  }
427
  X509_free (cert);
428 429 430 431
  fclose (fp);

  return pass;
}
432 433 434 435 436 437 438 439

static int ssl_check_certificate (sslsockdata * data)
{
  char *part[] =
  {"/CN=", "/Email=", "/O=", "/OU=", "/L=", "/ST=", "/C="};
  char helpstr[SHORT_STRING];
  char buf[SHORT_STRING];
  MUTTMENU *menu;
440
  int done, row, i;
441
  FILE *fp;
442 443 444 445 446 447 448
  char *name = NULL, *c;

  if (check_certificate_by_signer (data->cert))
  {
    dprint (1, (debugfile, "ssl_check_certificate: signer check passed\n"));
    return 1;
  }
449 450

  /* automatic check from user's database */
451 452 453
  if (SslCertFile && check_certificate_by_digest (data->cert))
  {
    dprint (1, (debugfile, "ssl_check_certificate: digest check passed\n"));
454
    return 1;
455
  }
456

457
  /* interactive check from user */
458
  menu = mutt_new_menu ();
459
  menu->max = 19;
460 461 462 463
  menu->dialog = (char **) safe_calloc (1, menu->max * sizeof (char *));
  for (i = 0; i < menu->max; i++)
    menu->dialog[i] = (char *) safe_calloc (1, SHORT_STRING * sizeof (char));

464 465
  row = 0;
  strncpy (menu->dialog[row++], _("This certificate belongs to:"), SHORT_STRING);
Thomas Roessler's avatar
Thomas Roessler committed
466
  name = X509_NAME_oneline (X509_get_subject_name (data->cert),
467
			    buf, sizeof (buf));
468
  for (i = 0; i < 5; i++)
469
  {
470 471
    c = x509_get_part (name, part[i]);
    snprintf (menu->dialog[row++], SHORT_STRING, "   %s", c);
472 473
  }

474 475
  row++;
  strncpy (menu->dialog[row++], _("This certificate was issued by:"), SHORT_STRING);
Thomas Roessler's avatar
Thomas Roessler committed
476
  name = X509_NAME_oneline (X509_get_issuer_name (data->cert),
477
			    buf, sizeof (buf));
478
  for (i = 0; i < 5; i++)
479
  {
480 481
    c = x509_get_part (name, part[i]);
    snprintf (menu->dialog[row++], SHORT_STRING, "   %s", c);
482 483
  }

484 485 486 487 488 489 490 491
  row++;
  snprintf (menu->dialog[row++], SHORT_STRING, _("This certificate is valid"));
  snprintf (menu->dialog[row++], SHORT_STRING, _("   from %s"), 
      asn1time_to_string (X509_get_notBefore (data->cert)));
  snprintf (menu->dialog[row++], SHORT_STRING, _("     to %s"), 
      asn1time_to_string (X509_get_notAfter (data->cert)));

  row++;
492 493
  buf[0] = '\0';
  x509_fingerprint (buf, sizeof (buf), data->cert);
494
  snprintf (menu->dialog[row++], SHORT_STRING, _("Fingerprint: %s"), buf);
495 496

  menu->title = _("SSL Certificate check");
497 498 499 500 501 502 503 504 505 506 507
  if (SslCertFile)
  {
    menu->prompt = _("(r)eject, accept (o)nce, (a)ccept always");
    menu->keys = _("roa");
  }
  else
  {
    menu->prompt = _("(r)eject, accept (o)nce");
    menu->keys = _("ro");
  }
  
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
  helpstr[0] = '\0';
  mutt_make_help (buf, sizeof (buf), _("Exit  "), MENU_GENERIC, OP_EXIT);
  strncat (helpstr, buf, sizeof (helpstr));
  mutt_make_help (buf, sizeof (buf), _("Help"), MENU_GENERIC, OP_HELP);
  strncat (helpstr, buf, sizeof (helpstr));
  menu->help = helpstr;

  done = 0;
  while (!done)
  {
    switch (mutt_menuLoop (menu))
    {
      case -1:			/* abort */
      case OP_MAX + 1:		/* reject */
      case OP_EXIT:
        done = 1;
        break;
      case OP_MAX + 3:		/* accept always */
        done = 0;
527
        if ((fp = fopen (SslCertFile, "a")))
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
	{
	  if (PEM_write_X509 (fp, data->cert))
	    done = 1;
	  fclose (fp);
	}
	if (!done)
	  mutt_error (_("Warning: Couldn't save certificate"));
	else
	  mutt_message (_("Certificate saved"));
	sleep (1);
        /* fall through */
      case OP_MAX + 2:		/* accept once */
        done = 2;
        break;
    }
  }
  mutt_menuDestroy (&menu);
  return (done == 2);
}