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 (FIXME more here later) */
255 X509_NAME_add_entry_by_txt(name, "C",
256 MBSTRING_ASC, "US", -1, -1, 0);
258 X509_NAME_add_entry_by_txt(name, "CN",
259 MBSTRING_ASC, config.c_fqdn, -1, -1, 0);
261 X509_REQ_set_subject_name(x, name);
264 if (!X509_REQ_sign(x, pk, EVP_md5())) {
265 lprintf(3, "X509_REQ_sign(): error\n");
268 /* Write it to disk. */
269 fp = fopen(CTDL_CSR_PATH, "w");
271 chmod(CTDL_CSR_PATH, 0600);
272 PEM_write_X509_REQ(fp, x);
285 lprintf(3, "Unable to read private key.\n");
292 * Generate a self-signed certificate if we don't have one.
294 if (access(CTDL_CER_PATH, R_OK) != 0) {
295 lprintf(3, "Generating a self-signed certificate.\n");
298 /* FIXME ... do it */
303 * Now try to bind to the key and certificate.
305 if (ctdl_install_certificate(ssl_ctx,
309 lprintf(2, "Cannot install certificate: %s\n",
310 ERR_reason_error_string(ERR_get_error()));
313 /* Finally let the server know we're here */
314 CtdlRegisterProtoHook(cmd_stls, "STLS", "Start SSL/TLS session");
315 CtdlRegisterProtoHook(cmd_gtls, "GTLS",
316 "Get SSL/TLS session status");
317 CtdlRegisterSessionHook(endtls, EVT_STOP);
322 * client_write_ssl() Send binary data to the client encrypted.
324 void client_write_ssl(char *buf, int nbytes)
332 while (nremain > 0) {
333 if (SSL_want_write(CC->ssl)) {
334 if ((SSL_read(CC->ssl, junk, 0)) < 1) {
335 lprintf(9, "SSL_read in client_write:\n");
336 ERR_print_errors_fp(stderr);
340 SSL_write(CC->ssl, &buf[nbytes - nremain], nremain);
344 errval = SSL_get_error(CC->ssl, retval);
345 if (errval == SSL_ERROR_WANT_READ ||
346 errval == SSL_ERROR_WANT_WRITE) {
350 lprintf(9, "SSL_write got error %ld, ret %d\n", errval, retval);
352 lprintf(9, "errno is %d\n", errno);
354 client_write(&buf[nbytes - nremain], nremain);
363 * client_read_ssl() - read data from the encrypted layer.
365 int client_read_ssl(char *buf, int bytes, int timeout)
377 while (len < bytes) {
380 * This code is disabled because we don't need it when
381 * using blocking reads (which we are). -IO
384 s = BIO_get_fd(CC->ssl->rbio, NULL);
389 retval = select(s + 1, &rfds, NULL, NULL, &tv);
391 if (FD_ISSET(s, &rfds) == 0) {
396 if (SSL_want_read(CC->ssl)) {
397 if ((SSL_write(CC->ssl, junk, 0)) < 1) {
398 lprintf(9, "SSL_write in client_read:\n");
399 ERR_print_errors_fp(stderr);
402 rlen = SSL_read(CC->ssl, &buf[len], bytes - len);
406 errval = SSL_get_error(CC->ssl, rlen);
407 if (errval == SSL_ERROR_WANT_READ ||
408 errval == SSL_ERROR_WANT_WRITE) {
412 lprintf(9, "SSL_read got error %ld\n", errval);
414 return (client_read_to
415 (&buf[len], bytes - len, timeout));
424 * CtdlStartTLS() starts SSL/TLS encryption for the current session. It
425 * must be supplied with pre-generated strings for responses of "ok," "no
426 * support for TLS," and "error" so that we can use this in any protocol.
428 void CtdlStartTLS(char *ok_response, char *nosup_response,
429 char *error_response) {
431 int retval, bits, alg_bits;
434 cprintf("%s", nosup_response);
437 if (!(CC->ssl = SSL_new(ssl_ctx))) {
438 lprintf(2, "SSL_new failed: %s\n",
439 ERR_reason_error_string(ERR_get_error()));
440 cprintf("%s", error_response);
443 if (!(SSL_set_fd(CC->ssl, CC->client_socket))) {
444 lprintf(2, "SSL_set_fd failed: %s\n",
445 ERR_reason_error_string(ERR_get_error()));
448 cprintf("%s", error_response);
451 cprintf("%s", ok_response);
452 retval = SSL_accept(CC->ssl);
455 * Can't notify the client of an error here; they will
456 * discover the problem at the SSL layer and should
457 * revert to unencrypted communications.
461 errval = SSL_get_error(CC->ssl, retval);
462 lprintf(2, "SSL_accept failed: %s\n",
463 ERR_reason_error_string(ERR_get_error()));
468 BIO_set_close(CC->ssl->rbio, BIO_NOCLOSE);
470 SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl),
472 lprintf(3, "SSL/TLS using %s on %s (%d of %d bits)\n",
473 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
474 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
476 CC->redirect_ssl = 1;
481 * cmd_stls() starts SSL/TLS encryption for the current session
483 void cmd_stls(char *params)
485 char ok_response[SIZ];
486 char nosup_response[SIZ];
487 char error_response[SIZ];
490 "%d Begin TLS negotiation now\n",
492 sprintf(nosup_response,
493 "%d TLS not supported here\n",
494 ERROR + CMD_NOT_SUPPORTED);
495 sprintf(error_response,
496 "%d TLS negotiation error\n",
497 ERROR + INTERNAL_ERROR);
499 CtdlStartTLS(ok_response, nosup_response, error_response);
504 * cmd_gtls() returns status info about the TLS connection
506 void cmd_gtls(char *params)
510 if (!CC->ssl || !CC->redirect_ssl) {
511 cprintf("%d Session is not encrypted.\n", ERROR);
515 SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl),
517 cprintf("%d %s|%s|%d|%d\n", CIT_OK,
518 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
519 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
525 * endtls() shuts down the TLS connection
527 * WARNING: This may make your session vulnerable to a known plaintext
528 * attack in the current implmentation.
532 lprintf(7, "Ending SSL/TLS\n");
535 CC->redirect_ssl = 0;
539 SSL_shutdown(CC->ssl);
542 CC->redirect_ssl = 0;
547 * ssl_lock() callback for OpenSSL mutex locks
549 void ssl_lock(int mode, int n, const char *file, int line)
551 if (mode & CRYPTO_LOCK)
552 pthread_mutex_lock(SSLCritters[n]);
554 pthread_mutex_unlock(SSLCritters[n]);
556 #endif /* HAVE_OPENSSL */