76c80d4de8df5aad59ab963bc62c7e4208655a6c
[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         "./keys" 
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 /**
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(WC_EXIT_SSL);
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(WC_EXIT_SSL);
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          * If there is no certificate file on disk, we will be generating a self-signed certificate
157          * in the next step.  Therefore, if we have neither a CSR nor a certificate, generate
158          * the CSR in this step so that the next step may commence.
159          */
160         if ( (access(CTDL_CER_PATH, R_OK) != 0) && (access(CTDL_CSR_PATH, R_OK) != 0) ) {
161                 lprintf(5, "Generating a certificate signing request.\n");
162
163                 /**
164                  * Read our key from the file.  No, we don't just keep this
165                  * in memory from the above key-generation function, because
166                  * there is the possibility that the key was already on disk
167                  * and we didn't just generate it now.
168                  */
169                 fp = fopen(CTDL_KEY_PATH, "r");
170                 if (fp) {
171                         rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
172                         fclose(fp);
173                 }
174
175                 if (rsa) {
176
177                         /** Create a public key from the private key */
178                         if (pk=EVP_PKEY_new(), pk != NULL) {
179                                 EVP_PKEY_assign_RSA(pk, rsa);
180                                 if (req = X509_REQ_new(), req != NULL) {
181
182                                         /** Set the public key */
183                                         X509_REQ_set_pubkey(req, pk);
184                                         X509_REQ_set_version(req, 0L);
185
186                                         name = X509_REQ_get_subject_name(req);
187
188                                         /** Tell it who we are */
189
190                                         /* \todo whats this?
191                                         X509_NAME_add_entry_by_txt(name, "C",
192                                                 MBSTRING_ASC, "US", -1, -1, 0);
193
194                                         X509_NAME_add_entry_by_txt(name, "ST",
195                                                 MBSTRING_ASC, "New York", -1, -1, 0);
196
197                                         X509_NAME_add_entry_by_txt(name, "L",
198                                                 MBSTRING_ASC, "Mount Kisco", -1, -1, 0);
199                                         */
200
201                                         X509_NAME_add_entry_by_txt(name, "O",
202                                                 MBSTRING_ASC, "Organization name", -1, -1, 0);
203
204                                         X509_NAME_add_entry_by_txt(name, "OU",
205                                                 MBSTRING_ASC, "Citadel server", -1, -1, 0);
206
207                                         X509_NAME_add_entry_by_txt(name, "CN",
208                                                 MBSTRING_ASC, "*", -1, -1, 0);
209                                 
210                                         X509_REQ_set_subject_name(req, name);
211
212                                         /** Sign the CSR */
213                                         if (!X509_REQ_sign(req, pk, EVP_md5())) {
214                                                 lprintf(3, "X509_REQ_sign(): error\n");
215                                         }
216                                         else {
217                                                 /** Write it to disk. */        
218                                                 fp = fopen(CTDL_CSR_PATH, "w");
219                                                 if (fp != NULL) {
220                                                         chmod(CTDL_CSR_PATH, 0600);
221                                                         PEM_write_X509_REQ(fp, req);
222                                                         fclose(fp);
223                                                 }
224                                         }
225
226                                         X509_REQ_free(req);
227                                 }
228                         }
229
230                         RSA_free(rsa);
231                 }
232
233                 else {
234                         lprintf(3, "Unable to read private key.\n");
235                 }
236         }
237
238
239
240         /**
241          * Generate a self-signed certificate if we don't have one.
242          */
243         if (access(CTDL_CER_PATH, R_OK) != 0) {
244                 lprintf(5, "Generating a self-signed certificate.\n");
245
246                 /** Same deal as before: always read the key from disk because
247                  * it may or may not have just been generated.
248                  */
249                 fp = fopen(CTDL_KEY_PATH, "r");
250                 if (fp) {
251                         rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
252                         fclose(fp);
253                 }
254
255                 /** This also holds true for the CSR. */
256                 req = NULL;
257                 cer = NULL;
258                 pk = NULL;
259                 if (rsa) {
260                         if (pk=EVP_PKEY_new(), pk != NULL) {
261                                 EVP_PKEY_assign_RSA(pk, rsa);
262                         }
263
264                         fp = fopen(CTDL_CSR_PATH, "r");
265                         if (fp) {
266                                 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
267                                 fclose(fp);
268                         }
269
270                         if (req) {
271                                 if (cer = X509_new(), cer != NULL) {
272
273                                         ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
274                                         X509_set_issuer_name(cer, req->req_info->subject);
275                                         X509_set_subject_name(cer, req->req_info->subject);
276                                         X509_gmtime_adj(X509_get_notBefore(cer), 0);
277                                         X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
278
279                                         req_pkey = X509_REQ_get_pubkey(req);
280                                         X509_set_pubkey(cer, req_pkey);
281                                         EVP_PKEY_free(req_pkey);
282                                         
283                                         /** Sign the cert */
284                                         if (!X509_sign(cer, pk, EVP_md5())) {
285                                                 lprintf(3, "X509_sign(): error\n");
286                                         }
287                                         else {
288                                                 /** Write it to disk. */        
289                                                 fp = fopen(CTDL_CER_PATH, "w");
290                                                 if (fp != NULL) {
291                                                         chmod(CTDL_CER_PATH, 0600);
292                                                         PEM_write_X509(fp, cer);
293                                                         fclose(fp);
294                                                 }
295                                         }
296                                         X509_free(cer);
297                                 }
298                         }
299
300                         RSA_free(rsa);
301                 }
302         }
303
304         /**
305          * Now try to bind to the key and certificate.
306          * Note that we use SSL_CTX_use_certificate_chain_file() which allows
307          * the certificate file to contain intermediate certificates.
308          */
309         SSL_CTX_use_certificate_chain_file(ssl_ctx, CTDL_CER_PATH);
310         SSL_CTX_use_PrivateKey_file(ssl_ctx, CTDL_KEY_PATH, SSL_FILETYPE_PEM);
311         if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
312                 lprintf(3, "Cannot install certificate: %s\n",
313                                 ERR_reason_error_string(ERR_get_error()));
314         }
315         
316 }
317
318
319 /**
320  * \brief starts SSL/TLS encryption for the current session.
321  * \param sock the socket connection
322  * \return Zero if the SSL/TLS handshake succeeded, non-zero otherwise.
323  */
324 int starttls(int sock) {
325         int retval, bits, alg_bits;
326         SSL *newssl;
327
328         pthread_setspecific(ThreadSSL, NULL);
329
330         if (!ssl_ctx) {
331                 return(1);
332         }
333         if (!(newssl = SSL_new(ssl_ctx))) {
334                 lprintf(3, "SSL_new failed: %s\n",
335                                 ERR_reason_error_string(ERR_get_error()));
336                 return(2);
337         }
338         if (!(SSL_set_fd(newssl, sock))) {
339                 lprintf(3, "SSL_set_fd failed: %s\n",
340                         ERR_reason_error_string(ERR_get_error()));
341                 SSL_free(newssl);
342                 return(3);
343         }
344         retval = SSL_accept(newssl);
345         if (retval < 1) {
346                 /**
347                  * Can't notify the client of an error here; they will
348                  * discover the problem at the SSL layer and should
349                  * revert to unencrypted communications.
350                  */
351                 long errval;
352
353                 errval = SSL_get_error(newssl, retval);
354                 lprintf(3, "SSL_accept failed: %s\n",
355                         ERR_reason_error_string(ERR_get_error()));
356                 SSL_free(newssl);
357                 newssl = NULL;
358                 return(4);
359         }
360         BIO_set_close(newssl->rbio, BIO_NOCLOSE);
361         bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(newssl), &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
389         /** I don't think this is needed, and it crashes the server anyway
390          *
391          *      if (ctx != NULL) {
392          *              lprintf(9, "Freeing CTX at %x\n", (int)ctx );
393          *              SSL_CTX_free(ctx);
394          *      }
395          */
396
397         SSL_free(THREADSSL);
398         pthread_setspecific(ThreadSSL, NULL);
399 }
400
401
402 /**
403  * \brief callback for OpenSSL mutex locks
404  * \param mode which mode??????
405  * \param n  how many???
406  * \param file which filename ???
407  * \param line what line????
408  */
409 void ssl_lock(int mode, int n, const char *file, int line)
410 {
411         if (mode & CRYPTO_LOCK)
412                 pthread_mutex_lock(SSLCritters[n]);
413         else
414                 pthread_mutex_unlock(SSLCritters[n]);
415 }
416
417 /**
418  * \brief Send binary data to the client encrypted.
419  * \param buf chars to send to the client
420  * \param nbytes how many chars
421  */
422 void client_write_ssl(char *buf, int nbytes)
423 {
424         int retval;
425         int nremain;
426         char junk[1];
427
428         if (THREADSSL == NULL) return;
429
430         nremain = nbytes;
431
432         while (nremain > 0) {
433                 if (SSL_want_write(THREADSSL)) {
434                         if ((SSL_read(THREADSSL, junk, 0)) < 1) {
435                                 lprintf(9, "SSL_read in client_write: %s\n",
436                                                 ERR_reason_error_string(ERR_get_error()));
437                         }
438                 }
439                 retval = SSL_write(THREADSSL, &buf[nbytes - nremain], nremain);
440                 if (retval < 1) {
441                         long errval;
442
443                         errval = SSL_get_error(THREADSSL, retval);
444                         if (errval == SSL_ERROR_WANT_READ ||
445                             errval == SSL_ERROR_WANT_WRITE) {
446                                 sleep(1);
447                                 continue;
448                         }
449                         lprintf(9, "SSL_write got error %ld, ret %d\n", errval, retval);
450                         if (retval == -1) {
451                                 lprintf(9, "errno is %d\n", errno);
452                         }
453                         endtls();
454                         return;
455                 }
456                 nremain -= retval;
457         }
458 }
459
460
461 /**
462  * \brief read data from the encrypted layer.
463  * \param buf charbuffer to read to 
464  * \param bytes how many
465  * \param timeout how long should we wait?
466  * \returns what???
467  */
468 int client_read_ssl(char *buf, int bytes, int timeout)
469 {
470 #if 0
471         fd_set rfds;
472         struct timeval tv;
473         int retval;
474         int s;
475 #endif
476         int len, rlen;
477         char junk[1];
478
479         if (THREADSSL == NULL) return(0);
480
481         len = 0;
482         while (len < bytes) {
483 #if 0
484                 /**
485                  * This code is disabled because we don't need it when
486                  * using blocking reads (which we are). -IO
487                  */
488                 FD_ZERO(&rfds);
489                 s = BIO_get_fd(THREADSSL->rbio, NULL);
490                 FD_SET(s, &rfds);
491                 tv.tv_sec = timeout;
492                 tv.tv_usec = 0;
493
494                 retval = select(s + 1, &rfds, NULL, NULL, &tv);
495
496                 if (FD_ISSET(s, &rfds) == 0) {
497                         return (0);
498                 }
499
500 #endif
501                 if (SSL_want_read(THREADSSL)) {
502                         if ((SSL_write(THREADSSL, junk, 0)) < 1) {
503                                 lprintf(9, "SSL_write in client_read: %s\n", ERR_reason_error_string(ERR_get_error()));
504                         }
505                 }
506                 rlen = SSL_read(THREADSSL, &buf[len], bytes - len);
507                 if (rlen < 1) {
508                         long errval;
509
510                         errval = SSL_get_error(THREADSSL, rlen);
511                         if (errval == SSL_ERROR_WANT_READ ||
512                             errval == SSL_ERROR_WANT_WRITE) {
513                                 sleep(1);
514                                 continue;
515                         }
516                         lprintf(9, "SSL_read got error %ld\n", errval);
517                         endtls();
518                         return (0);
519                 }
520                 len += rlen;
521         }
522         return (1);
523 }
524
525
526 #endif                          /* HAVE_OPENSSL */
527 /*@}*/