]> code.citadel.org Git - citadel.git/blob - citadel/serv_crypto.c
* Replace ctdl_install_certificate() with convenience functions found
[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                                         X509_set_issuer_name(cer, req->req_info->subject);
304                                         X509_set_subject_name(cer, req->req_info->subject);
305                                         X509_gmtime_adj(X509_get_notBefore(cer),0);
306                                         X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
307                                         req_pkey = X509_REQ_get_pubkey(req);
308                                         X509_set_pubkey(cer, req_pkey);
309                                         EVP_PKEY_free(req_pkey);
310                                         
311                                         /* Sign the cert */
312                                         if (!X509_sign(cer, pk, EVP_md5())) {
313                                                 lprintf(CTDL_CRIT, "X509_sign(): error\n");
314                                         }
315                                         else {
316                                                 /* Write it to disk. */ 
317                                                 fp = fopen(CTDL_CER_PATH, "w");
318                                                 if (fp != NULL) {
319                                                         chmod(CTDL_CER_PATH, 0600);
320                                                         PEM_write_X509(fp, cer);
321                                                         fclose(fp);
322                                                 }
323                                         }
324                                         X509_free(cer);
325                                 }
326                         }
327
328                         RSA_free(rsa);
329                 }
330         }
331
332
333         /*
334          * Now try to bind to the key and certificate.
335          */
336         SSL_CTX_use_certificate_file(ssl_ctx, CTDL_CER_PATH, SSL_FILETYPE_PEM);
337         SSL_CTX_use_PrivateKey_file(ssl_ctx, CTDL_KEY_PATH, SSL_FILETYPE_PEM);
338         if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
339                 lprintf(CTDL_CRIT, "Cannot install certificate: %s\n",
340                                 ERR_reason_error_string(ERR_get_error()));
341         }
342
343         /* Finally let the server know we're here */
344         CtdlRegisterProtoHook(cmd_stls, "STLS", "Start SSL/TLS session");
345         CtdlRegisterProtoHook(cmd_gtls, "GTLS",
346                               "Get SSL/TLS session status");
347         CtdlRegisterSessionHook(endtls, EVT_STOP);
348 }
349
350
351 /*
352  * client_write_ssl() Send binary data to the client encrypted.
353  */
354 void client_write_ssl(char *buf, int nbytes)
355 {
356         int retval;
357         int nremain;
358         char junk[1];
359
360         nremain = nbytes;
361
362         while (nremain > 0) {
363                 if (SSL_want_write(CC->ssl)) {
364                         if ((SSL_read(CC->ssl, junk, 0)) < 1) {
365                                 lprintf(CTDL_DEBUG, "SSL_read in client_write: %s\n", ERR_reason_error_string(ERR_get_error()));
366                         }
367                 }
368                 retval =
369                     SSL_write(CC->ssl, &buf[nbytes - nremain], nremain);
370                 if (retval < 1) {
371                         long errval;
372
373                         errval = SSL_get_error(CC->ssl, retval);
374                         if (errval == SSL_ERROR_WANT_READ ||
375                             errval == SSL_ERROR_WANT_WRITE) {
376                                 sleep(1);
377                                 continue;
378                         }
379                         lprintf(CTDL_DEBUG, "SSL_write got error %ld, ret %d\n", errval, retval);
380                         if (retval == -1)
381                                 lprintf(CTDL_DEBUG, "errno is %d\n", errno);
382                         endtls();
383                         client_write(&buf[nbytes - nremain], nremain);
384                         return;
385                 }
386                 nremain -= retval;
387         }
388 }
389
390
391 /*
392  * client_read_ssl() - read data from the encrypted layer.
393  */
394 int client_read_ssl(char *buf, int bytes, int timeout)
395 {
396 #if 0
397         fd_set rfds;
398         struct timeval tv;
399         int retval;
400         int s;
401 #endif
402         int len, rlen;
403         char junk[1];
404
405         len = 0;
406         while (len < bytes) {
407 #if 0
408                 /*
409                  * This code is disabled because we don't need it when
410                  * using blocking reads (which we are). -IO
411                  */
412                 FD_ZERO(&rfds);
413                 s = BIO_get_fd(CC->ssl->rbio, NULL);
414                 FD_SET(s, &rfds);
415                 tv.tv_sec = timeout;
416                 tv.tv_usec = 0;
417
418                 retval = select(s + 1, &rfds, NULL, NULL, &tv);
419
420                 if (FD_ISSET(s, &rfds) == 0) {
421                         return (0);
422                 }
423
424 #endif
425                 if (SSL_want_read(CC->ssl)) {
426                         if ((SSL_write(CC->ssl, junk, 0)) < 1) {
427                                 lprintf(CTDL_DEBUG, "SSL_write in client_read: %s\n", ERR_reason_error_string(ERR_get_error()));
428                         }
429                 }
430                 rlen = SSL_read(CC->ssl, &buf[len], bytes - len);
431                 if (rlen < 1) {
432                         long errval;
433
434                         errval = SSL_get_error(CC->ssl, rlen);
435                         if (errval == SSL_ERROR_WANT_READ ||
436                             errval == SSL_ERROR_WANT_WRITE) {
437                                 sleep(1);
438                                 continue;
439                         }
440                         lprintf(CTDL_DEBUG, "SSL_read got error %ld\n", errval);
441                         endtls();
442                         return (client_read_to
443                                 (&buf[len], bytes - len, timeout));
444                 }
445                 len += rlen;
446         }
447         return (1);
448 }
449
450
451 /*
452  * CtdlStartTLS() starts SSL/TLS encryption for the current session.  It
453  * must be supplied with pre-generated strings for responses of "ok," "no
454  * support for TLS," and "error" so that we can use this in any protocol.
455  */
456 void CtdlStartTLS(char *ok_response, char *nosup_response,
457                         char *error_response) {
458
459         int retval, bits, alg_bits;
460
461         if (!ssl_ctx) {
462                 cprintf("%s", nosup_response);
463                 return;
464         }
465         if (!(CC->ssl = SSL_new(ssl_ctx))) {
466                 lprintf(CTDL_CRIT, "SSL_new failed: %s\n",
467                                 ERR_reason_error_string(ERR_get_error()));
468                 cprintf("%s", error_response);
469                 return;
470         }
471         if (!(SSL_set_fd(CC->ssl, CC->client_socket))) {
472                 lprintf(CTDL_CRIT, "SSL_set_fd failed: %s\n",
473                         ERR_reason_error_string(ERR_get_error()));
474                 SSL_free(CC->ssl);
475                 CC->ssl = NULL;
476                 cprintf("%s", error_response);
477                 return;
478         }
479         cprintf("%s", ok_response);
480         retval = SSL_accept(CC->ssl);
481         if (retval < 1) {
482                 /*
483                  * Can't notify the client of an error here; they will
484                  * discover the problem at the SSL layer and should
485                  * revert to unencrypted communications.
486                  */
487                 long errval;
488
489                 errval = SSL_get_error(CC->ssl, retval);
490                 lprintf(CTDL_CRIT, "SSL_accept failed: %s\n",
491                         ERR_reason_error_string(ERR_get_error()));
492                 SSL_free(CC->ssl);
493                 CC->ssl = NULL;
494                 return;
495         }
496         BIO_set_close(CC->ssl->rbio, BIO_NOCLOSE);
497         bits =
498             SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl),
499                                 &alg_bits);
500         lprintf(CTDL_INFO, "SSL/TLS using %s on %s (%d of %d bits)\n",
501                 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
502                 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
503                 bits, alg_bits);
504         CC->redirect_ssl = 1;
505 }
506
507
508 /*
509  * cmd_stls() starts SSL/TLS encryption for the current session
510  */
511 void cmd_stls(char *params)
512 {
513         char ok_response[SIZ];
514         char nosup_response[SIZ];
515         char error_response[SIZ];
516
517         sprintf(ok_response,
518                 "%d Begin TLS negotiation now\n",
519                 CIT_OK);
520         sprintf(nosup_response,
521                 "%d TLS not supported here\n",
522                 ERROR + CMD_NOT_SUPPORTED);
523         sprintf(error_response,
524                 "%d TLS negotiation error\n",
525                 ERROR + INTERNAL_ERROR);
526
527         CtdlStartTLS(ok_response, nosup_response, error_response);
528 }
529
530
531 /*
532  * cmd_gtls() returns status info about the TLS connection
533  */
534 void cmd_gtls(char *params)
535 {
536         int bits, alg_bits;
537
538         if (!CC->ssl || !CC->redirect_ssl) {
539                 cprintf("%d Session is not encrypted.\n", ERROR);
540                 return;
541         }
542         bits =
543             SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl),
544                                 &alg_bits);
545         cprintf("%d %s|%s|%d|%d\n", CIT_OK,
546                 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
547                 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
548                 alg_bits, bits);
549 }
550
551
552 /*
553  * endtls() shuts down the TLS connection
554  *
555  * WARNING:  This may make your session vulnerable to a known plaintext
556  * attack in the current implmentation.
557  */
558 void endtls(void)
559 {
560         if (!CC->ssl) {
561                 CC->redirect_ssl = 0;
562                 return;
563         }
564
565         lprintf(CTDL_INFO, "Ending SSL/TLS\n");
566         SSL_shutdown(CC->ssl);
567         SSL_free(CC->ssl);
568         CC->ssl = NULL;
569         CC->redirect_ssl = 0;
570 }
571
572
573 /*
574  * ssl_lock() callback for OpenSSL mutex locks
575  */
576 void ssl_lock(int mode, int n, const char *file, int line)
577 {
578         if (mode & CRYPTO_LOCK)
579                 pthread_mutex_lock(SSLCritters[n]);
580         else
581                 pthread_mutex_unlock(SSLCritters[n]);
582 }
583 #endif                          /* HAVE_OPENSSL */