Removed SSL cleanup function. Let the operating system do this for us.
[citadel.git] / citadel / modules / crypto / serv_crypto.c
index ba9a6d03c2b4575f8c43cf46e730d32618cd0e17..83545f2fcfd79c55f80c0f1e218a3329eed5377f 100644 (file)
@@ -1,14 +1,12 @@
-/*
- * Copyright (c) 1987-2018 by the citadel.org team
- *
- * This program is open source software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License version 3.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- */
+// Copyright (c) 1987-2021 by the citadel.org team
+//
+// This program is open source software; you can redistribute it and/or modify
+// it under the terms of the GNU General Public License version 3.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
 
 #include <string.h>
 #include <unistd.h>
 #include <openssl/rand.h>
 #endif
 
-#if TIME_WITH_SYS_TIME
-# include <sys/time.h>
-# include <time.h>
-#else
-# if HAVE_SYS_TIME_H
-#  include <sys/time.h>
-# else
-#  include <time.h>
-# endif
-#endif
+#include <time.h>
 
 #ifdef HAVE_PTHREAD_H
 #include <pthread.h>
 #include "sysdep_decls.h"
 #include "citadel.h"
 #include "config.h"
-
-
 #include "ctdl_module.h"
 
 #ifdef HAVE_OPENSSL
-SSL_CTX *ssl_ctx;              /* SSL context */
-pthread_mutex_t **SSLCritters; /* Things needing locking */
+SSL_CTX *ssl_ctx;                      // SSL context
+pthread_mutex_t **SSLCritters;         // Things needing locking
 
-static unsigned long id_callback(void)
-{
-       return (unsigned long) pthread_self();
-}
 
-void destruct_ssl(void)
-{
-       int a;
-       for (a = 0; a < CRYPTO_num_locks(); a++) 
-               free(SSLCritters[a]);
-       free (SSLCritters);
+static unsigned long id_callback(void) {
+       return (unsigned long) pthread_self();
 }
 
 
-void generate_key(char *keyfilename)
-{
+void generate_key(char *keyfilename) {
        int ret = 0;
        RSA *rsa = NULL;
        BIGNUM *bne = NULL;
@@ -102,13 +80,13 @@ void generate_key(char *keyfilename)
        fp = fopen(keyfilename, "w");
        if (fp != NULL) {
                chmod(keyfilename, 0600);
-               if (PEM_write_RSAPrivateKey(fp, /* the file */
-                                       rsa,    /* the key */
-                                       NULL,   /* no enc */
-                                       NULL,   /* no passphr */
-                                       0,      /* no passphr */
-                                       NULL,   /* no callbk */
-                                       NULL    /* no callbk */
+               if (PEM_write_RSAPrivateKey(fp, // the file
+                                       rsa,    // the key
+                                       NULL,   // no enc
+                                       NULL,   // no passphrase
+                                       0,      // no passphrase
+                                       NULL,   // no callback
+                                       NULL    // no callback
                ) != 1) {
                        syslog(LOG_ERR, "crypto: cannot write key: %s", ERR_reason_error_string(ERR_get_error()));
                        unlink(keyfilename);
@@ -116,15 +94,14 @@ void generate_key(char *keyfilename)
                fclose(fp);
        }
 
-    // 4. free
+    // free the memory we used
 free_all:
     RSA_free(rsa);
     BN_free(bne);
 }
 
 
-void init_ssl(void)
-{
+void init_ssl(void) {
        const SSL_METHOD *ssl_method;
        RSA *rsa = NULL;
        X509_REQ *req = NULL;
@@ -138,7 +115,8 @@ void init_ssl(void)
        if (!SSLCritters) {
                syslog(LOG_ERR, "crypto: can't allocate memory!");
                exit(CTDLEXIT_CRYPTO);
-       } else {
+       }
+       else {
                int a;
 
                for (a = 0; a < CRYPTO_num_locks(); a++) {
@@ -151,9 +129,7 @@ void init_ssl(void)
                }
        }
 
-       /*
-        * Initialize SSL transport layer
-        */
+       // Initialize SSL transport layer
        SSL_library_init();
        SSL_load_error_strings();
        ssl_method = SSLv23_server_method();
@@ -174,20 +150,16 @@ void init_ssl(void)
        mkdir(ctdl_key_dir, 0700);              // If the keys directory does not exist, create it
        generate_key(file_crpt_file_key);       // If a private key does not exist, create it
 
-       /*
-        * If there is no certificate file on disk, we will be generating a self-signed certificate
-        * in the next step.  Therefore, if we have neither a CSR nor a certificate, generate
-        * the CSR in this step so that the next step may commence.
-        */
+       // If there is no certificate file on disk, we will be generating a self-signed certificate
+       // in the next step.  Therefore, if we have neither a CSR nor a certificate, generate
+       // the CSR in this step so that the next step may commence.
        if ( (access(file_crpt_file_cer, R_OK) != 0) && (access(file_crpt_file_csr, R_OK) != 0) ) {
                syslog(LOG_INFO, "crypto: generating a generic certificate signing request.");
 
-               /*
-                * Read our key from the file.  No, we don't just keep this
-                * in memory from the above key-generation function, because
-                * there is the possibility that the key was already on disk
-                * and we didn't just generate it now.
-                */
+               // Read our key from the file.  No, we don't just keep this
+               // in memory from the above key-generation function, because
+               // there is the possibility that the key was already on disk
+               // and we didn't just generate it now.
                fp = fopen(file_crpt_file_key, "r");
                if (fp) {
                        rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
@@ -196,18 +168,18 @@ void init_ssl(void)
 
                if (rsa) {
 
-                       /* Create a public key from the private key */
+                       // Create a public key from the private key
                        if (pk=EVP_PKEY_new(), pk != NULL) {
                                EVP_PKEY_assign_RSA(pk, rsa);
                                if (req = X509_REQ_new(), req != NULL) {
 
-                                       /* Set the public key */
+                                       // Set the public key
                                        X509_REQ_set_pubkey(req, pk);
                                        X509_REQ_set_version(req, 0L);
 
                                        name = X509_REQ_get_subject_name(req);
 
-                                       /* Tell it who we are */
+                                       // Tell it who we are
                                        X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC, (unsigned const char *)"ZZ", -1, -1, 0);
                                        X509_NAME_add_entry_by_txt(name, "ST", MBSTRING_ASC, (unsigned const char *)"The World", -1, -1, 0);
                                        X509_NAME_add_entry_by_txt(name, "L", MBSTRING_ASC, (unsigned const char *)"My Location", -1, -1, 0);
@@ -216,12 +188,12 @@ void init_ssl(void)
                                        X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, (unsigned const char *)"*", -1, -1, 0);
                                        X509_REQ_set_subject_name(req, name);
 
-                                       /* Sign the CSR */
+                                       // Sign the CSR
                                        if (!X509_REQ_sign(req, pk, EVP_md5())) {
                                                syslog(LOG_ERR, "crypto: X509_REQ_sign(): error");
                                        }
                                        else {
-                                               /* Write it to disk. */ 
+                                               // Write it to disk
                                                fp = fopen(file_crpt_file_csr, "w");
                                                if (fp != NULL) {
                                                        chmod(file_crpt_file_csr, 0600);
@@ -242,23 +214,19 @@ void init_ssl(void)
                }
        }
 
-
-       /*
-        * Generate a self-signed certificate if we don't have one.
-        */
+       // Generate a self-signed certificate if we don't have one.
        if (access(file_crpt_file_cer, R_OK) != 0) {
                syslog(LOG_INFO, "crypto: generating a generic self-signed certificate.");
 
-               /* Same deal as before: always read the key from disk because
-                * it may or may not have just been generated.
-                */
+               // Same deal as before: always read the key from disk because
+               // it may or may not have just been generated.
                fp = fopen(file_crpt_file_key, "r");
                if (fp) {
                        rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
                        fclose(fp);
                }
 
-               /* This also holds true for the CSR. */
+               // This also holds true for the CSR.
                req = NULL;
                cer = NULL;
                pk = NULL;
@@ -284,12 +252,12 @@ void init_ssl(void)
                                        X509_set_pubkey(cer, req_pkey);
                                        EVP_PKEY_free(req_pkey);
                                        
-                                       /* Sign the cert */
+                                       // Sign the cert
                                        if (!X509_sign(cer, pk, EVP_md5())) {
                                                syslog(LOG_ERR, "crypto: X509_sign() error");
                                        }
                                        else {
-                                               /* Write it to disk. */ 
+                                               // Write it to disk.
                                                fp = fopen(file_crpt_file_cer, "w");
                                                if (fp != NULL) {
                                                        chmod(file_crpt_file_cer, 0600);
@@ -305,28 +273,22 @@ void init_ssl(void)
                }
        }
 
-
-       /*
-        * Now try to bind to the key and certificate.
-        */
+       // Now try to bind to the key and certificate.
         SSL_CTX_use_certificate_chain_file(ssl_ctx, file_crpt_file_cer);
         SSL_CTX_use_PrivateKey_file(ssl_ctx, file_crpt_file_key, SSL_FILETYPE_PEM);
         if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
                syslog(LOG_ERR, "crypto: cannot install certificate: %s", ERR_reason_error_string(ERR_get_error()));
         }
 
-       /* Finally let the server know we're here */
+       // Finally let the server know we're here
        CtdlRegisterProtoHook(cmd_stls, "STLS", "Start SSL/TLS session");
        CtdlRegisterProtoHook(cmd_gtls, "GTLS", "Get SSL/TLS session status");
        CtdlRegisterSessionHook(endtls, EVT_STOP, PRIO_STOP + 10);
 }
 
 
-/*
- * client_write_ssl() Send binary data to the client encrypted.
- */
-void client_write_ssl(const char *buf, int nbytes)
-{
+// client_write_ssl() Send binary data to the client encrypted.
+void client_write_ssl(const char *buf, int nbytes) {
        int retval;
        int nremain;
        char junk[1];
@@ -363,12 +325,9 @@ void client_write_ssl(const char *buf, int nbytes)
 }
 
 
-/*
- * read data from the encrypted layer.
- */
-int client_read_sslbuffer(StrBuf *buf, int timeout)
-{
-       char sbuf[16384]; /* OpenSSL communicates in 16k blocks, so let's speak its native tongue. */
+// read data from the encrypted layer.
+int client_read_sslbuffer(StrBuf *buf, int timeout) {
+       char sbuf[16384];       // OpenSSL communicates in 16k blocks, so let's speak its native tongue.
        int rlen;
        char junk[1];
        SSL *pssl = CC->ssl;
@@ -400,9 +359,8 @@ int client_read_sslbuffer(StrBuf *buf, int timeout)
        return (0);
 }
 
-int client_readline_sslbuffer(StrBuf *Line, StrBuf *IOBuf, const char **Pos, int timeout)
-{
-       CitContext *CCC = CC;
+
+int client_readline_sslbuffer(StrBuf *Line, StrBuf *IOBuf, const char **Pos, int timeout) {
        const char *pos = NULL;
        const char *pLF;
        int len, rlen;
@@ -451,7 +409,7 @@ int client_readline_sslbuffer(StrBuf *Line, StrBuf *IOBuf, const char **Pos, int
        pLF = NULL;
        while ((nSuccessLess < timeout) && 
               (pLF == NULL) &&
-              (CCC->ssl != NULL)) {
+              (CC->ssl != NULL)) {
 
                rlen = client_read_sslbuffer(IOBuf, timeout);
                if (rlen < 1) {
@@ -480,71 +438,60 @@ int client_readline_sslbuffer(StrBuf *Line, StrBuf *IOBuf, const char **Pos, int
 }
 
 
-int client_read_sslblob(StrBuf *Target, long bytes, int timeout)
-{
+int client_read_sslblob(StrBuf *Target, long bytes, int timeout) {
        long baselen;
        long RemainRead;
        int retval = 0;
-       CitContext *CCC = CC;
 
        baselen = StrLength(Target);
 
-       if (StrLength(CCC->RecvBuf.Buf) > 0)
-       {
+       if (StrLength(CC->RecvBuf.Buf) > 0) {
                long RemainLen;
                long TotalLen;
                const char *pchs;
 
-               if (CCC->RecvBuf.ReadWritePointer == NULL)
-               {
-                       CCC->RecvBuf.ReadWritePointer = ChrPtr(CCC->RecvBuf.Buf);
+               if (CC->RecvBuf.ReadWritePointer == NULL) {
+                       CC->RecvBuf.ReadWritePointer = ChrPtr(CC->RecvBuf.Buf);
                }
-               pchs = ChrPtr(CCC->RecvBuf.Buf);
-               TotalLen = StrLength(CCC->RecvBuf.Buf);
-               RemainLen = TotalLen - (pchs - CCC->RecvBuf.ReadWritePointer);
-               if (RemainLen > bytes)
-               {
+               pchs = ChrPtr(CC->RecvBuf.Buf);
+               TotalLen = StrLength(CC->RecvBuf.Buf);
+               RemainLen = TotalLen - (pchs - CC->RecvBuf.ReadWritePointer);
+               if (RemainLen > bytes) {
                        RemainLen = bytes;
                }
-               if (RemainLen > 0)
-               {
-                       StrBufAppendBufPlain(Target, CCC->RecvBuf.ReadWritePointer, RemainLen, 0);
-                       CCC->RecvBuf.ReadWritePointer += RemainLen;
+               if (RemainLen > 0) {
+                       StrBufAppendBufPlain(Target, CC->RecvBuf.ReadWritePointer, RemainLen, 0);
+                       CC->RecvBuf.ReadWritePointer += RemainLen;
                }
-               if ((ChrPtr(CCC->RecvBuf.Buf) + StrLength(CCC->RecvBuf.Buf)) <= CCC->RecvBuf.ReadWritePointer)
-               {
-                       CCC->RecvBuf.ReadWritePointer = NULL;
-                       FlushStrBuf(CCC->RecvBuf.Buf);
+               if ((ChrPtr(CC->RecvBuf.Buf) + StrLength(CC->RecvBuf.Buf)) <= CC->RecvBuf.ReadWritePointer) {
+                       CC->RecvBuf.ReadWritePointer = NULL;
+                       FlushStrBuf(CC->RecvBuf.Buf);
                }
        }
 
-       if (StrLength(Target) >= bytes + baselen)
-       {
+       if (StrLength(Target) >= bytes + baselen) {
                return 1;
        }
 
-       CCC->RecvBuf.ReadWritePointer = NULL;
+       CC->RecvBuf.ReadWritePointer = NULL;
 
-       while ((StrLength(Target) < bytes + baselen) && (retval >= 0))
-       {
-               retval = client_read_sslbuffer(CCC->RecvBuf.Buf, timeout);
+       while ((StrLength(Target) < bytes + baselen) && (retval >= 0)) {
+               retval = client_read_sslbuffer(CC->RecvBuf.Buf, timeout);
                if (retval >= 0) {
                        RemainRead = bytes - (StrLength (Target) - baselen);
-                       if (RemainRead < StrLength(CCC->RecvBuf.Buf))
-                       {
+                       if (RemainRead < StrLength(CC->RecvBuf.Buf)) {
                                StrBufAppendBufPlain(
                                        Target, 
-                                       ChrPtr(CCC->RecvBuf.Buf), 
+                                       ChrPtr(CC->RecvBuf.Buf), 
                                        RemainRead, 0);
-                               CCC->RecvBuf.ReadWritePointer = ChrPtr(CCC->RecvBuf.Buf) + RemainRead;
+                               CC->RecvBuf.ReadWritePointer = ChrPtr(CC->RecvBuf.Buf) + RemainRead;
                                break;
                        }
-                       StrBufAppendBuf(Target, CCC->RecvBuf.Buf, 0); /* todo: Buf > bytes? */
-                       FlushStrBuf(CCC->RecvBuf.Buf);
+                       StrBufAppendBuf(Target, CC->RecvBuf.Buf, 0);    // todo: Buf > bytes?
+                       FlushStrBuf(CC->RecvBuf.Buf);
                }
-               else 
-               {
-                       FlushStrBuf(CCC->RecvBuf.Buf);
+               else {
+                       FlushStrBuf(CC->RecvBuf.Buf);
                        return -1;
        
                }
@@ -553,15 +500,20 @@ int client_read_sslblob(StrBuf *Target, long bytes, int timeout)
 }
 
 
-/*
- * CtdlStartTLS() starts SSL/TLS encryption for the current session.  It
- * must be supplied with pre-generated strings for responses of "ok," "no
- * support for TLS," and "error" so that we can use this in any protocol.
- */
-void CtdlStartTLS(char *ok_response, char *nosup_response, char *error_response)
-{
+// CtdlStartTLS() starts SSL/TLS encryption for the current session.  It
+// must be supplied with pre-generated strings for responses of "ok," "no
+// support for TLS," and "error" so that we can use this in any protocol.
+void CtdlStartTLS(char *ok_response, char *nosup_response, char *error_response) {
        int retval, bits, alg_bits;
 
+       if (CC->redirect_ssl) {
+               syslog(LOG_ERR, "crypto: attempt to begin SSL on an already encrypted connection");
+               if (error_response != NULL) {
+                       cprintf("%s", error_response);
+               }
+               return;
+       }
+
        if (!ssl_ctx) {
                syslog(LOG_ERR, "crypto: SSL failed: no ssl_ctx exists?");
                if (nosup_response != NULL) cprintf("%s", nosup_response);
@@ -584,11 +536,9 @@ void CtdlStartTLS(char *ok_response, char *nosup_response, char *error_response)
        if (ok_response != NULL) cprintf("%s", ok_response);
        retval = SSL_accept(CC->ssl);
        if (retval < 1) {
-               /*
-                * Can't notify the client of an error here; they will
-                * discover the problem at the SSL layer and should
-                * revert to unencrypted communications.
-                */
+               // Can't notify the client of an error here; they will
+               // discover the problem at the SSL layer and should
+               // revert to unencrypted communications.
                long errval;
                char error_string[128];
 
@@ -613,11 +563,8 @@ void CtdlStartTLS(char *ok_response, char *nosup_response, char *error_response)
 }
 
 
-/*
- * cmd_stls() starts SSL/TLS encryption for the current session
- */
-void cmd_stls(char *params)
-{
+// cmd_stls() starts SSL/TLS encryption for the current session
+void cmd_stls(char *params) {
        char ok_response[SIZ];
        char nosup_response[SIZ];
        char error_response[SIZ];
@@ -632,11 +579,8 @@ void cmd_stls(char *params)
 }
 
 
-/*
- * cmd_gtls() returns status info about the TLS connection
- */
-void cmd_gtls(char *params)
-{
+// cmd_gtls() returns status info about the TLS connection
+void cmd_gtls(char *params) {
        int bits, alg_bits;
 
        if (!CC->ssl || !CC->redirect_ssl) {
@@ -653,14 +597,11 @@ void cmd_gtls(char *params)
 }
 
 
-/*
- * endtls() shuts down the TLS connection
- *
- * WARNING:  This may make your session vulnerable to a known plaintext
- * attack in the current implmentation.
- */
-void endtls(void)
-{
+// endtls() shuts down the TLS connection
+//
+// WARNING:  This may make your session vulnerable to a known plaintext
+// attack in the current implmentation.
+void endtls(void) {
        if (!CC->ssl) {
                CC->redirect_ssl = 0;
                return;
@@ -674,17 +615,13 @@ void endtls(void)
 }
 
 
-/*
- * ssl_lock() callback for OpenSSL mutex locks
- */
-void ssl_lock(int mode, int n, const char *file, int line)
-{
-       if (mode & CRYPTO_LOCK)
-       {
+// ssl_lock() callback for OpenSSL mutex locks
+void ssl_lock(int mode, int n, const char *file, int line) {
+       if (mode & CRYPTO_LOCK) {
                pthread_mutex_lock(SSLCritters[n]);
        }
        else {
                pthread_mutex_unlock(SSLCritters[n]);
        }
 }
-#endif                         /* HAVE_OPENSSL */
+#endif // HAVE_OPENSSL