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>
36 #include "serv_crypto.h"
37 #include "sysdep_decls.h"
42 #include "ctdl_module.h"
43 /* TODO: should we use the standard module init stuff to start this? */
44 /* TODO: should we register an event handler to call destruct_ssl? */
47 SSL_CTX *ssl_ctx; /* SSL context */
48 pthread_mutex_t **SSLCritters; /* Things needing locking */
50 static unsigned long id_callback(void)
52 return (unsigned long) pthread_self();
55 void destruct_ssl(void)
58 CtdlUnregisterProtoHook(cmd_stls, "STLS");
59 CtdlUnregisterProtoHook(cmd_gtls, "GTLS");
60 for (a = 0; a < CRYPTO_num_locks(); a++)
67 SSL_METHOD *ssl_method;
73 EVP_PKEY *req_pkey = NULL;
74 X509_NAME *name = NULL;
77 if (!access(EGD_POOL, F_OK))
82 "PRNG not adequately seeded, won't do SSL/TLS\n");
86 malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
88 lprintf(CTDL_EMERG, "citserver: can't allocate memory!!\n");
89 /* Nothing's been initialized, just die */
94 for (a = 0; a < CRYPTO_num_locks(); a++) {
95 SSLCritters[a] = malloc(sizeof(pthread_mutex_t));
96 if (!SSLCritters[a]) {
98 "citserver: can't allocate memory!!\n");
99 /* Nothing's been initialized, just die */
102 pthread_mutex_init(SSLCritters[a], NULL);
107 * Initialize SSL transport layer
110 SSL_load_error_strings();
111 ssl_method = SSLv23_server_method();
112 if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
113 lprintf(CTDL_CRIT, "SSL_CTX_new failed: %s\n",
114 ERR_reason_error_string(ERR_get_error()));
117 if (!(SSL_CTX_set_cipher_list(ssl_ctx, CIT_CIPHERS))) {
118 lprintf(CTDL_CRIT, "SSL: No ciphers available\n");
119 SSL_CTX_free(ssl_ctx);
124 #if SSLEAY_VERSION_NUMBER >= 0x00906000L
125 SSL_CTX_set_mode(ssl_ctx, SSL_CTX_get_mode(ssl_ctx) |
126 SSL_MODE_AUTO_RETRY);
130 CRYPTO_set_locking_callback(ssl_lock);
131 CRYPTO_set_id_callback(id_callback);
133 /* Load DH parameters into the context */
136 lprintf(CTDL_CRIT, "init_ssl() can't allocate a DH object: %s\n",
137 ERR_reason_error_string(ERR_get_error()));
138 SSL_CTX_free(ssl_ctx);
142 if (!(BN_hex2bn(&(dh->p), DH_P))) {
143 lprintf(CTDL_CRIT, "init_ssl() can't assign DH_P: %s\n",
144 ERR_reason_error_string(ERR_get_error()));
145 SSL_CTX_free(ssl_ctx);
149 if (!(BN_hex2bn(&(dh->g), DH_G))) {
150 lprintf(CTDL_CRIT, "init_ssl() can't assign DH_G: %s\n",
151 ERR_reason_error_string(ERR_get_error()));
152 SSL_CTX_free(ssl_ctx);
157 SSL_CTX_set_tmp_dh(ssl_ctx, dh);
160 /* Get our certificates in order.
161 * First, create the key/cert directory if it's not there already...
163 mkdir(ctdl_key_dir, 0700);
166 * Generate a key pair if we don't have one.
168 if (access(file_crpt_file_key, R_OK) != 0) {
169 lprintf(CTDL_INFO, "Generating RSA key pair.\n");
170 rsa = RSA_generate_key(1024, /* modulus size */
171 65537, /* exponent */
172 NULL, /* no callback */
173 NULL); /* no callback */
175 lprintf(CTDL_CRIT, "Key generation failed: %s\n",
176 ERR_reason_error_string(ERR_get_error()));
179 fp = fopen(file_crpt_file_key, "w");
181 chmod(file_crpt_file_key, 0600);
182 if (PEM_write_RSAPrivateKey(fp, /* the file */
185 NULL, /* no passphr */
187 NULL, /* no callbk */
190 lprintf(CTDL_CRIT, "Cannot write key: %s\n",
191 ERR_reason_error_string(ERR_get_error()));
192 unlink(file_crpt_file_key);
201 * If there is no certificate file on disk, we will be generating a self-signed certificate
202 * in the next step. Therefore, if we have neither a CSR nor a certificate, generate
203 * the CSR in this step so that the next step may commence.
205 if ( (access(file_crpt_file_cer, R_OK) != 0) && (access(file_crpt_file_csr, R_OK) != 0) ) {
206 lprintf(CTDL_INFO, "Generating a certificate signing request.\n");
209 * Read our key from the file. No, we don't just keep this
210 * in memory from the above key-generation function, because
211 * there is the possibility that the key was already on disk
212 * and we didn't just generate it now.
214 fp = fopen(file_crpt_file_key, "r");
216 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
222 /* Create a public key from the private key */
223 if (pk=EVP_PKEY_new(), pk != NULL) {
224 EVP_PKEY_assign_RSA(pk, rsa);
225 if (req = X509_REQ_new(), req != NULL) {
227 /* Set the public key */
228 X509_REQ_set_pubkey(req, pk);
229 X509_REQ_set_version(req, 0L);
231 name = X509_REQ_get_subject_name(req);
233 /* Tell it who we are */
236 X509_NAME_add_entry_by_txt(name, "C",
237 MBSTRING_ASC, "US", -1, -1, 0);
239 X509_NAME_add_entry_by_txt(name, "ST",
240 MBSTRING_ASC, "New York", -1, -1, 0);
242 X509_NAME_add_entry_by_txt(name, "L",
243 MBSTRING_ASC, "Mount Kisco", -1, -1, 0);
246 X509_NAME_add_entry_by_txt(name, "O",
247 MBSTRING_ASC, config.c_humannode, -1, -1, 0);
249 X509_NAME_add_entry_by_txt(name, "OU",
250 MBSTRING_ASC, "Citadel server", -1, -1, 0);
252 /* X509_NAME_add_entry_by_txt(name, "CN",
253 MBSTRING_ASC, config.c_fqdn, -1, -1, 0);
256 X509_NAME_add_entry_by_txt(name, "CN",
257 MBSTRING_ASC, "*", -1, -1, 0);
259 X509_REQ_set_subject_name(req, name);
262 if (!X509_REQ_sign(req, pk, EVP_md5())) {
263 lprintf(CTDL_CRIT, "X509_REQ_sign(): error\n");
266 /* Write it to disk. */
267 fp = fopen(file_crpt_file_csr, "w");
269 chmod(file_crpt_file_csr, 0600);
270 PEM_write_X509_REQ(fp, req);
283 lprintf(CTDL_CRIT, "Unable to read private key.\n");
290 * Generate a self-signed certificate if we don't have one.
292 if (access(file_crpt_file_cer, R_OK) != 0) {
293 lprintf(CTDL_INFO, "Generating a self-signed certificate.\n");
295 /* Same deal as before: always read the key from disk because
296 * it may or may not have just been generated.
298 fp = fopen(file_crpt_file_key, "r");
300 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
304 /* This also holds true for the CSR. */
309 if (pk=EVP_PKEY_new(), pk != NULL) {
310 EVP_PKEY_assign_RSA(pk, rsa);
313 fp = fopen(file_crpt_file_csr, "r");
315 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
320 if (cer = X509_new(), cer != NULL) {
322 ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
323 X509_set_issuer_name(cer, req->req_info->subject);
324 X509_set_subject_name(cer, req->req_info->subject);
325 X509_gmtime_adj(X509_get_notBefore(cer),0);
326 X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
327 req_pkey = X509_REQ_get_pubkey(req);
328 X509_set_pubkey(cer, req_pkey);
329 EVP_PKEY_free(req_pkey);
332 if (!X509_sign(cer, pk, EVP_md5())) {
333 lprintf(CTDL_CRIT, "X509_sign(): error\n");
336 /* Write it to disk. */
337 fp = fopen(file_crpt_file_cer, "w");
339 chmod(file_crpt_file_cer, 0600);
340 PEM_write_X509(fp, cer);
354 * Now try to bind to the key and certificate.
356 SSL_CTX_use_certificate_chain_file(ssl_ctx, file_crpt_file_cer);
357 SSL_CTX_use_PrivateKey_file(ssl_ctx, file_crpt_file_key, SSL_FILETYPE_PEM);
358 if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
359 lprintf(CTDL_CRIT, "Cannot install certificate: %s\n",
360 ERR_reason_error_string(ERR_get_error()));
363 /* Finally let the server know we're here */
364 CtdlRegisterProtoHook(cmd_stls, "STLS", "Start SSL/TLS session");
365 CtdlRegisterProtoHook(cmd_gtls, "GTLS",
366 "Get SSL/TLS session status");
367 CtdlRegisterSessionHook(endtls, EVT_STOP);
372 * client_write_ssl() Send binary data to the client encrypted.
374 void client_write_ssl(char *buf, int nbytes)
382 while (nremain > 0) {
383 if (SSL_want_write(CC->ssl)) {
384 if ((SSL_read(CC->ssl, junk, 0)) < 1) {
385 lprintf(CTDL_DEBUG, "SSL_read in client_write: %s\n", ERR_reason_error_string(ERR_get_error()));
389 SSL_write(CC->ssl, &buf[nbytes - nremain], nremain);
393 errval = SSL_get_error(CC->ssl, retval);
394 if (errval == SSL_ERROR_WANT_READ ||
395 errval == SSL_ERROR_WANT_WRITE) {
399 lprintf(CTDL_DEBUG, "SSL_write got error %ld, ret %d\n", errval, retval);
401 lprintf(CTDL_DEBUG, "errno is %d\n", errno);
403 client_write(&buf[nbytes - nremain], nremain);
412 * client_read_ssl() - read data from the encrypted layer.
414 int client_read_ssl(char *buf, int bytes, int timeout)
426 while (len < bytes) {
429 * This code is disabled because we don't need it when
430 * using blocking reads (which we are). -IO
433 s = BIO_get_fd(CC->ssl->rbio, NULL);
438 retval = select(s + 1, &rfds, NULL, NULL, &tv);
440 if (FD_ISSET(s, &rfds) == 0) {
445 if (SSL_want_read(CC->ssl)) {
446 if ((SSL_write(CC->ssl, junk, 0)) < 1) {
447 lprintf(CTDL_DEBUG, "SSL_write in client_read: %s\n", ERR_reason_error_string(ERR_get_error()));
450 rlen = SSL_read(CC->ssl, &buf[len], bytes - len);
454 errval = SSL_get_error(CC->ssl, rlen);
455 if (errval == SSL_ERROR_WANT_READ ||
456 errval == SSL_ERROR_WANT_WRITE) {
460 lprintf(CTDL_DEBUG, "SSL_read got error %ld\n", errval);
462 return (client_read_to
463 (&buf[len], bytes - len, timeout));
472 * CtdlStartTLS() starts SSL/TLS encryption for the current session. It
473 * must be supplied with pre-generated strings for responses of "ok," "no
474 * support for TLS," and "error" so that we can use this in any protocol.
476 void CtdlStartTLS(char *ok_response, char *nosup_response,
477 char *error_response) {
479 int retval, bits, alg_bits;
482 lprintf(CTDL_CRIT, "SSL failed: no ssl_ctx exists?\n");
483 if (nosup_response != NULL) cprintf("%s", nosup_response);
486 if (!(CC->ssl = SSL_new(ssl_ctx))) {
487 lprintf(CTDL_CRIT, "SSL_new failed: %s\n",
488 ERR_reason_error_string(ERR_get_error()));
489 if (error_response != NULL) cprintf("%s", error_response);
492 if (!(SSL_set_fd(CC->ssl, CC->client_socket))) {
493 lprintf(CTDL_CRIT, "SSL_set_fd failed: %s\n",
494 ERR_reason_error_string(ERR_get_error()));
497 if (error_response != NULL) cprintf("%s", error_response);
500 if (ok_response != NULL) cprintf("%s", ok_response);
501 retval = SSL_accept(CC->ssl);
504 * Can't notify the client of an error here; they will
505 * discover the problem at the SSL layer and should
506 * revert to unencrypted communications.
509 char error_string[128];
511 errval = SSL_get_error(CC->ssl, retval);
512 lprintf(CTDL_CRIT, "SSL_accept failed: retval=%d, errval=%ld, err=%s\n",
515 ERR_error_string(errval, error_string)
521 BIO_set_close(CC->ssl->rbio, BIO_NOCLOSE);
522 bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl), &alg_bits);
523 lprintf(CTDL_INFO, "SSL/TLS using %s on %s (%d of %d bits)\n",
524 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
525 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
527 CC->redirect_ssl = 1;
532 * cmd_stls() starts SSL/TLS encryption for the current session
534 void cmd_stls(char *params)
536 char ok_response[SIZ];
537 char nosup_response[SIZ];
538 char error_response[SIZ];
543 "%d Begin TLS negotiation now\n",
545 sprintf(nosup_response,
546 "%d TLS not supported here\n",
547 ERROR + CMD_NOT_SUPPORTED);
548 sprintf(error_response,
549 "%d TLS negotiation error\n",
550 ERROR + INTERNAL_ERROR);
552 CtdlStartTLS(ok_response, nosup_response, error_response);
557 * cmd_gtls() returns status info about the TLS connection
559 void cmd_gtls(char *params)
563 if (!CC->ssl || !CC->redirect_ssl) {
564 cprintf("%d Session is not encrypted.\n", ERROR);
568 SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl),
570 cprintf("%d %s|%s|%d|%d\n", CIT_OK,
571 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
572 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
578 * endtls() shuts down the TLS connection
580 * WARNING: This may make your session vulnerable to a known plaintext
581 * attack in the current implmentation.
586 CC->redirect_ssl = 0;
590 lprintf(CTDL_INFO, "Ending SSL/TLS\n");
591 SSL_shutdown(CC->ssl);
594 CC->redirect_ssl = 0;
599 * ssl_lock() callback for OpenSSL mutex locks
601 void ssl_lock(int mode, int n, const char *file, int line)
603 if (mode & CRYPTO_LOCK)
604 pthread_mutex_lock(SSLCritters[n]);
606 pthread_mutex_unlock(SSLCritters[n]);
608 #endif /* HAVE_OPENSSL */