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