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