* CN...
[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                                         const char *env;
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                                         env = getenv("O");
215                                         if (env == NULL)
216                                                 env = "Organization name",
217
218                                         X509_NAME_add_entry_by_txt(
219                                                 name, "O",
220                                                 MBSTRING_ASC, 
221                                                 (unsigned char*)env, 
222                                                 -1, -1, 0
223                                         );
224
225                                         env = getenv("OU");
226                                         if (env == NULL)
227                                                 env = "Citadel server";
228
229                                         X509_NAME_add_entry_by_txt(
230                                                 name, "OU",
231                                                 MBSTRING_ASC, 
232                                                 (unsigned char*)env, 
233                                                 -1, -1, 0
234                                         );
235
236                                         env = getenv("CN");
237                                         if (env == NULL)
238                                                 env = "*";
239
240                                         X509_NAME_add_entry_by_txt(
241                                                 name, "CN",
242                                                 MBSTRING_ASC, 
243                                                 (unsigned char*)env,
244                                                 -1, -1, 0
245                                         );
246                                 
247                                         X509_REQ_set_subject_name(req, name);
248
249                                         /* Sign the CSR */
250                                         if (!X509_REQ_sign(req, pk, EVP_md5())) {
251                                                 lprintf(3, "X509_REQ_sign(): error\n");
252                                         }
253                                         else {
254                                                 /* Write it to disk. */ 
255                                                 fp = fopen(CTDL_CSR_PATH, "w");
256                                                 if (fp != NULL) {
257                                                         chmod(CTDL_CSR_PATH, 0600);
258                                                         PEM_write_X509_REQ(fp, req);
259                                                         fclose(fp);
260                                                 }
261                                                 else {
262                                                         lprintf(3, "Cannot write key: %s\n", CTDL_CSR_PATH);
263                                                         ShutDownWebcit();
264                                                         exit(0);
265                                                 }
266                                         }
267
268                                         X509_REQ_free(req);
269                                 }
270                         }
271
272                         RSA_free(rsa);
273                 }
274
275                 else {
276                         lprintf(3, "Unable to read private key.\n");
277                 }
278         }
279
280
281
282         /*
283          * Generate a self-signed certificate if we don't have one.
284          */
285         if (access(CTDL_CER_PATH, R_OK) != 0) {
286                 lprintf(5, "Generating a self-signed certificate.\n");
287
288                 /* Same deal as before: always read the key from disk because
289                  * it may or may not have just been generated.
290                  */
291                 fp = fopen(CTDL_KEY_PATH, "r");
292                 if (fp) {
293                         rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
294                         fclose(fp);
295                 }
296
297                 /* This also holds true for the CSR. */
298                 req = NULL;
299                 cer = NULL;
300                 pk = NULL;
301                 if (rsa) {
302                         if (pk=EVP_PKEY_new(), pk != NULL) {
303                                 EVP_PKEY_assign_RSA(pk, rsa);
304                         }
305
306                         fp = fopen(CTDL_CSR_PATH, "r");
307                         if (fp) {
308                                 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
309                                 fclose(fp);
310                         }
311
312                         if (req) {
313                                 if (cer = X509_new(), cer != NULL) {
314
315                                         ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
316                                         X509_set_issuer_name(cer, req->req_info->subject);
317                                         X509_set_subject_name(cer, req->req_info->subject);
318                                         X509_gmtime_adj(X509_get_notBefore(cer), 0);
319                                         X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
320
321                                         req_pkey = X509_REQ_get_pubkey(req);
322                                         X509_set_pubkey(cer, req_pkey);
323                                         EVP_PKEY_free(req_pkey);
324                                         
325                                         /* Sign the cert */
326                                         if (!X509_sign(cer, pk, EVP_md5())) {
327                                                 lprintf(3, "X509_sign(): error\n");
328                                         }
329                                         else {
330                                                 /* Write it to disk. */ 
331                                                 fp = fopen(CTDL_CER_PATH, "w");
332                                                 if (fp != NULL) {
333                                                         chmod(CTDL_CER_PATH, 0600);
334                                                         PEM_write_X509(fp, cer);
335                                                         fclose(fp);
336                                                 }
337                                                 else {
338                                                         lprintf(3, "Cannot write key: %s\n", CTDL_CER_PATH);
339                                                         ShutDownWebcit();
340                                                         exit(0);
341                                                 }
342                                         }
343                                         X509_free(cer);
344                                 }
345                         }
346
347                         RSA_free(rsa);
348                 }
349         }
350
351         /*
352          * Now try to bind to the key and certificate.
353          * Note that we use SSL_CTX_use_certificate_chain_file() which allows
354          * the certificate file to contain intermediate certificates.
355          */
356         SSL_CTX_use_certificate_chain_file(ssl_ctx, CTDL_CER_PATH);
357         SSL_CTX_use_PrivateKey_file(ssl_ctx, CTDL_KEY_PATH, SSL_FILETYPE_PEM);
358         if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
359                 lprintf(3, "Cannot install certificate: %s\n",
360                                 ERR_reason_error_string(ERR_get_error()));
361         }
362         
363 }
364
365
366 /*
367  * starts SSL/TLS encryption for the current session.
368  */
369 int starttls(int sock) {
370         int retval, bits, alg_bits, r;
371         SSL *newssl;
372
373         pthread_setspecific(ThreadSSL, NULL);
374
375         if (!ssl_ctx) {
376                 return(1);
377         }
378         if (!(newssl = SSL_new(ssl_ctx))) {
379                 lprintf(3, "SSL_new failed: %s\n", ERR_reason_error_string(ERR_get_error()));
380                 return(2);
381         }
382         if (!(SSL_set_fd(newssl, sock))) {
383                 lprintf(3, "SSL_set_fd failed: %s\n", ERR_reason_error_string(ERR_get_error()));
384                 SSL_free(newssl);
385                 return(3);
386         }
387         retval = SSL_accept(newssl);
388         if (retval < 1) {
389                 /*
390                  * Can't notify the client of an error here; they will
391                  * discover the problem at the SSL layer and should
392                  * revert to unencrypted communications.
393                  */
394                 long errval;
395                 const char *ssl_error_reason = NULL;
396
397                 errval = SSL_get_error(newssl, retval);
398                 ssl_error_reason = ERR_reason_error_string(ERR_get_error());
399                 if (ssl_error_reason == NULL) {
400                         lprintf(3, "SSL_accept failed: errval=%i, retval=%i %s\n", errval, retval, strerror(errval));
401                 }
402                 else {
403                         lprintf(3, "SSL_accept failed: %s\n", ssl_error_reason);
404                 }
405                 sleeeeeeeeeep(1);
406                 retval = SSL_accept(newssl);
407         }
408         if (retval < 1) {
409                 long errval;
410                 const char *ssl_error_reason = NULL;
411
412                 errval = SSL_get_error(newssl, retval);
413                 ssl_error_reason = ERR_reason_error_string(ERR_get_error());
414                 if (ssl_error_reason == NULL) {
415                         lprintf(3, "SSL_accept failed: errval=%i, retval=%i (%s)\n", errval, retval, strerror(errval));
416                 }
417                 else {
418                         lprintf(3, "SSL_accept failed: %s\n", ssl_error_reason);
419                 }
420                 SSL_free(newssl);
421                 newssl = NULL;
422                 return(4);
423         }
424         else {
425                 lprintf(15, "SSL_accept success\n");
426         }
427         r = BIO_set_close(newssl->rbio, BIO_NOCLOSE);
428         bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(newssl), &alg_bits);
429         lprintf(15, "SSL/TLS using %s on %s (%d of %d bits)\n",
430                 SSL_CIPHER_get_name(SSL_get_current_cipher(newssl)),
431                 SSL_CIPHER_get_version(SSL_get_current_cipher(newssl)),
432                 bits, alg_bits);
433
434         pthread_setspecific(ThreadSSL, newssl);
435         lprintf(15, "SSL started\n");
436         return(0);
437 }
438
439
440
441 /*
442  * shuts down the TLS connection
443  *
444  * WARNING:  This may make your session vulnerable to a known plaintext
445  * attack in the current implmentation.
446  */
447 void endtls(void)
448 {
449         SSL_CTX *ctx = NULL;
450
451         if (THREADSSL == NULL) return;
452
453         lprintf(15, "Ending SSL/TLS\n");
454         SSL_shutdown(THREADSSL);
455         ctx = SSL_get_SSL_CTX(THREADSSL);
456
457         /* I don't think this is needed, and it crashes the server anyway
458          *
459          *      if (ctx != NULL) {
460          *              lprintf(9, "Freeing CTX at %x\n", (int)ctx );
461          *              SSL_CTX_free(ctx);
462          *      }
463          */
464
465         SSL_free(THREADSSL);
466         pthread_setspecific(ThreadSSL, NULL);
467 }
468
469
470 /*
471  * callback for OpenSSL mutex locks
472  */
473 void ssl_lock(int mode, int n, const char *file, int line)
474 {
475         if (mode & CRYPTO_LOCK) {
476                 pthread_mutex_lock(SSLCritters[n]);
477         }
478         else {
479                 pthread_mutex_unlock(SSLCritters[n]);
480         }
481 }
482
483 /*
484  * Send binary data to the client encrypted.
485  */
486 void client_write_ssl(const StrBuf *Buf)
487 {
488         const char *buf;
489         int retval;
490         int nremain;
491         long nbytes;
492         char junk[1];
493
494         if (THREADSSL == NULL) return;
495
496         nbytes = nremain = StrLength(Buf);
497         buf = ChrPtr(Buf);
498
499         while (nremain > 0) {
500                 if (SSL_want_write(THREADSSL)) {
501                         if ((SSL_read(THREADSSL, junk, 0)) < 1) {
502                                 lprintf(9, "SSL_read in client_write: %s\n",
503                                                 ERR_reason_error_string(ERR_get_error()));
504                         }
505                 }
506                 retval = SSL_write(THREADSSL, &buf[nbytes - nremain], nremain);
507                 if (retval < 1) {
508                         long errval;
509
510                         errval = SSL_get_error(THREADSSL, retval);
511                         if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
512                                 sleeeeeeeeeep(1);
513                                 continue;
514                         }
515                         lprintf(9, "SSL_write got error %ld, ret %d\n", errval, retval);
516                         if (retval == -1) {
517                                 lprintf(9, "errno is %d\n", errno);
518                         }
519                         endtls();
520                         return;
521                 }
522                 nremain -= retval;
523         }
524 }
525
526
527 /*
528  * read data from the encrypted layer.
529  */
530 int client_read_sslbuffer(StrBuf *buf, int timeout)
531 {
532         char sbuf[16384]; /* OpenSSL communicates in 16k blocks, so let's speak its native tongue. */
533         int rlen;
534         char junk[1];
535         SSL *pssl = THREADSSL;
536
537         if (pssl == NULL) return(-1);
538
539         while (1) {
540                 if (SSL_want_read(pssl)) {
541                         if ((SSL_write(pssl, junk, 0)) < 1) {
542                                 lprintf(9, "SSL_write in client_read\n");
543                         }
544                 }
545                 rlen = SSL_read(pssl, sbuf, sizeof(sbuf));
546                 if (rlen < 1) {
547                         long errval;
548
549                         errval = SSL_get_error(pssl, rlen);
550                         if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
551                                 sleeeeeeeeeep(1);
552                                 continue;
553                         }
554                         lprintf(9, "SSL_read got error %ld\n", errval);
555                         endtls();
556                         return (-1);
557                 }
558                 StrBufAppendBufPlain(buf, sbuf, rlen, 0);
559                 return rlen;
560         }
561         return (0);
562 }
563
564 #endif                          /* HAVE_OPENSSL */