* compatibility with Berkeley DB < 3.3
[citadel.git] / citadel / serv_crypto.c
1 /* $Id$ */
2
3 #include <string.h>
4 #include <unistd.h>
5 #include <sys/types.h>
6 #include "sysdep.h"
7
8 #ifdef HAVE_OPENSSL
9 #include <openssl/ssl.h>
10 #include <openssl/err.h>
11 #include <openssl/rand.h>
12 #endif
13
14 #if TIME_WITH_SYS_TIME
15 # include <sys/time.h>
16 # include <time.h>
17 #else
18 # if HAVE_SYS_TIME_H
19 #  include <sys/time.h>
20 # else
21 #  include <time.h>
22 # endif
23 #endif
24
25 #ifdef HAVE_PTHREAD_H
26 #include <pthread.h>
27 #endif
28
29 #ifdef HAVE_SYS_SELECT_H
30 #include <sys/select.h>
31 #endif
32
33 #include <stdio.h>
34 #include "server.h"
35 #include "serv_crypto.h"
36 #include "sysdep_decls.h"
37 #include "dynloader.h"
38
39
40 #ifdef HAVE_OPENSSL
41 SSL_CTX *ssl_ctx;                               /* SSL context */
42 pthread_mutex_t **SSLCritters;                  /* Things needing locking */
43
44 static unsigned long id_callback(void) {
45         return pthread_self();
46 }
47
48 void init_ssl(void)
49 {
50         SSL_METHOD *ssl_method;
51         DH *dh;
52
53         if (!access("/var/run/egd-pool", F_OK))
54                 RAND_egd("/var/run/egd-pool");
55         
56         if (!RAND_status()) {
57                 lprintf(2, "PRNG not adequately seeded, won't do SSL/TLS\n");
58                 return;
59         }
60         SSLCritters = mallok(CRYPTO_num_locks() * sizeof (pthread_mutex_t *));
61         if (!SSLCritters) {
62                 lprintf(1, "citserver: can't allocate memory!!\n");
63                 /* Nothing's been initialized, just die */
64                 exit(1);
65         } else {
66                 int a;
67
68                 for (a=0; a<CRYPTO_num_locks(); a++) {
69                         SSLCritters[a] = mallok(sizeof (pthread_mutex_t));
70                         if (!SSLCritters[a]) {
71                                 lprintf(1, "citserver: can't allocate memory!!\n");
72                                 /* Nothing's been initialized, just die */
73                                 exit(1);
74                         }
75                         pthread_mutex_init(SSLCritters[a], NULL);
76                 }
77         }
78
79         /*
80          * Initialize SSL transport layer
81          */
82         SSL_library_init();
83         SSL_load_error_strings();
84         ssl_method = SSLv23_server_method();
85         if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
86                 lprintf(2, "SSL_CTX_new failed: %s\n",
87                                 ERR_reason_error_string(ERR_get_error()));
88                 return;
89         }
90         if (!(SSL_CTX_set_cipher_list(ssl_ctx, CIT_CIPHERS))) {
91                 lprintf(2, "SSL: No ciphers available\n");
92                 SSL_CTX_free(ssl_ctx);
93                 ssl_ctx = NULL;
94                 return;
95         }
96 #if 0
97 #if SSLEAY_VERSION_NUMBER >= 0x00906000L
98         SSL_CTX_set_mode(ssl_ctx, SSL_CTX_get_mode(ssl_ctx) |
99                         SSL_MODE_AUTO_RETRY);
100 #endif
101 #endif
102         CRYPTO_set_locking_callback(ssl_lock);
103         CRYPTO_set_id_callback(id_callback);
104
105         /* Load DH parameters into the context */
106         dh = DH_new();
107         if (!dh) {
108                 lprintf(2, "init_ssl() can't allocate a DH object: %s\n",
109                                 ERR_reason_error_string(ERR_get_error()));
110                 SSL_CTX_free(ssl_ctx);
111                 ssl_ctx = NULL;
112                 return;
113         }
114         if (!(BN_hex2bn(&(dh->p), DH_P))) {
115                 lprintf(2, "init_ssl() can't assign DH_P: %s\n",
116                                 ERR_reason_error_string(ERR_get_error()));
117                 SSL_CTX_free(ssl_ctx);
118                 ssl_ctx = NULL;
119                 return;
120         }
121         if (!(BN_hex2bn(&(dh->g), DH_G))) {
122                 lprintf(2, "init_ssl() can't assign DH_G: %s\n",
123                                 ERR_reason_error_string(ERR_get_error()));
124                 SSL_CTX_free(ssl_ctx);
125                 ssl_ctx = NULL;
126                 return;
127         }
128         dh->length = DH_L;
129         SSL_CTX_set_tmp_dh(ssl_ctx, dh);
130         DH_free(dh);
131
132         /* Finally let the server know we're here */
133         CtdlRegisterProtoHook(cmd_stls, "STLS", "Start SSL/TLS session");
134         CtdlRegisterProtoHook(cmd_gtls, "GTLS", "Get SSL/TLS session status");
135         CtdlRegisterSessionHook(endtls, EVT_STOP);
136 }
137
138
139 /*
140  * client_write_ssl() Send binary data to the client encrypted.
141  */
142 void client_write_ssl(char *buf, int nbytes)
143 {
144         int retval;
145         int nremain;
146         char junk[1];
147
148         nremain = nbytes;
149
150         while (nremain > 0) {
151                 if (SSL_want_write(CC->ssl)) {
152                         if ((SSL_read(CC->ssl, junk, 0)) < 1) {
153                                 lprintf(9, "SSL_read in client_write:\n");
154                                 ERR_print_errors_fp(stderr);
155                         }
156                 }
157                 retval = SSL_write(CC->ssl, &buf[nbytes - nremain], nremain);
158                 if (retval < 1) {
159                         long errval;
160
161                         errval = SSL_get_error(CC->ssl, retval);
162                         if (errval == SSL_ERROR_WANT_READ ||
163                                         errval == SSL_ERROR_WANT_WRITE) {
164                                 sleep(1);
165                                 continue;
166                         }
167                         lprintf(9, "SSL_write got error %ld\n", errval);
168                         endtls();
169                         client_write(&buf[nbytes - nremain], nremain);
170                         return;
171                 }
172                 nremain -= retval;
173         }
174 }
175
176
177 /*
178  * client_read_ssl() - read data from the encrypted layer.
179  */
180 int client_read_ssl(char *buf, int bytes, int timeout)
181 {
182         int len,rlen;
183         fd_set rfds;
184         struct timeval tv;
185         int retval;
186         int s;
187         char junk[1];
188
189         len = 0;
190         while(len<bytes) {
191                 FD_ZERO(&rfds);
192                 s = BIO_get_fd(CC->ssl->rbio, NULL);
193                 FD_SET(s, &rfds);
194                 tv.tv_sec = timeout;
195                 tv.tv_usec = 0;
196
197                 retval = select(s+1, &rfds, NULL, NULL, &tv);
198
199                 if (FD_ISSET(s, &rfds) == 0) {
200                         return(0);
201                 }
202
203                 if (SSL_want_read(CC->ssl)) {
204                         if ((SSL_write(CC->ssl, junk, 0)) < 1) {
205                                 lprintf(9, "SSL_write in client_read:\n");
206                                 ERR_print_errors_fp(stderr);
207                         }
208                 }
209                 rlen = SSL_read(CC->ssl, &buf[len], bytes-len);
210                 if (rlen<1) {
211                         long errval;
212
213                         errval = SSL_get_error(CC->ssl, rlen);
214                         if (errval == SSL_ERROR_WANT_READ ||
215                                         errval == SSL_ERROR_WANT_WRITE) {
216                                 sleep(1);
217                                 continue;
218                         }
219                         lprintf(9, "SSL_read got error %ld\n", errval);
220                         endtls();
221                         return (client_read_to(&buf[len], bytes - len, timeout));
222                 }
223                 len += rlen;
224         }
225         return(1);
226 }
227
228
229 /*
230  * cmd_stls() starts SSL/TLS encryption for the current session
231  */
232 void cmd_stls(char *params)
233 {
234         int retval, bits, alg_bits;
235
236         if (!ssl_ctx) {
237                 cprintf("%d No SSL_CTX available\n", ERROR);
238                 return;
239         }
240         if (!(CC->ssl = SSL_new(ssl_ctx))) {
241                 lprintf(2, "SSL_new failed: %s\n",
242                                 ERR_reason_error_string(ERR_peek_error()));
243                 cprintf("%d SSL_new: %s\n", ERROR,
244                                 ERR_reason_error_string(ERR_get_error()));
245                 return;
246         }
247         if (!(SSL_set_fd(CC->ssl, CC->client_socket))) {
248                 lprintf(2, "SSL_set_fd failed: %s\n",
249                                 ERR_reason_error_string(ERR_peek_error()));
250                 SSL_free(CC->ssl);
251                 CC->ssl = NULL;
252                 cprintf("%d SSL_set_fd: %s\n", ERROR,
253                                 ERR_reason_error_string(ERR_get_error()));
254                 return;
255         }
256         cprintf("%d \n", CIT_OK);
257         retval = SSL_accept(CC->ssl);
258         if (retval < 1) {
259                 /*
260                  * Can't notify the client of an error here; they will
261                  * discover the problem at the SSL layer and should
262                  * revert to unencrypted communications.
263                  */
264                 long errval;
265
266                 errval = SSL_get_error(CC->ssl, retval);
267                 lprintf(2, "SSL_accept failed: %s\n",
268                                 ERR_reason_error_string(ERR_get_error()));
269                 SSL_free(CC->ssl);
270                 CC->ssl = NULL;
271                 return;
272         }
273         BIO_set_close(CC->ssl->rbio, BIO_NOCLOSE);
274         bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl), &alg_bits);
275         lprintf(3, "SSL/TLS using %s on %s (%d of %d bits)\n",
276                         SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
277                         SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
278                         bits, alg_bits);
279         CC->redirect_ssl = 1;
280 }
281
282
283 /*
284  * cmd_gtls() returns status info about the TLS connection
285  */
286 void cmd_gtls(char *params)
287 {
288         int bits, alg_bits;
289         
290         if (!CC->ssl || !CC->redirect_ssl) {
291                 cprintf("%d Session is not encrypted.\n", ERROR);
292                 return;
293         }
294         bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl), &alg_bits);
295         cprintf("%d %s|%s|%d|%d\n", CIT_OK,
296                 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
297                 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
298                 alg_bits, bits);
299 }
300
301
302 /*
303  * endtls() shuts down the TLS connection
304  *
305  * WARNING:  This may make your session vulnerable to a known plaintext
306  * attack in the current implmentation.
307  */
308 void endtls(void)
309 {
310         lprintf(7, "Ending SSL/TLS\n");
311
312         if (!CC->ssl) {
313                 CC->redirect_ssl = 0;
314                 return;
315         }
316         
317         SSL_shutdown(CC->ssl);
318         SSL_free(CC->ssl);
319         CC->ssl = NULL;
320         CC->redirect_ssl = 0;
321 }
322
323
324 /*
325  * ssl_lock() callback for OpenSSL mutex locks
326  */
327 void ssl_lock(int mode, int n, const char *file, int line)
328 {
329         if (mode & CRYPTO_LOCK)
330                 pthread_mutex_lock(SSLCritters[n]);
331         else
332                 pthread_mutex_unlock(SSLCritters[n]);
333 }
334 #endif /* HAVE_OPENSSL */