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 CtdlUnregisterProtoHook(cmd_stls, "STLS");
60 CtdlUnregisterProtoHook(cmd_gtls, "GTLS");
61 for (a = 0; a < CRYPTO_num_locks(); a++)
68 SSL_METHOD *ssl_method;
74 EVP_PKEY *req_pkey = NULL;
75 X509_NAME *name = NULL;
78 if (!access(EGD_POOL, F_OK))
82 CtdlLogPrintf(CTDL_CRIT,
83 "PRNG not adequately seeded, won't do SSL/TLS\n");
87 malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
89 CtdlLogPrintf(CTDL_EMERG, "citserver: can't allocate memory!!\n");
90 /* Nothing's been initialized, just die */
95 for (a = 0; a < CRYPTO_num_locks(); a++) {
96 SSLCritters[a] = malloc(sizeof(pthread_mutex_t));
97 if (!SSLCritters[a]) {
98 CtdlLogPrintf(CTDL_EMERG,
99 "citserver: can't allocate memory!!\n");
100 /* Nothing's been initialized, just die */
103 pthread_mutex_init(SSLCritters[a], NULL);
108 * Initialize SSL transport layer
111 SSL_load_error_strings();
112 ssl_method = SSLv23_server_method();
113 if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
114 CtdlLogPrintf(CTDL_CRIT, "SSL_CTX_new failed: %s\n",
115 ERR_reason_error_string(ERR_get_error()));
118 if (!(SSL_CTX_set_cipher_list(ssl_ctx, CIT_CIPHERS))) {
119 CtdlLogPrintf(CTDL_CRIT, "SSL: No ciphers available\n");
120 SSL_CTX_free(ssl_ctx);
125 #if SSLEAY_VERSION_NUMBER >= 0x00906000L
126 SSL_CTX_set_mode(ssl_ctx, SSL_CTX_get_mode(ssl_ctx) |
127 SSL_MODE_AUTO_RETRY);
131 CRYPTO_set_locking_callback(ssl_lock);
132 CRYPTO_set_id_callback(id_callback);
134 /* Load DH parameters into the context */
137 CtdlLogPrintf(CTDL_CRIT, "init_ssl() can't allocate a DH object: %s\n",
138 ERR_reason_error_string(ERR_get_error()));
139 SSL_CTX_free(ssl_ctx);
143 if (!(BN_hex2bn(&(dh->p), DH_P))) {
144 CtdlLogPrintf(CTDL_CRIT, "init_ssl() can't assign DH_P: %s\n",
145 ERR_reason_error_string(ERR_get_error()));
146 SSL_CTX_free(ssl_ctx);
150 if (!(BN_hex2bn(&(dh->g), DH_G))) {
151 CtdlLogPrintf(CTDL_CRIT, "init_ssl() can't assign DH_G: %s\n",
152 ERR_reason_error_string(ERR_get_error()));
153 SSL_CTX_free(ssl_ctx);
158 SSL_CTX_set_tmp_dh(ssl_ctx, dh);
161 /* Get our certificates in order.
162 * First, create the key/cert directory if it's not there already...
164 mkdir(ctdl_key_dir, 0700);
167 * Generate a key pair if we don't have one.
169 if (access(file_crpt_file_key, R_OK) != 0) {
170 CtdlLogPrintf(CTDL_INFO, "Generating RSA key pair.\n");
171 rsa = RSA_generate_key(1024, /* modulus size */
172 65537, /* exponent */
173 NULL, /* no callback */
174 NULL); /* no callback */
176 CtdlLogPrintf(CTDL_CRIT, "Key generation failed: %s\n",
177 ERR_reason_error_string(ERR_get_error()));
180 fp = fopen(file_crpt_file_key, "w");
182 chmod(file_crpt_file_key, 0600);
183 if (PEM_write_RSAPrivateKey(fp, /* the file */
186 NULL, /* no passphr */
188 NULL, /* no callbk */
191 CtdlLogPrintf(CTDL_CRIT, "Cannot write key: %s\n",
192 ERR_reason_error_string(ERR_get_error()));
193 unlink(file_crpt_file_key);
202 * If there is no certificate file on disk, we will be generating a self-signed certificate
203 * in the next step. Therefore, if we have neither a CSR nor a certificate, generate
204 * the CSR in this step so that the next step may commence.
206 if ( (access(file_crpt_file_cer, R_OK) != 0) && (access(file_crpt_file_csr, R_OK) != 0) ) {
207 CtdlLogPrintf(CTDL_INFO, "Generating a certificate signing request.\n");
210 * Read our key from the file. No, we don't just keep this
211 * in memory from the above key-generation function, because
212 * there is the possibility that the key was already on disk
213 * and we didn't just generate it now.
215 fp = fopen(file_crpt_file_key, "r");
217 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
223 /* Create a public key from the private key */
224 if (pk=EVP_PKEY_new(), pk != NULL) {
225 EVP_PKEY_assign_RSA(pk, rsa);
226 if (req = X509_REQ_new(), req != NULL) {
228 /* Set the public key */
229 X509_REQ_set_pubkey(req, pk);
230 X509_REQ_set_version(req, 0L);
232 name = X509_REQ_get_subject_name(req);
234 /* Tell it who we are */
237 X509_NAME_add_entry_by_txt(name, "C",
238 MBSTRING_ASC, "US", -1, -1, 0);
240 X509_NAME_add_entry_by_txt(name, "ST",
241 MBSTRING_ASC, "New York", -1, -1, 0);
243 X509_NAME_add_entry_by_txt(name, "L",
244 MBSTRING_ASC, "Mount Kisco", -1, -1, 0);
247 X509_NAME_add_entry_by_txt(name, "O",
248 MBSTRING_ASC, config.c_humannode, -1, -1, 0);
250 X509_NAME_add_entry_by_txt(name, "OU",
251 MBSTRING_ASC, "Citadel server", -1, -1, 0);
253 /* X509_NAME_add_entry_by_txt(name, "CN",
254 MBSTRING_ASC, config.c_fqdn, -1, -1, 0);
257 X509_NAME_add_entry_by_txt(name, "CN",
258 MBSTRING_ASC, "*", -1, -1, 0);
260 X509_REQ_set_subject_name(req, name);
263 if (!X509_REQ_sign(req, pk, EVP_md5())) {
264 CtdlLogPrintf(CTDL_CRIT, "X509_REQ_sign(): error\n");
267 /* Write it to disk. */
268 fp = fopen(file_crpt_file_csr, "w");
270 chmod(file_crpt_file_csr, 0600);
271 PEM_write_X509_REQ(fp, req);
284 CtdlLogPrintf(CTDL_CRIT, "Unable to read private key.\n");
291 * Generate a self-signed certificate if we don't have one.
293 if (access(file_crpt_file_cer, R_OK) != 0) {
294 CtdlLogPrintf(CTDL_INFO, "Generating a self-signed certificate.\n");
296 /* Same deal as before: always read the key from disk because
297 * it may or may not have just been generated.
299 fp = fopen(file_crpt_file_key, "r");
301 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
305 /* This also holds true for the CSR. */
310 if (pk=EVP_PKEY_new(), pk != NULL) {
311 EVP_PKEY_assign_RSA(pk, rsa);
314 fp = fopen(file_crpt_file_csr, "r");
316 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
321 if (cer = X509_new(), cer != NULL) {
323 ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
324 X509_set_issuer_name(cer, req->req_info->subject);
325 X509_set_subject_name(cer, req->req_info->subject);
326 X509_gmtime_adj(X509_get_notBefore(cer),0);
327 X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
328 req_pkey = X509_REQ_get_pubkey(req);
329 X509_set_pubkey(cer, req_pkey);
330 EVP_PKEY_free(req_pkey);
333 if (!X509_sign(cer, pk, EVP_md5())) {
334 CtdlLogPrintf(CTDL_CRIT, "X509_sign(): error\n");
337 /* Write it to disk. */
338 fp = fopen(file_crpt_file_cer, "w");
340 chmod(file_crpt_file_cer, 0600);
341 PEM_write_X509(fp, cer);
355 * Now try to bind to the key and certificate.
357 SSL_CTX_use_certificate_chain_file(ssl_ctx, file_crpt_file_cer);
358 SSL_CTX_use_PrivateKey_file(ssl_ctx, file_crpt_file_key, SSL_FILETYPE_PEM);
359 if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
360 CtdlLogPrintf(CTDL_CRIT, "Cannot install certificate: %s\n",
361 ERR_reason_error_string(ERR_get_error()));
364 /* Finally let the server know we're here */
365 CtdlRegisterProtoHook(cmd_stls, "STLS", "Start SSL/TLS session");
366 CtdlRegisterProtoHook(cmd_gtls, "GTLS",
367 "Get SSL/TLS session status");
368 CtdlRegisterSessionHook(endtls, EVT_STOP);
373 * client_write_ssl() Send binary data to the client encrypted.
375 void client_write_ssl(char *buf, int nbytes)
383 while (nremain > 0) {
384 if (SSL_want_write(CC->ssl)) {
385 if ((SSL_read(CC->ssl, junk, 0)) < 1) {
386 CtdlLogPrintf(CTDL_DEBUG, "SSL_read in client_write: %s\n", ERR_reason_error_string(ERR_get_error()));
390 SSL_write(CC->ssl, &buf[nbytes - nremain], nremain);
394 errval = SSL_get_error(CC->ssl, retval);
395 if (errval == SSL_ERROR_WANT_READ ||
396 errval == SSL_ERROR_WANT_WRITE) {
400 CtdlLogPrintf(CTDL_DEBUG, "SSL_write got error %ld, ret %d\n", errval, retval);
402 CtdlLogPrintf(CTDL_DEBUG, "errno is %d\n", errno);
404 client_write(&buf[nbytes - nremain], nremain);
413 * client_read_ssl() - read data from the encrypted layer.
415 int client_read_ssl(char *buf, int bytes, int timeout)
427 while (len < bytes) {
430 * This code is disabled because we don't need it when
431 * using blocking reads (which we are). -IO
434 s = BIO_get_fd(CC->ssl->rbio, NULL);
439 retval = select(s + 1, &rfds, NULL, NULL, &tv);
441 if (FD_ISSET(s, &rfds) == 0) {
446 if (SSL_want_read(CC->ssl)) {
447 if ((SSL_write(CC->ssl, junk, 0)) < 1) {
448 CtdlLogPrintf(CTDL_DEBUG, "SSL_write in client_read: %s\n", ERR_reason_error_string(ERR_get_error()));
451 rlen = SSL_read(CC->ssl, &buf[len], bytes - len);
455 errval = SSL_get_error(CC->ssl, rlen);
456 if (errval == SSL_ERROR_WANT_READ ||
457 errval == SSL_ERROR_WANT_WRITE) {
461 CtdlLogPrintf(CTDL_DEBUG, "SSL_read got error %ld\n", errval);
463 return (client_read_to
464 (&buf[len], bytes - len, timeout));
473 * CtdlStartTLS() starts SSL/TLS encryption for the current session. It
474 * must be supplied with pre-generated strings for responses of "ok," "no
475 * support for TLS," and "error" so that we can use this in any protocol.
477 void CtdlStartTLS(char *ok_response, char *nosup_response,
478 char *error_response) {
480 int retval, bits, alg_bits;
483 CtdlLogPrintf(CTDL_CRIT, "SSL failed: no ssl_ctx exists?\n");
484 if (nosup_response != NULL) cprintf("%s", nosup_response);
487 if (!(CC->ssl = SSL_new(ssl_ctx))) {
488 CtdlLogPrintf(CTDL_CRIT, "SSL_new failed: %s\n",
489 ERR_reason_error_string(ERR_get_error()));
490 if (error_response != NULL) cprintf("%s", error_response);
493 if (!(SSL_set_fd(CC->ssl, CC->client_socket))) {
494 CtdlLogPrintf(CTDL_CRIT, "SSL_set_fd failed: %s\n",
495 ERR_reason_error_string(ERR_get_error()));
498 if (error_response != NULL) cprintf("%s", error_response);
501 if (ok_response != NULL) cprintf("%s", ok_response);
502 retval = SSL_accept(CC->ssl);
505 * Can't notify the client of an error here; they will
506 * discover the problem at the SSL layer and should
507 * revert to unencrypted communications.
510 char error_string[128];
512 errval = SSL_get_error(CC->ssl, retval);
513 CtdlLogPrintf(CTDL_CRIT, "SSL_accept failed: retval=%d, errval=%ld, err=%s\n",
516 ERR_error_string(errval, error_string)
522 BIO_set_close(CC->ssl->rbio, BIO_NOCLOSE);
523 bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl), &alg_bits);
524 CtdlLogPrintf(CTDL_INFO, "SSL/TLS using %s on %s (%d of %d bits)\n",
525 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
526 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
528 CC->redirect_ssl = 1;
533 * cmd_stls() starts SSL/TLS encryption for the current session
535 void cmd_stls(char *params)
537 char ok_response[SIZ];
538 char nosup_response[SIZ];
539 char error_response[SIZ];
544 "%d Begin TLS negotiation now\n",
546 sprintf(nosup_response,
547 "%d TLS not supported here\n",
548 ERROR + CMD_NOT_SUPPORTED);
549 sprintf(error_response,
550 "%d TLS negotiation error\n",
551 ERROR + INTERNAL_ERROR);
553 CtdlStartTLS(ok_response, nosup_response, error_response);
558 * cmd_gtls() returns status info about the TLS connection
560 void cmd_gtls(char *params)
564 if (!CC->ssl || !CC->redirect_ssl) {
565 cprintf("%d Session is not encrypted.\n", ERROR);
569 SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl),
571 cprintf("%d %s|%s|%d|%d\n", CIT_OK,
572 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
573 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
579 * endtls() shuts down the TLS connection
581 * WARNING: This may make your session vulnerable to a known plaintext
582 * attack in the current implmentation.
587 CC->redirect_ssl = 0;
591 CtdlLogPrintf(CTDL_INFO, "Ending SSL/TLS\n");
592 SSL_shutdown(CC->ssl);
595 CC->redirect_ssl = 0;
600 * ssl_lock() callback for OpenSSL mutex locks
602 void ssl_lock(int mode, int n, const char *file, int line)
604 if (mode & CRYPTO_LOCK)
605 pthread_mutex_lock(SSLCritters[n]);
607 pthread_mutex_unlock(SSLCritters[n]);
609 #endif /* HAVE_OPENSSL */