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