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"
38 #include "serv_extensions.h"
44 SSL_CTX *ssl_ctx; /* SSL context */
45 pthread_mutex_t **SSLCritters; /* Things needing locking */
47 static unsigned long id_callback(void)
49 return (unsigned long) pthread_self();
54 SSL_METHOD *ssl_method;
60 EVP_PKEY *req_pkey = NULL;
61 X509_NAME *name = NULL;
64 if (!access("/var/run/egd-pool", F_OK))
65 RAND_egd("/var/run/egd-pool");
69 "PRNG not adequately seeded, won't do SSL/TLS\n");
73 malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
75 lprintf(CTDL_EMERG, "citserver: can't allocate memory!!\n");
76 /* Nothing's been initialized, just die */
81 for (a = 0; a < CRYPTO_num_locks(); a++) {
82 SSLCritters[a] = malloc(sizeof(pthread_mutex_t));
83 if (!SSLCritters[a]) {
85 "citserver: can't allocate memory!!\n");
86 /* Nothing's been initialized, just die */
89 pthread_mutex_init(SSLCritters[a], NULL);
94 * Initialize SSL transport layer
97 SSL_load_error_strings();
98 ssl_method = SSLv23_server_method();
99 if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
100 lprintf(CTDL_CRIT, "SSL_CTX_new failed: %s\n",
101 ERR_reason_error_string(ERR_get_error()));
104 if (!(SSL_CTX_set_cipher_list(ssl_ctx, CIT_CIPHERS))) {
105 lprintf(CTDL_CRIT, "SSL: No ciphers available\n");
106 SSL_CTX_free(ssl_ctx);
111 #if SSLEAY_VERSION_NUMBER >= 0x00906000L
112 SSL_CTX_set_mode(ssl_ctx, SSL_CTX_get_mode(ssl_ctx) |
113 SSL_MODE_AUTO_RETRY);
117 CRYPTO_set_locking_callback(ssl_lock);
118 CRYPTO_set_id_callback(id_callback);
120 /* Load DH parameters into the context */
123 lprintf(CTDL_CRIT, "init_ssl() can't allocate a DH object: %s\n",
124 ERR_reason_error_string(ERR_get_error()));
125 SSL_CTX_free(ssl_ctx);
129 if (!(BN_hex2bn(&(dh->p), DH_P))) {
130 lprintf(CTDL_CRIT, "init_ssl() can't assign DH_P: %s\n",
131 ERR_reason_error_string(ERR_get_error()));
132 SSL_CTX_free(ssl_ctx);
136 if (!(BN_hex2bn(&(dh->g), DH_G))) {
137 lprintf(CTDL_CRIT, "init_ssl() can't assign DH_G: %s\n",
138 ERR_reason_error_string(ERR_get_error()));
139 SSL_CTX_free(ssl_ctx);
144 SSL_CTX_set_tmp_dh(ssl_ctx, dh);
147 /* Get our certificates in order.
148 * First, create the key/cert directory if it's not there already...
150 mkdir(CTDL_CRYPTO_DIR, 0700);
153 * Generate a key pair if we don't have one.
155 if (access(CTDL_KEY_PATH, R_OK) != 0) {
156 lprintf(CTDL_INFO, "Generating RSA key pair.\n");
157 rsa = RSA_generate_key(1024, /* modulus size */
158 65537, /* exponent */
159 NULL, /* no callback */
160 NULL); /* no callback */
162 lprintf(CTDL_CRIT, "Key generation failed: %s\n",
163 ERR_reason_error_string(ERR_get_error()));
166 fp = fopen(CTDL_KEY_PATH, "w");
168 chmod(CTDL_KEY_PATH, 0600);
169 if (PEM_write_RSAPrivateKey(fp, /* the file */
172 NULL, /* no passphr */
174 NULL, /* no callbk */
177 lprintf(CTDL_CRIT, "Cannot write key: %s\n",
178 ERR_reason_error_string(ERR_get_error()));
179 unlink(CTDL_KEY_PATH);
188 * Generate a CSR if we don't have one.
190 if (access(CTDL_CSR_PATH, R_OK) != 0) {
191 lprintf(CTDL_INFO, "Generating a certificate signing request.\n");
194 * Read our key from the file. No, we don't just keep this
195 * in memory from the above key-generation function, because
196 * there is the possibility that the key was already on disk
197 * and we didn't just generate it now.
199 fp = fopen(CTDL_KEY_PATH, "r");
201 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
207 /* Create a public key from the private key */
208 if (pk=EVP_PKEY_new(), pk != NULL) {
209 EVP_PKEY_assign_RSA(pk, rsa);
210 if (req = X509_REQ_new(), req != NULL) {
212 /* Set the public key */
213 X509_REQ_set_pubkey(req, pk);
214 X509_REQ_set_version(req, 0L);
216 name = X509_REQ_get_subject_name(req);
218 /* Tell it who we are */
221 X509_NAME_add_entry_by_txt(name, "C",
222 MBSTRING_ASC, "US", -1, -1, 0);
224 X509_NAME_add_entry_by_txt(name, "ST",
225 MBSTRING_ASC, "New York", -1, -1, 0);
227 X509_NAME_add_entry_by_txt(name, "L",
228 MBSTRING_ASC, "Mount Kisco", -1, -1, 0);
231 X509_NAME_add_entry_by_txt(name, "O",
232 MBSTRING_ASC, config.c_humannode, -1, -1, 0);
234 X509_NAME_add_entry_by_txt(name, "OU",
235 MBSTRING_ASC, "Citadel server", -1, -1, 0);
237 X509_NAME_add_entry_by_txt(name, "CN",
238 MBSTRING_ASC, config.c_fqdn, -1, -1, 0);
240 X509_REQ_set_subject_name(req, name);
243 if (!X509_REQ_sign(req, pk, EVP_md5())) {
244 lprintf(CTDL_CRIT, "X509_REQ_sign(): error\n");
247 /* Write it to disk. */
248 fp = fopen(CTDL_CSR_PATH, "w");
250 chmod(CTDL_CSR_PATH, 0600);
251 PEM_write_X509_REQ(fp, req);
264 lprintf(CTDL_CRIT, "Unable to read private key.\n");
271 * Generate a self-signed certificate if we don't have one.
273 if (access(CTDL_CER_PATH, R_OK) != 0) {
274 lprintf(CTDL_INFO, "Generating a self-signed certificate.\n");
276 /* Same deal as before: always read the key from disk because
277 * it may or may not have just been generated.
279 fp = fopen(CTDL_KEY_PATH, "r");
281 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
285 /* This also holds true for the CSR. */
290 if (pk=EVP_PKEY_new(), pk != NULL) {
291 EVP_PKEY_assign_RSA(pk, rsa);
294 fp = fopen(CTDL_CSR_PATH, "r");
296 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
301 if (cer = X509_new(), cer != NULL) {
303 ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
304 X509_set_issuer_name(cer, req->req_info->subject);
305 X509_set_subject_name(cer, req->req_info->subject);
306 X509_gmtime_adj(X509_get_notBefore(cer),0);
307 X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
308 req_pkey = X509_REQ_get_pubkey(req);
309 X509_set_pubkey(cer, req_pkey);
310 EVP_PKEY_free(req_pkey);
313 if (!X509_sign(cer, pk, EVP_md5())) {
314 lprintf(CTDL_CRIT, "X509_sign(): error\n");
317 /* Write it to disk. */
318 fp = fopen(CTDL_CER_PATH, "w");
320 chmod(CTDL_CER_PATH, 0600);
321 PEM_write_X509(fp, cer);
335 * Now try to bind to the key and certificate.
337 SSL_CTX_use_certificate_chain_file(ssl_ctx, CTDL_CER_PATH);
338 SSL_CTX_use_PrivateKey_file(ssl_ctx, CTDL_KEY_PATH, SSL_FILETYPE_PEM);
339 if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
340 lprintf(CTDL_CRIT, "Cannot install certificate: %s\n",
341 ERR_reason_error_string(ERR_get_error()));
344 /* Finally let the server know we're here */
345 CtdlRegisterProtoHook(cmd_stls, "STLS", "Start SSL/TLS session");
346 CtdlRegisterProtoHook(cmd_gtls, "GTLS",
347 "Get SSL/TLS session status");
348 CtdlRegisterSessionHook(endtls, EVT_STOP);
353 * client_write_ssl() Send binary data to the client encrypted.
355 void client_write_ssl(char *buf, int nbytes)
363 while (nremain > 0) {
364 if (SSL_want_write(CC->ssl)) {
365 if ((SSL_read(CC->ssl, junk, 0)) < 1) {
366 lprintf(CTDL_DEBUG, "SSL_read in client_write: %s\n", ERR_reason_error_string(ERR_get_error()));
370 SSL_write(CC->ssl, &buf[nbytes - nremain], nremain);
374 errval = SSL_get_error(CC->ssl, retval);
375 if (errval == SSL_ERROR_WANT_READ ||
376 errval == SSL_ERROR_WANT_WRITE) {
380 lprintf(CTDL_DEBUG, "SSL_write got error %ld, ret %d\n", errval, retval);
382 lprintf(CTDL_DEBUG, "errno is %d\n", errno);
384 client_write(&buf[nbytes - nremain], nremain);
393 * client_read_ssl() - read data from the encrypted layer.
395 int client_read_ssl(char *buf, int bytes, int timeout)
407 while (len < bytes) {
410 * This code is disabled because we don't need it when
411 * using blocking reads (which we are). -IO
414 s = BIO_get_fd(CC->ssl->rbio, NULL);
419 retval = select(s + 1, &rfds, NULL, NULL, &tv);
421 if (FD_ISSET(s, &rfds) == 0) {
426 if (SSL_want_read(CC->ssl)) {
427 if ((SSL_write(CC->ssl, junk, 0)) < 1) {
428 lprintf(CTDL_DEBUG, "SSL_write in client_read: %s\n", ERR_reason_error_string(ERR_get_error()));
431 rlen = SSL_read(CC->ssl, &buf[len], bytes - len);
435 errval = SSL_get_error(CC->ssl, rlen);
436 if (errval == SSL_ERROR_WANT_READ ||
437 errval == SSL_ERROR_WANT_WRITE) {
441 lprintf(CTDL_DEBUG, "SSL_read got error %ld\n", errval);
443 return (client_read_to
444 (&buf[len], bytes - len, timeout));
453 * CtdlStartTLS() starts SSL/TLS encryption for the current session. It
454 * must be supplied with pre-generated strings for responses of "ok," "no
455 * support for TLS," and "error" so that we can use this in any protocol.
457 void CtdlStartTLS(char *ok_response, char *nosup_response,
458 char *error_response) {
460 int retval, bits, alg_bits;
463 lprintf(CTDL_CRIT, "SSL failed: no ssl_ctx exists?\n");
464 if (nosup_response != NULL) cprintf("%s", nosup_response);
467 if (!(CC->ssl = SSL_new(ssl_ctx))) {
468 lprintf(CTDL_CRIT, "SSL_new failed: %s\n",
469 ERR_reason_error_string(ERR_get_error()));
470 if (error_response != NULL) cprintf("%s", error_response);
473 if (!(SSL_set_fd(CC->ssl, CC->client_socket))) {
474 lprintf(CTDL_CRIT, "SSL_set_fd failed: %s\n",
475 ERR_reason_error_string(ERR_get_error()));
478 if (error_response != NULL) cprintf("%s", error_response);
481 if (ok_response != NULL) cprintf("%s", ok_response);
482 retval = SSL_accept(CC->ssl);
485 * Can't notify the client of an error here; they will
486 * discover the problem at the SSL layer and should
487 * revert to unencrypted communications.
491 errval = SSL_get_error(CC->ssl, retval);
492 lprintf(CTDL_CRIT, "SSL_accept failed: %s\n",
493 ERR_reason_error_string(ERR_get_error()));
498 BIO_set_close(CC->ssl->rbio, BIO_NOCLOSE);
500 SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl),
502 lprintf(CTDL_INFO, "SSL/TLS using %s on %s (%d of %d bits)\n",
503 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
504 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
506 CC->redirect_ssl = 1;
511 * cmd_stls() starts SSL/TLS encryption for the current session
513 void cmd_stls(char *params)
515 char ok_response[SIZ];
516 char nosup_response[SIZ];
517 char error_response[SIZ];
522 "%d Begin TLS negotiation now\n",
524 sprintf(nosup_response,
525 "%d TLS not supported here\n",
526 ERROR + CMD_NOT_SUPPORTED);
527 sprintf(error_response,
528 "%d TLS negotiation error\n",
529 ERROR + INTERNAL_ERROR);
531 CtdlStartTLS(ok_response, nosup_response, error_response);
536 * cmd_gtls() returns status info about the TLS connection
538 void cmd_gtls(char *params)
542 if (!CC->ssl || !CC->redirect_ssl) {
543 cprintf("%d Session is not encrypted.\n", ERROR);
547 SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl),
549 cprintf("%d %s|%s|%d|%d\n", CIT_OK,
550 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
551 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
557 * endtls() shuts down the TLS connection
559 * WARNING: This may make your session vulnerable to a known plaintext
560 * attack in the current implmentation.
565 CC->redirect_ssl = 0;
569 lprintf(CTDL_INFO, "Ending SSL/TLS\n");
570 SSL_shutdown(CC->ssl);
573 CC->redirect_ssl = 0;
578 * ssl_lock() callback for OpenSSL mutex locks
580 void ssl_lock(int mode, int n, const char *file, int line)
582 if (mode & CRYPTO_LOCK)
583 pthread_mutex_lock(SSLCritters[n]);
585 pthread_mutex_unlock(SSLCritters[n]);
587 #endif /* HAVE_OPENSSL */