Revert "serv_rssclient.c: style update"
[citadel.git] / webcit / crypto.c
1 // Copyright (c) 1996-2022 by the citadel.org team
2 //
3 // This program is open source software.  You can redistribute it and/or
4 // modify it under the terms of the GNU General Public License, version 3.
5 // 
6 // This program is distributed in the hope that it will be useful,
7 // but WITHOUT ANY WARRANTY; without even the implied warranty of
8 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
9 // GNU General Public License for more details.
10
11 #include "sysdep.h"
12 #ifdef HAVE_OPENSSL
13
14 #include "webcit.h"
15 #include "webserver.h"
16
17
18 SSL_CTX *ssl_ctx;               // Global SSL context
19 char key_file[PATH_MAX] = "";
20 char cert_file[PATH_MAX] = "";
21 char *ssl_cipher_list = DEFAULT_SSL_CIPHER_LIST;
22
23 pthread_key_t ThreadSSL;        // Per-thread SSL context
24
25
26 // Set the private key and certificate chain for the global SSL Context.
27 // This is called during initialization, and can be called again later if the certificate changes.
28 void bind_to_key_and_certificate(void) {
29
30         SSL_CTX *old_ctx, *new_ctx;
31
32         if (IsEmptyStr(key_file)) {
33                 snprintf(key_file, sizeof key_file, "%s/keys/citadel.key", ctdl_dir);
34         }
35         if (IsEmptyStr(cert_file)) {
36                 snprintf(cert_file, sizeof key_file, "%s/keys/citadel.cer", ctdl_dir);
37         }
38
39         if (!(new_ctx = SSL_CTX_new(SSLv23_server_method()))) {
40                 syslog(LOG_WARNING, "SSL_CTX_new failed: %s", ERR_reason_error_string(ERR_get_error()));
41                 return;
42         }
43
44         syslog(LOG_INFO, "Requesting cipher list: %s", ssl_cipher_list);
45         if (!(SSL_CTX_set_cipher_list(new_ctx, ssl_cipher_list))) {
46                 syslog(LOG_WARNING, "SSL_CTX_set_cipher_list failed: %s", ERR_reason_error_string(ERR_get_error()));
47                 return;
48         }
49
50         syslog(LOG_DEBUG, "crypto: [re]installing key \"%s\" and certificate \"%s\"", key_file, cert_file);
51
52         SSL_CTX_use_certificate_chain_file(new_ctx, cert_file);
53         SSL_CTX_use_PrivateKey_file(new_ctx, key_file, SSL_FILETYPE_PEM);
54
55         if ( !SSL_CTX_check_private_key(new_ctx) ) {
56                 syslog(LOG_WARNING, "crypto: cannot install certificate: %s", ERR_reason_error_string(ERR_get_error()));
57         }
58
59         old_ctx = ssl_ctx;
60         ssl_ctx = new_ctx;
61         sleep(1);
62         SSL_CTX_free(old_ctx);
63 }
64
65
66 // initialize ssl engine, load certs and initialize openssl internals
67 void init_ssl(void) {
68
69         // Initialize the OpenSSL library
70         SSL_load_error_strings();
71         ERR_load_crypto_strings();
72         OpenSSL_add_all_algorithms();
73         SSL_library_init();
74
75         // Now try to bind to the key and certificate.
76         bind_to_key_and_certificate();
77 }
78
79
80 // Check the modification time of the key and certificate -- reload if either one changed
81 void update_key_and_cert_if_needed(void) {
82         static time_t previous_mtime = 0;
83         struct stat keystat;
84         struct stat certstat;
85
86         if (stat(key_file, &keystat) != 0) {
87                 syslog(LOG_ERR, "%s: %s", key_file, strerror(errno));
88                 return;
89         }
90         if (stat(cert_file, &certstat) != 0) {
91                 syslog(LOG_ERR, "%s: %s", cert_file, strerror(errno));
92                 return;
93         }
94
95         if ((keystat.st_mtime + certstat.st_mtime) != previous_mtime) {
96                 bind_to_key_and_certificate();
97                 previous_mtime = keystat.st_mtime + certstat.st_mtime;
98         }
99 }
100
101
102 // starts SSL/TLS encryption for the current session.
103 int starttls(int sock) {
104         SSL *newssl;
105         int retval, bits, alg_bits;
106
107         // Check the modification time of the key and certificate -- reload if they changed
108         update_key_and_cert_if_needed();
109         
110         // SSL is a thread-specific thing, I think.
111         pthread_setspecific(ThreadSSL, NULL);
112
113         if (!ssl_ctx) {
114                 return(1);
115         }
116         if (!(newssl = SSL_new(ssl_ctx))) {
117                 syslog(LOG_WARNING, "SSL_new failed: %s", ERR_reason_error_string(ERR_get_error()));
118                 return(2);
119         }
120         if (!(SSL_set_fd(newssl, sock))) {
121                 syslog(LOG_WARNING, "SSL_set_fd failed: %s", ERR_reason_error_string(ERR_get_error()));
122                 SSL_free(newssl);
123                 return(3);
124         }
125         retval = SSL_accept(newssl);
126         if (retval < 1) {
127                 // Can't notify the client of an error here; they will
128                 // discover the problem at the SSL layer and should
129                 // revert to unencrypted communications.
130                 long errval;
131                 const char *ssl_error_reason = NULL;
132
133                 errval = SSL_get_error(newssl, retval);
134                 ssl_error_reason = ERR_reason_error_string(ERR_get_error());
135                 if (ssl_error_reason == NULL) {
136                         syslog(LOG_WARNING, "first SSL_accept failed: errval=%ld, retval=%d %s", errval, retval, strerror(errval));
137                 }
138                 else {
139                         syslog(LOG_WARNING, "first SSL_accept failed: %s", ssl_error_reason);
140                 }
141         }
142         else {
143                 syslog(LOG_INFO, "SSL_accept success");
144         }
145         BIO_set_close(SSL_get_rbio(newssl), BIO_NOCLOSE);
146         bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(newssl), &alg_bits);
147         syslog(LOG_INFO, "SSL/TLS using %s on %s (%d of %d bits)",
148                 SSL_CIPHER_get_name(SSL_get_current_cipher(newssl)),
149                 SSL_CIPHER_get_version(SSL_get_current_cipher(newssl)),
150                 bits, alg_bits);
151
152         pthread_setspecific(ThreadSSL, newssl);
153         syslog(LOG_INFO, "SSL started");
154         return(0);
155 }
156
157
158 // shuts down the TLS connection
159 //
160 // WARNING:  This may make your session vulnerable to a known plaintext
161 // attack in the current implmentation.
162 void endtls(void) {
163
164         if (THREADSSL == NULL) {
165                 return;
166         }
167
168         syslog(LOG_INFO, "Ending SSL/TLS");
169         SSL_shutdown(THREADSSL);
170         SSL_get_SSL_CTX(THREADSSL);
171         SSL_free(THREADSSL);
172         pthread_setspecific(ThreadSSL, NULL);
173 }
174
175
176 // Send binary data to the client encrypted.
177 int client_write_ssl(const StrBuf *Buf) {
178         const char *buf;
179         int retval;
180         int nremain;
181         long nbytes;
182         char junk[1];
183
184         if (THREADSSL == NULL) return -1;
185
186         nbytes = nremain = StrLength(Buf);
187         buf = ChrPtr(Buf);
188
189         while (nremain > 0) {
190                 if (SSL_want_write(THREADSSL)) {
191                         if ((SSL_read(THREADSSL, junk, 0)) < 1) {
192                                 syslog(LOG_WARNING, "SSL_read in client_write: %s", ERR_reason_error_string(ERR_get_error()));
193                         }
194                 }
195                 retval = SSL_write(THREADSSL, &buf[nbytes - nremain], nremain);
196                 if (retval < 1) {
197                         long errval;
198
199                         errval = SSL_get_error(THREADSSL, retval);
200                         if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
201                                 sleeeeeeeeeep(1);
202                                 continue;
203                         }
204                         syslog(LOG_WARNING, "SSL_write: %s", ERR_reason_error_string(ERR_get_error()));
205                         if (retval == -1) {
206                                 syslog(LOG_WARNING, "errno is %d\n", errno);
207                         }
208                         endtls();
209                         return -1;
210                 }
211                 nremain -= retval;
212         }
213         return 0;
214 }
215
216
217 // read data from the encrypted layer.
218 int client_read_sslbuffer(StrBuf *buf, int timeout) {
219         char sbuf[16384];       // OpenSSL communicates in 16k blocks, so let's speak its native tongue.
220         int rlen;
221         char junk[1];
222         SSL *pssl = THREADSSL;
223
224         if (pssl == NULL) return(-1);
225
226         while (1) {
227                 if (SSL_want_read(pssl)) {
228                         if ((SSL_write(pssl, junk, 0)) < 1) {
229                                 syslog(LOG_WARNING, "SSL_write in client_read");
230                         }
231                 }
232                 rlen = SSL_read(pssl, sbuf, sizeof(sbuf));
233                 if (rlen < 1) {
234                         long errval;
235
236                         errval = SSL_get_error(pssl, rlen);
237                         if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
238                                 sleeeeeeeeeep(1);
239                                 continue;
240                         }
241                         syslog(LOG_WARNING, "SSL_read in client_read: %s", ERR_reason_error_string(ERR_get_error()));
242                         endtls();
243                         return (-1);
244                 }
245                 StrBufAppendBufPlain(buf, sbuf, rlen, 0);
246                 return rlen;
247         }
248         return (0);
249 }
250
251 #endif                          /* HAVE_OPENSSL */