10 #include <openssl/ssl.h>
11 #include <openssl/err.h>
12 #include <openssl/rand.h>
15 #if TIME_WITH_SYS_TIME
16 # include <sys/time.h>
20 # include <sys/time.h>
30 #ifdef HAVE_SYS_SELECT_H
31 #include <sys/select.h>
35 #include <libcitadel.h>
37 #include "serv_crypto.h"
38 #include "sysdep_decls.h"
43 #include "ctdl_module.h"
44 /* TODO: should we use the standard module init stuff to start this? */
45 /* TODO: should we register an event handler to call destruct_ssl? */
48 SSL_CTX *ssl_ctx; /* SSL context */
49 pthread_mutex_t **SSLCritters; /* Things needing locking */
51 static unsigned long id_callback(void)
53 return (unsigned long) pthread_self();
56 void destruct_ssl(void)
59 for (a = 0; a < CRYPTO_num_locks(); a++)
66 SSL_METHOD *ssl_method;
72 EVP_PKEY *req_pkey = NULL;
73 X509_NAME *name = NULL;
76 if (!access(EGD_POOL, F_OK))
80 CtdlLogPrintf(CTDL_CRIT,
81 "PRNG not adequately seeded, won't do SSL/TLS\n");
85 malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
87 CtdlLogPrintf(CTDL_EMERG, "citserver: can't allocate memory!!\n");
88 /* Nothing's been initialized, just die */
93 for (a = 0; a < CRYPTO_num_locks(); a++) {
94 SSLCritters[a] = malloc(sizeof(pthread_mutex_t));
95 if (!SSLCritters[a]) {
96 CtdlLogPrintf(CTDL_EMERG,
97 "citserver: can't allocate memory!!\n");
98 /* Nothing's been initialized, just die */
101 pthread_mutex_init(SSLCritters[a], NULL);
106 * Initialize SSL transport layer
109 SSL_load_error_strings();
110 ssl_method = SSLv23_server_method();
111 if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
112 CtdlLogPrintf(CTDL_CRIT, "SSL_CTX_new failed: %s\n",
113 ERR_reason_error_string(ERR_get_error()));
116 if (!(SSL_CTX_set_cipher_list(ssl_ctx, CIT_CIPHERS))) {
117 CtdlLogPrintf(CTDL_CRIT, "SSL: No ciphers available\n");
118 SSL_CTX_free(ssl_ctx);
123 #if SSLEAY_VERSION_NUMBER >= 0x00906000L
124 SSL_CTX_set_mode(ssl_ctx, SSL_CTX_get_mode(ssl_ctx) |
125 SSL_MODE_AUTO_RETRY);
129 CRYPTO_set_locking_callback(ssl_lock);
130 CRYPTO_set_id_callback(id_callback);
132 /* Load DH parameters into the context */
135 CtdlLogPrintf(CTDL_CRIT, "init_ssl() can't allocate a DH object: %s\n",
136 ERR_reason_error_string(ERR_get_error()));
137 SSL_CTX_free(ssl_ctx);
141 if (!(BN_hex2bn(&(dh->p), DH_P))) {
142 CtdlLogPrintf(CTDL_CRIT, "init_ssl() can't assign DH_P: %s\n",
143 ERR_reason_error_string(ERR_get_error()));
144 SSL_CTX_free(ssl_ctx);
148 if (!(BN_hex2bn(&(dh->g), DH_G))) {
149 CtdlLogPrintf(CTDL_CRIT, "init_ssl() can't assign DH_G: %s\n",
150 ERR_reason_error_string(ERR_get_error()));
151 SSL_CTX_free(ssl_ctx);
156 SSL_CTX_set_tmp_dh(ssl_ctx, dh);
159 /* Get our certificates in order.
160 * First, create the key/cert directory if it's not there already...
162 mkdir(ctdl_key_dir, 0700);
165 * Generate a key pair if we don't have one.
167 if (access(file_crpt_file_key, R_OK) != 0) {
168 CtdlLogPrintf(CTDL_INFO, "Generating RSA key pair.\n");
169 rsa = RSA_generate_key(1024, /* modulus size */
170 65537, /* exponent */
171 NULL, /* no callback */
172 NULL); /* no callback */
174 CtdlLogPrintf(CTDL_CRIT, "Key generation failed: %s\n",
175 ERR_reason_error_string(ERR_get_error()));
178 fp = fopen(file_crpt_file_key, "w");
180 chmod(file_crpt_file_key, 0600);
181 if (PEM_write_RSAPrivateKey(fp, /* the file */
184 NULL, /* no passphr */
186 NULL, /* no callbk */
189 CtdlLogPrintf(CTDL_CRIT, "Cannot write key: %s\n",
190 ERR_reason_error_string(ERR_get_error()));
191 unlink(file_crpt_file_key);
200 * If there is no certificate file on disk, we will be generating a self-signed certificate
201 * in the next step. Therefore, if we have neither a CSR nor a certificate, generate
202 * the CSR in this step so that the next step may commence.
204 if ( (access(file_crpt_file_cer, R_OK) != 0) && (access(file_crpt_file_csr, R_OK) != 0) ) {
205 CtdlLogPrintf(CTDL_INFO, "Generating a certificate signing request.\n");
208 * Read our key from the file. No, we don't just keep this
209 * in memory from the above key-generation function, because
210 * there is the possibility that the key was already on disk
211 * and we didn't just generate it now.
213 fp = fopen(file_crpt_file_key, "r");
215 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
221 /* Create a public key from the private key */
222 if (pk=EVP_PKEY_new(), pk != NULL) {
223 EVP_PKEY_assign_RSA(pk, rsa);
224 if (req = X509_REQ_new(), req != NULL) {
226 /* Set the public key */
227 X509_REQ_set_pubkey(req, pk);
228 X509_REQ_set_version(req, 0L);
230 name = X509_REQ_get_subject_name(req);
232 /* Tell it who we are */
235 X509_NAME_add_entry_by_txt(name, "C",
236 MBSTRING_ASC, "US", -1, -1, 0);
238 X509_NAME_add_entry_by_txt(name, "ST",
239 MBSTRING_ASC, "New York", -1, -1, 0);
241 X509_NAME_add_entry_by_txt(name, "L",
242 MBSTRING_ASC, "Mount Kisco", -1, -1, 0);
245 X509_NAME_add_entry_by_txt(name, "O",
246 MBSTRING_ASC, config.c_humannode, -1, -1, 0);
248 X509_NAME_add_entry_by_txt(name, "OU",
249 MBSTRING_ASC, "Citadel server", -1, -1, 0);
251 /* X509_NAME_add_entry_by_txt(name, "CN",
252 MBSTRING_ASC, config.c_fqdn, -1, -1, 0);
255 X509_NAME_add_entry_by_txt(name, "CN",
256 MBSTRING_ASC, "*", -1, -1, 0);
258 X509_REQ_set_subject_name(req, name);
261 if (!X509_REQ_sign(req, pk, EVP_md5())) {
262 CtdlLogPrintf(CTDL_CRIT, "X509_REQ_sign(): error\n");
265 /* Write it to disk. */
266 fp = fopen(file_crpt_file_csr, "w");
268 chmod(file_crpt_file_csr, 0600);
269 PEM_write_X509_REQ(fp, req);
282 CtdlLogPrintf(CTDL_CRIT, "Unable to read private key.\n");
289 * Generate a self-signed certificate if we don't have one.
291 if (access(file_crpt_file_cer, R_OK) != 0) {
292 CtdlLogPrintf(CTDL_INFO, "Generating a self-signed certificate.\n");
294 /* Same deal as before: always read the key from disk because
295 * it may or may not have just been generated.
297 fp = fopen(file_crpt_file_key, "r");
299 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
303 /* This also holds true for the CSR. */
308 if (pk=EVP_PKEY_new(), pk != NULL) {
309 EVP_PKEY_assign_RSA(pk, rsa);
312 fp = fopen(file_crpt_file_csr, "r");
314 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
319 if (cer = X509_new(), cer != NULL) {
321 ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
322 X509_set_issuer_name(cer, req->req_info->subject);
323 X509_set_subject_name(cer, req->req_info->subject);
324 X509_gmtime_adj(X509_get_notBefore(cer),0);
325 X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
326 req_pkey = X509_REQ_get_pubkey(req);
327 X509_set_pubkey(cer, req_pkey);
328 EVP_PKEY_free(req_pkey);
331 if (!X509_sign(cer, pk, EVP_md5())) {
332 CtdlLogPrintf(CTDL_CRIT, "X509_sign(): error\n");
335 /* Write it to disk. */
336 fp = fopen(file_crpt_file_cer, "w");
338 chmod(file_crpt_file_cer, 0600);
339 PEM_write_X509(fp, cer);
353 * Now try to bind to the key and certificate.
355 SSL_CTX_use_certificate_chain_file(ssl_ctx, file_crpt_file_cer);
356 SSL_CTX_use_PrivateKey_file(ssl_ctx, file_crpt_file_key, SSL_FILETYPE_PEM);
357 if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
358 CtdlLogPrintf(CTDL_CRIT, "Cannot install certificate: %s\n",
359 ERR_reason_error_string(ERR_get_error()));
362 /* Finally let the server know we're here */
363 CtdlRegisterProtoHook(cmd_stls, "STLS", "Start SSL/TLS session");
364 CtdlRegisterProtoHook(cmd_gtls, "GTLS",
365 "Get SSL/TLS session status");
366 CtdlRegisterSessionHook(endtls, EVT_STOP);
371 * client_write_ssl() Send binary data to the client encrypted.
373 void client_write_ssl(char *buf, int nbytes)
381 while (nremain > 0) {
382 if (SSL_want_write(CC->ssl)) {
383 if ((SSL_read(CC->ssl, junk, 0)) < 1) {
384 CtdlLogPrintf(CTDL_DEBUG, "SSL_read in client_write: %s\n", ERR_reason_error_string(ERR_get_error()));
388 SSL_write(CC->ssl, &buf[nbytes - nremain], nremain);
392 errval = SSL_get_error(CC->ssl, retval);
393 if (errval == SSL_ERROR_WANT_READ ||
394 errval == SSL_ERROR_WANT_WRITE) {
398 CtdlLogPrintf(CTDL_DEBUG, "SSL_write got error %ld, ret %d\n", errval, retval);
400 CtdlLogPrintf(CTDL_DEBUG, "errno is %d\n", errno);
402 client_write(&buf[nbytes - nremain], nremain);
411 * client_read_ssl() - read data from the encrypted layer.
413 int client_read_ssl(char *buf, int bytes, int timeout)
425 while (len < bytes) {
428 * This code is disabled because we don't need it when
429 * using blocking reads (which we are). -IO
432 s = BIO_get_fd(CC->ssl->rbio, NULL);
437 retval = select(s + 1, &rfds, NULL, NULL, &tv);
439 if (FD_ISSET(s, &rfds) == 0) {
444 if (SSL_want_read(CC->ssl)) {
445 if ((SSL_write(CC->ssl, junk, 0)) < 1) {
446 CtdlLogPrintf(CTDL_DEBUG, "SSL_write in client_read: %s\n", ERR_reason_error_string(ERR_get_error()));
449 rlen = SSL_read(CC->ssl, &buf[len], bytes - len);
453 errval = SSL_get_error(CC->ssl, rlen);
454 if (errval == SSL_ERROR_WANT_READ ||
455 errval == SSL_ERROR_WANT_WRITE) {
459 CtdlLogPrintf(CTDL_DEBUG, "SSL_read got error %ld\n", errval);
461 return (client_read_to
462 (&buf[len], bytes - len, timeout));
471 * CtdlStartTLS() starts SSL/TLS encryption for the current session. It
472 * must be supplied with pre-generated strings for responses of "ok," "no
473 * support for TLS," and "error" so that we can use this in any protocol.
475 void CtdlStartTLS(char *ok_response, char *nosup_response,
476 char *error_response) {
478 int retval, bits, alg_bits;
481 CtdlLogPrintf(CTDL_CRIT, "SSL failed: no ssl_ctx exists?\n");
482 if (nosup_response != NULL) cprintf("%s", nosup_response);
485 if (!(CC->ssl = SSL_new(ssl_ctx))) {
486 CtdlLogPrintf(CTDL_CRIT, "SSL_new failed: %s\n",
487 ERR_reason_error_string(ERR_get_error()));
488 if (error_response != NULL) cprintf("%s", error_response);
491 if (!(SSL_set_fd(CC->ssl, CC->client_socket))) {
492 CtdlLogPrintf(CTDL_CRIT, "SSL_set_fd failed: %s\n",
493 ERR_reason_error_string(ERR_get_error()));
496 if (error_response != NULL) cprintf("%s", error_response);
499 if (ok_response != NULL) cprintf("%s", ok_response);
500 retval = SSL_accept(CC->ssl);
503 * Can't notify the client of an error here; they will
504 * discover the problem at the SSL layer and should
505 * revert to unencrypted communications.
508 char error_string[128];
510 errval = SSL_get_error(CC->ssl, retval);
511 CtdlLogPrintf(CTDL_CRIT, "SSL_accept failed: retval=%d, errval=%ld, err=%s\n",
514 ERR_error_string(errval, error_string)
520 BIO_set_close(CC->ssl->rbio, BIO_NOCLOSE);
521 bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl), &alg_bits);
522 CtdlLogPrintf(CTDL_INFO, "SSL/TLS using %s on %s (%d of %d bits)\n",
523 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
524 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
526 CC->redirect_ssl = 1;
531 * cmd_stls() starts SSL/TLS encryption for the current session
533 void cmd_stls(char *params)
535 char ok_response[SIZ];
536 char nosup_response[SIZ];
537 char error_response[SIZ];
542 "%d Begin TLS negotiation now\n",
544 sprintf(nosup_response,
545 "%d TLS not supported here\n",
546 ERROR + CMD_NOT_SUPPORTED);
547 sprintf(error_response,
548 "%d TLS negotiation error\n",
549 ERROR + INTERNAL_ERROR);
551 CtdlStartTLS(ok_response, nosup_response, error_response);
556 * cmd_gtls() returns status info about the TLS connection
558 void cmd_gtls(char *params)
562 if (!CC->ssl || !CC->redirect_ssl) {
563 cprintf("%d Session is not encrypted.\n", ERROR);
567 SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl),
569 cprintf("%d %s|%s|%d|%d\n", CIT_OK,
570 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
571 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
577 * endtls() shuts down the TLS connection
579 * WARNING: This may make your session vulnerable to a known plaintext
580 * attack in the current implmentation.
585 CC->redirect_ssl = 0;
589 CtdlLogPrintf(CTDL_INFO, "Ending SSL/TLS\n");
590 SSL_shutdown(CC->ssl);
593 CC->redirect_ssl = 0;
598 * ssl_lock() callback for OpenSSL mutex locks
600 void ssl_lock(int mode, int n, const char *file, int line)
602 if (mode & CRYPTO_LOCK)
603 pthread_mutex_lock(SSLCritters[n]);
605 pthread_mutex_unlock(SSLCritters[n]);
607 #endif /* HAVE_OPENSSL */