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