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