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