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