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