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(CTDL_CRIT, "unable to get certificate from '%s'",
72 if (SSL_CTX_use_PrivateKey_file(ctx, key_file,
73 SSL_FILETYPE_PEM) <= 0) {
74 lprintf(CTDL_CRIT, "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;
98 EVP_PKEY *req_pkey = NULL;
99 X509_NAME *name = NULL;
102 if (!access("/var/run/egd-pool", F_OK))
103 RAND_egd("/var/run/egd-pool");
105 if (!RAND_status()) {
107 "PRNG not adequately seeded, won't do SSL/TLS\n");
111 mallok(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
113 lprintf(CTDL_EMERG, "citserver: can't allocate memory!!\n");
114 /* Nothing's been initialized, just die */
119 for (a = 0; a < CRYPTO_num_locks(); a++) {
120 SSLCritters[a] = mallok(sizeof(pthread_mutex_t));
121 if (!SSLCritters[a]) {
123 "citserver: can't allocate memory!!\n");
124 /* Nothing's been initialized, just die */
127 pthread_mutex_init(SSLCritters[a], NULL);
132 * Initialize SSL transport layer
135 SSL_load_error_strings();
136 ssl_method = SSLv23_server_method();
137 if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
138 lprintf(CTDL_CRIT, "SSL_CTX_new failed: %s\n",
139 ERR_reason_error_string(ERR_get_error()));
142 if (!(SSL_CTX_set_cipher_list(ssl_ctx, CIT_CIPHERS))) {
143 lprintf(CTDL_CRIT, "SSL: No ciphers available\n");
144 SSL_CTX_free(ssl_ctx);
149 #if SSLEAY_VERSION_NUMBER >= 0x00906000L
150 SSL_CTX_set_mode(ssl_ctx, SSL_CTX_get_mode(ssl_ctx) |
151 SSL_MODE_AUTO_RETRY);
155 CRYPTO_set_locking_callback(ssl_lock);
156 CRYPTO_set_id_callback(id_callback);
158 /* Load DH parameters into the context */
161 lprintf(CTDL_CRIT, "init_ssl() can't allocate a DH object: %s\n",
162 ERR_reason_error_string(ERR_get_error()));
163 SSL_CTX_free(ssl_ctx);
167 if (!(BN_hex2bn(&(dh->p), DH_P))) {
168 lprintf(CTDL_CRIT, "init_ssl() can't assign DH_P: %s\n",
169 ERR_reason_error_string(ERR_get_error()));
170 SSL_CTX_free(ssl_ctx);
174 if (!(BN_hex2bn(&(dh->g), DH_G))) {
175 lprintf(CTDL_CRIT, "init_ssl() can't assign DH_G: %s\n",
176 ERR_reason_error_string(ERR_get_error()));
177 SSL_CTX_free(ssl_ctx);
182 SSL_CTX_set_tmp_dh(ssl_ctx, dh);
185 /* Get our certificates in order.
186 * First, create the key/cert directory if it's not there already...
188 mkdir(CTDL_CRYPTO_DIR, 0700);
191 * Generate a key pair if we don't have one.
193 if (access(CTDL_KEY_PATH, R_OK) != 0) {
194 lprintf(CTDL_INFO, "Generating RSA key pair.\n");
195 rsa = RSA_generate_key(1024, /* modulus size */
196 65537, /* exponent */
197 NULL, /* no callback */
198 NULL); /* no callback */
200 lprintf(CTDL_CRIT, "Key generation failed: %s\n",
201 ERR_reason_error_string(ERR_get_error()));
204 fp = fopen(CTDL_KEY_PATH, "w");
206 chmod(CTDL_KEY_PATH, 0600);
207 if (PEM_write_RSAPrivateKey(fp, /* the file */
210 NULL, /* no passphr */
212 NULL, /* no callbk */
215 lprintf(CTDL_CRIT, "Cannot write key: %s\n",
216 ERR_reason_error_string(ERR_get_error()));
217 unlink(CTDL_KEY_PATH);
226 * Generate a CSR if we don't have one.
228 if (access(CTDL_CSR_PATH, R_OK) != 0) {
229 lprintf(CTDL_INFO, "Generating a certificate signing request.\n");
232 * Read our key from the file. No, we don't just keep this
233 * in memory from the above key-generation function, because
234 * there is the possibility that the key was already on disk
235 * and we didn't just generate it now.
237 fp = fopen(CTDL_KEY_PATH, "r");
239 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
245 /* Create a public key from the private key */
246 if (pk=EVP_PKEY_new(), pk != NULL) {
247 EVP_PKEY_assign_RSA(pk, rsa);
248 if (req = X509_REQ_new(), req != NULL) {
250 /* Set the public key */
251 X509_REQ_set_pubkey(req, pk);
252 X509_REQ_set_version(req, 0L);
254 name = X509_REQ_get_subject_name(req);
256 /* Tell it who we are */
259 X509_NAME_add_entry_by_txt(name, "C",
260 MBSTRING_ASC, "US", -1, -1, 0);
262 X509_NAME_add_entry_by_txt(name, "ST",
263 MBSTRING_ASC, "New York", -1, -1, 0);
265 X509_NAME_add_entry_by_txt(name, "L",
266 MBSTRING_ASC, "Mount Kisco", -1, -1, 0);
269 X509_NAME_add_entry_by_txt(name, "O",
270 MBSTRING_ASC, config.c_humannode, -1, -1, 0);
272 X509_NAME_add_entry_by_txt(name, "OU",
273 MBSTRING_ASC, "Citadel server", -1, -1, 0);
275 X509_NAME_add_entry_by_txt(name, "CN",
276 MBSTRING_ASC, config.c_fqdn, -1, -1, 0);
278 X509_REQ_set_subject_name(req, name);
281 if (!X509_REQ_sign(req, pk, EVP_md5())) {
282 lprintf(CTDL_CRIT, "X509_REQ_sign(): error\n");
285 /* Write it to disk. */
286 fp = fopen(CTDL_CSR_PATH, "w");
288 chmod(CTDL_CSR_PATH, 0600);
289 PEM_write_X509_REQ(fp, req);
302 lprintf(CTDL_CRIT, "Unable to read private key.\n");
309 * Generate a self-signed certificate if we don't have one.
311 if (access(CTDL_CER_PATH, R_OK) != 0) {
312 lprintf(CTDL_INFO, "Generating a self-signed certificate.\n");
314 /* Same deal as before: always read the key from disk because
315 * it may or may not have just been generated.
317 fp = fopen(CTDL_KEY_PATH, "r");
319 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
323 /* This also holds true for the CSR. */
328 if (pk=EVP_PKEY_new(), pk != NULL) {
329 EVP_PKEY_assign_RSA(pk, rsa);
332 fp = fopen(CTDL_CSR_PATH, "r");
334 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
339 if (cer = X509_new(), cer != NULL) {
341 X509_set_issuer_name(cer, req->req_info->subject);
342 X509_set_subject_name(cer, req->req_info->subject);
343 X509_gmtime_adj(X509_get_notBefore(cer),0);
344 X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
345 req_pkey = X509_REQ_get_pubkey(req);
346 X509_set_pubkey(cer, req_pkey);
347 EVP_PKEY_free(req_pkey);
350 if (!X509_sign(cer, pk, EVP_md5())) {
351 lprintf(CTDL_CRIT, "X509_sign(): error\n");
354 /* Write it to disk. */
355 fp = fopen(CTDL_CER_PATH, "w");
357 chmod(CTDL_CER_PATH, 0600);
358 PEM_write_X509(fp, cer);
372 * Now try to bind to the key and certificate.
374 if (ctdl_install_certificate(ssl_ctx,
378 lprintf(CTDL_CRIT, "Cannot install certificate: %s\n",
379 ERR_reason_error_string(ERR_get_error()));
382 /* Finally let the server know we're here */
383 CtdlRegisterProtoHook(cmd_stls, "STLS", "Start SSL/TLS session");
384 CtdlRegisterProtoHook(cmd_gtls, "GTLS",
385 "Get SSL/TLS session status");
386 CtdlRegisterSessionHook(endtls, EVT_STOP);
391 * client_write_ssl() Send binary data to the client encrypted.
393 void client_write_ssl(char *buf, int nbytes)
401 while (nremain > 0) {
402 if (SSL_want_write(CC->ssl)) {
403 if ((SSL_read(CC->ssl, junk, 0)) < 1) {
404 lprintf(CTDL_DEBUG, "SSL_read in client_write: %s\n", ERR_reason_error_string(ERR_get_error()));
408 SSL_write(CC->ssl, &buf[nbytes - nremain], nremain);
412 errval = SSL_get_error(CC->ssl, retval);
413 if (errval == SSL_ERROR_WANT_READ ||
414 errval == SSL_ERROR_WANT_WRITE) {
418 lprintf(CTDL_DEBUG, "SSL_write got error %ld, ret %d\n", errval, retval);
420 lprintf(CTDL_DEBUG, "errno is %d\n", errno);
422 client_write(&buf[nbytes - nremain], nremain);
431 * client_read_ssl() - read data from the encrypted layer.
433 int client_read_ssl(char *buf, int bytes, int timeout)
445 while (len < bytes) {
448 * This code is disabled because we don't need it when
449 * using blocking reads (which we are). -IO
452 s = BIO_get_fd(CC->ssl->rbio, NULL);
457 retval = select(s + 1, &rfds, NULL, NULL, &tv);
459 if (FD_ISSET(s, &rfds) == 0) {
464 if (SSL_want_read(CC->ssl)) {
465 if ((SSL_write(CC->ssl, junk, 0)) < 1) {
466 lprintf(CTDL_DEBUG, "SSL_write in client_read: %s\n", ERR_reason_error_string(ERR_get_error()));
469 rlen = SSL_read(CC->ssl, &buf[len], bytes - len);
473 errval = SSL_get_error(CC->ssl, rlen);
474 if (errval == SSL_ERROR_WANT_READ ||
475 errval == SSL_ERROR_WANT_WRITE) {
479 lprintf(CTDL_DEBUG, "SSL_read got error %ld\n", errval);
481 return (client_read_to
482 (&buf[len], bytes - len, timeout));
491 * CtdlStartTLS() starts SSL/TLS encryption for the current session. It
492 * must be supplied with pre-generated strings for responses of "ok," "no
493 * support for TLS," and "error" so that we can use this in any protocol.
495 void CtdlStartTLS(char *ok_response, char *nosup_response,
496 char *error_response) {
498 int retval, bits, alg_bits;
501 cprintf("%s", nosup_response);
504 if (!(CC->ssl = SSL_new(ssl_ctx))) {
505 lprintf(CTDL_CRIT, "SSL_new failed: %s\n",
506 ERR_reason_error_string(ERR_get_error()));
507 cprintf("%s", error_response);
510 if (!(SSL_set_fd(CC->ssl, CC->client_socket))) {
511 lprintf(CTDL_CRIT, "SSL_set_fd failed: %s\n",
512 ERR_reason_error_string(ERR_get_error()));
515 cprintf("%s", error_response);
518 cprintf("%s", ok_response);
519 retval = SSL_accept(CC->ssl);
522 * Can't notify the client of an error here; they will
523 * discover the problem at the SSL layer and should
524 * revert to unencrypted communications.
528 errval = SSL_get_error(CC->ssl, retval);
529 lprintf(CTDL_CRIT, "SSL_accept failed: %s\n",
530 ERR_reason_error_string(ERR_get_error()));
535 BIO_set_close(CC->ssl->rbio, BIO_NOCLOSE);
537 SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl),
539 lprintf(CTDL_INFO, "SSL/TLS using %s on %s (%d of %d bits)\n",
540 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
541 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
543 CC->redirect_ssl = 1;
548 * cmd_stls() starts SSL/TLS encryption for the current session
550 void cmd_stls(char *params)
552 char ok_response[SIZ];
553 char nosup_response[SIZ];
554 char error_response[SIZ];
557 "%d Begin TLS negotiation now\n",
559 sprintf(nosup_response,
560 "%d TLS not supported here\n",
561 ERROR + CMD_NOT_SUPPORTED);
562 sprintf(error_response,
563 "%d TLS negotiation error\n",
564 ERROR + INTERNAL_ERROR);
566 CtdlStartTLS(ok_response, nosup_response, error_response);
571 * cmd_gtls() returns status info about the TLS connection
573 void cmd_gtls(char *params)
577 if (!CC->ssl || !CC->redirect_ssl) {
578 cprintf("%d Session is not encrypted.\n", ERROR);
582 SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl),
584 cprintf("%d %s|%s|%d|%d\n", CIT_OK,
585 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
586 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
592 * endtls() shuts down the TLS connection
594 * WARNING: This may make your session vulnerable to a known plaintext
595 * attack in the current implmentation.
599 lprintf(CTDL_INFO, "Ending SSL/TLS\n");
602 CC->redirect_ssl = 0;
606 SSL_shutdown(CC->ssl);
609 CC->redirect_ssl = 0;
614 * ssl_lock() callback for OpenSSL mutex locks
616 void ssl_lock(int mode, int n, const char *file, int line)
618 if (mode & CRYPTO_LOCK)
619 pthread_mutex_lock(SSLCritters[n]);
621 pthread_mutex_unlock(SSLCritters[n]);
623 #endif /* HAVE_OPENSSL */