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"
42 #include "ctdl_module.h"
43 /* TODO: should we use the standard module init stuff to start this? */
44 /* TODO: should we register an event handler to call destruct_ssl? */
47 SSL_CTX *ssl_ctx; /* SSL context */
48 pthread_mutex_t **SSLCritters; /* Things needing locking */
50 static unsigned long id_callback(void)
52 return (unsigned long) pthread_self();
55 void destruct_ssl(void)
58 CtdlUnregisterProtoHook(cmd_stls, "STLS");
59 CtdlUnregisterProtoHook(cmd_gtls, "GTLS");
60 for (a = 0; a < CRYPTO_num_locks(); a++)
67 SSL_METHOD *ssl_method;
73 EVP_PKEY *req_pkey = NULL;
74 X509_NAME *name = NULL;
77 if (!access(EGD_POOL, F_OK))
82 "PRNG not adequately seeded, won't do SSL/TLS\n");
86 malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
88 lprintf(CTDL_EMERG, "citserver: can't allocate memory!!\n");
89 /* Nothing's been initialized, just die */
94 for (a = 0; a < CRYPTO_num_locks(); a++) {
95 SSLCritters[a] = malloc(sizeof(pthread_mutex_t));
96 if (!SSLCritters[a]) {
98 "citserver: can't allocate memory!!\n");
99 /* Nothing's been initialized, just die */
102 pthread_mutex_init(SSLCritters[a], NULL);
107 * Initialize SSL transport layer
110 SSL_load_error_strings();
111 ssl_method = SSLv23_server_method();
112 if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
113 lprintf(CTDL_CRIT, "SSL_CTX_new failed: %s\n",
114 ERR_reason_error_string(ERR_get_error()));
117 if (!(SSL_CTX_set_cipher_list(ssl_ctx, CIT_CIPHERS))) {
118 lprintf(CTDL_CRIT, "SSL: No ciphers available\n");
119 SSL_CTX_free(ssl_ctx);
124 #if SSLEAY_VERSION_NUMBER >= 0x00906000L
125 SSL_CTX_set_mode(ssl_ctx, SSL_CTX_get_mode(ssl_ctx) |
126 SSL_MODE_AUTO_RETRY);
130 CRYPTO_set_locking_callback(ssl_lock);
131 CRYPTO_set_id_callback(id_callback);
133 /* Load DH parameters into the context */
136 lprintf(CTDL_CRIT, "init_ssl() can't allocate a DH object: %s\n",
137 ERR_reason_error_string(ERR_get_error()));
138 SSL_CTX_free(ssl_ctx);
142 if (!(BN_hex2bn(&(dh->p), DH_P))) {
143 lprintf(CTDL_CRIT, "init_ssl() can't assign DH_P: %s\n",
144 ERR_reason_error_string(ERR_get_error()));
145 SSL_CTX_free(ssl_ctx);
149 if (!(BN_hex2bn(&(dh->g), DH_G))) {
150 lprintf(CTDL_CRIT, "init_ssl() can't assign DH_G: %s\n",
151 ERR_reason_error_string(ERR_get_error()));
152 SSL_CTX_free(ssl_ctx);
157 SSL_CTX_set_tmp_dh(ssl_ctx, dh);
160 /* Get our certificates in order.
161 * First, create the key/cert directory if it's not there already...
163 mkdir(ctdl_key_dir, 0700);
166 * Generate a key pair if we don't have one.
168 if (access(file_crpt_file_key, R_OK) != 0) {
169 lprintf(CTDL_INFO, "Generating RSA key pair.\n");
170 rsa = RSA_generate_key(1024, /* modulus size */
171 65537, /* exponent */
172 NULL, /* no callback */
173 NULL); /* no callback */
175 lprintf(CTDL_CRIT, "Key generation failed: %s\n",
176 ERR_reason_error_string(ERR_get_error()));
179 fp = fopen(file_crpt_file_key, "w");
181 chmod(file_crpt_file_key, 0600);
182 if (PEM_write_RSAPrivateKey(fp, /* the file */
185 NULL, /* no passphr */
187 NULL, /* no callbk */
190 lprintf(CTDL_CRIT, "Cannot write key: %s\n",
191 ERR_reason_error_string(ERR_get_error()));
192 unlink(file_crpt_file_key);
201 * Generate a CSR if we don't have one.
203 if (access(file_crpt_file_csr, R_OK) != 0) {
204 lprintf(CTDL_INFO, "Generating a certificate signing request.\n");
207 * Read our key from the file. No, we don't just keep this
208 * in memory from the above key-generation function, because
209 * there is the possibility that the key was already on disk
210 * and we didn't just generate it now.
212 fp = fopen(file_crpt_file_key, "r");
214 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
220 /* Create a public key from the private key */
221 if (pk=EVP_PKEY_new(), pk != NULL) {
222 EVP_PKEY_assign_RSA(pk, rsa);
223 if (req = X509_REQ_new(), req != NULL) {
225 /* Set the public key */
226 X509_REQ_set_pubkey(req, pk);
227 X509_REQ_set_version(req, 0L);
229 name = X509_REQ_get_subject_name(req);
231 /* Tell it who we are */
234 X509_NAME_add_entry_by_txt(name, "C",
235 MBSTRING_ASC, "US", -1, -1, 0);
237 X509_NAME_add_entry_by_txt(name, "ST",
238 MBSTRING_ASC, "New York", -1, -1, 0);
240 X509_NAME_add_entry_by_txt(name, "L",
241 MBSTRING_ASC, "Mount Kisco", -1, -1, 0);
244 X509_NAME_add_entry_by_txt(name, "O",
245 MBSTRING_ASC, config.c_humannode, -1, -1, 0);
247 X509_NAME_add_entry_by_txt(name, "OU",
248 MBSTRING_ASC, "Citadel server", -1, -1, 0);
250 /* X509_NAME_add_entry_by_txt(name, "CN",
251 MBSTRING_ASC, config.c_fqdn, -1, -1, 0);
254 X509_NAME_add_entry_by_txt(name, "CN",
255 MBSTRING_ASC, "*", -1, -1, 0);
257 X509_REQ_set_subject_name(req, name);
260 if (!X509_REQ_sign(req, pk, EVP_md5())) {
261 lprintf(CTDL_CRIT, "X509_REQ_sign(): error\n");
264 /* Write it to disk. */
265 fp = fopen(file_crpt_file_csr, "w");
267 chmod(file_crpt_file_csr, 0600);
268 PEM_write_X509_REQ(fp, req);
281 lprintf(CTDL_CRIT, "Unable to read private key.\n");
288 * Generate a self-signed certificate if we don't have one.
290 if (access(file_crpt_file_cer, R_OK) != 0) {
291 lprintf(CTDL_INFO, "Generating a self-signed certificate.\n");
293 /* Same deal as before: always read the key from disk because
294 * it may or may not have just been generated.
296 fp = fopen(file_crpt_file_key, "r");
298 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
302 /* This also holds true for the CSR. */
307 if (pk=EVP_PKEY_new(), pk != NULL) {
308 EVP_PKEY_assign_RSA(pk, rsa);
311 fp = fopen(file_crpt_file_csr, "r");
313 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
318 if (cer = X509_new(), cer != NULL) {
320 ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
321 X509_set_issuer_name(cer, req->req_info->subject);
322 X509_set_subject_name(cer, req->req_info->subject);
323 X509_gmtime_adj(X509_get_notBefore(cer),0);
324 X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
325 req_pkey = X509_REQ_get_pubkey(req);
326 X509_set_pubkey(cer, req_pkey);
327 EVP_PKEY_free(req_pkey);
330 if (!X509_sign(cer, pk, EVP_md5())) {
331 lprintf(CTDL_CRIT, "X509_sign(): error\n");
334 /* Write it to disk. */
335 fp = fopen(file_crpt_file_cer, "w");
337 chmod(file_crpt_file_cer, 0600);
338 PEM_write_X509(fp, cer);
352 * Now try to bind to the key and certificate.
354 SSL_CTX_use_certificate_chain_file(ssl_ctx, file_crpt_file_cer);
355 SSL_CTX_use_PrivateKey_file(ssl_ctx, file_crpt_file_key, SSL_FILETYPE_PEM);
356 if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
357 lprintf(CTDL_CRIT, "Cannot install certificate: %s\n",
358 ERR_reason_error_string(ERR_get_error()));
361 /* Finally let the server know we're here */
362 CtdlRegisterProtoHook(cmd_stls, "STLS", "Start SSL/TLS session");
363 CtdlRegisterProtoHook(cmd_gtls, "GTLS",
364 "Get SSL/TLS session status");
365 CtdlRegisterSessionHook(endtls, EVT_STOP);
370 * client_write_ssl() Send binary data to the client encrypted.
372 void client_write_ssl(char *buf, int nbytes)
380 while (nremain > 0) {
381 if (SSL_want_write(CC->ssl)) {
382 if ((SSL_read(CC->ssl, junk, 0)) < 1) {
383 lprintf(CTDL_DEBUG, "SSL_read in client_write: %s\n", ERR_reason_error_string(ERR_get_error()));
387 SSL_write(CC->ssl, &buf[nbytes - nremain], nremain);
391 errval = SSL_get_error(CC->ssl, retval);
392 if (errval == SSL_ERROR_WANT_READ ||
393 errval == SSL_ERROR_WANT_WRITE) {
397 lprintf(CTDL_DEBUG, "SSL_write got error %ld, ret %d\n", errval, retval);
399 lprintf(CTDL_DEBUG, "errno is %d\n", errno);
401 client_write(&buf[nbytes - nremain], nremain);
410 * client_read_ssl() - read data from the encrypted layer.
412 int client_read_ssl(char *buf, int bytes, int timeout)
424 while (len < bytes) {
427 * This code is disabled because we don't need it when
428 * using blocking reads (which we are). -IO
431 s = BIO_get_fd(CC->ssl->rbio, NULL);
436 retval = select(s + 1, &rfds, NULL, NULL, &tv);
438 if (FD_ISSET(s, &rfds) == 0) {
443 if (SSL_want_read(CC->ssl)) {
444 if ((SSL_write(CC->ssl, junk, 0)) < 1) {
445 lprintf(CTDL_DEBUG, "SSL_write in client_read: %s\n", ERR_reason_error_string(ERR_get_error()));
448 rlen = SSL_read(CC->ssl, &buf[len], bytes - len);
452 errval = SSL_get_error(CC->ssl, rlen);
453 if (errval == SSL_ERROR_WANT_READ ||
454 errval == SSL_ERROR_WANT_WRITE) {
458 lprintf(CTDL_DEBUG, "SSL_read got error %ld\n", errval);
460 return (client_read_to
461 (&buf[len], bytes - len, timeout));
470 * CtdlStartTLS() starts SSL/TLS encryption for the current session. It
471 * must be supplied with pre-generated strings for responses of "ok," "no
472 * support for TLS," and "error" so that we can use this in any protocol.
474 void CtdlStartTLS(char *ok_response, char *nosup_response,
475 char *error_response) {
477 int retval, bits, alg_bits;
480 lprintf(CTDL_CRIT, "SSL failed: no ssl_ctx exists?\n");
481 if (nosup_response != NULL) cprintf("%s", nosup_response);
484 if (!(CC->ssl = SSL_new(ssl_ctx))) {
485 lprintf(CTDL_CRIT, "SSL_new failed: %s\n",
486 ERR_reason_error_string(ERR_get_error()));
487 if (error_response != NULL) cprintf("%s", error_response);
490 if (!(SSL_set_fd(CC->ssl, CC->client_socket))) {
491 lprintf(CTDL_CRIT, "SSL_set_fd failed: %s\n",
492 ERR_reason_error_string(ERR_get_error()));
495 if (error_response != NULL) cprintf("%s", error_response);
498 if (ok_response != NULL) cprintf("%s", ok_response);
499 retval = SSL_accept(CC->ssl);
502 * Can't notify the client of an error here; they will
503 * discover the problem at the SSL layer and should
504 * revert to unencrypted communications.
507 char error_string[128];
509 errval = SSL_get_error(CC->ssl, retval);
510 lprintf(CTDL_CRIT, "SSL_accept failed: retval=%d, errval=%ld, err=%s\n",
513 ERR_error_string(errval, error_string)
519 BIO_set_close(CC->ssl->rbio, BIO_NOCLOSE);
520 bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl), &alg_bits);
521 lprintf(CTDL_INFO, "SSL/TLS using %s on %s (%d of %d bits)\n",
522 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
523 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
525 CC->redirect_ssl = 1;
530 * cmd_stls() starts SSL/TLS encryption for the current session
532 void cmd_stls(char *params)
534 char ok_response[SIZ];
535 char nosup_response[SIZ];
536 char error_response[SIZ];
541 "%d Begin TLS negotiation now\n",
543 sprintf(nosup_response,
544 "%d TLS not supported here\n",
545 ERROR + CMD_NOT_SUPPORTED);
546 sprintf(error_response,
547 "%d TLS negotiation error\n",
548 ERROR + INTERNAL_ERROR);
550 CtdlStartTLS(ok_response, nosup_response, error_response);
555 * cmd_gtls() returns status info about the TLS connection
557 void cmd_gtls(char *params)
561 if (!CC->ssl || !CC->redirect_ssl) {
562 cprintf("%d Session is not encrypted.\n", ERROR);
566 SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl),
568 cprintf("%d %s|%s|%d|%d\n", CIT_OK,
569 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
570 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
576 * endtls() shuts down the TLS connection
578 * WARNING: This may make your session vulnerable to a known plaintext
579 * attack in the current implmentation.
584 CC->redirect_ssl = 0;
588 lprintf(CTDL_INFO, "Ending SSL/TLS\n");
589 SSL_shutdown(CC->ssl);
592 CC->redirect_ssl = 0;
597 * ssl_lock() callback for OpenSSL mutex locks
599 void ssl_lock(int mode, int n, const char *file, int line)
601 if (mode & CRYPTO_LOCK)
602 pthread_mutex_lock(SSLCritters[n]);
604 pthread_mutex_unlock(SSLCritters[n]);
606 #endif /* HAVE_OPENSSL */