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