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