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