Print this page
8982 Support building with OpenSSL 1.1
   1 /*
   2  * Copyright (c) 2000-2006, 2008, 2009 Sendmail, Inc. and its suppliers.
   3  *      All rights reserved.
   4  * Copyright (c) 2012, OmniTI Computer Consulting, Inc. All rights reserved.

   5  *
   6  * By using this file, you agree to the terms and conditions set
   7  * forth in the LICENSE file which can be found at the top level of
   8  * the sendmail distribution.
   9  *
  10  */
  11 
  12 #include <sendmail.h>
  13 
  14 SM_RCSID("@(#)$Id: tls.c,v 8.114 2009/08/10 15:11:09 ca Exp $")
  15 
  16 #if STARTTLS
  17 #  include <openssl/err.h>
  18 #  include <openssl/bio.h>
  19 #  include <openssl/pem.h>

  20 #  ifndef HASURANDOMDEV
  21 #   include <openssl/rand.h>
  22 #  endif /* ! HASURANDOMDEV */
  23 # if !TLS_NO_RSA

  24 static RSA *rsa_tmp = NULL;     /* temporary RSA key */
  25 static RSA *tmp_rsa_key __P((SSL *, int, int));
  26 # endif /* !TLS_NO_RSA */
  27 #  if !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER < 0x00907000L
  28 static int      tls_verify_cb __P((X509_STORE_CTX *));
  29 #  else /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */
  30 static int      tls_verify_cb __P((X509_STORE_CTX *, void *));
  31 #  endif /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */
  32 
  33 # if OPENSSL_VERSION_NUMBER > 0x00907000L
  34 static int x509_verify_cb __P((int, X509_STORE_CTX *));
  35 # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
  36 
  37 # if !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER < 0x00907000L
  38 #  define CONST097
  39 # else /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */
  40 #  define CONST097 const
  41 # endif /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */
  42 static void     apps_ssl_info_cb __P((CONST097 SSL *, int , int));
  43 static bool     tls_ok_f __P((char *, char *, int));
  44 static bool     tls_safe_f __P((char *, long, bool));
  45 static int      tls_verify_log __P((int, X509_STORE_CTX *, char *));
  46 
  47 # if !NO_DH










































  48 static DH *get_dh512 __P((void));
  49 
  50 static unsigned char dh512_p[] =
  51 {
  52         0xDA,0x58,0x3C,0x16,0xD9,0x85,0x22,0x89,0xD0,0xE4,0xAF,0x75,
  53         0x6F,0x4C,0xCA,0x92,0xDD,0x4B,0xE5,0x33,0xB8,0x04,0xFB,0x0F,
  54         0xED,0x94,0xEF,0x9C,0x8A,0x44,0x03,0xED,0x57,0x46,0x50,0xD3,
  55         0x69,0x99,0xDB,0x29,0xD7,0x76,0x27,0x6B,0xA2,0xD3,0xD4,0x12,
  56         0xE2,0x18,0xF4,0xDD,0x1E,0x08,0x4C,0xF6,0xD8,0x00,0x3E,0x7C,
  57         0x47,0x74,0xE8,0x33
  58 };
  59 static unsigned char dh512_g[] =
  60 {
  61         0x02
  62 };
  63 
  64 static DH *
  65 get_dh512()
  66 {
  67         DH *dh = NULL;

  68 
  69         if ((dh = DH_new()) == NULL)
  70                 return NULL;
  71         dh->p = BN_bin2bn(dh512_p, sizeof(dh512_p), NULL);
  72         dh->g = BN_bin2bn(dh512_g, sizeof(dh512_g), NULL);
  73         if ((dh->p == NULL) || (dh->g == NULL))



  74                 return NULL;




  75         return dh;
  76 }
  77 # endif /* !NO_DH */
  78 
  79 
  80 /*
  81 **  TLS_RAND_INIT -- initialize STARTTLS random generator
  82 **
  83 **      Parameters:
  84 **              randfile -- name of file with random data
  85 **              logl -- loglevel
  86 **
  87 **      Returns:
  88 **              success/failure
  89 **
  90 **      Side Effects:
  91 **              initializes PRNG for tls library.
  92 */
  93 
  94 # define MIN_RAND_BYTES 128     /* 1024 bits */


 261         done = ok ? RI_SUCCESS : RI_FAIL;
 262         return ok;
 263 # else /* ! HASURANDOMDEV */
 264         return true;
 265 # endif /* ! HASURANDOMDEV */
 266 }
 267 /*
 268 **  INIT_TLS_LIBRARY -- Calls functions which setup TLS library for global use.
 269 **
 270 **      Parameters:
 271 **              none.
 272 **
 273 **      Returns:
 274 **              succeeded?
 275 */
 276 
 277 bool
 278 init_tls_library()
 279 {
 280         /* basic TLS initialization, ignore result for now */


 281         SSL_library_init();
 282         SSL_load_error_strings();

 283 # if 0
 284         /* this is currently a macro for SSL_library_init */
 285         SSLeay_add_ssl_algorithms();
 286 # endif /* 0 */
 287 
 288         return tls_rand_init(RandFile, 7);
 289 }
 290 /*
 291 **  TLS_SET_VERIFY -- request client certificate?
 292 **
 293 **      Parameters:
 294 **              ctx -- TLS context
 295 **              ssl -- TLS structure
 296 **              vrfy -- require certificate?
 297 **
 298 **      Returns:
 299 **              none.
 300 **
 301 **      Side Effects:
 302 **              Sets verification state for TLS


 491 **              srv -- server side?
 492 **              certfile -- filename of certificate
 493 **              keyfile -- filename of private key
 494 **              cacertpath -- path to CAs
 495 **              cacertfile -- file with CA(s)
 496 **              dhparam -- parameters for DH
 497 **
 498 **      Returns:
 499 **              succeeded?
 500 */
 501 
 502 /*
 503 **  The session_id_context identifies the service that created a session.
 504 **  This information is used to distinguish between multiple TLS-based
 505 **  servers running on the same server. We use the name of the mail system.
 506 **  Note: the session cache is not persistent.
 507 */
 508 
 509 static char server_session_id_context[] = "sendmail8";
 510 
 511 /* 0.9.8a and b have a problem with SSL_OP_TLS_BLOCK_PADDING_BUG */
 512 #if (OPENSSL_VERSION_NUMBER >= 0x0090800fL)
 513 # define SM_SSL_OP_TLS_BLOCK_PADDING_BUG        1
 514 #else
 515 # define SM_SSL_OP_TLS_BLOCK_PADDING_BUG        0
 516 #endif
 517 
 518 bool
 519 inittls(ctx, req, options, srv, certfile, keyfile, cacertpath, cacertfile, dhparam)
 520         SSL_CTX **ctx;
 521         unsigned long req;
 522         long options;
 523         bool srv;
 524         char *certfile, *keyfile, *cacertpath, *cacertfile, *dhparam;
 525 {
 526 # if !NO_DH
 527         static DH *dh = NULL;
 528 # endif /* !NO_DH */
 529         int r;
 530         bool ok;
 531         long sff, status;
 532         char *who;
 533 # if _FFR_TLS_1
 534         char *cf2, *kf2;
 535 # endif /* _FFR_TLS_1 */
 536 #  if SM_CONF_SHM
 537         extern int ShmId;
 538 #  endif /* SM_CONF_SHM */
 539 # if OPENSSL_VERSION_NUMBER > 0x00907000L
 540         BIO *crl_file;
 541         X509_CRL *crl;
 542         X509_STORE *store;
 543 # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
 544 #if SM_SSL_OP_TLS_BLOCK_PADDING_BUG
 545         long rt_version;
 546         STACK_OF(SSL_COMP) *comp_methods;
 547 #endif
 548 
 549         status = TLS_S_NONE;
 550         who = srv ? "server" : "client";
 551         if (ctx == NULL)
 552         {
 553                 syserr("STARTTLS=%s, inittls: ctx == NULL", who);
 554                 /* NOTREACHED */
 555                 SM_ASSERT(ctx != NULL);
 556         }
 557 
 558         /* already initialized? (we could re-init...) */
 559         if (*ctx != NULL)
 560                 return true;
 561         ok = true;
 562 
 563 # if _FFR_TLS_1
 564         /*
 565         **  look for a second filename: it must be separated by a ','
 566         **  no blanks allowed (they won't be skipped).
 567         **  we change a global variable here! this change will be undone


 576         if (certfile != NULL && (cf2 = strchr(certfile, ',')) != NULL)
 577         {
 578                 *cf2++ = '\0';
 579                 if (keyfile != NULL && (kf2 = strchr(keyfile, ',')) != NULL)
 580                         *kf2++ = '\0';
 581         }
 582 # endif /* _FFR_TLS_1 */
 583 
 584         /*
 585         **  Check whether files/paths are defined
 586         */
 587 
 588         TLS_OK_F(certfile, "CertFile", bitset(TLS_I_CERT_EX, req),
 589                  TLS_S_CERT_EX, srv ? TLS_T_SRV : TLS_T_CLT);
 590         TLS_OK_F(keyfile, "KeyFile", bitset(TLS_I_KEY_EX, req),
 591                  TLS_S_KEY_EX, srv ? TLS_T_SRV : TLS_T_CLT);
 592         TLS_OK_F(cacertpath, "CACertPath", bitset(TLS_I_CERTP_EX, req),
 593                  TLS_S_CERTP_EX, TLS_T_OTHER);
 594         TLS_OK_F(cacertfile, "CACertFile", bitset(TLS_I_CERTF_EX, req),
 595                  TLS_S_CERTF_EX, TLS_T_OTHER);
 596 
 597 # if OPENSSL_VERSION_NUMBER > 0x00907000L
 598         TLS_OK_F(CRLFile, "CRLFile", bitset(TLS_I_CRLF_EX, req),
 599                  TLS_S_CRLF_EX, TLS_T_OTHER);
 600 # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
 601 
 602 # if _FFR_TLS_1
 603         /*
 604         **  if the second file is specified it must exist
 605         **  XXX: it is possible here to define only one of those files
 606         */
 607 
 608         if (cf2 != NULL)
 609         {
 610                 TLS_OK_F(cf2, "CertFile", bitset(TLS_I_CERT_EX, req),
 611                          TLS_S_CERT2_EX, srv ? TLS_T_SRV : TLS_T_CLT);
 612         }
 613         if (kf2 != NULL)
 614         {
 615                 TLS_OK_F(kf2, "KeyFile", bitset(TLS_I_KEY_EX, req),
 616                          TLS_S_KEY2_EX, srv ? TLS_T_SRV : TLS_T_CLT);
 617         }
 618 # endif /* _FFR_TLS_1 */
 619 
 620         /*


 662 
 663         /* certfile etc. must be "safe". */
 664         sff = SFF_REGONLY | SFF_SAFEDIRPATH | SFF_NOWLINK
 665              | SFF_NOGWFILES | SFF_NOWWFILES
 666              | SFF_MUSTOWN | SFF_ROOTOK | SFF_OPENASROOT;
 667         if (DontLockReadFiles)
 668                 sff |= SFF_NOLOCK;
 669 
 670         TLS_SAFE_F(certfile, sff | TLS_UNR(TLS_I_CERT_UNR, req),
 671                    bitset(TLS_I_CERT_EX, req),
 672                    bitset(TLS_S_CERT_EX, status), TLS_S_CERT_OK, srv);
 673         TLS_SAFE_F(keyfile, sff | TLS_KEYSFF(req),
 674                    bitset(TLS_I_KEY_EX, req),
 675                    bitset(TLS_S_KEY_EX, status), TLS_S_KEY_OK, srv);
 676         TLS_SAFE_F(cacertfile, sff | TLS_UNR(TLS_I_CERTF_UNR, req),
 677                    bitset(TLS_I_CERTF_EX, req),
 678                    bitset(TLS_S_CERTF_EX, status), TLS_S_CERTF_OK, srv);
 679         TLS_SAFE_F(dhparam, sff | TLS_UNR(TLS_I_DHPAR_UNR, req),
 680                    bitset(TLS_I_DHPAR_EX, req),
 681                    bitset(TLS_S_DHPAR_EX, status), TLS_S_DHPAR_OK, srv);
 682 # if OPENSSL_VERSION_NUMBER > 0x00907000L
 683         TLS_SAFE_F(CRLFile, sff | TLS_UNR(TLS_I_CRLF_UNR, req),
 684                    bitset(TLS_I_CRLF_EX, req),
 685                    bitset(TLS_S_CRLF_EX, status), TLS_S_CRLF_OK, srv);
 686 # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
 687         if (!ok)
 688                 return ok;
 689 # if _FFR_TLS_1
 690         if (cf2 != NULL)
 691         {
 692                 TLS_SAFE_F(cf2, sff | TLS_UNR(TLS_I_CERT_UNR, req),
 693                            bitset(TLS_I_CERT_EX, req),
 694                            bitset(TLS_S_CERT2_EX, status), TLS_S_CERT2_OK, srv);
 695         }
 696         if (kf2 != NULL)
 697         {
 698                 TLS_SAFE_F(kf2, sff | TLS_KEYSFF(req),
 699                            bitset(TLS_I_KEY_EX, req),
 700                            bitset(TLS_S_KEY2_EX, status), TLS_S_KEY2_OK, srv);
 701         }
 702 # endif /* _FFR_TLS_1 */
 703 
 704         /* create a method and a new context */
 705         if ((*ctx = SSL_CTX_new(srv ? SSLv23_server_method() :
 706                                       SSLv23_client_method())) == NULL)
 707         {
 708                 if (LogLevel > 7)
 709                         sm_syslog(LOG_WARNING, NOQID,
 710                                   "STARTTLS=%s, error: SSL_CTX_new(SSLv23_%s_method()) failed",
 711                                   who, who);
 712                 if (LogLevel > 9)
 713                         tlslogerr(who);
 714                 return false;
 715         }
 716 
 717 # if OPENSSL_VERSION_NUMBER > 0x00907000L
 718         if (CRLFile != NULL)
 719         {
 720                 /* get a pointer to the current certificate validation store */
 721                 store = SSL_CTX_get_cert_store(*ctx);   /* does not fail */
 722                 crl_file = BIO_new(BIO_s_file_internal());
 723                 if (crl_file != NULL)
 724                 {
 725                         if (BIO_read_filename(crl_file, CRLFile) >= 0)
 726                         {
 727                                 crl = PEM_read_bio_X509_CRL(crl_file, NULL,
 728                                                         NULL, NULL);
 729                                 BIO_free(crl_file);
 730                                 X509_STORE_add_crl(store, crl);
 731                                 X509_CRL_free(crl);
 732                                 X509_STORE_set_flags(store,
 733                                         X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
 734                                 X509_STORE_set_verify_cb_func(store,
 735                                                 x509_verify_cb);
 736                         }
 737                         else
 738                         {
 739                                 if (LogLevel > 9)
 740                                 {
 741                                         sm_syslog(LOG_WARNING, NOQID,
 742                                                   "STARTTLS=%s, error: PEM_read_bio_X509_CRL(%s)=failed",


 759         if (CRLPath != NULL && store != NULL)
 760         {
 761                 X509_LOOKUP *lookup;
 762 
 763                 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
 764                 if (lookup == NULL)
 765                 {
 766                         if (LogLevel > 9)
 767                         {
 768                                 sm_syslog(LOG_WARNING, NOQID,
 769                                           "STARTTLS=%s, error: X509_STORE_add_lookup(hash)=failed",
 770                                           who, CRLFile);
 771                         }
 772                         return false;
 773                 }
 774                 X509_LOOKUP_add_dir(lookup, CRLPath, X509_FILETYPE_PEM);
 775                 X509_STORE_set_flags(store,
 776                         X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
 777         }
 778 #  endif /* _FFR_CRLPATH */
 779 # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
 780 
 781 # if TLS_NO_RSA
 782         /* turn off backward compatibility, required for no-rsa */
 783         SSL_CTX_set_options(*ctx, SSL_OP_NO_SSLv2);
 784 # endif /* TLS_NO_RSA */
 785 
 786 
 787 # if !TLS_NO_RSA
 788         /*
 789         **  Create a temporary RSA key
 790         **  XXX  Maybe we shouldn't create this always (even though it
 791         **  is only at startup).
 792         **  It is a time-consuming operation and it is not always necessary.
 793         **  maybe we should do it only on demand...
 794         */
 795 
 796         if (bitset(TLS_I_RSA_TMP, req)
 797 #   if SM_CONF_SHM
 798             && ShmId != SM_SHM_NO_ID &&
 799             (rsa_tmp = RSA_generate_key(RSA_KEYLENGTH, RSA_F4, NULL,
 800                                         NULL)) == NULL
 801 #   else /* SM_CONF_SHM */
 802             && 0        /* no shared memory: no need to generate key now */
 803 #   endif /* SM_CONF_SHM */
 804            )
 805         {










 806                 if (LogLevel > 7)
 807                 {
 808                         sm_syslog(LOG_WARNING, NOQID,
 809                                   "STARTTLS=%s, error: RSA_generate_key failed",
 810                                   who);
 811                         if (LogLevel > 9)
 812                                 tlslogerr(who);
 813                 }
 814                 return false;
 815         }


 816 # endif /* !TLS_NO_RSA */
 817 
 818         /*
 819         **  load private key
 820         **  XXX change this for DSA-only version
 821         */
 822 
 823         if (bitset(TLS_S_KEY_OK, status) &&
 824             SSL_CTX_use_PrivateKey_file(*ctx, keyfile,
 825                                          SSL_FILETYPE_PEM) <= 0)
 826         {
 827                 if (LogLevel > 7)
 828                 {
 829                         sm_syslog(LOG_WARNING, NOQID,
 830                                   "STARTTLS=%s, error: SSL_CTX_use_PrivateKey_file(%s) failed",
 831                                   who, keyfile);
 832                         if (LogLevel > 9)
 833                                 tlslogerr(who);
 834                 }
 835                 if (bitset(TLS_I_USE_KEY, req))


 902         }
 903 
 904         /* also check the private key */
 905         if (bitset(TLS_S_KEY2_OK, status) &&
 906             (r = SSL_CTX_check_private_key(*ctx)) <= 0)
 907         {
 908                 /* Private key does not match the certificate public key */
 909                 if (LogLevel > 5)
 910                 {
 911                         sm_syslog(LOG_WARNING, NOQID,
 912                                   "STARTTLS=%s, error: SSL_CTX_check_private_key 2 failed: %d",
 913                                   who, r);
 914                         if (LogLevel > 9)
 915                                 tlslogerr(who);
 916                 }
 917         }
 918 # endif /* _FFR_TLS_1 */
 919 
 920         /* SSL_CTX_set_quiet_shutdown(*ctx, 1); violation of standard? */
 921 
 922 #if SM_SSL_OP_TLS_BLOCK_PADDING_BUG
 923 
 924         /*
 925         **  In OpenSSL 0.9.8[ab], enabling zlib compression breaks the
 926         **  padding bug work-around, leading to false positives and
 927         **  failed connections. We may not interoperate with systems
 928         **  with the bug, but this is better than breaking on all 0.9.8[ab]
 929         **  systems that have zlib support enabled.
 930         **  Note: this checks the runtime version of the library, not
 931         **  just the compile time version.
 932         */
 933 
 934         rt_version = SSLeay();
 935         if (rt_version >= 0x00908000L && rt_version <= 0x0090802fL)
 936         {
 937                 comp_methods = SSL_COMP_get_compression_methods();
 938                 if (comp_methods != NULL && sk_SSL_COMP_num(comp_methods) > 0)
 939                         options &= ~SSL_OP_TLS_BLOCK_PADDING_BUG;
 940         }
 941 #endif
 942         SSL_CTX_set_options(*ctx, options);
 943 
 944 # if !NO_DH
 945         /* Diffie-Hellman initialization */
 946         if (bitset(TLS_I_TRY_DH, req))
 947         {
 948                 if (bitset(TLS_S_DHPAR_OK, status))
 949                 {
 950                         BIO *bio;
 951 
 952                         if ((bio = BIO_new_file(dhparam, "r")) != NULL)
 953                         {
 954                                 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
 955                                 BIO_free(bio);
 956                                 if (dh == NULL && LogLevel > 7)
 957                                 {
 958                                         unsigned long err;
 959 
 960                                         err = ERR_get_error();
 961                                         sm_syslog(LOG_WARNING, NOQID,


 963                                                   who, dhparam,
 964                                                   ERR_error_string(err, NULL));
 965                                         if (LogLevel > 9)
 966                                                 tlslogerr(who);
 967                                 }
 968                         }
 969                         else
 970                         {
 971                                 if (LogLevel > 5)
 972                                 {
 973                                         sm_syslog(LOG_WARNING, NOQID,
 974                                                   "STARTTLS=%s, error: BIO_new_file(%s) failed",
 975                                                   who, dhparam);
 976                                         if (LogLevel > 9)
 977                                                 tlslogerr(who);
 978                                 }
 979                         }
 980                 }
 981                 if (dh == NULL && bitset(TLS_I_DH1024, req))
 982                 {
 983                         DSA *dsa;
 984 
 985                         /* this takes a while! (7-130s on a 450MHz AMD K6-2) */
 986                         dsa = DSA_generate_parameters(1024, NULL, 0, NULL,
 987                                                       NULL, 0, NULL);



 988                         dh = DSA_dup_DH(dsa);

 989                         DSA_free(dsa);
 990                 }
 991                 else
 992                 if (dh == NULL && bitset(TLS_I_DH512, req))
 993                         dh = get_dh512();
 994 
 995                 if (dh == NULL)
 996                 {
 997                         if (LogLevel > 9)
 998                         {
 999                                 unsigned long err;
1000 
1001                                 err = ERR_get_error();
1002                                 sm_syslog(LOG_WARNING, NOQID,
1003                                           "STARTTLS=%s, error: cannot read or set DH parameters(%s): %s",
1004                                           who, dhparam,
1005                                           ERR_error_string(err, NULL));
1006                         }
1007                         if (bitset(TLS_I_REQ_DH, req))
1008                                 return false;
1009                 }
1010                 else
1011                 {
1012                         SSL_CTX_set_tmp_dh(*ctx, dh);


1029                 SSL_CTX_sess_set_cache_size(*ctx, 1);
1030                 SSL_CTX_set_timeout(*ctx, 1);
1031                 SSL_CTX_set_session_id_context(*ctx,
1032                         (void *) &server_session_id_context,
1033                         sizeof(server_session_id_context));
1034                 (void) SSL_CTX_set_session_cache_mode(*ctx,
1035                                 SSL_SESS_CACHE_SERVER);
1036         }
1037         else
1038         {
1039                 (void) SSL_CTX_set_session_cache_mode(*ctx,
1040                                 SSL_SESS_CACHE_OFF);
1041         }
1042 
1043         /* load certificate locations and default CA paths */
1044         if (bitset(TLS_S_CERTP_EX, status) && bitset(TLS_S_CERTF_EX, status))
1045         {
1046                 if ((r = SSL_CTX_load_verify_locations(*ctx, cacertfile,
1047                                                        cacertpath)) == 1)
1048                 {
1049 # if !TLS_NO_RSA
1050                         if (bitset(TLS_I_RSA_TMP, req))
1051                                 SSL_CTX_set_tmp_rsa_callback(*ctx, tmp_rsa_key);
1052 # endif /* !TLS_NO_RSA */
1053 
1054                         /*
1055                         **  We have to install our own verify callback:
1056                         **  SSL_VERIFY_PEER requests a client cert but even
1057                         **  though *FAIL_IF* isn't set, the connection
1058                         **  will be aborted if the client presents a cert
1059                         **  that is not "liked" (can't be verified?) by
1060                         **  the TLS library :-(
1061                         */
1062 
1063                         /*
1064                         **  XXX currently we could call tls_set_verify()
1065                         **  but we hope that that function will later on
1066                         **  only set the mode per connection.
1067                         */
1068                         SSL_CTX_set_verify(*ctx,
1069                                 bitset(TLS_I_NO_VRFY, req) ? SSL_VERIFY_NONE
1070                                                            : SSL_VERIFY_PEER,
1071                                 NULL);
1072 
1073                         /* install verify callback */


1169         MACROS_T *mac;
1170         bool certreq;
1171 {
1172         const SSL_CIPHER *c;
1173         int b, r;
1174         long verifyok;
1175         char *s, *who;
1176         char bitstr[16];
1177         X509 *cert;
1178 
1179         c = SSL_get_current_cipher(ssl);
1180 
1181         /* cast is just workaround for compiler warning */
1182         macdefine(mac, A_TEMP, macid("{cipher}"),
1183                   (char *) SSL_CIPHER_get_name(c));
1184         b = SSL_CIPHER_get_bits(c, &r);
1185         (void) sm_snprintf(bitstr, sizeof(bitstr), "%d", b);
1186         macdefine(mac, A_TEMP, macid("{cipher_bits}"), bitstr);
1187         (void) sm_snprintf(bitstr, sizeof(bitstr), "%d", r);
1188         macdefine(mac, A_TEMP, macid("{alg_bits}"), bitstr);
1189         s = SSL_CIPHER_get_version(c);
1190         if (s == NULL)
1191                 s = "UNKNOWN";
1192         macdefine(mac, A_TEMP, macid("{tls_version}"), s);
1193 
1194         who = srv ? "server" : "client";
1195         cert = SSL_get_peer_certificate(ssl);
1196         verifyok = SSL_get_verify_result(ssl);
1197         if (LogLevel > 14)
1198                 sm_syslog(LOG_INFO, NOQID,
1199                           "STARTTLS=%s, get_verify: %ld get_peer: 0x%lx",
1200                           who, verifyok, (unsigned long) cert);
1201         if (cert != NULL)
1202         {
1203                 unsigned int n;
1204                 X509_NAME *subj, *issuer;
1205                 unsigned char md[EVP_MAX_MD_SIZE];
1206                 char buf[MAXNAME];
1207 
1208                 subj = X509_get_subject_name(cert);
1209                 issuer = X509_get_issuer_name(cert);


1363         SSL *ssl;
1364         char *side;
1365 {
1366         int ret = EX_OK;
1367 
1368         if (ssl != NULL)
1369         {
1370                 int r;
1371 
1372                 if ((r = SSL_shutdown(ssl)) < 0)
1373                 {
1374                         if (LogLevel > 11)
1375                         {
1376                                 sm_syslog(LOG_WARNING, NOQID,
1377                                           "STARTTLS=%s, SSL_shutdown failed: %d",
1378                                           side, r);
1379                                 tlslogerr(side);
1380                         }
1381                         ret = EX_SOFTWARE;
1382                 }
1383 # if !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER > 0x0090602fL
1384 
1385                 /*
1386                 **  Bug in OpenSSL (at least up to 0.9.6b):
1387                 **  From: Lutz.Jaenicke@aet.TU-Cottbus.DE
1388                 **  Message-ID: <20010723152244.A13122@serv01.aet.tu-cottbus.de>
1389                 **  To: openssl-users@openssl.org
1390                 **  Subject: Re: SSL_shutdown() woes (fwd)
1391                 **
1392                 **  The side sending the shutdown alert first will
1393                 **  not care about the answer of the peer but will
1394                 **  immediately return with a return value of "0"
1395                 **  (ssl/s3_lib.c:ssl3_shutdown()). SSL_get_error will evaluate
1396                 **  the value of "0" and as the shutdown alert of the peer was
1397                 **  not received (actually, the program did not even wait for
1398                 **  the answer), an SSL_ERROR_SYSCALL is flagged, because this
1399                 **  is the default rule in case everything else does not apply.
1400                 **
1401                 **  For your server the problem is different, because it
1402                 **  receives the shutdown first (setting SSL_RECEIVED_SHUTDOWN),
1403                 **  then sends its response (SSL_SENT_SHUTDOWN), so for the


1412                 **  probably with another API, as the change would not be
1413                 **  compatible to the way it is now.  Things do not become
1414                 **  easier as other programs do not follow the shutdown
1415                 **  guidelines anyway, so that a lot error conditions and
1416                 **  compitibility issues would have to be caught.
1417                 **
1418                 **  For now the recommondation is to ignore the error message.
1419                 */
1420 
1421                 else if (r == 0)
1422                 {
1423                         if (LogLevel > 15)
1424                         {
1425                                 sm_syslog(LOG_WARNING, NOQID,
1426                                           "STARTTLS=%s, SSL_shutdown not done",
1427                                           side);
1428                                 tlslogerr(side);
1429                         }
1430                         ret = EX_SOFTWARE;
1431                 }
1432 # endif /* !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER > 0x0090602fL */
1433                 SSL_free(ssl);
1434                 ssl = NULL;
1435         }
1436         return ret;
1437 }
1438 
1439 # if !TLS_NO_RSA
1440 /*
1441 **  TMP_RSA_KEY -- return temporary RSA key
1442 **
1443 **      Parameters:
1444 **              s -- TLS connection structure
1445 **              export --
1446 **              keylength --
1447 **
1448 **      Returns:
1449 **              temporary RSA key.
1450 */
1451 
1452 #   ifndef MAX_RSA_TMP_CNT
1453 #    define MAX_RSA_TMP_CNT     1000    /* XXX better value? */
1454 #   endif /* ! MAX_RSA_TMP_CNT */
1455 
1456 /* ARGUSED0 */
1457 static RSA *
1458 tmp_rsa_key(s, export, keylength)
1459         SSL *s;
1460         int export;
1461         int keylength;
1462 {
1463 #   if SM_CONF_SHM
1464         extern int ShmId;
1465         extern int *PRSATmpCnt;
1466 
1467         if (ShmId != SM_SHM_NO_ID && rsa_tmp != NULL &&
1468             ++(*PRSATmpCnt) < MAX_RSA_TMP_CNT)
1469                 return rsa_tmp;
1470 #   endif /* SM_CONF_SHM */
1471 
1472         if (rsa_tmp != NULL)
1473                 RSA_free(rsa_tmp);
1474         rsa_tmp = RSA_generate_key(RSA_KEYLENGTH, RSA_F4, NULL, NULL);
1475         if (rsa_tmp == NULL)
1476         {
1477                 if (LogLevel > 0)
1478                         sm_syslog(LOG_ERR, NOQID,
1479                                   "STARTTLS=server, tmp_rsa_key: RSA_generate_key failed!");
1480         }
1481         else
1482         {
1483 #   if SM_CONF_SHM
1484 #    if 0
1485                 /*
1486                 **  XXX we can't (yet) share the new key...
1487                 **      The RSA structure contains pointers hence it can't be
1488                 **      easily kept in shared memory.  It must be transformed
1489                 **      into a continous memory region first, then stored,
1490                 **      and later read out again (each time re-transformed).
1491                 */
1492 
1493                 if (ShmId != SM_SHM_NO_ID)
1494                         *PRSATmpCnt = 0;
1495 #    endif /* 0 */
1496 #   endif /* SM_CONF_SHM */
1497                 if (LogLevel > 9)
1498                         sm_syslog(LOG_ERR, NOQID,
1499                                   "STARTTLS=server, tmp_rsa_key: new temp RSA key");
1500         }
1501         return rsa_tmp;
1502 }
1503 # endif /* !TLS_NO_RSA */
1504 /*
1505 **  APPS_SSL_INFO_CB -- info callback for TLS connections
1506 **
1507 **      Parameters:
1508 **              s -- TLS connection structure
1509 **              where -- state in handshake
1510 **              ret -- return code of last operation
1511 **
1512 **      Returns:
1513 **              none.
1514 */
1515 
1516 static void
1517 apps_ssl_info_cb(s, where, ret)
1518         CONST097 SSL *s;
1519         int where;
1520         int ret;
1521 {
1522         int w;
1523         char *str;
1524         BIO *bio_err = NULL;


1612 
1613         X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf));
1614         sm_syslog(LOG_INFO, NOQID,
1615                   "STARTTLS: %s cert verify: depth=%d %s, state=%d, reason=%s",
1616                   name, depth, buf, ok, X509_verify_cert_error_string(reason));
1617         return 1;
1618 }
1619 
1620 /*
1621 **  TLS_VERIFY_CB -- verify callback for TLS certificates
1622 **
1623 **      Parameters:
1624 **              ctx -- x509 context
1625 **
1626 **      Returns:
1627 **              accept connection?
1628 **              currently: always yes.
1629 */
1630 
1631 static int
1632 #  if !defined(OPENSSL_VERSION_NUMBER) || OPENSSL_VERSION_NUMBER < 0x00907000L
1633 tls_verify_cb(ctx)
1634         X509_STORE_CTX *ctx;
1635 #  else /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */
1636 tls_verify_cb(ctx, unused)
1637         X509_STORE_CTX *ctx;
1638         void *unused;
1639 #  endif /* !defined() || OPENSSL_VERSION_NUMBER < 0x00907000L */
1640 {
1641         int ok;
1642 
1643         /*
1644         **  man SSL_CTX_set_cert_verify_callback():
1645         **  callback should return 1 to indicate verification success
1646         **  and 0 to indicate verification failure.
1647         */
1648 
1649         ok = X509_verify_cert(ctx);
1650         if (ok <= 0)
1651         {
1652                 if (LogLevel > 13)
1653                         return tls_verify_log(ok, ctx, "TLS");
1654         }
1655         return 1;
1656 }
1657 /*
1658 **  TLSLOGERR -- log the errors from the TLS error stack
1659 **
1660 **      Parameters:
1661 **              who -- server/client (for logging).
1662 **
1663 **      Returns:
1664 **              none.
1665 */
1666 
1667 void
1668 tlslogerr(who)
1669         const char *who;
1670 {
1671         unsigned long l;
1672         int line, flags;
1673         unsigned long es;
1674         char *file, *data;
1675         char buf[256];
1676 #  define CP (const char **)
1677 



1678         es = CRYPTO_thread_id();

1679         while ((l = ERR_get_error_line_data(CP &file, &line, CP &data, &flags))
1680                 != 0)
1681         {
1682                 sm_syslog(LOG_WARNING, NOQID,
1683                           "STARTTLS=%s: %lu:%s:%s:%d:%s", who, es,
1684                           ERR_error_string(l, buf),
1685                           file, line,
1686                           bitset(ERR_TXT_STRING, flags) ? data : "");
1687         }
1688 }
1689 
1690 # if OPENSSL_VERSION_NUMBER > 0x00907000L
1691 /*
1692 **  X509_VERIFY_CB -- verify callback
1693 **
1694 **      Parameters:
1695 **              ctx -- x509 context
1696 **
1697 **      Returns:
1698 **              accept connection?
1699 **              currently: always yes.
1700 */
1701 
1702 static int
1703 x509_verify_cb(ok, ctx)
1704         int ok;
1705         X509_STORE_CTX *ctx;
1706 {
1707         if (ok == 0)
1708         {
1709                 if (LogLevel > 13)
1710                         tls_verify_log(ok, ctx, "x509");
1711                 if (ctx->error == X509_V_ERR_UNABLE_TO_GET_CRL)

1712                 {
1713                         ctx->error = 0;
1714                         return 1;       /* override it */
1715                 }
1716         }
1717         return ok;
1718 }
1719 # endif /* OPENSSL_VERSION_NUMBER > 0x00907000L */
1720 #endif /* STARTTLS */
   1 /*
   2  * Copyright (c) 2000-2006, 2008, 2009 Sendmail, Inc. and its suppliers.
   3  *      All rights reserved.
   4  * Copyright (c) 2012, OmniTI Computer Consulting, Inc. All rights reserved.
   5  * Copyright 2018 OmniOS Community Edition (OmniOSce) Association.
   6  *
   7  * By using this file, you agree to the terms and conditions set
   8  * forth in the LICENSE file which can be found at the top level of
   9  * the sendmail distribution.
  10  *
  11  */
  12 
  13 #include <sendmail.h>
  14 
  15 SM_RCSID("@(#)$Id: tls.c,v 8.114 2009/08/10 15:11:09 ca Exp $")
  16 
  17 #if STARTTLS
  18 #  include <openssl/err.h>
  19 #  include <openssl/bio.h>
  20 #  include <openssl/pem.h>
  21 #  include <openssl/bn.h>
  22 #  ifndef HASURANDOMDEV
  23 #   include <openssl/rand.h>
  24 #  endif /* ! HASURANDOMDEV */
  25 # if !TLS_NO_RSA
  26 #  include <openssl/rsa.h>
  27 static RSA *rsa_tmp = NULL;     /* temporary RSA key */

  28 # endif /* !TLS_NO_RSA */



  29 static int      tls_verify_cb __P((X509_STORE_CTX *, void *));



  30 static int x509_verify_cb __P((int, X509_STORE_CTX *));

  31 



  32 #  define CONST097 const

  33 static void     apps_ssl_info_cb __P((CONST097 SSL *, int , int));
  34 static bool     tls_ok_f __P((char *, char *, int));
  35 static bool     tls_safe_f __P((char *, long, bool));
  36 static int      tls_verify_log __P((int, X509_STORE_CTX *, char *));
  37 
  38 # if !NO_DH
  39 #  include <openssl/dh.h>
  40 #  include <openssl/dsa.h>
  41 
  42 #if OPENSSL_VERSION_NUMBER < 0x10100000L
  43 
  44 /*
  45  * This compatibility function is taken from
  46  * https://wiki.openssl.org/index.php/OpenSSL_1.1.0_Changes
  47  *     #Adding_forward-compatible_code_to_older_versions
  48  */
  49 
  50 #define DH_set0_pqg __DH_set0_pqg
  51 int __DH_set0_pqg(DH *dh, BIGNUM *p, BIGNUM *q, BIGNUM *g)
  52 {
  53     /* If the fields p and g in d are NULL, the corresponding input
  54      * parameters MUST be non-NULL.  q may remain NULL.
  55      */
  56     if ((dh->p == NULL && p == NULL)
  57         || (dh->g == NULL && g == NULL))
  58         return 0;
  59 
  60     if (p != NULL) {
  61         BN_free(dh->p);
  62         dh->p = p;
  63     }
  64     if (q != NULL) {
  65         BN_free(dh->q);
  66         dh->q = q;
  67     }
  68     if (g != NULL) {
  69         BN_free(dh->g);
  70         dh->g = g;
  71     }
  72 
  73     if (q != NULL) {
  74         dh->length = BN_num_bits(q);
  75     }
  76 
  77     return 1;
  78 }
  79 #endif
  80 
  81 static DH *get_dh512 __P((void));
  82 
  83 static unsigned char dh512_p[] =
  84 {
  85         0xDA,0x58,0x3C,0x16,0xD9,0x85,0x22,0x89,0xD0,0xE4,0xAF,0x75,
  86         0x6F,0x4C,0xCA,0x92,0xDD,0x4B,0xE5,0x33,0xB8,0x04,0xFB,0x0F,
  87         0xED,0x94,0xEF,0x9C,0x8A,0x44,0x03,0xED,0x57,0x46,0x50,0xD3,
  88         0x69,0x99,0xDB,0x29,0xD7,0x76,0x27,0x6B,0xA2,0xD3,0xD4,0x12,
  89         0xE2,0x18,0xF4,0xDD,0x1E,0x08,0x4C,0xF6,0xD8,0x00,0x3E,0x7C,
  90         0x47,0x74,0xE8,0x33
  91 };
  92 static unsigned char dh512_g[] =
  93 {
  94         0x02
  95 };
  96 
  97 static DH *
  98 get_dh512()
  99 {
 100         DH *dh = NULL;
 101         BIGNUM *p, *g;
 102 
 103         if ((dh = DH_new()) == NULL)
 104                 return NULL;
 105         p = BN_bin2bn(dh512_p, sizeof(dh512_p), NULL);
 106         g = BN_bin2bn(dh512_g, sizeof(dh512_g), NULL);
 107         if ((p == NULL) || (g == NULL)) {
 108                 BN_free(p);
 109                 BN_free(g);
 110                 DH_free(dh);
 111                 return NULL;
 112         }
 113 
 114         DH_set0_pqg(dh, p, NULL, g);
 115 
 116         return dh;
 117 }
 118 # endif /* !NO_DH */
 119 
 120 
 121 /*
 122 **  TLS_RAND_INIT -- initialize STARTTLS random generator
 123 **
 124 **      Parameters:
 125 **              randfile -- name of file with random data
 126 **              logl -- loglevel
 127 **
 128 **      Returns:
 129 **              success/failure
 130 **
 131 **      Side Effects:
 132 **              initializes PRNG for tls library.
 133 */
 134 
 135 # define MIN_RAND_BYTES 128     /* 1024 bits */


 302         done = ok ? RI_SUCCESS : RI_FAIL;
 303         return ok;
 304 # else /* ! HASURANDOMDEV */
 305         return true;
 306 # endif /* ! HASURANDOMDEV */
 307 }
 308 /*
 309 **  INIT_TLS_LIBRARY -- Calls functions which setup TLS library for global use.
 310 **
 311 **      Parameters:
 312 **              none.
 313 **
 314 **      Returns:
 315 **              succeeded?
 316 */
 317 
 318 bool
 319 init_tls_library()
 320 {
 321         /* basic TLS initialization, ignore result for now */
 322 #if OPENSSL_VERSION_NUMBER < 0x10100000L
 323         /* No longer available (nor necessary) in OpenSSL 1.1 */
 324         SSL_library_init();
 325         SSL_load_error_strings();
 326 #endif
 327 # if 0
 328         /* this is currently a macro for SSL_library_init */
 329         SSLeay_add_ssl_algorithms();
 330 # endif /* 0 */
 331 
 332         return tls_rand_init(RandFile, 7);
 333 }
 334 /*
 335 **  TLS_SET_VERIFY -- request client certificate?
 336 **
 337 **      Parameters:
 338 **              ctx -- TLS context
 339 **              ssl -- TLS structure
 340 **              vrfy -- require certificate?
 341 **
 342 **      Returns:
 343 **              none.
 344 **
 345 **      Side Effects:
 346 **              Sets verification state for TLS


 535 **              srv -- server side?
 536 **              certfile -- filename of certificate
 537 **              keyfile -- filename of private key
 538 **              cacertpath -- path to CAs
 539 **              cacertfile -- file with CA(s)
 540 **              dhparam -- parameters for DH
 541 **
 542 **      Returns:
 543 **              succeeded?
 544 */
 545 
 546 /*
 547 **  The session_id_context identifies the service that created a session.
 548 **  This information is used to distinguish between multiple TLS-based
 549 **  servers running on the same server. We use the name of the mail system.
 550 **  Note: the session cache is not persistent.
 551 */
 552 
 553 static char server_session_id_context[] = "sendmail8";
 554 







 555 bool
 556 inittls(ctx, req, options, srv, certfile, keyfile, cacertpath, cacertfile, dhparam)
 557         SSL_CTX **ctx;
 558         unsigned long req;
 559         long options;
 560         bool srv;
 561         char *certfile, *keyfile, *cacertpath, *cacertfile, *dhparam;
 562 {
 563 # if !NO_DH
 564         static DH *dh = NULL;
 565 # endif /* !NO_DH */
 566         int r;
 567         bool ok;
 568         long sff, status;
 569         char *who;
 570 # if _FFR_TLS_1
 571         char *cf2, *kf2;
 572 # endif /* _FFR_TLS_1 */
 573 #  if SM_CONF_SHM
 574         extern int ShmId;
 575 #  endif /* SM_CONF_SHM */

 576         BIO *crl_file;
 577         X509_CRL *crl;
 578         X509_STORE *store;





 579 
 580         status = TLS_S_NONE;
 581         who = srv ? "server" : "client";
 582         if (ctx == NULL)
 583         {
 584                 syserr("STARTTLS=%s, inittls: ctx == NULL", who);
 585                 /* NOTREACHED */
 586                 SM_ASSERT(ctx != NULL);
 587         }
 588 
 589         /* already initialized? (we could re-init...) */
 590         if (*ctx != NULL)
 591                 return true;
 592         ok = true;
 593 
 594 # if _FFR_TLS_1
 595         /*
 596         **  look for a second filename: it must be separated by a ','
 597         **  no blanks allowed (they won't be skipped).
 598         **  we change a global variable here! this change will be undone


 607         if (certfile != NULL && (cf2 = strchr(certfile, ',')) != NULL)
 608         {
 609                 *cf2++ = '\0';
 610                 if (keyfile != NULL && (kf2 = strchr(keyfile, ',')) != NULL)
 611                         *kf2++ = '\0';
 612         }
 613 # endif /* _FFR_TLS_1 */
 614 
 615         /*
 616         **  Check whether files/paths are defined
 617         */
 618 
 619         TLS_OK_F(certfile, "CertFile", bitset(TLS_I_CERT_EX, req),
 620                  TLS_S_CERT_EX, srv ? TLS_T_SRV : TLS_T_CLT);
 621         TLS_OK_F(keyfile, "KeyFile", bitset(TLS_I_KEY_EX, req),
 622                  TLS_S_KEY_EX, srv ? TLS_T_SRV : TLS_T_CLT);
 623         TLS_OK_F(cacertpath, "CACertPath", bitset(TLS_I_CERTP_EX, req),
 624                  TLS_S_CERTP_EX, TLS_T_OTHER);
 625         TLS_OK_F(cacertfile, "CACertFile", bitset(TLS_I_CERTF_EX, req),
 626                  TLS_S_CERTF_EX, TLS_T_OTHER);


 627         TLS_OK_F(CRLFile, "CRLFile", bitset(TLS_I_CRLF_EX, req),
 628                  TLS_S_CRLF_EX, TLS_T_OTHER);

 629 
 630 # if _FFR_TLS_1
 631         /*
 632         **  if the second file is specified it must exist
 633         **  XXX: it is possible here to define only one of those files
 634         */
 635 
 636         if (cf2 != NULL)
 637         {
 638                 TLS_OK_F(cf2, "CertFile", bitset(TLS_I_CERT_EX, req),
 639                          TLS_S_CERT2_EX, srv ? TLS_T_SRV : TLS_T_CLT);
 640         }
 641         if (kf2 != NULL)
 642         {
 643                 TLS_OK_F(kf2, "KeyFile", bitset(TLS_I_KEY_EX, req),
 644                          TLS_S_KEY2_EX, srv ? TLS_T_SRV : TLS_T_CLT);
 645         }
 646 # endif /* _FFR_TLS_1 */
 647 
 648         /*


 690 
 691         /* certfile etc. must be "safe". */
 692         sff = SFF_REGONLY | SFF_SAFEDIRPATH | SFF_NOWLINK
 693              | SFF_NOGWFILES | SFF_NOWWFILES
 694              | SFF_MUSTOWN | SFF_ROOTOK | SFF_OPENASROOT;
 695         if (DontLockReadFiles)
 696                 sff |= SFF_NOLOCK;
 697 
 698         TLS_SAFE_F(certfile, sff | TLS_UNR(TLS_I_CERT_UNR, req),
 699                    bitset(TLS_I_CERT_EX, req),
 700                    bitset(TLS_S_CERT_EX, status), TLS_S_CERT_OK, srv);
 701         TLS_SAFE_F(keyfile, sff | TLS_KEYSFF(req),
 702                    bitset(TLS_I_KEY_EX, req),
 703                    bitset(TLS_S_KEY_EX, status), TLS_S_KEY_OK, srv);
 704         TLS_SAFE_F(cacertfile, sff | TLS_UNR(TLS_I_CERTF_UNR, req),
 705                    bitset(TLS_I_CERTF_EX, req),
 706                    bitset(TLS_S_CERTF_EX, status), TLS_S_CERTF_OK, srv);
 707         TLS_SAFE_F(dhparam, sff | TLS_UNR(TLS_I_DHPAR_UNR, req),
 708                    bitset(TLS_I_DHPAR_EX, req),
 709                    bitset(TLS_S_DHPAR_EX, status), TLS_S_DHPAR_OK, srv);

 710         TLS_SAFE_F(CRLFile, sff | TLS_UNR(TLS_I_CRLF_UNR, req),
 711                    bitset(TLS_I_CRLF_EX, req),
 712                    bitset(TLS_S_CRLF_EX, status), TLS_S_CRLF_OK, srv);

 713         if (!ok)
 714                 return ok;
 715 # if _FFR_TLS_1
 716         if (cf2 != NULL)
 717         {
 718                 TLS_SAFE_F(cf2, sff | TLS_UNR(TLS_I_CERT_UNR, req),
 719                            bitset(TLS_I_CERT_EX, req),
 720                            bitset(TLS_S_CERT2_EX, status), TLS_S_CERT2_OK, srv);
 721         }
 722         if (kf2 != NULL)
 723         {
 724                 TLS_SAFE_F(kf2, sff | TLS_KEYSFF(req),
 725                            bitset(TLS_I_KEY_EX, req),
 726                            bitset(TLS_S_KEY2_EX, status), TLS_S_KEY2_OK, srv);
 727         }
 728 # endif /* _FFR_TLS_1 */
 729 
 730         /* create a method and a new context */
 731         if ((*ctx = SSL_CTX_new(srv ? SSLv23_server_method() :
 732                                       SSLv23_client_method())) == NULL)
 733         {
 734                 if (LogLevel > 7)
 735                         sm_syslog(LOG_WARNING, NOQID,
 736                                   "STARTTLS=%s, error: SSL_CTX_new(SSLv23_%s_method()) failed",
 737                                   who, who);
 738                 if (LogLevel > 9)
 739                         tlslogerr(who);
 740                 return false;
 741         }
 742 

 743         if (CRLFile != NULL)
 744         {
 745                 /* get a pointer to the current certificate validation store */
 746                 store = SSL_CTX_get_cert_store(*ctx);   /* does not fail */
 747                 crl_file = BIO_new(BIO_s_file());
 748                 if (crl_file != NULL)
 749                 {
 750                         if (BIO_read_filename(crl_file, CRLFile) >= 0)
 751                         {
 752                                 crl = PEM_read_bio_X509_CRL(crl_file, NULL,
 753                                                         NULL, NULL);
 754                                 BIO_free(crl_file);
 755                                 X509_STORE_add_crl(store, crl);
 756                                 X509_CRL_free(crl);
 757                                 X509_STORE_set_flags(store,
 758                                         X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
 759                                 X509_STORE_set_verify_cb_func(store,
 760                                                 x509_verify_cb);
 761                         }
 762                         else
 763                         {
 764                                 if (LogLevel > 9)
 765                                 {
 766                                         sm_syslog(LOG_WARNING, NOQID,
 767                                                   "STARTTLS=%s, error: PEM_read_bio_X509_CRL(%s)=failed",


 784         if (CRLPath != NULL && store != NULL)
 785         {
 786                 X509_LOOKUP *lookup;
 787 
 788                 lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
 789                 if (lookup == NULL)
 790                 {
 791                         if (LogLevel > 9)
 792                         {
 793                                 sm_syslog(LOG_WARNING, NOQID,
 794                                           "STARTTLS=%s, error: X509_STORE_add_lookup(hash)=failed",
 795                                           who, CRLFile);
 796                         }
 797                         return false;
 798                 }
 799                 X509_LOOKUP_add_dir(lookup, CRLPath, X509_FILETYPE_PEM);
 800                 X509_STORE_set_flags(store,
 801                         X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
 802         }
 803 #  endif /* _FFR_CRLPATH */

 804 
 805 # if TLS_NO_RSA
 806         /* turn off backward compatibility, required for no-rsa */
 807         SSL_CTX_set_options(*ctx, SSL_OP_NO_SSLv2);
 808 # endif /* TLS_NO_RSA */
 809 
 810 
 811 # if !TLS_NO_RSA
 812         /*
 813         **  Create a temporary RSA key
 814         **  XXX  Maybe we shouldn't create this always (even though it
 815         **  is only at startup).
 816         **  It is a time-consuming operation and it is not always necessary.
 817         **  maybe we should do it only on demand...
 818         */
 819 
 820         if (bitset(TLS_I_RSA_TMP, req)
 821 #   if SM_CONF_SHM
 822             && ShmId != SM_SHM_NO_ID


 823 #   else /* SM_CONF_SHM */
 824             && 0        /* no shared memory: no need to generate key now */
 825 #   endif /* SM_CONF_SHM */
 826             )
 827         {
 828                 BIGNUM *e = BN_new();
 829                 BN_set_word(e, RSA_F4);
 830 
 831                 if ((rsa_tmp = RSA_new()) == NULL || RSA_generate_key_ex(
 832                     rsa_tmp, RSA_KEYLENGTH, e, NULL) == 0)
 833                 {
 834                         BN_free(e);
 835                         if (rsa_tmp != NULL)
 836                                 RSA_free(rsa_tmp);
 837                         rsa_tmp = NULL;
 838                         if (LogLevel > 7)
 839                         {
 840                                 sm_syslog(LOG_WARNING, NOQID,
 841                                           "STARTTLS=%s, error: RSA_generate_key failed",
 842                                           who);
 843                                 if (LogLevel > 9)
 844                                         tlslogerr(who);
 845                         }
 846                         return false;
 847                 }
 848                 BN_free(e);
 849         }
 850 # endif /* !TLS_NO_RSA */
 851 
 852         /*
 853         **  load private key
 854         **  XXX change this for DSA-only version
 855         */
 856 
 857         if (bitset(TLS_S_KEY_OK, status) &&
 858             SSL_CTX_use_PrivateKey_file(*ctx, keyfile,
 859                                          SSL_FILETYPE_PEM) <= 0)
 860         {
 861                 if (LogLevel > 7)
 862                 {
 863                         sm_syslog(LOG_WARNING, NOQID,
 864                                   "STARTTLS=%s, error: SSL_CTX_use_PrivateKey_file(%s) failed",
 865                                   who, keyfile);
 866                         if (LogLevel > 9)
 867                                 tlslogerr(who);
 868                 }
 869                 if (bitset(TLS_I_USE_KEY, req))


 936         }
 937 
 938         /* also check the private key */
 939         if (bitset(TLS_S_KEY2_OK, status) &&
 940             (r = SSL_CTX_check_private_key(*ctx)) <= 0)
 941         {
 942                 /* Private key does not match the certificate public key */
 943                 if (LogLevel > 5)
 944                 {
 945                         sm_syslog(LOG_WARNING, NOQID,
 946                                   "STARTTLS=%s, error: SSL_CTX_check_private_key 2 failed: %d",
 947                                   who, r);
 948                         if (LogLevel > 9)
 949                                 tlslogerr(who);
 950                 }
 951         }
 952 # endif /* _FFR_TLS_1 */
 953 
 954         /* SSL_CTX_set_quiet_shutdown(*ctx, 1); violation of standard? */
 955 




















 956         SSL_CTX_set_options(*ctx, options);
 957 
 958 # if !NO_DH
 959         /* Diffie-Hellman initialization */
 960         if (bitset(TLS_I_TRY_DH, req))
 961         {
 962                 if (bitset(TLS_S_DHPAR_OK, status))
 963                 {
 964                         BIO *bio;
 965 
 966                         if ((bio = BIO_new_file(dhparam, "r")) != NULL)
 967                         {
 968                                 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
 969                                 BIO_free(bio);
 970                                 if (dh == NULL && LogLevel > 7)
 971                                 {
 972                                         unsigned long err;
 973 
 974                                         err = ERR_get_error();
 975                                         sm_syslog(LOG_WARNING, NOQID,


 977                                                   who, dhparam,
 978                                                   ERR_error_string(err, NULL));
 979                                         if (LogLevel > 9)
 980                                                 tlslogerr(who);
 981                                 }
 982                         }
 983                         else
 984                         {
 985                                 if (LogLevel > 5)
 986                                 {
 987                                         sm_syslog(LOG_WARNING, NOQID,
 988                                                   "STARTTLS=%s, error: BIO_new_file(%s) failed",
 989                                                   who, dhparam);
 990                                         if (LogLevel > 9)
 991                                                 tlslogerr(who);
 992                                 }
 993                         }
 994                 }
 995                 if (dh == NULL && bitset(TLS_I_DH1024, req))
 996                 {
 997                         DSA *dsa = NULL;
 998 
 999                         /* this takes a while! (7-130s on a 450MHz AMD K6-2) */
1000                         if ((dsa = DSA_new()) == NULL ||
1001                             DSA_generate_parameters_ex(dsa, 1024,
1002                             NULL, 0, NULL, 0, NULL) == 0)
1003                                 dh = NULL;
1004                         else
1005                                 dh = DSA_dup_DH(dsa);
1006                         if (dsa != NULL)
1007                                 DSA_free(dsa);
1008                 }
1009                 else if (dh == NULL && bitset(TLS_I_DH512, req))

1010                         dh = get_dh512();
1011 
1012                 if (dh == NULL)
1013                 {
1014                         if (LogLevel > 9)
1015                         {
1016                                 unsigned long err;
1017 
1018                                 err = ERR_get_error();
1019                                 sm_syslog(LOG_WARNING, NOQID,
1020                                           "STARTTLS=%s, error: cannot read or set DH parameters(%s): %s",
1021                                           who, dhparam,
1022                                           ERR_error_string(err, NULL));
1023                         }
1024                         if (bitset(TLS_I_REQ_DH, req))
1025                                 return false;
1026                 }
1027                 else
1028                 {
1029                         SSL_CTX_set_tmp_dh(*ctx, dh);


1046                 SSL_CTX_sess_set_cache_size(*ctx, 1);
1047                 SSL_CTX_set_timeout(*ctx, 1);
1048                 SSL_CTX_set_session_id_context(*ctx,
1049                         (void *) &server_session_id_context,
1050                         sizeof(server_session_id_context));
1051                 (void) SSL_CTX_set_session_cache_mode(*ctx,
1052                                 SSL_SESS_CACHE_SERVER);
1053         }
1054         else
1055         {
1056                 (void) SSL_CTX_set_session_cache_mode(*ctx,
1057                                 SSL_SESS_CACHE_OFF);
1058         }
1059 
1060         /* load certificate locations and default CA paths */
1061         if (bitset(TLS_S_CERTP_EX, status) && bitset(TLS_S_CERTF_EX, status))
1062         {
1063                 if ((r = SSL_CTX_load_verify_locations(*ctx, cacertfile,
1064                                                        cacertpath)) == 1)
1065                 {





1066                         /*
1067                         **  We have to install our own verify callback:
1068                         **  SSL_VERIFY_PEER requests a client cert but even
1069                         **  though *FAIL_IF* isn't set, the connection
1070                         **  will be aborted if the client presents a cert
1071                         **  that is not "liked" (can't be verified?) by
1072                         **  the TLS library :-(
1073                         */
1074 
1075                         /*
1076                         **  XXX currently we could call tls_set_verify()
1077                         **  but we hope that that function will later on
1078                         **  only set the mode per connection.
1079                         */
1080                         SSL_CTX_set_verify(*ctx,
1081                                 bitset(TLS_I_NO_VRFY, req) ? SSL_VERIFY_NONE
1082                                                            : SSL_VERIFY_PEER,
1083                                 NULL);
1084 
1085                         /* install verify callback */


1181         MACROS_T *mac;
1182         bool certreq;
1183 {
1184         const SSL_CIPHER *c;
1185         int b, r;
1186         long verifyok;
1187         char *s, *who;
1188         char bitstr[16];
1189         X509 *cert;
1190 
1191         c = SSL_get_current_cipher(ssl);
1192 
1193         /* cast is just workaround for compiler warning */
1194         macdefine(mac, A_TEMP, macid("{cipher}"),
1195                   (char *) SSL_CIPHER_get_name(c));
1196         b = SSL_CIPHER_get_bits(c, &r);
1197         (void) sm_snprintf(bitstr, sizeof(bitstr), "%d", b);
1198         macdefine(mac, A_TEMP, macid("{cipher_bits}"), bitstr);
1199         (void) sm_snprintf(bitstr, sizeof(bitstr), "%d", r);
1200         macdefine(mac, A_TEMP, macid("{alg_bits}"), bitstr);
1201         s = (char *)SSL_CIPHER_get_version(c);
1202         if (s == NULL)
1203                 s = "UNKNOWN";
1204         macdefine(mac, A_TEMP, macid("{tls_version}"), s);
1205 
1206         who = srv ? "server" : "client";
1207         cert = SSL_get_peer_certificate(ssl);
1208         verifyok = SSL_get_verify_result(ssl);
1209         if (LogLevel > 14)
1210                 sm_syslog(LOG_INFO, NOQID,
1211                           "STARTTLS=%s, get_verify: %ld get_peer: 0x%lx",
1212                           who, verifyok, (unsigned long) cert);
1213         if (cert != NULL)
1214         {
1215                 unsigned int n;
1216                 X509_NAME *subj, *issuer;
1217                 unsigned char md[EVP_MAX_MD_SIZE];
1218                 char buf[MAXNAME];
1219 
1220                 subj = X509_get_subject_name(cert);
1221                 issuer = X509_get_issuer_name(cert);


1375         SSL *ssl;
1376         char *side;
1377 {
1378         int ret = EX_OK;
1379 
1380         if (ssl != NULL)
1381         {
1382                 int r;
1383 
1384                 if ((r = SSL_shutdown(ssl)) < 0)
1385                 {
1386                         if (LogLevel > 11)
1387                         {
1388                                 sm_syslog(LOG_WARNING, NOQID,
1389                                           "STARTTLS=%s, SSL_shutdown failed: %d",
1390                                           side, r);
1391                                 tlslogerr(side);
1392                         }
1393                         ret = EX_SOFTWARE;
1394                 }

1395 
1396                 /*
1397                 **  Bug in OpenSSL (at least up to 0.9.6b):
1398                 **  From: Lutz.Jaenicke@aet.TU-Cottbus.DE
1399                 **  Message-ID: <20010723152244.A13122@serv01.aet.tu-cottbus.de>
1400                 **  To: openssl-users@openssl.org
1401                 **  Subject: Re: SSL_shutdown() woes (fwd)
1402                 **
1403                 **  The side sending the shutdown alert first will
1404                 **  not care about the answer of the peer but will
1405                 **  immediately return with a return value of "0"
1406                 **  (ssl/s3_lib.c:ssl3_shutdown()). SSL_get_error will evaluate
1407                 **  the value of "0" and as the shutdown alert of the peer was
1408                 **  not received (actually, the program did not even wait for
1409                 **  the answer), an SSL_ERROR_SYSCALL is flagged, because this
1410                 **  is the default rule in case everything else does not apply.
1411                 **
1412                 **  For your server the problem is different, because it
1413                 **  receives the shutdown first (setting SSL_RECEIVED_SHUTDOWN),
1414                 **  then sends its response (SSL_SENT_SHUTDOWN), so for the


1423                 **  probably with another API, as the change would not be
1424                 **  compatible to the way it is now.  Things do not become
1425                 **  easier as other programs do not follow the shutdown
1426                 **  guidelines anyway, so that a lot error conditions and
1427                 **  compitibility issues would have to be caught.
1428                 **
1429                 **  For now the recommondation is to ignore the error message.
1430                 */
1431 
1432                 else if (r == 0)
1433                 {
1434                         if (LogLevel > 15)
1435                         {
1436                                 sm_syslog(LOG_WARNING, NOQID,
1437                                           "STARTTLS=%s, SSL_shutdown not done",
1438                                           side);
1439                                 tlslogerr(side);
1440                         }
1441                         ret = EX_SOFTWARE;
1442                 }

1443                 SSL_free(ssl);
1444                 ssl = NULL;
1445         }
1446         return ret;
1447 }
1448 

1449 /*
































































1450 **  APPS_SSL_INFO_CB -- info callback for TLS connections
1451 **
1452 **      Parameters:
1453 **              s -- TLS connection structure
1454 **              where -- state in handshake
1455 **              ret -- return code of last operation
1456 **
1457 **      Returns:
1458 **              none.
1459 */
1460 
1461 static void
1462 apps_ssl_info_cb(s, where, ret)
1463         CONST097 SSL *s;
1464         int where;
1465         int ret;
1466 {
1467         int w;
1468         char *str;
1469         BIO *bio_err = NULL;


1557 
1558         X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf));
1559         sm_syslog(LOG_INFO, NOQID,
1560                   "STARTTLS: %s cert verify: depth=%d %s, state=%d, reason=%s",
1561                   name, depth, buf, ok, X509_verify_cert_error_string(reason));
1562         return 1;
1563 }
1564 
1565 /*
1566 **  TLS_VERIFY_CB -- verify callback for TLS certificates
1567 **
1568 **      Parameters:
1569 **              ctx -- x509 context
1570 **
1571 **      Returns:
1572 **              accept connection?
1573 **              currently: always yes.
1574 */
1575 
1576 static int




1577 tls_verify_cb(ctx, unused)
1578         X509_STORE_CTX *ctx;
1579         void *unused;

1580 {
1581         int ok;
1582 
1583         /*
1584         **  man SSL_CTX_set_cert_verify_callback():
1585         **  callback should return 1 to indicate verification success
1586         **  and 0 to indicate verification failure.
1587         */
1588 
1589         ok = X509_verify_cert(ctx);
1590         if (ok <= 0)
1591         {
1592                 if (LogLevel > 13)
1593                         return tls_verify_log(ok, ctx, "TLS");
1594         }
1595         return 1;
1596 }
1597 /*
1598 **  TLSLOGERR -- log the errors from the TLS error stack
1599 **
1600 **      Parameters:
1601 **              who -- server/client (for logging).
1602 **
1603 **      Returns:
1604 **              none.
1605 */
1606 
1607 void
1608 tlslogerr(who)
1609         const char *who;
1610 {
1611         unsigned long l;
1612         int line, flags;
1613         unsigned long es;
1614         char *file, *data;
1615         char buf[256];
1616 #  define CP (const char **)
1617 
1618 #if OPENSSL_VERSION_NUMBER >= 0x10100000L
1619         es = 0;
1620 #else
1621         es = CRYPTO_thread_id();
1622 #endif
1623         while ((l = ERR_get_error_line_data(CP &file, &line, CP &data, &flags))
1624                 != 0)
1625         {
1626                 sm_syslog(LOG_WARNING, NOQID,
1627                           "STARTTLS=%s: %lu:%s:%s:%d:%s", who, es,
1628                           ERR_error_string(l, buf),
1629                           file, line,
1630                           bitset(ERR_TXT_STRING, flags) ? data : "");
1631         }
1632 }
1633 

1634 /*
1635 **  X509_VERIFY_CB -- verify callback
1636 **
1637 **      Parameters:
1638 **              ctx -- x509 context
1639 **
1640 **      Returns:
1641 **              accept connection?
1642 **              currently: always yes.
1643 */
1644 
1645 static int
1646 x509_verify_cb(ok, ctx)
1647         int ok;
1648         X509_STORE_CTX *ctx;
1649 {
1650         if (ok == 0)
1651         {
1652                 if (LogLevel > 13)
1653                         tls_verify_log(ok, ctx, "x509");
1654                 if (X509_STORE_CTX_get_error(ctx)
1655                     == X509_V_ERR_UNABLE_TO_GET_CRL)
1656                 {
1657                         X509_STORE_CTX_set_error(ctx, 0);
1658                         return 1;       /* override it */
1659                 }
1660         }
1661         return ok;
1662 }

1663 #endif /* STARTTLS */