Citadel Server and WebCit (classic) now both reload the key and cert if the modificat...
[citadel.git] / webcit / crypto.c
1 // Copyright (c) 1996-2021 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 void shutdown_ssl(void) {
26         ERR_free_strings();
27 }
28
29
30 // Set the private key and certificate chain for the global SSL Context.
31 // This is called during initialization, and can be called again later if the certificate changes.
32 void bind_to_key_and_certificate(void) {
33         if (IsEmptyStr(key_file)) {
34                 snprintf(key_file, sizeof key_file, "%s/keys/citadel.key", ctdl_dir);
35         }
36         if (IsEmptyStr(cert_file)) {
37                 snprintf(cert_file, sizeof key_file, "%s/keys/citadel.cer", ctdl_dir);
38         }
39
40         syslog(LOG_DEBUG, "crypto: [re]installing key \"%s\" and certificate \"%s\"", key_file, cert_file);
41
42         SSL_CTX_use_certificate_chain_file(ssl_ctx, cert_file);
43         SSL_CTX_use_PrivateKey_file(ssl_ctx, key_file, SSL_FILETYPE_PEM);
44
45         if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
46                 syslog(LOG_WARNING, "crypto: cannot install certificate: %s", ERR_reason_error_string(ERR_get_error()));
47         }
48 }
49
50
51 // initialize ssl engine, load certs and initialize openssl internals
52 void init_ssl(void) {
53         const SSL_METHOD *ssl_method;
54
55 #ifndef OPENSSL_NO_EGD
56         if (!access("/var/run/egd-pool", F_OK)) {
57                 RAND_egd("/var/run/egd-pool");
58         }
59 #endif
60
61         if (!RAND_status()) {
62                 syslog(LOG_WARNING, "PRNG not adequately seeded, won't do SSL/TLS");
63                 return;
64         }
65
66         // Initialize SSL transport layer
67         SSL_library_init();
68         SSL_load_error_strings();
69         ssl_method = SSLv23_server_method();
70         if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
71                 syslog(LOG_WARNING, "SSL_CTX_new failed: %s", ERR_reason_error_string(ERR_get_error()));
72                 return;
73         }
74
75         syslog(LOG_INFO, "Requesting cipher list: %s", ssl_cipher_list);
76         if (!(SSL_CTX_set_cipher_list(ssl_ctx, ssl_cipher_list))) {
77                 syslog(LOG_WARNING, "SSL_CTX_set_cipher_list failed: %s", ERR_reason_error_string(ERR_get_error()));
78                 return;
79         }
80
81
82         // Now try to bind to the key and certificate.
83         bind_to_key_and_certificate();
84 }
85
86
87 // Check the modification time of the key and certificate -- reload if they changed
88 void update_key_and_cert_if_needed(void) {
89         static time_t cert_mtime = 0;
90         struct stat keystat;
91         struct stat certstat;
92
93         if (stat(key_file, &keystat) != 0) {
94                 syslog(LOG_ERR, "%s: %s", key_file, strerror(errno));
95                 return;
96         }
97         if (stat(cert_file, &certstat) != 0) {
98                 syslog(LOG_ERR, "%s: %s", cert_file, strerror(errno));
99                 return;
100         }
101
102         if ((keystat.st_mtime > cert_mtime) || (certstat.st_mtime > cert_mtime)) {
103                 bind_to_key_and_certificate();
104                 cert_mtime = certstat.st_mtime;
105         }
106 }
107
108
109 // starts SSL/TLS encryption for the current session.
110 int starttls(int sock) {
111         SSL *newssl;
112         int retval, bits, alg_bits;
113
114         // Check the modification time of the key and certificate -- reload if they changed
115         update_key_and_cert_if_needed();
116         
117         // SSL is a thread-specific thing, I think.
118         pthread_setspecific(ThreadSSL, NULL);
119
120         if (!ssl_ctx) {
121                 return(1);
122         }
123         if (!(newssl = SSL_new(ssl_ctx))) {
124                 syslog(LOG_WARNING, "SSL_new failed: %s", ERR_reason_error_string(ERR_get_error()));
125                 return(2);
126         }
127         if (!(SSL_set_fd(newssl, sock))) {
128                 syslog(LOG_WARNING, "SSL_set_fd failed: %s", ERR_reason_error_string(ERR_get_error()));
129                 SSL_free(newssl);
130                 return(3);
131         }
132         retval = SSL_accept(newssl);
133         if (retval < 1) {
134                 // Can't notify the client of an error here; they will
135                 // discover the problem at the SSL layer and should
136                 // revert to unencrypted communications.
137                 long errval;
138                 const char *ssl_error_reason = NULL;
139
140                 errval = SSL_get_error(newssl, retval);
141                 ssl_error_reason = ERR_reason_error_string(ERR_get_error());
142                 if (ssl_error_reason == NULL) {
143                         syslog(LOG_WARNING, "first SSL_accept failed: errval=%ld, retval=%d %s", errval, retval, strerror(errval));
144                 }
145                 else {
146                         syslog(LOG_WARNING, "first SSL_accept failed: %s", ssl_error_reason);
147                 }
148                 // sleeeeeeeeeep(1);
149                 // retval = SSL_accept(newssl);
150         }
151         // if (retval < 1) {
152                 // long errval;
153                 // const char *ssl_error_reason = NULL;
154 // 
155                 // errval = SSL_get_error(newssl, retval);
156                 // ssl_error_reason = ERR_reason_error_string(ERR_get_error());
157                 // if (ssl_error_reason == NULL) {
158                         // syslog(LOG_WARNING, "second SSL_accept failed: errval=%ld, retval=%d (%s)", errval, retval, strerror(errval));
159                 // }
160                 // else {
161                         // syslog(LOG_WARNING, "second SSL_accept failed: %s", ssl_error_reason);
162                 // }
163                 // SSL_free(newssl);
164                 // newssl = NULL;
165                 // return(4);
166         // }
167         else {
168                 syslog(LOG_INFO, "SSL_accept success");
169         }
170         /*r = */BIO_set_close(SSL_get_rbio(newssl), BIO_NOCLOSE);
171         bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(newssl), &alg_bits);
172         syslog(LOG_INFO, "SSL/TLS using %s on %s (%d of %d bits)",
173                 SSL_CIPHER_get_name(SSL_get_current_cipher(newssl)),
174                 SSL_CIPHER_get_version(SSL_get_current_cipher(newssl)),
175                 bits, alg_bits);
176
177         pthread_setspecific(ThreadSSL, newssl);
178         syslog(LOG_INFO, "SSL started");
179         return(0);
180 }
181
182
183 // shuts down the TLS connection
184 //
185 // WARNING:  This may make your session vulnerable to a known plaintext
186 // attack in the current implmentation.
187 void endtls(void) {
188
189         if (THREADSSL == NULL) {
190                 return;
191         }
192
193         syslog(LOG_INFO, "Ending SSL/TLS");
194         SSL_shutdown(THREADSSL);
195         SSL_get_SSL_CTX(THREADSSL);
196         SSL_free(THREADSSL);
197         pthread_setspecific(ThreadSSL, NULL);
198 }
199
200
201 // Send binary data to the client encrypted.
202 int client_write_ssl(const StrBuf *Buf) {
203         const char *buf;
204         int retval;
205         int nremain;
206         long nbytes;
207         char junk[1];
208
209         if (THREADSSL == NULL) return -1;
210
211         nbytes = nremain = StrLength(Buf);
212         buf = ChrPtr(Buf);
213
214         while (nremain > 0) {
215                 if (SSL_want_write(THREADSSL)) {
216                         if ((SSL_read(THREADSSL, junk, 0)) < 1) {
217                                 syslog(LOG_WARNING, "SSL_read in client_write: %s", ERR_reason_error_string(ERR_get_error()));
218                         }
219                 }
220                 retval = SSL_write(THREADSSL, &buf[nbytes - nremain], nremain);
221                 if (retval < 1) {
222                         long errval;
223
224                         errval = SSL_get_error(THREADSSL, retval);
225                         if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
226                                 sleeeeeeeeeep(1);
227                                 continue;
228                         }
229                         syslog(LOG_WARNING, "SSL_write: %s", ERR_reason_error_string(ERR_get_error()));
230                         if (retval == -1) {
231                                 syslog(LOG_WARNING, "errno is %d\n", errno);
232                         }
233                         endtls();
234                         return -1;
235                 }
236                 nremain -= retval;
237         }
238         return 0;
239 }
240
241
242 // read data from the encrypted layer.
243 int client_read_sslbuffer(StrBuf *buf, int timeout) {
244         char sbuf[16384];       // OpenSSL communicates in 16k blocks, so let's speak its native tongue.
245         int rlen;
246         char junk[1];
247         SSL *pssl = THREADSSL;
248
249         if (pssl == NULL) return(-1);
250
251         while (1) {
252                 if (SSL_want_read(pssl)) {
253                         if ((SSL_write(pssl, junk, 0)) < 1) {
254                                 syslog(LOG_WARNING, "SSL_write in client_read");
255                         }
256                 }
257                 rlen = SSL_read(pssl, sbuf, sizeof(sbuf));
258                 if (rlen < 1) {
259                         long errval;
260
261                         errval = SSL_get_error(pssl, rlen);
262                         if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
263                                 sleeeeeeeeeep(1);
264                                 continue;
265                         }
266                         syslog(LOG_WARNING, "SSL_read in client_read: %s", ERR_reason_error_string(ERR_get_error()));
267                         endtls();
268                         return (-1);
269                 }
270                 StrBufAppendBufPlain(buf, sbuf, rlen, 0);
271                 return rlen;
272         }
273         return (0);
274 }
275
276 #endif                          /* HAVE_OPENSSL */