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