Back to index

webcit  8.12-dfsg
crypto.c
Go to the documentation of this file.
00001 /*
00002  * Copyright (c) 1996-2012 by the citadel.org team
00003  *
00004  * This program is open source software.  You can redistribute it and/or
00005  * modify it under the terms of the GNU General Public License, version 3.
00006  * 
00007  * This program is distributed in the hope that it will be useful,
00008  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00009  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00010  * GNU General Public License for more details.
00011  */
00012 
00013 #include "sysdep.h"
00014 #ifdef HAVE_OPENSSL
00015 
00016 #include "webcit.h"
00017 #include "webserver.h"
00018 
00019 /* where to find the keys */
00020 #define       CTDL_CRYPTO_DIR             ctdl_key_dir
00021 #define CTDL_KEY_PATH              file_crpt_file_key
00022 #define CTDL_CSR_PATH              file_crpt_file_csr
00023 #define CTDL_CER_PATH              file_crpt_file_cer
00024 #define SIGN_DAYS           3650                 /* how long our certificate should live */
00025 
00026 SSL_CTX *ssl_ctx;           /* SSL context */
00027 pthread_mutex_t **SSLCritters;     /* Things needing locking */
00028 char *ssl_cipher_list = DEFAULT_SSL_CIPHER_LIST;
00029 
00030 pthread_key_t ThreadSSL;    /* Per-thread SSL context */
00031 
00032 static unsigned long id_callback(void)
00033 {
00034        return (unsigned long) pthread_self();
00035 }
00036 
00037 void shutdown_ssl(void)
00038 {
00039        ERR_free_strings();
00040 
00041        /* Openssl requires these while shutdown. 
00042         * Didn't find a way to get out of this clean.
00043         * int i, n = CRYPTO_num_locks();
00044         * for (i = 0; i < n; i++)
00045         *     free(SSLCritters[i]);
00046         * free(SSLCritters);
00047         */
00048 }
00049 
00050 /*
00051  * initialize ssl engine, load certs and initialize openssl internals
00052  */
00053 void init_ssl(void)
00054 {
00055        const SSL_METHOD *ssl_method;
00056        RSA *rsa=NULL;
00057        X509_REQ *req = NULL;
00058        X509 *cer = NULL;
00059        EVP_PKEY *pk = NULL;
00060        EVP_PKEY *req_pkey = NULL;
00061        X509_NAME *name = NULL;
00062        FILE *fp;
00063        char buf[SIZ];
00064        int rv = 0;
00065 
00066        if (!access("/var/run/egd-pool", F_OK)) {
00067               RAND_egd("/var/run/egd-pool");
00068        }
00069 
00070        if (!RAND_status()) {
00071               syslog(3, "PRNG not adequately seeded, won't do SSL/TLS\n");
00072               return;
00073        }
00074        SSLCritters = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
00075        if (!SSLCritters) {
00076               syslog(1, "citserver: can't allocate memory!!\n");
00077               /* Nothing's been initialized, just die */
00078               ShutDownWebcit();
00079               exit(WC_EXIT_SSL);
00080        } else {
00081               int a;
00082 
00083               for (a = 0; a < CRYPTO_num_locks(); a++) {
00084                      SSLCritters[a] = malloc(sizeof(pthread_mutex_t));
00085                      if (!SSLCritters[a]) {
00086                             syslog(1,
00087                                    "citserver: can't allocate memory!!\n");
00089                             ShutDownWebcit();
00090                             exit(WC_EXIT_SSL);
00091                      }
00092                      pthread_mutex_init(SSLCritters[a], NULL);
00093               }
00094        }
00095 
00096        /*
00097         * Initialize SSL transport layer
00098         */
00099        SSL_library_init();
00100        SSL_load_error_strings();
00101        ssl_method = SSLv23_server_method();
00102        if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
00103               syslog(3, "SSL_CTX_new failed: %s\n", ERR_reason_error_string(ERR_get_error()));
00104               return;
00105        }
00106 
00107        syslog(9, "Requesting cipher list: %s\n", ssl_cipher_list);
00108        if (!(SSL_CTX_set_cipher_list(ssl_ctx, ssl_cipher_list))) {
00109               syslog(3, "SSL_CTX_set_cipher_list failed: %s\n", ERR_reason_error_string(ERR_get_error()));
00110               return;
00111        }
00112 
00113        CRYPTO_set_locking_callback(ssl_lock);
00114        CRYPTO_set_id_callback(id_callback);
00115 
00116        /*
00117         * Get our certificates in order. (FIXME: dirify. this is a setup job.)
00118         * First, create the key/cert directory if it's not there already...
00119         */
00120        mkdir(CTDL_CRYPTO_DIR, 0700);
00121 
00122        /*
00123         * Before attempting to generate keys/certificates, first try
00124         * link to them from the Citadel server if it's on the same host.
00125         * We ignore any error return because it either meant that there
00126         * was nothing in Citadel to link from (in which case we just
00127         * generate new files) or the target files already exist (which
00128         * is not fatal either).
00129         */
00130        if (!strcasecmp(ctdlhost, "uds")) {
00131               sprintf(buf, "%s/keys/citadel.key", ctdlport);
00132               rv = symlink(buf, CTDL_KEY_PATH);
00133               if (!rv) syslog(1, "%s\n", strerror(errno));
00134               sprintf(buf, "%s/keys/citadel.csr", ctdlport);
00135               rv = symlink(buf, CTDL_CSR_PATH);
00136               if (!rv) syslog(1, "%s\n", strerror(errno));
00137               sprintf(buf, "%s/keys/citadel.cer", ctdlport);
00138               rv = symlink(buf, CTDL_CER_PATH);
00139               if (!rv) syslog(1, "%s\n", strerror(errno));
00140        }
00141 
00142        /*
00143         * If we still don't have a private key, generate one.
00144         */
00145        if (access(CTDL_KEY_PATH, R_OK) != 0) {
00146               syslog(5, "Generating RSA key pair.\n");
00147               rsa = RSA_generate_key(1024,       /* modulus size */
00148                                    65537, /* exponent */
00149                                    NULL,  /* no callback */
00150                                    NULL   /* no callback */
00151               );
00152               if (rsa == NULL) {
00153                      syslog(3, "Key generation failed: %s\n", ERR_reason_error_string(ERR_get_error()));
00154               }
00155               if (rsa != NULL) {
00156                      fp = fopen(CTDL_KEY_PATH, "w");
00157                      if (fp != NULL) {
00158                             chmod(CTDL_KEY_PATH, 0600);
00159                             if (PEM_write_RSAPrivateKey(fp,    /* the file */
00160                                                  rsa,   /* the key */
00161                                                  NULL,  /* no enc */
00162                                                  NULL,  /* no passphr */
00163                                                  0,     /* no passphr */
00164                                                  NULL,  /* no callbk */
00165                                                  NULL   /* no callbk */
00166                             ) != 1) {
00167                                    syslog(3, "Cannot write key: %s\n",
00168                                           ERR_reason_error_string(ERR_get_error()));
00169                                    unlink(CTDL_KEY_PATH);
00170                             }
00171                             fclose(fp);
00172                      }
00173                      else {
00174                             syslog(3, "Cannot write key: %s\n", CTDL_KEY_PATH);
00175                             ShutDownWebcit();
00176                             exit(0);
00177                      }
00178                      RSA_free(rsa);
00179               }
00180        }
00181 
00182        /*
00183         * If there is no certificate file on disk, we will be generating a self-signed certificate
00184         * in the next step.  Therefore, if we have neither a CSR nor a certificate, generate
00185         * the CSR in this step so that the next step may commence.
00186         */
00187        if ( (access(CTDL_CER_PATH, R_OK) != 0) && (access(CTDL_CSR_PATH, R_OK) != 0) ) {
00188               syslog(5, "Generating a certificate signing request.\n");
00189 
00190               /*
00191                * Read our key from the file.  No, we don't just keep this
00192                * in memory from the above key-generation function, because
00193                * there is the possibility that the key was already on disk
00194                * and we didn't just generate it now.
00195                */
00196               fp = fopen(CTDL_KEY_PATH, "r");
00197               if (fp) {
00198                      rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
00199                      fclose(fp);
00200               }
00201 
00202               if (rsa) {
00203 
00205                      if (pk=EVP_PKEY_new(), pk != NULL) {
00206                             EVP_PKEY_assign_RSA(pk, rsa);
00207                             if (req = X509_REQ_new(), req != NULL) {
00208                                    const char *env;
00209                                    /* Set the public key */
00210                                    X509_REQ_set_pubkey(req, pk);
00211                                    X509_REQ_set_version(req, 0L);
00212 
00213                                    name = X509_REQ_get_subject_name(req);
00214 
00215                                    /* Tell it who we are */
00216 
00217                                    /*
00218                                     * We used to add these fields to the subject, but
00219                                     * now we don't.  Someone doing this for real isn't
00220                                     * going to use the webcit-generated CSR anyway.
00221                                     *
00222                                    X509_NAME_add_entry_by_txt(name, "C",
00223                                           MBSTRING_ASC, "US", -1, -1, 0);
00224                                    *
00225                                    X509_NAME_add_entry_by_txt(name, "ST",
00226                                           MBSTRING_ASC, "New York", -1, -1, 0);
00227                                    *
00228                                    X509_NAME_add_entry_by_txt(name, "L",
00229                                           MBSTRING_ASC, "Mount Kisco", -1, -1, 0);
00230                                    */
00231 
00232                                    env = getenv("O");
00233                                    if (env == NULL)
00234                                           env = "Organization name",
00235 
00236                                    X509_NAME_add_entry_by_txt(
00237                                           name, "O",
00238                                           MBSTRING_ASC, 
00239                                           (unsigned char*)env, 
00240                                           -1, -1, 0
00241                                    );
00242 
00243                                    env = getenv("OU");
00244                                    if (env == NULL)
00245                                           env = "Citadel server";
00246 
00247                                    X509_NAME_add_entry_by_txt(
00248                                           name, "OU",
00249                                           MBSTRING_ASC, 
00250                                           (unsigned char*)env, 
00251                                           -1, -1, 0
00252                                    );
00253 
00254                                    env = getenv("CN");
00255                                    if (env == NULL)
00256                                           env = "*";
00257 
00258                                    X509_NAME_add_entry_by_txt(
00259                                           name, "CN",
00260                                           MBSTRING_ASC, 
00261                                           (unsigned char*)env,
00262                                           -1, -1, 0
00263                                    );
00264                             
00265                                    X509_REQ_set_subject_name(req, name);
00266 
00267                                    /* Sign the CSR */
00268                                    if (!X509_REQ_sign(req, pk, EVP_md5())) {
00269                                           syslog(3, "X509_REQ_sign(): error\n");
00270                                    }
00271                                    else {
00272                                           /* Write it to disk. */     
00273                                           fp = fopen(CTDL_CSR_PATH, "w");
00274                                           if (fp != NULL) {
00275                                                  chmod(CTDL_CSR_PATH, 0600);
00276                                                  PEM_write_X509_REQ(fp, req);
00277                                                  fclose(fp);
00278                                           }
00279                                           else {
00280                                                  syslog(3, "Cannot write key: %s\n", CTDL_CSR_PATH);
00281                                                  ShutDownWebcit();
00282                                                  exit(0);
00283                                           }
00284                                    }
00285 
00286                                    X509_REQ_free(req);
00287                             }
00288                      }
00289 
00290                      RSA_free(rsa);
00291               }
00292 
00293               else {
00294                      syslog(3, "Unable to read private key.\n");
00295               }
00296        }
00297 
00298 
00299 
00300        /*
00301         * Generate a self-signed certificate if we don't have one.
00302         */
00303        if (access(CTDL_CER_PATH, R_OK) != 0) {
00304               syslog(5, "Generating a self-signed certificate.\n");
00305 
00306               /* Same deal as before: always read the key from disk because
00307                * it may or may not have just been generated.
00308                */
00309               fp = fopen(CTDL_KEY_PATH, "r");
00310               if (fp) {
00311                      rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
00312                      fclose(fp);
00313               }
00314 
00315               /* This also holds true for the CSR. */
00316               req = NULL;
00317               cer = NULL;
00318               pk = NULL;
00319               if (rsa) {
00320                      if (pk=EVP_PKEY_new(), pk != NULL) {
00321                             EVP_PKEY_assign_RSA(pk, rsa);
00322                      }
00323 
00324                      fp = fopen(CTDL_CSR_PATH, "r");
00325                      if (fp) {
00326                             req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
00327                             fclose(fp);
00328                      }
00329 
00330                      if (req) {
00331                             if (cer = X509_new(), cer != NULL) {
00332 
00333                                    ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
00334                                    X509_set_issuer_name(cer, req->req_info->subject);
00335                                    X509_set_subject_name(cer, req->req_info->subject);
00336                                    X509_gmtime_adj(X509_get_notBefore(cer), 0);
00337                                    X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
00338 
00339                                    req_pkey = X509_REQ_get_pubkey(req);
00340                                    X509_set_pubkey(cer, req_pkey);
00341                                    EVP_PKEY_free(req_pkey);
00342                                    
00343                                    /* Sign the cert */
00344                                    if (!X509_sign(cer, pk, EVP_md5())) {
00345                                           syslog(3, "X509_sign(): error\n");
00346                                    }
00347                                    else {
00348                                           /* Write it to disk. */     
00349                                           fp = fopen(CTDL_CER_PATH, "w");
00350                                           if (fp != NULL) {
00351                                                  chmod(CTDL_CER_PATH, 0600);
00352                                                  PEM_write_X509(fp, cer);
00353                                                  fclose(fp);
00354                                           }
00355                                           else {
00356                                                  syslog(3, "Cannot write key: %s\n", CTDL_CER_PATH);
00357                                                  ShutDownWebcit();
00358                                                  exit(0);
00359                                           }
00360                                    }
00361                                    X509_free(cer);
00362                             }
00363                      }
00364 
00365                      RSA_free(rsa);
00366               }
00367        }
00368 
00369        /*
00370         * Now try to bind to the key and certificate.
00371         * Note that we use SSL_CTX_use_certificate_chain_file() which allows
00372         * the certificate file to contain intermediate certificates.
00373         */
00374        SSL_CTX_use_certificate_chain_file(ssl_ctx, CTDL_CER_PATH);
00375        SSL_CTX_use_PrivateKey_file(ssl_ctx, CTDL_KEY_PATH, SSL_FILETYPE_PEM);
00376        if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
00377               syslog(3, "Cannot install certificate: %s\n",
00378                             ERR_reason_error_string(ERR_get_error()));
00379        }
00380        
00381 }
00382 
00383 
00384 /*
00385  * starts SSL/TLS encryption for the current session.
00386  */
00387 int starttls(int sock) {
00388        int retval, bits, alg_bits;/*r; */
00389        SSL *newssl;
00390 
00391        pthread_setspecific(ThreadSSL, NULL);
00392 
00393        if (!ssl_ctx) {
00394               return(1);
00395        }
00396        if (!(newssl = SSL_new(ssl_ctx))) {
00397               syslog(3, "SSL_new failed: %s\n", ERR_reason_error_string(ERR_get_error()));
00398               return(2);
00399        }
00400        if (!(SSL_set_fd(newssl, sock))) {
00401               syslog(3, "SSL_set_fd failed: %s\n", ERR_reason_error_string(ERR_get_error()));
00402               SSL_free(newssl);
00403               return(3);
00404        }
00405        retval = SSL_accept(newssl);
00406        if (retval < 1) {
00407               /*
00408                * Can't notify the client of an error here; they will
00409                * discover the problem at the SSL layer and should
00410                * revert to unencrypted communications.
00411                */
00412               long errval;
00413               const char *ssl_error_reason = NULL;
00414 
00415               errval = SSL_get_error(newssl, retval);
00416               ssl_error_reason = ERR_reason_error_string(ERR_get_error());
00417               if (ssl_error_reason == NULL) {
00418                      syslog(3, "SSL_accept failed: errval=%ld, retval=%d %s\n", errval, retval, strerror(errval));
00419               }
00420               else {
00421                      syslog(3, "SSL_accept failed: %s\n", ssl_error_reason);
00422               }
00423               sleeeeeeeeeep(1);
00424               retval = SSL_accept(newssl);
00425        }
00426        if (retval < 1) {
00427               long errval;
00428               const char *ssl_error_reason = NULL;
00429 
00430               errval = SSL_get_error(newssl, retval);
00431               ssl_error_reason = ERR_reason_error_string(ERR_get_error());
00432               if (ssl_error_reason == NULL) {
00433                      syslog(3, "SSL_accept failed: errval=%ld, retval=%d (%s)\n", errval, retval, strerror(errval));
00434               }
00435               else {
00436                      syslog(3, "SSL_accept failed: %s\n", ssl_error_reason);
00437               }
00438               SSL_free(newssl);
00439               newssl = NULL;
00440               return(4);
00441        }
00442        else {
00443               syslog(15, "SSL_accept success\n");
00444        }
00445        /*r = */BIO_set_close(newssl->rbio, BIO_NOCLOSE);
00446        bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(newssl), &alg_bits);
00447        syslog(15, "SSL/TLS using %s on %s (%d of %d bits)\n",
00448               SSL_CIPHER_get_name(SSL_get_current_cipher(newssl)),
00449               SSL_CIPHER_get_version(SSL_get_current_cipher(newssl)),
00450               bits, alg_bits);
00451 
00452        pthread_setspecific(ThreadSSL, newssl);
00453        syslog(15, "SSL started\n");
00454        return(0);
00455 }
00456 
00457 
00458 
00459 /*
00460  * shuts down the TLS connection
00461  *
00462  * WARNING:  This may make your session vulnerable to a known plaintext
00463  * attack in the current implmentation.
00464  */
00465 void endtls(void)
00466 {
00467        /*SSL_CTX *ctx;*/
00468 
00469        if (THREADSSL == NULL) return;
00470 
00471        syslog(15, "Ending SSL/TLS\n");
00472        SSL_shutdown(THREADSSL);
00473        /*ctx = */SSL_get_SSL_CTX(THREADSSL);
00474 
00475        /* I don't think this is needed, and it crashes the server anyway
00476         *
00477         *     if (ctx != NULL) {
00478         *            syslog(9, "Freeing CTX at %x\n", (int)ctx );
00479         *            SSL_CTX_free(ctx);
00480         *     }
00481         */
00482 
00483        SSL_free(THREADSSL);
00484        pthread_setspecific(ThreadSSL, NULL);
00485 }
00486 
00487 
00488 /*
00489  * callback for OpenSSL mutex locks
00490  */
00491 void ssl_lock(int mode, int n, const char *file, int line)
00492 {
00493        if (mode & CRYPTO_LOCK) {
00494               pthread_mutex_lock(SSLCritters[n]);
00495        }
00496        else {
00497               pthread_mutex_unlock(SSLCritters[n]);
00498        }
00499 }
00500 
00501 /*
00502  * Send binary data to the client encrypted.
00503  */
00504 void client_write_ssl(const StrBuf *Buf)
00505 {
00506        const char *buf;
00507        int retval;
00508        int nremain;
00509        long nbytes;
00510        char junk[1];
00511 
00512        if (THREADSSL == NULL) return;
00513 
00514        nbytes = nremain = StrLength(Buf);
00515        buf = ChrPtr(Buf);
00516 
00517        while (nremain > 0) {
00518               if (SSL_want_write(THREADSSL)) {
00519                      if ((SSL_read(THREADSSL, junk, 0)) < 1) {
00520                             syslog(9, "SSL_read in client_write: %s\n",
00521                                           ERR_reason_error_string(ERR_get_error()));
00522                      }
00523               }
00524               retval = SSL_write(THREADSSL, &buf[nbytes - nremain], nremain);
00525               if (retval < 1) {
00526                      long errval;
00527 
00528                      errval = SSL_get_error(THREADSSL, retval);
00529                      if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
00530                             sleeeeeeeeeep(1);
00531                             continue;
00532                      }
00533                      syslog(9, "SSL_write got error %ld, ret %d\n", errval, retval);
00534                      if (retval == -1) {
00535                             syslog(9, "errno is %d\n", errno);
00536                      }
00537                      endtls();
00538                      return;
00539               }
00540               nremain -= retval;
00541        }
00542 }
00543 
00544 
00545 /*
00546  * read data from the encrypted layer.
00547  */
00548 int client_read_sslbuffer(StrBuf *buf, int timeout)
00549 {
00550        char sbuf[16384]; /* OpenSSL communicates in 16k blocks, so let's speak its native tongue. */
00551        int rlen;
00552        char junk[1];
00553        SSL *pssl = THREADSSL;
00554 
00555        if (pssl == NULL) return(-1);
00556 
00557        while (1) {
00558               if (SSL_want_read(pssl)) {
00559                      if ((SSL_write(pssl, junk, 0)) < 1) {
00560                             syslog(9, "SSL_write in client_read\n");
00561                      }
00562               }
00563               rlen = SSL_read(pssl, sbuf, sizeof(sbuf));
00564               if (rlen < 1) {
00565                      long errval;
00566 
00567                      errval = SSL_get_error(pssl, rlen);
00568                      if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
00569                             sleeeeeeeeeep(1);
00570                             continue;
00571                      }
00572                      syslog(9, "SSL_read got error %ld\n", errval);
00573                      endtls();
00574                      return (-1);
00575               }
00576               StrBufAppendBufPlain(buf, sbuf, rlen, 0);
00577               return rlen;
00578        }
00579        return (0);
00580 }
00581 
00582 #endif                      /* HAVE_OPENSSL */