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