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