* Reduced iconbar button size to 90% because it looked obtuse on a smaller screen
[citadel.git] / webcit / crypto.c
blobfda0c406d605ad65eea88aa1711914059d8eefaa
1 /*
2 * $Id$
3 */
4 /**
5 * \defgroup https Provides HTTPS, when the OpenSSL library is available.
6 * \ingroup WebcitHttpServer
7 */
9 /*@{*/
10 #include "sysdep.h"
11 #ifdef HAVE_OPENSSL
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 */
23 SSL_CTX *ssl_ctx; /**< SSL context */
24 pthread_mutex_t **SSLCritters; /**< Things needing locking */
26 pthread_key_t ThreadSSL; /**< Per-thread SSL context */
28 /**
29 * \brief what?????
30 * \return thread id???
32 static unsigned long id_callback(void)
34 return (unsigned long) pthread_self();
37 void shutdown_ssl(void)
39 ERR_free_strings();
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);
50 /**
51 * \brief initialize ssl engine
52 * load certs and initialize openssl internals
54 void init_ssl(void)
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];
66 if (!access("/var/run/egd-pool", F_OK))
67 RAND_egd("/var/run/egd-pool");
69 if (!RAND_status()) {
70 lprintf(3,
71 "PRNG not adequately seeded, won't do SSL/TLS\n");
72 return;
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;
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);
93 pthread_mutex_init(SSLCritters[a], NULL);
97 /**
98 * Initialize SSL transport layer
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;
109 CRYPTO_set_locking_callback(ssl_lock);
110 CRYPTO_set_id_callback(id_callback);
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...
116 mkdir(CTDL_CRYPTO_DIR, 0700);
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
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);
136 * If we still don't have a private key, generate one.
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()));
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);
164 fclose(fp);
166 else {
167 lprintf(3, "Cannot write key: %s\n", CTDL_KEY_PATH);
168 ShutDownWebcit();
169 exit(0);
171 RSA_free(rsa);
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.
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");
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.
189 fp = fopen(CTDL_KEY_PATH, "r");
190 if (fp) {
191 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
192 fclose(fp);
195 if (rsa) {
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) {
202 /** Set the public key */
203 X509_REQ_set_pubkey(req, pk);
204 X509_REQ_set_version(req, 0L);
206 name = X509_REQ_get_subject_name(req);
208 /** Tell it who we are */
210 /* \todo whats this?
211 X509_NAME_add_entry_by_txt(name, "C",
212 MBSTRING_ASC, "US", -1, -1, 0);
214 X509_NAME_add_entry_by_txt(name, "ST",
215 MBSTRING_ASC, "New York", -1, -1, 0);
217 X509_NAME_add_entry_by_txt(name, "L",
218 MBSTRING_ASC, "Mount Kisco", -1, -1, 0);
221 X509_NAME_add_entry_by_txt(
222 name, "O",
223 MBSTRING_ASC,
224 (unsigned char*)"Organization name",
225 -1, -1, 0);
227 X509_NAME_add_entry_by_txt(
228 name, "OU",
229 MBSTRING_ASC,
230 (unsigned char*)"Citadel server1",
231 -1, -1, 0);
233 X509_NAME_add_entry_by_txt(
234 name, "CN",
235 MBSTRING_ASC,
236 (unsigned char*)"*", -1, -1, 0);
238 X509_REQ_set_subject_name(req, name);
240 /** Sign the CSR */
241 if (!X509_REQ_sign(req, pk, EVP_md5())) {
242 lprintf(3, "X509_REQ_sign(): error\n");
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);
252 else {
253 lprintf(3, "Cannot write key: %s\n", CTDL_CSR_PATH);
254 ShutDownWebcit();
255 exit(0);
259 X509_REQ_free(req);
263 RSA_free(rsa);
266 else {
267 lprintf(3, "Unable to read private key.\n");
274 * Generate a self-signed certificate if we don't have one.
276 if (access(CTDL_CER_PATH, R_OK) != 0) {
277 lprintf(5, "Generating a self-signed certificate.\n");
279 /** Same deal as before: always read the key from disk because
280 * it may or may not have just been generated.
282 fp = fopen(CTDL_KEY_PATH, "r");
283 if (fp) {
284 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
285 fclose(fp);
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);
297 fp = fopen(CTDL_CSR_PATH, "r");
298 if (fp) {
299 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
300 fclose(fp);
303 if (req) {
304 if (cer = X509_new(), cer != NULL) {
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);
312 req_pkey = X509_REQ_get_pubkey(req);
313 X509_set_pubkey(cer, req_pkey);
314 EVP_PKEY_free(req_pkey);
316 /** Sign the cert */
317 if (!X509_sign(cer, pk, EVP_md5())) {
318 lprintf(3, "X509_sign(): error\n");
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);
328 else {
329 lprintf(3, "Cannot write key: %s\n", CTDL_CER_PATH);
330 ShutDownWebcit();
331 exit(0);
334 X509_free(cer);
338 RSA_free(rsa);
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.
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()));
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.
362 int starttls(int sock) {
363 int retval, bits, alg_bits, r;
364 SSL *newssl;
366 pthread_setspecific(ThreadSSL, NULL);
368 if (!ssl_ctx) {
369 return(1);
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);
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);
382 retval = SSL_accept(newssl);
383 if (retval < 1) {
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.
389 long errval;
390 const char *ssl_error_reason = NULL;
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 sleeeeeeeeeep(1);
399 retval = SSL_accept(newssl);
401 if (retval < 1) {
402 long errval;
403 const char *ssl_error_reason = NULL;
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);
422 pthread_setspecific(ThreadSSL, newssl);
423 lprintf(15, "SSL started\n");
424 return(0);
430 * \brief shuts down the TLS connection
432 * WARNING: This may make your session vulnerable to a known plaintext
433 * attack in the current implmentation.
435 void endtls(void)
437 SSL_CTX *ctx = NULL;
439 if (THREADSSL == NULL) return;
441 lprintf(15, "Ending SSL/TLS\n");
442 SSL_shutdown(THREADSSL);
443 ctx = SSL_get_SSL_CTX(THREADSSL);
445 /** I don't think this is needed, and it crashes the server anyway
447 * if (ctx != NULL) {
448 * lprintf(9, "Freeing CTX at %x\n", (int)ctx );
449 * SSL_CTX_free(ctx);
453 SSL_free(THREADSSL);
454 pthread_setspecific(ThreadSSL, NULL);
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????
465 void ssl_lock(int mode, int n, const char *file, int line)
467 if (mode & CRYPTO_LOCK)
468 pthread_mutex_lock(SSLCritters[n]);
469 else
470 pthread_mutex_unlock(SSLCritters[n]);
474 * \brief Send binary data to the client encrypted.
475 * \param buf chars to send to the client
476 * \param nbytes how many chars
478 void client_write_ssl(const StrBuf *Buf)
480 const char *buf;
481 int retval;
482 int nremain;
483 long nbytes;
484 char junk[1];
486 if (THREADSSL == NULL) return;
488 nbytes = nremain = StrLength(Buf);
489 buf = ChrPtr(Buf);
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()));
498 retval = SSL_write(THREADSSL, &buf[nbytes - nremain], nremain);
499 if (retval < 1) {
500 long errval;
502 errval = SSL_get_error(THREADSSL, retval);
503 if (errval == SSL_ERROR_WANT_READ ||
504 errval == SSL_ERROR_WANT_WRITE) {
505 sleeeeeeeeeep(1);
506 continue;
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);
512 endtls();
513 return;
515 nremain -= retval;
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???
527 int client_read_sslbuffer(StrBuf *buf, int timeout)
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 SSL *pssl = THREADSSL;
540 if (pssl == NULL) return(-1);
542 while (1) {
543 #if 0
545 * This code is disabled because we don't need it when
546 * using blocking reads (which we are). -IO
548 FD_ZERO(&rfds);
549 s = BIO_get_fd(pssl->rbio, NULL);
550 FD_SET(s, &rfds);
551 tv.tv_sec = timeout;
552 tv.tv_usec = 0;
554 retval = select(s + 1, &rfds, NULL, NULL, &tv);
556 if (FD_ISSET(s, &rfds) == 0) {
557 return (0);
560 #endif
561 if (SSL_want_read(pssl)) {
562 if ((SSL_write(pssl, junk, 0)) < 1) {
563 lprintf(9, "SSL_write in client_read\n");
566 rlen = SSL_read(pssl, sbuf, sizeof(sbuf));
567 if (rlen < 1) {
568 long errval;
570 errval = SSL_get_error(pssl, rlen);
571 if (errval == SSL_ERROR_WANT_READ ||
572 errval == SSL_ERROR_WANT_WRITE) {
573 sleeeeeeeeeep(1);
574 continue;
576 lprintf(9, "SSL_read got error %ld\n", errval);
577 endtls();
578 return (-1);
580 StrBufAppendBufPlain(buf, sbuf, rlen, 0);
581 return rlen;
583 return (0);
587 #endif /* HAVE_OPENSSL */
588 /*@}*/