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