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