]> code.citadel.org Git - citadel.git/blob - citadel/serv_crypto.c
d757141568f2d3e2365eeb698b5aaf962481e861
[citadel.git] / citadel / serv_crypto.c
1 /* $Id$ */
2
3 #include <string.h>
4 #include <unistd.h>
5 #include <sys/stat.h>
6 #include <sys/types.h>
7 #include "sysdep.h"
8
9 #ifdef HAVE_OPENSSL
10 #include <openssl/ssl.h>
11 #include <openssl/err.h>
12 #include <openssl/rand.h>
13 #endif
14
15 #if TIME_WITH_SYS_TIME
16 # include <sys/time.h>
17 # include <time.h>
18 #else
19 # if HAVE_SYS_TIME_H
20 #  include <sys/time.h>
21 # else
22 #  include <time.h>
23 # endif
24 #endif
25
26 #ifdef HAVE_PTHREAD_H
27 #include <pthread.h>
28 #endif
29
30 #ifdef HAVE_SYS_SELECT_H
31 #include <sys/select.h>
32 #endif
33
34 #include <stdio.h>
35 #include "server.h"
36 #include "serv_crypto.h"
37 #include "sysdep_decls.h"
38 #include "serv_extensions.h"
39 #include "citadel.h"
40 #include "config.h"
41
42
43 #ifdef HAVE_OPENSSL
44 SSL_CTX *ssl_ctx;               /* SSL context */
45 pthread_mutex_t **SSLCritters;  /* Things needing locking */
46
47 static unsigned long id_callback(void)
48 {
49         return (unsigned long) pthread_self();
50 }
51
52  /*
53   * Set up the cert things on the server side. We do need both the
54   * private key (in key_file) and the cert (in cert_file).
55   * Both files may be identical.
56   *
57   * This function is taken from OpenSSL apps/s_cb.c
58   */
59
60 static int ctdl_install_certificate(SSL_CTX * ctx,
61                           const char *cert_file, const char *key_file)
62 {
63         if (cert_file != NULL) {
64                 if (SSL_CTX_use_certificate_file(ctx, cert_file,
65                                                  SSL_FILETYPE_PEM) <= 0) {
66                         lprintf(3, "unable to get certificate from '%s'",
67                                 cert_file);
68                         return (0);
69                 }
70                 if (key_file == NULL)
71                         key_file = cert_file;
72                 if (SSL_CTX_use_PrivateKey_file(ctx, key_file,
73                                                 SSL_FILETYPE_PEM) <= 0) {
74                         lprintf(3, "unable to get private key from '%s'",
75                                 key_file);
76                         return (0);
77                 }
78                 /* Now we know that a key and cert have been set against
79                  * the SSL context */
80                 if (!SSL_CTX_check_private_key(ctx)) {
81                         lprintf(3,
82                                 "Private key does not match the certificate public key");
83                         return (0);
84                 }
85         }
86         return (1);
87 }
88
89
90 void init_ssl(void)
91 {
92         SSL_METHOD *ssl_method;
93         DH *dh;
94         RSA *rsa=NULL;
95         X509_REQ *x = NULL;
96         EVP_PKEY *pk = NULL;
97         X509_NAME *name = NULL;
98         FILE *fp;
99
100         if (!access("/var/run/egd-pool", F_OK))
101                 RAND_egd("/var/run/egd-pool");
102
103         if (!RAND_status()) {
104                 lprintf(2,
105                         "PRNG not adequately seeded, won't do SSL/TLS\n");
106                 return;
107         }
108         SSLCritters =
109             mallok(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
110         if (!SSLCritters) {
111                 lprintf(1, "citserver: can't allocate memory!!\n");
112                 /* Nothing's been initialized, just die */
113                 exit(1);
114         } else {
115                 int a;
116
117                 for (a = 0; a < CRYPTO_num_locks(); a++) {
118                         SSLCritters[a] = mallok(sizeof(pthread_mutex_t));
119                         if (!SSLCritters[a]) {
120                                 lprintf(1,
121                                         "citserver: can't allocate memory!!\n");
122                                 /* Nothing's been initialized, just die */
123                                 exit(1);
124                         }
125                         pthread_mutex_init(SSLCritters[a], NULL);
126                 }
127         }
128
129         /*
130          * Initialize SSL transport layer
131          */
132         SSL_library_init();
133         SSL_load_error_strings();
134         ssl_method = SSLv23_server_method();
135         if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
136                 lprintf(2, "SSL_CTX_new failed: %s\n",
137                         ERR_reason_error_string(ERR_get_error()));
138                 return;
139         }
140         if (!(SSL_CTX_set_cipher_list(ssl_ctx, CIT_CIPHERS))) {
141                 lprintf(2, "SSL: No ciphers available\n");
142                 SSL_CTX_free(ssl_ctx);
143                 ssl_ctx = NULL;
144                 return;
145         }
146 #if 0
147 #if SSLEAY_VERSION_NUMBER >= 0x00906000L
148         SSL_CTX_set_mode(ssl_ctx, SSL_CTX_get_mode(ssl_ctx) |
149                          SSL_MODE_AUTO_RETRY);
150 #endif
151 #endif
152
153         CRYPTO_set_locking_callback(ssl_lock);
154         CRYPTO_set_id_callback(id_callback);
155
156         /* Load DH parameters into the context */
157         dh = DH_new();
158         if (!dh) {
159                 lprintf(2, "init_ssl() can't allocate a DH object: %s\n",
160                         ERR_reason_error_string(ERR_get_error()));
161                 SSL_CTX_free(ssl_ctx);
162                 ssl_ctx = NULL;
163                 return;
164         }
165         if (!(BN_hex2bn(&(dh->p), DH_P))) {
166                 lprintf(2, "init_ssl() can't assign DH_P: %s\n",
167                         ERR_reason_error_string(ERR_get_error()));
168                 SSL_CTX_free(ssl_ctx);
169                 ssl_ctx = NULL;
170                 return;
171         }
172         if (!(BN_hex2bn(&(dh->g), DH_G))) {
173                 lprintf(2, "init_ssl() can't assign DH_G: %s\n",
174                         ERR_reason_error_string(ERR_get_error()));
175                 SSL_CTX_free(ssl_ctx);
176                 ssl_ctx = NULL;
177                 return;
178         }
179         dh->length = DH_L;
180         SSL_CTX_set_tmp_dh(ssl_ctx, dh);
181         DH_free(dh);
182
183         /* Get our certificates in order.
184          * First, create the key/cert directory if it's not there already...
185          */
186         mkdir(CTDL_CRYPTO_DIR, 0700);
187
188         /*
189          * Generate a key pair if we don't have one.
190          */
191         if (access(CTDL_KEY_PATH, R_OK) != 0) {
192                 lprintf(3, "Generating RSA key pair.\n");
193                 rsa = RSA_generate_key(1024,    /* modulus size */
194                                         65537,  /* exponent */
195                                         NULL,   /* no callback */
196                                         NULL);  /* no callback */
197                 if (rsa == NULL) {
198                         lprintf(2, "Key generation failed: %s\n",
199                                 ERR_reason_error_string(ERR_get_error()));
200                 }
201                 if (rsa != NULL) {
202                         fp = fopen(CTDL_KEY_PATH, "w");
203                         if (fp != NULL) {
204                                 chmod(CTDL_KEY_PATH, 0600);
205                                 if (PEM_write_RSAPrivateKey(fp, /* the file */
206                                                         rsa,    /* the key */
207                                                         NULL,   /* no enc */
208                                                         NULL,   /* no passphr */
209                                                         0,      /* no passphr */
210                                                         NULL,   /* no callbk */
211                                                         NULL    /* no callbk */
212                                 ) != 1) {
213                                         lprintf(2, "Cannot write key: %s\n",
214                                                 ERR_reason_error_string(ERR_get_error()));
215                                         unlink(CTDL_KEY_PATH);
216                                 }
217                                 fclose(fp);
218                         }
219                         RSA_free(rsa);
220                 }
221         }
222
223         /*
224          * Generate a CSR if we don't have one.
225          */
226         if (access(CTDL_CSR_PATH, R_OK) != 0) {
227                 lprintf(3, "Generating a certificate signing request.\n");
228
229                 /*
230                  * Read our key from the file.  No, we don't just keep this
231                  * in memory from the above key-generation function, because
232                  * there is the possibility that the key was already on disk
233                  * and we didn't just generate it now.
234                  */
235                 fp = fopen(CTDL_KEY_PATH, "r");
236                 if (fp) {
237                         rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
238                         fclose(fp);
239                 }
240
241                 if (rsa) {
242
243                         /* Create a public key from the private key */
244                         if (pk=EVP_PKEY_new(), pk != NULL) {
245                                 EVP_PKEY_assign_RSA(pk, rsa);
246                                 if (x = X509_REQ_new(), x != NULL) {
247
248                                         /* Set the public key */
249                                         X509_REQ_set_pubkey(x, pk);
250                                         X509_REQ_set_version(x, 0L);
251
252                                         name = X509_REQ_get_subject_name(x);
253
254                                         /* Tell it who we are */
255
256                                         /*
257                                         X509_NAME_add_entry_by_txt(name, "C",
258                                                 MBSTRING_ASC, "US", -1, -1, 0);
259
260                                         X509_NAME_add_entry_by_txt(name, "ST",
261                                                 MBSTRING_ASC, "New York", -1, -1, 0);
262
263                                         X509_NAME_add_entry_by_txt(name, "L",
264                                                 MBSTRING_ASC, "Mount Kisco", -1, -1, 0);
265                                         */
266
267                                         X509_NAME_add_entry_by_txt(name, "O",
268                                                 MBSTRING_ASC, config.c_humannode, -1, -1, 0);
269
270                                         X509_NAME_add_entry_by_txt(name, "OU",
271                                                 MBSTRING_ASC, "Citadel server", -1, -1, 0);
272
273                                         X509_NAME_add_entry_by_txt(name, "CN",
274                                                 MBSTRING_ASC, config.c_fqdn, -1, -1, 0);
275                                 
276                                         X509_REQ_set_subject_name(x, name);
277
278                                         /* Sign the CSR */
279                                         if (!X509_REQ_sign(x, pk, EVP_md5())) {
280                                                 lprintf(3, "X509_REQ_sign(): error\n");
281                                         }
282                                         else {
283                                                 /* Write it to disk. */ 
284                                                 fp = fopen(CTDL_CSR_PATH, "w");
285                                                 if (fp != NULL) {
286                                                         chmod(CTDL_CSR_PATH, 0600);
287                                                         PEM_write_X509_REQ(fp, x);
288                                                         fclose(fp);
289                                                 }
290                                         }
291
292                                         X509_REQ_free(x);
293                                 }
294                         }
295
296                         RSA_free(rsa);
297                 }
298
299                 else {
300                         lprintf(3, "Unable to read private key.\n");
301                 }
302         }
303
304
305
306         /*
307          * Generate a self-signed certificate if we don't have one.
308          */
309         if (access(CTDL_CER_PATH, R_OK) != 0) {
310                 lprintf(3, "Generating a self-signed certificate.\n");
311
312
313                 /* FIXME ... do it */
314         }
315
316
317         /*
318          * Now try to bind to the key and certificate.
319          */
320         if (ctdl_install_certificate(ssl_ctx,
321                         CTDL_CER_PATH,
322                         CTDL_KEY_PATH) != 1)
323         {
324                 lprintf(2, "Cannot install certificate: %s\n",
325                                 ERR_reason_error_string(ERR_get_error()));
326         }
327
328         /* Finally let the server know we're here */
329         CtdlRegisterProtoHook(cmd_stls, "STLS", "Start SSL/TLS session");
330         CtdlRegisterProtoHook(cmd_gtls, "GTLS",
331                               "Get SSL/TLS session status");
332         CtdlRegisterSessionHook(endtls, EVT_STOP);
333 }
334
335
336 /*
337  * client_write_ssl() Send binary data to the client encrypted.
338  */
339 void client_write_ssl(char *buf, int nbytes)
340 {
341         int retval;
342         int nremain;
343         char junk[1];
344
345         nremain = nbytes;
346
347         while (nremain > 0) {
348                 if (SSL_want_write(CC->ssl)) {
349                         if ((SSL_read(CC->ssl, junk, 0)) < 1) {
350                                 lprintf(9, "SSL_read in client_write:\n");
351                                 ERR_print_errors_fp(stderr);
352                         }
353                 }
354                 retval =
355                     SSL_write(CC->ssl, &buf[nbytes - nremain], nremain);
356                 if (retval < 1) {
357                         long errval;
358
359                         errval = SSL_get_error(CC->ssl, retval);
360                         if (errval == SSL_ERROR_WANT_READ ||
361                             errval == SSL_ERROR_WANT_WRITE) {
362                                 sleep(1);
363                                 continue;
364                         }
365                         lprintf(9, "SSL_write got error %ld, ret %d\n", errval, retval);
366                         if (retval == -1)
367                                 lprintf(9, "errno is %d\n", errno);
368                         endtls();
369                         client_write(&buf[nbytes - nremain], nremain);
370                         return;
371                 }
372                 nremain -= retval;
373         }
374 }
375
376
377 /*
378  * client_read_ssl() - read data from the encrypted layer.
379  */
380 int client_read_ssl(char *buf, int bytes, int timeout)
381 {
382 #if 0
383         fd_set rfds;
384         struct timeval tv;
385         int retval;
386         int s;
387 #endif
388         int len, rlen;
389         char junk[1];
390
391         len = 0;
392         while (len < bytes) {
393 #if 0
394                 /*
395                  * This code is disabled because we don't need it when
396                  * using blocking reads (which we are). -IO
397                  */
398                 FD_ZERO(&rfds);
399                 s = BIO_get_fd(CC->ssl->rbio, NULL);
400                 FD_SET(s, &rfds);
401                 tv.tv_sec = timeout;
402                 tv.tv_usec = 0;
403
404                 retval = select(s + 1, &rfds, NULL, NULL, &tv);
405
406                 if (FD_ISSET(s, &rfds) == 0) {
407                         return (0);
408                 }
409
410 #endif
411                 if (SSL_want_read(CC->ssl)) {
412                         if ((SSL_write(CC->ssl, junk, 0)) < 1) {
413                                 lprintf(9, "SSL_write in client_read:\n");
414                                 ERR_print_errors_fp(stderr);
415                         }
416                 }
417                 rlen = SSL_read(CC->ssl, &buf[len], bytes - len);
418                 if (rlen < 1) {
419                         long errval;
420
421                         errval = SSL_get_error(CC->ssl, rlen);
422                         if (errval == SSL_ERROR_WANT_READ ||
423                             errval == SSL_ERROR_WANT_WRITE) {
424                                 sleep(1);
425                                 continue;
426                         }
427                         lprintf(9, "SSL_read got error %ld\n", errval);
428                         endtls();
429                         return (client_read_to
430                                 (&buf[len], bytes - len, timeout));
431                 }
432                 len += rlen;
433         }
434         return (1);
435 }
436
437
438 /*
439  * CtdlStartTLS() starts SSL/TLS encryption for the current session.  It
440  * must be supplied with pre-generated strings for responses of "ok," "no
441  * support for TLS," and "error" so that we can use this in any protocol.
442  */
443 void CtdlStartTLS(char *ok_response, char *nosup_response,
444                         char *error_response) {
445
446         int retval, bits, alg_bits;
447
448         if (!ssl_ctx) {
449                 cprintf("%s", nosup_response);
450                 return;
451         }
452         if (!(CC->ssl = SSL_new(ssl_ctx))) {
453                 lprintf(2, "SSL_new failed: %s\n",
454                                 ERR_reason_error_string(ERR_get_error()));
455                 cprintf("%s", error_response);
456                 return;
457         }
458         if (!(SSL_set_fd(CC->ssl, CC->client_socket))) {
459                 lprintf(2, "SSL_set_fd failed: %s\n",
460                         ERR_reason_error_string(ERR_get_error()));
461                 SSL_free(CC->ssl);
462                 CC->ssl = NULL;
463                 cprintf("%s", error_response);
464                 return;
465         }
466         cprintf("%s", ok_response);
467         retval = SSL_accept(CC->ssl);
468         if (retval < 1) {
469                 /*
470                  * Can't notify the client of an error here; they will
471                  * discover the problem at the SSL layer and should
472                  * revert to unencrypted communications.
473                  */
474                 long errval;
475
476                 errval = SSL_get_error(CC->ssl, retval);
477                 lprintf(2, "SSL_accept failed: %s\n",
478                         ERR_reason_error_string(ERR_get_error()));
479                 SSL_free(CC->ssl);
480                 CC->ssl = NULL;
481                 return;
482         }
483         BIO_set_close(CC->ssl->rbio, BIO_NOCLOSE);
484         bits =
485             SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl),
486                                 &alg_bits);
487         lprintf(3, "SSL/TLS using %s on %s (%d of %d bits)\n",
488                 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
489                 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
490                 bits, alg_bits);
491         CC->redirect_ssl = 1;
492 }
493
494
495 /*
496  * cmd_stls() starts SSL/TLS encryption for the current session
497  */
498 void cmd_stls(char *params)
499 {
500         char ok_response[SIZ];
501         char nosup_response[SIZ];
502         char error_response[SIZ];
503
504         sprintf(ok_response,
505                 "%d Begin TLS negotiation now\n",
506                 CIT_OK);
507         sprintf(nosup_response,
508                 "%d TLS not supported here\n",
509                 ERROR + CMD_NOT_SUPPORTED);
510         sprintf(error_response,
511                 "%d TLS negotiation error\n",
512                 ERROR + INTERNAL_ERROR);
513
514         CtdlStartTLS(ok_response, nosup_response, error_response);
515 }
516
517
518 /*
519  * cmd_gtls() returns status info about the TLS connection
520  */
521 void cmd_gtls(char *params)
522 {
523         int bits, alg_bits;
524
525         if (!CC->ssl || !CC->redirect_ssl) {
526                 cprintf("%d Session is not encrypted.\n", ERROR);
527                 return;
528         }
529         bits =
530             SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl),
531                                 &alg_bits);
532         cprintf("%d %s|%s|%d|%d\n", CIT_OK,
533                 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
534                 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
535                 alg_bits, bits);
536 }
537
538
539 /*
540  * endtls() shuts down the TLS connection
541  *
542  * WARNING:  This may make your session vulnerable to a known plaintext
543  * attack in the current implmentation.
544  */
545 void endtls(void)
546 {
547         lprintf(7, "Ending SSL/TLS\n");
548
549         if (!CC->ssl) {
550                 CC->redirect_ssl = 0;
551                 return;
552         }
553
554         SSL_shutdown(CC->ssl);
555         SSL_free(CC->ssl);
556         CC->ssl = NULL;
557         CC->redirect_ssl = 0;
558 }
559
560
561 /*
562  * ssl_lock() callback for OpenSSL mutex locks
563  */
564 void ssl_lock(int mode, int n, const char *file, int line)
565 {
566         if (mode & CRYPTO_LOCK)
567                 pthread_mutex_lock(SSLCritters[n]);
568         else
569                 pthread_mutex_unlock(SSLCritters[n]);
570 }
571 #endif                          /* HAVE_OPENSSL */