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