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();
52 void destruct_ssl(void)
55 CtdlUnregisterProtoHook(cmd_stls, "STLS");
56 CtdlUnregisterProtoHook(cmd_gtls, "GTLS");
57 for (a = 0; a < CRYPTO_num_locks(); a++)
64 SSL_METHOD *ssl_method;
70 EVP_PKEY *req_pkey = NULL;
71 X509_NAME *name = NULL;
74 if (!access(EGD_POOL, F_OK))
79 "PRNG not adequately seeded, won't do SSL/TLS\n");
83 malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
85 lprintf(CTDL_EMERG, "citserver: can't allocate memory!!\n");
86 /* Nothing's been initialized, just die */
91 for (a = 0; a < CRYPTO_num_locks(); a++) {
92 SSLCritters[a] = malloc(sizeof(pthread_mutex_t));
93 if (!SSLCritters[a]) {
95 "citserver: can't allocate memory!!\n");
96 /* Nothing's been initialized, just die */
99 pthread_mutex_init(SSLCritters[a], NULL);
104 * Initialize SSL transport layer
107 SSL_load_error_strings();
108 ssl_method = SSLv23_server_method();
109 if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
110 lprintf(CTDL_CRIT, "SSL_CTX_new failed: %s\n",
111 ERR_reason_error_string(ERR_get_error()));
114 if (!(SSL_CTX_set_cipher_list(ssl_ctx, CIT_CIPHERS))) {
115 lprintf(CTDL_CRIT, "SSL: No ciphers available\n");
116 SSL_CTX_free(ssl_ctx);
121 #if SSLEAY_VERSION_NUMBER >= 0x00906000L
122 SSL_CTX_set_mode(ssl_ctx, SSL_CTX_get_mode(ssl_ctx) |
123 SSL_MODE_AUTO_RETRY);
127 CRYPTO_set_locking_callback(ssl_lock);
128 CRYPTO_set_id_callback(id_callback);
130 /* Load DH parameters into the context */
133 lprintf(CTDL_CRIT, "init_ssl() can't allocate a DH object: %s\n",
134 ERR_reason_error_string(ERR_get_error()));
135 SSL_CTX_free(ssl_ctx);
139 if (!(BN_hex2bn(&(dh->p), DH_P))) {
140 lprintf(CTDL_CRIT, "init_ssl() can't assign DH_P: %s\n",
141 ERR_reason_error_string(ERR_get_error()));
142 SSL_CTX_free(ssl_ctx);
146 if (!(BN_hex2bn(&(dh->g), DH_G))) {
147 lprintf(CTDL_CRIT, "init_ssl() can't assign DH_G: %s\n",
148 ERR_reason_error_string(ERR_get_error()));
149 SSL_CTX_free(ssl_ctx);
154 SSL_CTX_set_tmp_dh(ssl_ctx, dh);
157 /* Get our certificates in order.
158 * First, create the key/cert directory if it's not there already...
160 mkdir(ctdl_key_dir, 0700);
163 * Generate a key pair if we don't have one.
165 if (access(file_crpt_file_key, R_OK) != 0) {
166 lprintf(CTDL_INFO, "Generating RSA key pair.\n");
167 rsa = RSA_generate_key(1024, /* modulus size */
168 65537, /* exponent */
169 NULL, /* no callback */
170 NULL); /* no callback */
172 lprintf(CTDL_CRIT, "Key generation failed: %s\n",
173 ERR_reason_error_string(ERR_get_error()));
176 fp = fopen(file_crpt_file_key, "w");
178 chmod(file_crpt_file_key, 0600);
179 if (PEM_write_RSAPrivateKey(fp, /* the file */
182 NULL, /* no passphr */
184 NULL, /* no callbk */
187 lprintf(CTDL_CRIT, "Cannot write key: %s\n",
188 ERR_reason_error_string(ERR_get_error()));
189 unlink(file_crpt_file_key);
198 * Generate a CSR if we don't have one.
200 if (access(file_crpt_file_csr, R_OK) != 0) {
201 lprintf(CTDL_INFO, "Generating a certificate signing request.\n");
204 * Read our key from the file. No, we don't just keep this
205 * in memory from the above key-generation function, because
206 * there is the possibility that the key was already on disk
207 * and we didn't just generate it now.
209 fp = fopen(file_crpt_file_key, "r");
211 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
217 /* Create a public key from the private key */
218 if (pk=EVP_PKEY_new(), pk != NULL) {
219 EVP_PKEY_assign_RSA(pk, rsa);
220 if (req = X509_REQ_new(), req != NULL) {
222 /* Set the public key */
223 X509_REQ_set_pubkey(req, pk);
224 X509_REQ_set_version(req, 0L);
226 name = X509_REQ_get_subject_name(req);
228 /* Tell it who we are */
231 X509_NAME_add_entry_by_txt(name, "C",
232 MBSTRING_ASC, "US", -1, -1, 0);
234 X509_NAME_add_entry_by_txt(name, "ST",
235 MBSTRING_ASC, "New York", -1, -1, 0);
237 X509_NAME_add_entry_by_txt(name, "L",
238 MBSTRING_ASC, "Mount Kisco", -1, -1, 0);
241 X509_NAME_add_entry_by_txt(name, "O",
242 MBSTRING_ASC, config.c_humannode, -1, -1, 0);
244 X509_NAME_add_entry_by_txt(name, "OU",
245 MBSTRING_ASC, "Citadel server", -1, -1, 0);
247 /* X509_NAME_add_entry_by_txt(name, "CN",
248 MBSTRING_ASC, config.c_fqdn, -1, -1, 0);
251 X509_NAME_add_entry_by_txt(name, "CN",
252 MBSTRING_ASC, "*", -1, -1, 0);
254 X509_REQ_set_subject_name(req, name);
257 if (!X509_REQ_sign(req, pk, EVP_md5())) {
258 lprintf(CTDL_CRIT, "X509_REQ_sign(): error\n");
261 /* Write it to disk. */
262 fp = fopen(file_crpt_file_csr, "w");
264 chmod(file_crpt_file_csr, 0600);
265 PEM_write_X509_REQ(fp, req);
278 lprintf(CTDL_CRIT, "Unable to read private key.\n");
285 * Generate a self-signed certificate if we don't have one.
287 if (access(file_crpt_file_cer, R_OK) != 0) {
288 lprintf(CTDL_INFO, "Generating a self-signed certificate.\n");
290 /* Same deal as before: always read the key from disk because
291 * it may or may not have just been generated.
293 fp = fopen(file_crpt_file_key, "r");
295 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
299 /* This also holds true for the CSR. */
304 if (pk=EVP_PKEY_new(), pk != NULL) {
305 EVP_PKEY_assign_RSA(pk, rsa);
308 fp = fopen(file_crpt_file_csr, "r");
310 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
315 if (cer = X509_new(), cer != NULL) {
317 ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
318 X509_set_issuer_name(cer, req->req_info->subject);
319 X509_set_subject_name(cer, req->req_info->subject);
320 X509_gmtime_adj(X509_get_notBefore(cer),0);
321 X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
322 req_pkey = X509_REQ_get_pubkey(req);
323 X509_set_pubkey(cer, req_pkey);
324 EVP_PKEY_free(req_pkey);
327 if (!X509_sign(cer, pk, EVP_md5())) {
328 lprintf(CTDL_CRIT, "X509_sign(): error\n");
331 /* Write it to disk. */
332 fp = fopen(file_crpt_file_cer, "w");
334 chmod(file_crpt_file_cer, 0600);
335 PEM_write_X509(fp, cer);
349 * Now try to bind to the key and certificate.
351 SSL_CTX_use_certificate_chain_file(ssl_ctx, file_crpt_file_cer);
352 SSL_CTX_use_PrivateKey_file(ssl_ctx, file_crpt_file_key, SSL_FILETYPE_PEM);
353 if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
354 lprintf(CTDL_CRIT, "Cannot install certificate: %s\n",
355 ERR_reason_error_string(ERR_get_error()));
358 /* Finally let the server know we're here */
359 CtdlRegisterProtoHook(cmd_stls, "STLS", "Start SSL/TLS session");
360 CtdlRegisterProtoHook(cmd_gtls, "GTLS",
361 "Get SSL/TLS session status");
362 CtdlRegisterSessionHook(endtls, EVT_STOP);
367 * client_write_ssl() Send binary data to the client encrypted.
369 void client_write_ssl(char *buf, int nbytes)
377 while (nremain > 0) {
378 if (SSL_want_write(CC->ssl)) {
379 if ((SSL_read(CC->ssl, junk, 0)) < 1) {
380 lprintf(CTDL_DEBUG, "SSL_read in client_write: %s\n", ERR_reason_error_string(ERR_get_error()));
384 SSL_write(CC->ssl, &buf[nbytes - nremain], nremain);
388 errval = SSL_get_error(CC->ssl, retval);
389 if (errval == SSL_ERROR_WANT_READ ||
390 errval == SSL_ERROR_WANT_WRITE) {
394 lprintf(CTDL_DEBUG, "SSL_write got error %ld, ret %d\n", errval, retval);
396 lprintf(CTDL_DEBUG, "errno is %d\n", errno);
398 client_write(&buf[nbytes - nremain], nremain);
407 * client_read_ssl() - read data from the encrypted layer.
409 int client_read_ssl(char *buf, int bytes, int timeout)
421 while (len < bytes) {
424 * This code is disabled because we don't need it when
425 * using blocking reads (which we are). -IO
428 s = BIO_get_fd(CC->ssl->rbio, NULL);
433 retval = select(s + 1, &rfds, NULL, NULL, &tv);
435 if (FD_ISSET(s, &rfds) == 0) {
440 if (SSL_want_read(CC->ssl)) {
441 if ((SSL_write(CC->ssl, junk, 0)) < 1) {
442 lprintf(CTDL_DEBUG, "SSL_write in client_read: %s\n", ERR_reason_error_string(ERR_get_error()));
445 rlen = SSL_read(CC->ssl, &buf[len], bytes - len);
449 errval = SSL_get_error(CC->ssl, rlen);
450 if (errval == SSL_ERROR_WANT_READ ||
451 errval == SSL_ERROR_WANT_WRITE) {
455 lprintf(CTDL_DEBUG, "SSL_read got error %ld\n", errval);
457 return (client_read_to
458 (&buf[len], bytes - len, timeout));
467 * CtdlStartTLS() starts SSL/TLS encryption for the current session. It
468 * must be supplied with pre-generated strings for responses of "ok," "no
469 * support for TLS," and "error" so that we can use this in any protocol.
471 void CtdlStartTLS(char *ok_response, char *nosup_response,
472 char *error_response) {
474 int retval, bits, alg_bits;
477 lprintf(CTDL_CRIT, "SSL failed: no ssl_ctx exists?\n");
478 if (nosup_response != NULL) cprintf("%s", nosup_response);
481 if (!(CC->ssl = SSL_new(ssl_ctx))) {
482 lprintf(CTDL_CRIT, "SSL_new failed: %s\n",
483 ERR_reason_error_string(ERR_get_error()));
484 if (error_response != NULL) cprintf("%s", error_response);
487 if (!(SSL_set_fd(CC->ssl, CC->client_socket))) {
488 lprintf(CTDL_CRIT, "SSL_set_fd failed: %s\n",
489 ERR_reason_error_string(ERR_get_error()));
492 if (error_response != NULL) cprintf("%s", error_response);
495 if (ok_response != NULL) cprintf("%s", ok_response);
496 retval = SSL_accept(CC->ssl);
499 * Can't notify the client of an error here; they will
500 * discover the problem at the SSL layer and should
501 * revert to unencrypted communications.
504 char error_string[128];
506 errval = SSL_get_error(CC->ssl, retval);
507 lprintf(CTDL_CRIT, "SSL_accept failed: retval=%d, errval=%ld, err=%s\n",
510 ERR_error_string(errval, error_string)
516 BIO_set_close(CC->ssl->rbio, BIO_NOCLOSE);
517 bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl), &alg_bits);
518 lprintf(CTDL_INFO, "SSL/TLS using %s on %s (%d of %d bits)\n",
519 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
520 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
522 CC->redirect_ssl = 1;
527 * cmd_stls() starts SSL/TLS encryption for the current session
529 void cmd_stls(char *params)
531 char ok_response[SIZ];
532 char nosup_response[SIZ];
533 char error_response[SIZ];
538 "%d Begin TLS negotiation now\n",
540 sprintf(nosup_response,
541 "%d TLS not supported here\n",
542 ERROR + CMD_NOT_SUPPORTED);
543 sprintf(error_response,
544 "%d TLS negotiation error\n",
545 ERROR + INTERNAL_ERROR);
547 CtdlStartTLS(ok_response, nosup_response, error_response);
552 * cmd_gtls() returns status info about the TLS connection
554 void cmd_gtls(char *params)
558 if (!CC->ssl || !CC->redirect_ssl) {
559 cprintf("%d Session is not encrypted.\n", ERROR);
563 SSL_CIPHER_get_bits(SSL_get_current_cipher(CC->ssl),
565 cprintf("%d %s|%s|%d|%d\n", CIT_OK,
566 SSL_CIPHER_get_version(SSL_get_current_cipher(CC->ssl)),
567 SSL_CIPHER_get_name(SSL_get_current_cipher(CC->ssl)),
573 * endtls() shuts down the TLS connection
575 * WARNING: This may make your session vulnerable to a known plaintext
576 * attack in the current implmentation.
581 CC->redirect_ssl = 0;
585 lprintf(CTDL_INFO, "Ending SSL/TLS\n");
586 SSL_shutdown(CC->ssl);
589 CC->redirect_ssl = 0;
594 * ssl_lock() callback for OpenSSL mutex locks
596 void ssl_lock(int mode, int n, const char *file, int line)
598 if (mode & CRYPTO_LOCK)
599 pthread_mutex_lock(SSLCritters[n]);
601 pthread_mutex_unlock(SSLCritters[n]);
603 #endif /* HAVE_OPENSSL */