* Replaced ctdl_install_certificate() with convenience functions found
[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                                         X509_set_issuer_name(cer, req->req_info->subject);
281                                         X509_set_subject_name(cer, req->req_info->subject);
282                                         X509_gmtime_adj(X509_get_notBefore(cer),0);
283                                         X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
284                                         req_pkey = X509_REQ_get_pubkey(req);
285                                         X509_set_pubkey(cer, req_pkey);
286                                         EVP_PKEY_free(req_pkey);
287                                         
288                                         /* Sign the cert */
289                                         if (!X509_sign(cer, pk, EVP_md5())) {
290                                                 lprintf(3, "X509_sign(): error\n");
291                                         }
292                                         else {
293                                                 /* Write it to disk. */ 
294                                                 fp = fopen(CTDL_CER_PATH, "w");
295                                                 if (fp != NULL) {
296                                                         chmod(CTDL_CER_PATH, 0600);
297                                                         PEM_write_X509(fp, cer);
298                                                         fclose(fp);
299                                                 }
300                                         }
301                                         X509_free(cer);
302                                 }
303                         }
304
305                         RSA_free(rsa);
306                 }
307         }
308
309
310         /*
311          * Now try to bind to the key and certificate.
312          */
313         SSL_CTX_use_certificate_file(ssl_ctx, CTDL_CER_PATH, SSL_FILETYPE_PEM);
314         SSL_CTX_use_PrivateKey_file(ssl_ctx, CTDL_KEY_PATH, SSL_FILETYPE_PEM);
315         if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
316                 lprintf(3, "Cannot install certificate: %s\n",
317                                 ERR_reason_error_string(ERR_get_error()));
318         }
319         
320 }
321
322
323 /*
324  * starttls() starts SSL/TLS encryption for the current session.
325  */
326 int starttls(int sock) {
327         int retval, bits, alg_bits;
328         SSL *newssl;
329
330         pthread_setspecific(ThreadSSL, NULL);
331
332         if (!ssl_ctx) {
333                 return(1);
334         }
335         if (!(newssl = SSL_new(ssl_ctx))) {
336                 lprintf(3, "SSL_new failed: %s\n",
337                                 ERR_reason_error_string(ERR_get_error()));
338                 return(2);
339         }
340         if (!(SSL_set_fd(newssl, sock))) {
341                 lprintf(3, "SSL_set_fd failed: %s\n",
342                         ERR_reason_error_string(ERR_get_error()));
343                 SSL_free(newssl);
344                 return(3);
345         }
346         retval = SSL_accept(newssl);
347         if (retval < 1) {
348                 /*
349                  * Can't notify the client of an error here; they will
350                  * discover the problem at the SSL layer and should
351                  * revert to unencrypted communications.
352                  */
353                 long errval;
354
355                 errval = SSL_get_error(newssl, retval);
356                 lprintf(3, "SSL_accept failed: %s\n",
357                         ERR_reason_error_string(ERR_get_error()));
358                 SSL_free(newssl);
359                 newssl = NULL;
360                 return(4);
361         }
362         BIO_set_close(newssl->rbio, BIO_NOCLOSE);
363         bits =
364             SSL_CIPHER_get_bits(SSL_get_current_cipher(newssl),
365                                 &alg_bits);
366         lprintf(5, "SSL/TLS using %s on %s (%d of %d bits)\n",
367                 SSL_CIPHER_get_name(SSL_get_current_cipher(newssl)),
368                 SSL_CIPHER_get_version(SSL_get_current_cipher(newssl)),
369                 bits, alg_bits);
370
371         pthread_setspecific(ThreadSSL, newssl);
372         return(0);
373 }
374
375
376
377 /*
378  * endtls() shuts down the TLS connection
379  *
380  * WARNING:  This may make your session vulnerable to a known plaintext
381  * attack in the current implmentation.
382  */
383 void endtls(void)
384 {
385         lprintf(5, "Ending SSL/TLS\n");
386         SSL_shutdown(THREADSSL);
387         SSL_free(THREADSSL);
388         pthread_setspecific(ThreadSSL, NULL);
389 }
390
391
392 /*
393  * ssl_lock() callback for OpenSSL mutex locks
394  */
395 void ssl_lock(int mode, int n, const char *file, int line)
396 {
397         if (mode & CRYPTO_LOCK)
398                 pthread_mutex_lock(SSLCritters[n]);
399         else
400                 pthread_mutex_unlock(SSLCritters[n]);
401 }
402
403 /*
404  * client_write_ssl() Send binary data to the client encrypted.
405  */
406 void client_write_ssl(char *buf, int nbytes)
407 {
408         int retval;
409         int nremain;
410         char junk[1];
411
412         nremain = nbytes;
413
414         while (nremain > 0) {
415                 if (SSL_want_write(THREADSSL)) {
416                         if ((SSL_read(THREADSSL, junk, 0)) < 1) {
417                                 lprintf(9, "SSL_read in client_write: %s\n", ERR_reason_error_string(ERR_get_error()));
418                         }
419                 }
420                 retval =
421                     SSL_write(THREADSSL, &buf[nbytes - nremain], nremain);
422                 if (retval < 1) {
423                         long errval;
424
425                         errval = SSL_get_error(THREADSSL, retval);
426                         if (errval == SSL_ERROR_WANT_READ ||
427                             errval == SSL_ERROR_WANT_WRITE) {
428                                 sleep(1);
429                                 continue;
430                         }
431                         lprintf(9, "SSL_write got error %ld, ret %d\n", errval, retval);
432                         if (retval == -1)
433                                 lprintf(9, "errno is %d\n", errno);
434                         endtls();
435                         client_write(&buf[nbytes - nremain], nremain);
436                         return;
437                 }
438                 nremain -= retval;
439         }
440 }
441
442
443 /*
444  * client_read_ssl() - read data from the encrypted layer.
445  */
446 int client_read_ssl(char *buf, int bytes, int timeout)
447 {
448 #if 0
449         fd_set rfds;
450         struct timeval tv;
451         int retval;
452         int s;
453 #endif
454         int len, rlen;
455         char junk[1];
456
457         len = 0;
458         while (len < bytes) {
459 #if 0
460                 /*
461                  * This code is disabled because we don't need it when
462                  * using blocking reads (which we are). -IO
463                  */
464                 FD_ZERO(&rfds);
465                 s = BIO_get_fd(THREADSSL->rbio, NULL);
466                 FD_SET(s, &rfds);
467                 tv.tv_sec = timeout;
468                 tv.tv_usec = 0;
469
470                 retval = select(s + 1, &rfds, NULL, NULL, &tv);
471
472                 if (FD_ISSET(s, &rfds) == 0) {
473                         return (0);
474                 }
475
476 #endif
477                 if (SSL_want_read(THREADSSL)) {
478                         if ((SSL_write(THREADSSL, junk, 0)) < 1) {
479                                 lprintf(9, "SSL_write in client_read: %s\n", ERR_reason_error_string(ERR_get_error()));
480                         }
481                 }
482                 rlen = SSL_read(THREADSSL, &buf[len], bytes - len);
483                 if (rlen < 1) {
484                         long errval;
485
486                         errval = SSL_get_error(THREADSSL, rlen);
487                         if (errval == SSL_ERROR_WANT_READ ||
488                             errval == SSL_ERROR_WANT_WRITE) {
489                                 sleep(1);
490                                 continue;
491                         }
492                         lprintf(9, "SSL_read got error %ld\n", errval);
493                         endtls();
494                         return (client_read_to
495                                 (WC->http_sock, &buf[len], bytes - len, timeout));
496                 }
497                 len += rlen;
498         }
499         return (1);
500 }
501
502
503 #endif                          /* HAVE_OPENSSL */