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