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