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();
53 * Set up the cert things on the server side. We do need both the
54 * private key (in key_file) and the cert (in cert_file).
55 * Both files may be identical.
57 * This function is taken from OpenSSL apps/s_cb.c
60 static int ctdl_install_certificate(SSL_CTX * ctx,
61 const char *cert_file, const char *key_file)
63 if (cert_file != NULL) {
64 if (SSL_CTX_use_certificate_file(ctx, cert_file,
65 SSL_FILETYPE_PEM) <= 0) {
66 lprintf(3, "unable to get certificate from '%s'",
72 if (SSL_CTX_use_PrivateKey_file(ctx, key_file,
73 SSL_FILETYPE_PEM) <= 0) {
74 lprintf(3, "unable to get private key from '%s'",
78 /* Now we know that a key and cert have been set against
80 if (!SSL_CTX_check_private_key(ctx)) {
82 "Private key does not match the certificate public key");
92 SSL_METHOD *ssl_method;
97 X509_NAME *name = NULL;
100 if (!access("/var/run/egd-pool", F_OK))
101 RAND_egd("/var/run/egd-pool");
103 if (!RAND_status()) {
105 "PRNG not adequately seeded, won't do SSL/TLS\n");
109 mallok(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
111 lprintf(1, "citserver: can't allocate memory!!\n");
112 /* Nothing's been initialized, just die */
117 for (a = 0; a < CRYPTO_num_locks(); a++) {
118 SSLCritters[a] = mallok(sizeof(pthread_mutex_t));
119 if (!SSLCritters[a]) {
121 "citserver: can't allocate memory!!\n");
122 /* Nothing's been initialized, just die */
125 pthread_mutex_init(SSLCritters[a], NULL);
130 * Initialize SSL transport layer
133 SSL_load_error_strings();
134 ssl_method = SSLv23_server_method();
135 if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
136 lprintf(2, "SSL_CTX_new failed: %s\n",
137 ERR_reason_error_string(ERR_get_error()));
140 if (!(SSL_CTX_set_cipher_list(ssl_ctx, CIT_CIPHERS))) {
141 lprintf(2, "SSL: No ciphers available\n");
142 SSL_CTX_free(ssl_ctx);
147 #if SSLEAY_VERSION_NUMBER >= 0x00906000L
148 SSL_CTX_set_mode(ssl_ctx, SSL_CTX_get_mode(ssl_ctx) |
149 SSL_MODE_AUTO_RETRY);
153 CRYPTO_set_locking_callback(ssl_lock);
154 CRYPTO_set_id_callback(id_callback);
156 /* Load DH parameters into the context */
159 lprintf(2, "init_ssl() can't allocate a DH object: %s\n",
160 ERR_reason_error_string(ERR_get_error()));
161 SSL_CTX_free(ssl_ctx);
165 if (!(BN_hex2bn(&(dh->p), DH_P))) {
166 lprintf(2, "init_ssl() can't assign DH_P: %s\n",
167 ERR_reason_error_string(ERR_get_error()));
168 SSL_CTX_free(ssl_ctx);
172 if (!(BN_hex2bn(&(dh->g), DH_G))) {
173 lprintf(2, "init_ssl() can't assign DH_G: %s\n",
174 ERR_reason_error_string(ERR_get_error()));
175 SSL_CTX_free(ssl_ctx);
180 SSL_CTX_set_tmp_dh(ssl_ctx, dh);
183 /* Get our certificates in order.
184 * First, create the key/cert directory if it's not there already...
186 mkdir(CTDL_CRYPTO_DIR, 0700);
189 * Generate a key pair if we don't have one.
191 if (access(CTDL_KEY_PATH, R_OK) != 0) {
192 lprintf(3, "Generating RSA key pair.\n");
193 rsa = RSA_generate_key(1024, /* modulus size */
194 65537, /* exponent */
195 NULL, /* no callback */
196 NULL); /* no callback */
198 lprintf(2, "Key generation failed: %s\n",
199 ERR_reason_error_string(ERR_get_error()));
202 fp = fopen(CTDL_KEY_PATH, "w");
204 chmod(CTDL_KEY_PATH, 0600);
205 if (PEM_write_RSAPrivateKey(fp, /* the file */
208 NULL, /* no passphr */
210 NULL, /* no callbk */
213 lprintf(2, "Cannot write key: %s\n",
214 ERR_reason_error_string(ERR_get_error()));
215 unlink(CTDL_KEY_PATH);
224 * Generate a CSR if we don't have one.
226 if (access(CTDL_CSR_PATH, R_OK) != 0) {
227 lprintf(3, "Generating a certificate signing request.\n");
230 * Read our key from the file. No, we don't just keep this
231 * in memory from the above key-generation function, because
232 * there is the possibility that the key was already on disk
233 * and we didn't just generate it now.
235 fp = fopen(CTDL_KEY_PATH, "r");
237 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
243 /* Create a public key from the private key */
244 if (pk=EVP_PKEY_new(), pk != NULL) {
245 EVP_PKEY_assign_RSA(pk, rsa);
246 if (x = X509_REQ_new(), x != NULL) {
248 /* Set the public key */
249 X509_REQ_set_pubkey(x, pk);
250 X509_REQ_set_version(x, 0L);
252 name = X509_REQ_get_subject_name(x);
254 /* Tell it who we are */
257 X509_NAME_add_entry_by_txt(name, "C",
258 MBSTRING_ASC, "US", -1, -1, 0);
260 X509_NAME_add_entry_by_txt(name, "ST",
261 MBSTRING_ASC, "New York", -1, -1, 0);
263 X509_NAME_add_entry_by_txt(name, "L",
264 MBSTRING_ASC, "Mount Kisco", -1, -1, 0);
267 X509_NAME_add_entry_by_txt(name, "O",
268 MBSTRING_ASC, config.c_humannode, -1, -1, 0);
270 X509_NAME_add_entry_by_txt(name, "OU",
271 MBSTRING_ASC, "Citadel server", -1, -1, 0);
273 X509_NAME_add_entry_by_txt(name, "CN",
274 MBSTRING_ASC, config.c_fqdn, -1, -1, 0);
276 X509_REQ_set_subject_name(x, name);
279 if (!X509_REQ_sign(x, pk, EVP_md5())) {
280 lprintf(3, "X509_REQ_sign(): error\n");
283 /* Write it to disk. */
284 fp = fopen(CTDL_CSR_PATH, "w");
286 chmod(CTDL_CSR_PATH, 0600);
287 PEM_write_X509_REQ(fp, x);
300 lprintf(3, "Unable to read private key.\n");
307 * Generate a self-signed certificate if we don't have one.
309 if (access(CTDL_CER_PATH, R_OK) != 0) {
310 lprintf(3, "Generating a self-signed certificate.\n");
313 /* FIXME ... do it */
318 * Now try to bind to the key and certificate.
320 if (ctdl_install_certificate(ssl_ctx,
324 lprintf(2, "Cannot install certificate: %s\n",
325 ERR_reason_error_string(ERR_get_error()));
328 /* Finally let the server know we're here */
329 CtdlRegisterProtoHook(cmd_stls, "STLS", "Start SSL/TLS session");
330 CtdlRegisterProtoHook(cmd_gtls, "GTLS",
331 "Get SSL/TLS session status");
332 CtdlRegisterSessionHook(endtls, EVT_STOP);
337 * client_write_ssl() Send binary data to the client encrypted.
339 void client_write_ssl(char *buf, int nbytes)
347 while (nremain > 0) {
348 if (SSL_want_write(CC->ssl)) {
349 if ((SSL_read(CC->ssl, junk, 0)) < 1) {
350 lprintf(9, "SSL_read in client_write:\n");
351 ERR_print_errors_fp(stderr);
355 SSL_write(CC->ssl, &buf[nbytes - nremain], nremain);
359 errval = SSL_get_error(CC->ssl, retval);
360 if (errval == SSL_ERROR_WANT_READ ||
361 errval == SSL_ERROR_WANT_WRITE) {
365 lprintf(9, "SSL_write got error %ld, ret %d\n", errval, retval);
367 lprintf(9, "errno is %d\n", errno);
369 client_write(&buf[nbytes - nremain], nremain);
378 * client_read_ssl() - read data from the encrypted layer.
380 int client_read_ssl(char *buf, int bytes, int timeout)
392 while (len < bytes) {
395 * This code is disabled because we don't need it when
396 * using blocking reads (which we are). -IO
399 s = BIO_get_fd(CC->ssl->rbio, NULL);
404 retval = select(s + 1, &rfds, NULL, NULL, &tv);
406 if (FD_ISSET(s, &rfds) == 0) {
411 if (SSL_want_read(CC->ssl)) {
412 if ((SSL_write(CC->ssl, junk, 0)) < 1) {
413 lprintf(9, "SSL_write in client_read:\n");
414 ERR_print_errors_fp(stderr);
417 rlen = SSL_read(CC->ssl, &buf[len], bytes - len);
421 errval = SSL_get_error(CC->ssl, rlen);
422 if (errval == SSL_ERROR_WANT_READ ||
423 errval == SSL_ERROR_WANT_WRITE) {
427 lprintf(9, "SSL_read got error %ld\n", errval);
429 return (client_read_to
430 (&buf[len], bytes - len, timeout));
439 * CtdlStartTLS() starts SSL/TLS encryption for the current session. It
440 * must be supplied with pre-generated strings for responses of "ok," "no
441 * support for TLS," and "error" so that we can use this in any protocol.
443 void CtdlStartTLS(char *ok_response, char *nosup_response,
444 char *error_response) {
446 int retval, bits, alg_bits;
449 cprintf("%s", nosup_response);
452 if (!(CC->ssl = SSL_new(ssl_ctx))) {
453 lprintf(2, "SSL_new failed: %s\n",
454 ERR_reason_error_string(ERR_get_error()));
455 cprintf("%s", error_response);
458 if (!(SSL_set_fd(CC->ssl, CC->client_socket))) {
459 lprintf(2, "SSL_set_fd failed: %s\n",
460 ERR_reason_error_string(ERR_get_error()));
463 cprintf("%s", error_response);
466 cprintf("%s", ok_response);
467 retval = SSL_accept(CC->ssl);
470 * Can't notify the client of an error here; they will
471 * discover the problem at the SSL layer and should
472 * revert to unencrypted communications.
476 errval = SSL_get_error(CC->ssl, retval);
477 lprintf(2, "SSL_accept failed: %s\n",
478 ERR_reason_error_string(ERR_get_error()));
483 BIO_set_close(CC->ssl->rbio, BIO_NOCLOSE);
485 SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl),
487 lprintf(3, "SSL/TLS using %s on %s (%d of %d bits)\n",
488 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
489 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
491 CC->redirect_ssl = 1;
496 * cmd_stls() starts SSL/TLS encryption for the current session
498 void cmd_stls(char *params)
500 char ok_response[SIZ];
501 char nosup_response[SIZ];
502 char error_response[SIZ];
505 "%d Begin TLS negotiation now\n",
507 sprintf(nosup_response,
508 "%d TLS not supported here\n",
509 ERROR + CMD_NOT_SUPPORTED);
510 sprintf(error_response,
511 "%d TLS negotiation error\n",
512 ERROR + INTERNAL_ERROR);
514 CtdlStartTLS(ok_response, nosup_response, error_response);
519 * cmd_gtls() returns status info about the TLS connection
521 void cmd_gtls(char *params)
525 if (!CC->ssl || !CC->redirect_ssl) {
526 cprintf("%d Session is not encrypted.\n", ERROR);
530 SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl),
532 cprintf("%d %s|%s|%d|%d\n", CIT_OK,
533 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
534 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
540 * endtls() shuts down the TLS connection
542 * WARNING: This may make your session vulnerable to a known plaintext
543 * attack in the current implmentation.
547 lprintf(7, "Ending SSL/TLS\n");
550 CC->redirect_ssl = 0;
554 SSL_shutdown(CC->ssl);
557 CC->redirect_ssl = 0;
562 * ssl_lock() callback for OpenSSL mutex locks
564 void ssl_lock(int mode, int n, const char *file, int line)
566 if (mode & CRYPTO_LOCK)
567 pthread_mutex_lock(SSLCritters[n]);
569 pthread_mutex_unlock(SSLCritters[n]);
571 #endif /* HAVE_OPENSSL */