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"
42 SSL_CTX *ssl_ctx; /* SSL context */
43 pthread_mutex_t **SSLCritters; /* Things needing locking */
45 static unsigned long id_callback(void)
47 return (unsigned long) pthread_self();
51 * Set up the cert things on the server side. We do need both the
52 * private key (in key_file) and the cert (in cert_file).
53 * Both files may be identical.
55 * This function is taken from OpenSSL apps/s_cb.c
58 static int ctdl_install_certificate(SSL_CTX * ctx,
59 const char *cert_file, const char *key_file)
61 if (cert_file != NULL) {
62 if (SSL_CTX_use_certificate_file(ctx, cert_file,
63 SSL_FILETYPE_PEM) <= 0) {
64 lprintf(3, "unable to get certificate from '%s'",
70 if (SSL_CTX_use_PrivateKey_file(ctx, key_file,
71 SSL_FILETYPE_PEM) <= 0) {
72 lprintf(3, "unable to get private key from '%s'",
76 /* Now we know that a key and cert have been set against
78 if (!SSL_CTX_check_private_key(ctx)) {
80 "Private key does not match the certificate public key");
90 SSL_METHOD *ssl_method;
95 if (!access("/var/run/egd-pool", F_OK))
96 RAND_egd("/var/run/egd-pool");
100 "PRNG not adequately seeded, won't do SSL/TLS\n");
104 mallok(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
106 lprintf(1, "citserver: can't allocate memory!!\n");
107 /* Nothing's been initialized, just die */
112 for (a = 0; a < CRYPTO_num_locks(); a++) {
113 SSLCritters[a] = mallok(sizeof(pthread_mutex_t));
114 if (!SSLCritters[a]) {
116 "citserver: can't allocate memory!!\n");
117 /* Nothing's been initialized, just die */
120 pthread_mutex_init(SSLCritters[a], NULL);
125 * Initialize SSL transport layer
128 SSL_load_error_strings();
129 ssl_method = SSLv23_server_method();
130 if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
131 lprintf(2, "SSL_CTX_new failed: %s\n",
132 ERR_reason_error_string(ERR_get_error()));
135 if (!(SSL_CTX_set_cipher_list(ssl_ctx, CIT_CIPHERS))) {
136 lprintf(2, "SSL: No ciphers available\n");
137 SSL_CTX_free(ssl_ctx);
142 #if SSLEAY_VERSION_NUMBER >= 0x00906000L
143 SSL_CTX_set_mode(ssl_ctx, SSL_CTX_get_mode(ssl_ctx) |
144 SSL_MODE_AUTO_RETRY);
148 CRYPTO_set_locking_callback(ssl_lock);
149 CRYPTO_set_id_callback(id_callback);
151 /* Load DH parameters into the context */
154 lprintf(2, "init_ssl() can't allocate a DH object: %s\n",
155 ERR_reason_error_string(ERR_get_error()));
156 SSL_CTX_free(ssl_ctx);
160 if (!(BN_hex2bn(&(dh->p), DH_P))) {
161 lprintf(2, "init_ssl() can't assign DH_P: %s\n",
162 ERR_reason_error_string(ERR_get_error()));
163 SSL_CTX_free(ssl_ctx);
167 if (!(BN_hex2bn(&(dh->g), DH_G))) {
168 lprintf(2, "init_ssl() can't assign DH_G: %s\n",
169 ERR_reason_error_string(ERR_get_error()));
170 SSL_CTX_free(ssl_ctx);
175 SSL_CTX_set_tmp_dh(ssl_ctx, dh);
178 /* Get our certificates in order.
179 * First, create the key/cert directory if it's not there already...
181 mkdir(CTDL_CRYPTO_DIR, 0700);
184 * Generate a key pair if we don't have one.
186 if (access(CTDL_KEY_PATH, R_OK) != 0) {
187 lprintf(3, "Generating RSA key pair.\n");
188 rsa = RSA_generate_key(1024, /* modulus size */
189 65537, /* exponent */
190 NULL, /* no callback */
191 NULL); /* no callback */
193 lprintf(2, "Key generation failed: %s\n",
194 ERR_reason_error_string(ERR_get_error()));
197 fp = fopen(CTDL_KEY_PATH, "w");
199 chmod(CTDL_KEY_PATH, 0600);
200 if (PEM_write_RSAPrivateKey(fp, /* the file */
203 NULL, /* no passphr */
205 NULL, /* no callbk */
208 lprintf(2, "Cannot write key: %s\n",
209 ERR_reason_error_string(ERR_get_error()));
210 unlink(CTDL_KEY_PATH);
219 * Now try to bind to the key and certificate.
221 if (ctdl_install_certificate(ssl_ctx,
225 lprintf(2, "Cannot install certificate: %s\n",
226 ERR_reason_error_string(ERR_get_error()));
229 /* Finally let the server know we're here */
230 CtdlRegisterProtoHook(cmd_stls, "STLS", "Start SSL/TLS session");
231 CtdlRegisterProtoHook(cmd_gtls, "GTLS",
232 "Get SSL/TLS session status");
233 CtdlRegisterSessionHook(endtls, EVT_STOP);
238 * client_write_ssl() Send binary data to the client encrypted.
240 void client_write_ssl(char *buf, int nbytes)
248 while (nremain > 0) {
249 if (SSL_want_write(CC->ssl)) {
250 if ((SSL_read(CC->ssl, junk, 0)) < 1) {
251 lprintf(9, "SSL_read in client_write:\n");
252 ERR_print_errors_fp(stderr);
256 SSL_write(CC->ssl, &buf[nbytes - nremain], nremain);
260 errval = SSL_get_error(CC->ssl, retval);
261 if (errval == SSL_ERROR_WANT_READ ||
262 errval == SSL_ERROR_WANT_WRITE) {
266 lprintf(9, "SSL_write got error %ld, ret %d\n", errval, retval);
268 lprintf(9, "errno is %d\n", errno);
270 client_write(&buf[nbytes - nremain], nremain);
279 * client_read_ssl() - read data from the encrypted layer.
281 int client_read_ssl(char *buf, int bytes, int timeout)
293 while (len < bytes) {
296 * This code is disabled because we don't need it when
297 * using blocking reads (which we are). -IO
300 s = BIO_get_fd(CC->ssl->rbio, NULL);
305 retval = select(s + 1, &rfds, NULL, NULL, &tv);
307 if (FD_ISSET(s, &rfds) == 0) {
312 if (SSL_want_read(CC->ssl)) {
313 if ((SSL_write(CC->ssl, junk, 0)) < 1) {
314 lprintf(9, "SSL_write in client_read:\n");
315 ERR_print_errors_fp(stderr);
318 rlen = SSL_read(CC->ssl, &buf[len], bytes - len);
322 errval = SSL_get_error(CC->ssl, rlen);
323 if (errval == SSL_ERROR_WANT_READ ||
324 errval == SSL_ERROR_WANT_WRITE) {
328 lprintf(9, "SSL_read got error %ld\n", errval);
330 return (client_read_to
331 (&buf[len], bytes - len, timeout));
340 * CtdlStartTLS() starts SSL/TLS encryption for the current session. It
341 * must be supplied with pre-generated strings for responses of "ok," "no
342 * support for TLS," and "error" so that we can use this in any protocol.
344 void CtdlStartTLS(char *ok_response, char *nosup_response,
345 char *error_response) {
347 int retval, bits, alg_bits;
350 cprintf("%s", nosup_response);
353 if (!(CC->ssl = SSL_new(ssl_ctx))) {
354 lprintf(2, "SSL_new failed: %s\n",
355 ERR_reason_error_string(ERR_get_error()));
356 cprintf("%s", error_response);
359 if (!(SSL_set_fd(CC->ssl, CC->client_socket))) {
360 lprintf(2, "SSL_set_fd failed: %s\n",
361 ERR_reason_error_string(ERR_get_error()));
364 cprintf("%s", error_response);
367 cprintf("%s", ok_response);
368 retval = SSL_accept(CC->ssl);
371 * Can't notify the client of an error here; they will
372 * discover the problem at the SSL layer and should
373 * revert to unencrypted communications.
377 errval = SSL_get_error(CC->ssl, retval);
378 lprintf(2, "SSL_accept failed: %s\n",
379 ERR_reason_error_string(ERR_get_error()));
384 BIO_set_close(CC->ssl->rbio, BIO_NOCLOSE);
386 SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl),
388 lprintf(3, "SSL/TLS using %s on %s (%d of %d bits)\n",
389 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
390 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
392 CC->redirect_ssl = 1;
397 * cmd_stls() starts SSL/TLS encryption for the current session
399 void cmd_stls(char *params)
401 char ok_response[SIZ];
402 char nosup_response[SIZ];
403 char error_response[SIZ];
406 "%d Begin TLS negotiation now\n",
408 sprintf(nosup_response,
409 "%d TLS not supported here\n",
410 ERROR + CMD_NOT_SUPPORTED);
411 sprintf(error_response,
412 "%d TLS negotiation error\n",
413 ERROR + INTERNAL_ERROR);
415 CtdlStartTLS(ok_response, nosup_response, error_response);
420 * cmd_gtls() returns status info about the TLS connection
422 void cmd_gtls(char *params)
426 if (!CC->ssl || !CC->redirect_ssl) {
427 cprintf("%d Session is not encrypted.\n", ERROR);
431 SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl),
433 cprintf("%d %s|%s|%d|%d\n", CIT_OK,
434 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
435 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
441 * endtls() shuts down the TLS connection
443 * WARNING: This may make your session vulnerable to a known plaintext
444 * attack in the current implmentation.
448 lprintf(7, "Ending SSL/TLS\n");
451 CC->redirect_ssl = 0;
455 SSL_shutdown(CC->ssl);
458 CC->redirect_ssl = 0;
463 * ssl_lock() callback for OpenSSL mutex locks
465 void ssl_lock(int mode, int n, const char *file, int line)
467 if (mode & CRYPTO_LOCK)
468 pthread_mutex_lock(SSLCritters[n]);
470 pthread_mutex_unlock(SSLCritters[n]);
472 #endif /* HAVE_OPENSSL */