11 /* where to find the keys */
12 #define CTDL_CRYPTO_DIR ctdl_key_dir
13 #define CTDL_KEY_PATH file_crpt_file_key
14 #define CTDL_CSR_PATH file_crpt_file_csr
15 #define CTDL_CER_PATH file_crpt_file_cer
16 #define SIGN_DAYS 3650 /* how long our certificate should live */
18 SSL_CTX *ssl_ctx; /* SSL context */
19 pthread_mutex_t **SSLCritters; /* Things needing locking */
20 char *ssl_cipher_list = DEFAULT_SSL_CIPHER_LIST;
22 pthread_key_t ThreadSSL; /* Per-thread SSL context */
24 static unsigned long id_callback(void)
26 return (unsigned long) pthread_self();
29 void shutdown_ssl(void)
33 /* Openssl requires these while shutdown.
34 * Didn't find a way to get out of this clean.
35 * int i, n = CRYPTO_num_locks();
36 * for (i = 0; i < n; i++)
37 * free(SSLCritters[i]);
43 * initialize ssl engine, load certs and initialize openssl internals
47 SSL_METHOD *ssl_method;
52 EVP_PKEY *req_pkey = NULL;
53 X509_NAME *name = NULL;
58 if (!access("/var/run/egd-pool", F_OK)) {
59 RAND_egd("/var/run/egd-pool");
63 lprintf(3, "PRNG not adequately seeded, won't do SSL/TLS\n");
66 SSLCritters = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
68 lprintf(1, "citserver: can't allocate memory!!\n");
69 /* Nothing's been initialized, just die */
75 for (a = 0; a < CRYPTO_num_locks(); a++) {
76 SSLCritters[a] = malloc(sizeof(pthread_mutex_t));
77 if (!SSLCritters[a]) {
79 "citserver: can't allocate memory!!\n");
80 /** Nothing's been initialized, just die */
84 pthread_mutex_init(SSLCritters[a], NULL);
89 * Initialize SSL transport layer
92 SSL_load_error_strings();
93 ssl_method = SSLv23_server_method();
94 if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
95 lprintf(3, "SSL_CTX_new failed: %s\n", ERR_reason_error_string(ERR_get_error()));
99 lprintf(9, "Requesting cipher list: %s\n", ssl_cipher_list);
100 if (!(SSL_CTX_set_cipher_list(ssl_ctx, ssl_cipher_list))) {
101 lprintf(3, "SSL_CTX_set_cipher_list failed: %s\n", ERR_reason_error_string(ERR_get_error()));
105 CRYPTO_set_locking_callback(ssl_lock);
106 CRYPTO_set_id_callback(id_callback);
109 * Get our certificates in order. (FIXME: dirify. this is a setup job.)
110 * First, create the key/cert directory if it's not there already...
112 mkdir(CTDL_CRYPTO_DIR, 0700);
115 * Before attempting to generate keys/certificates, first try
116 * link to them from the Citadel server if it's on the same host.
117 * We ignore any error return because it either meant that there
118 * was nothing in Citadel to link from (in which case we just
119 * generate new files) or the target files already exist (which
120 * is not fatal either).
122 if (!strcasecmp(ctdlhost, "uds")) {
123 sprintf(buf, "%s/keys/citadel.key", ctdlport);
124 rv = symlink(buf, CTDL_KEY_PATH);
125 if (!rv) lprintf(1, "%s\n", strerror(errno));
126 sprintf(buf, "%s/keys/citadel.csr", ctdlport);
127 rv = symlink(buf, CTDL_CSR_PATH);
128 if (!rv) lprintf(1, "%s\n", strerror(errno));
129 sprintf(buf, "%s/keys/citadel.cer", ctdlport);
130 rv = symlink(buf, CTDL_CER_PATH);
131 if (!rv) lprintf(1, "%s\n", strerror(errno));
135 * If we still don't have a private key, generate one.
137 if (access(CTDL_KEY_PATH, R_OK) != 0) {
138 lprintf(5, "Generating RSA key pair.\n");
139 rsa = RSA_generate_key(1024, /* modulus size */
140 65537, /* exponent */
141 NULL, /* no callback */
142 NULL /* no callback */
145 lprintf(3, "Key generation failed: %s\n", ERR_reason_error_string(ERR_get_error()));
148 fp = fopen(CTDL_KEY_PATH, "w");
150 chmod(CTDL_KEY_PATH, 0600);
151 if (PEM_write_RSAPrivateKey(fp, /* the file */
154 NULL, /* no passphr */
156 NULL, /* no callbk */
159 lprintf(3, "Cannot write key: %s\n",
160 ERR_reason_error_string(ERR_get_error()));
161 unlink(CTDL_KEY_PATH);
166 lprintf(3, "Cannot write key: %s\n", CTDL_KEY_PATH);
175 * If there is no certificate file on disk, we will be generating a self-signed certificate
176 * in the next step. Therefore, if we have neither a CSR nor a certificate, generate
177 * the CSR in this step so that the next step may commence.
179 if ( (access(CTDL_CER_PATH, R_OK) != 0) && (access(CTDL_CSR_PATH, R_OK) != 0) ) {
180 lprintf(5, "Generating a certificate signing request.\n");
183 * Read our key from the file. No, we don't just keep this
184 * in memory from the above key-generation function, because
185 * there is the possibility that the key was already on disk
186 * and we didn't just generate it now.
188 fp = fopen(CTDL_KEY_PATH, "r");
190 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
196 /** Create a public key from the private key */
197 if (pk=EVP_PKEY_new(), pk != NULL) {
198 EVP_PKEY_assign_RSA(pk, rsa);
199 if (req = X509_REQ_new(), req != NULL) {
201 /* Set the public key */
202 X509_REQ_set_pubkey(req, pk);
203 X509_REQ_set_version(req, 0L);
205 name = X509_REQ_get_subject_name(req);
207 /* Tell it who we are */
210 * We used to add these fields to the subject, but
211 * now we don't. Someone doing this for real isn't
212 * going to use the webcit-generated CSR anyway.
214 X509_NAME_add_entry_by_txt(name, "C",
215 MBSTRING_ASC, "US", -1, -1, 0);
217 X509_NAME_add_entry_by_txt(name, "ST",
218 MBSTRING_ASC, "New York", -1, -1, 0);
220 X509_NAME_add_entry_by_txt(name, "L",
221 MBSTRING_ASC, "Mount Kisco", -1, -1, 0);
226 env = "Organization name",
228 X509_NAME_add_entry_by_txt(
237 env = "Citadel server";
239 X509_NAME_add_entry_by_txt(
250 X509_NAME_add_entry_by_txt(
257 X509_REQ_set_subject_name(req, name);
260 if (!X509_REQ_sign(req, pk, EVP_md5())) {
261 lprintf(3, "X509_REQ_sign(): error\n");
264 /* Write it to disk. */
265 fp = fopen(CTDL_CSR_PATH, "w");
267 chmod(CTDL_CSR_PATH, 0600);
268 PEM_write_X509_REQ(fp, req);
272 lprintf(3, "Cannot write key: %s\n", CTDL_CSR_PATH);
286 lprintf(3, "Unable to read private key.\n");
293 * Generate a self-signed certificate if we don't have one.
295 if (access(CTDL_CER_PATH, R_OK) != 0) {
296 lprintf(5, "Generating a self-signed certificate.\n");
298 /* Same deal as before: always read the key from disk because
299 * it may or may not have just been generated.
301 fp = fopen(CTDL_KEY_PATH, "r");
303 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
307 /* This also holds true for the CSR. */
312 if (pk=EVP_PKEY_new(), pk != NULL) {
313 EVP_PKEY_assign_RSA(pk, rsa);
316 fp = fopen(CTDL_CSR_PATH, "r");
318 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
323 if (cer = X509_new(), cer != NULL) {
325 ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
326 X509_set_issuer_name(cer, req->req_info->subject);
327 X509_set_subject_name(cer, req->req_info->subject);
328 X509_gmtime_adj(X509_get_notBefore(cer), 0);
329 X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
331 req_pkey = X509_REQ_get_pubkey(req);
332 X509_set_pubkey(cer, req_pkey);
333 EVP_PKEY_free(req_pkey);
336 if (!X509_sign(cer, pk, EVP_md5())) {
337 lprintf(3, "X509_sign(): error\n");
340 /* Write it to disk. */
341 fp = fopen(CTDL_CER_PATH, "w");
343 chmod(CTDL_CER_PATH, 0600);
344 PEM_write_X509(fp, cer);
348 lprintf(3, "Cannot write key: %s\n", CTDL_CER_PATH);
362 * Now try to bind to the key and certificate.
363 * Note that we use SSL_CTX_use_certificate_chain_file() which allows
364 * the certificate file to contain intermediate certificates.
366 SSL_CTX_use_certificate_chain_file(ssl_ctx, CTDL_CER_PATH);
367 SSL_CTX_use_PrivateKey_file(ssl_ctx, CTDL_KEY_PATH, SSL_FILETYPE_PEM);
368 if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
369 lprintf(3, "Cannot install certificate: %s\n",
370 ERR_reason_error_string(ERR_get_error()));
377 * starts SSL/TLS encryption for the current session.
379 int starttls(int sock) {
380 int retval, bits, alg_bits, r;
383 pthread_setspecific(ThreadSSL, NULL);
388 if (!(newssl = SSL_new(ssl_ctx))) {
389 lprintf(3, "SSL_new failed: %s\n", ERR_reason_error_string(ERR_get_error()));
392 if (!(SSL_set_fd(newssl, sock))) {
393 lprintf(3, "SSL_set_fd failed: %s\n", ERR_reason_error_string(ERR_get_error()));
397 retval = SSL_accept(newssl);
400 * Can't notify the client of an error here; they will
401 * discover the problem at the SSL layer and should
402 * revert to unencrypted communications.
405 const char *ssl_error_reason = NULL;
407 errval = SSL_get_error(newssl, retval);
408 ssl_error_reason = ERR_reason_error_string(ERR_get_error());
409 if (ssl_error_reason == NULL) {
410 lprintf(3, "SSL_accept failed: errval=%i, retval=%i %s\n", errval, retval, strerror(errval));
413 lprintf(3, "SSL_accept failed: %s\n", ssl_error_reason);
416 retval = SSL_accept(newssl);
420 const char *ssl_error_reason = NULL;
422 errval = SSL_get_error(newssl, retval);
423 ssl_error_reason = ERR_reason_error_string(ERR_get_error());
424 if (ssl_error_reason == NULL) {
425 lprintf(3, "SSL_accept failed: errval=%i, retval=%i (%s)\n", errval, retval, strerror(errval));
428 lprintf(3, "SSL_accept failed: %s\n", ssl_error_reason);
435 lprintf(15, "SSL_accept success\n");
437 r = BIO_set_close(newssl->rbio, BIO_NOCLOSE);
438 bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(newssl), &alg_bits);
439 lprintf(15, "SSL/TLS using %s on %s (%d of %d bits)\n",
440 SSL_CIPHER_get_name(SSL_get_current_cipher(newssl)),
441 SSL_CIPHER_get_version(SSL_get_current_cipher(newssl)),
444 pthread_setspecific(ThreadSSL, newssl);
445 lprintf(15, "SSL started\n");
452 * shuts down the TLS connection
454 * WARNING: This may make your session vulnerable to a known plaintext
455 * attack in the current implmentation.
461 if (THREADSSL == NULL) return;
463 lprintf(15, "Ending SSL/TLS\n");
464 SSL_shutdown(THREADSSL);
465 ctx = SSL_get_SSL_CTX(THREADSSL);
467 /* I don't think this is needed, and it crashes the server anyway
470 * lprintf(9, "Freeing CTX at %x\n", (int)ctx );
476 pthread_setspecific(ThreadSSL, NULL);
481 * callback for OpenSSL mutex locks
483 void ssl_lock(int mode, int n, const char *file, int line)
485 if (mode & CRYPTO_LOCK) {
486 pthread_mutex_lock(SSLCritters[n]);
489 pthread_mutex_unlock(SSLCritters[n]);
494 * Send binary data to the client encrypted.
496 void client_write_ssl(const StrBuf *Buf)
504 if (THREADSSL == NULL) return;
506 nbytes = nremain = StrLength(Buf);
509 while (nremain > 0) {
510 if (SSL_want_write(THREADSSL)) {
511 if ((SSL_read(THREADSSL, junk, 0)) < 1) {
512 lprintf(9, "SSL_read in client_write: %s\n",
513 ERR_reason_error_string(ERR_get_error()));
516 retval = SSL_write(THREADSSL, &buf[nbytes - nremain], nremain);
520 errval = SSL_get_error(THREADSSL, retval);
521 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
525 lprintf(9, "SSL_write got error %ld, ret %d\n", errval, retval);
527 lprintf(9, "errno is %d\n", errno);
538 * read data from the encrypted layer.
540 int client_read_sslbuffer(StrBuf *buf, int timeout)
542 char sbuf[16384]; /* OpenSSL communicates in 16k blocks, so let's speak its native tongue. */
545 SSL *pssl = THREADSSL;
547 if (pssl == NULL) return(-1);
550 if (SSL_want_read(pssl)) {
551 if ((SSL_write(pssl, junk, 0)) < 1) {
552 lprintf(9, "SSL_write in client_read\n");
555 rlen = SSL_read(pssl, sbuf, sizeof(sbuf));
559 errval = SSL_get_error(pssl, rlen);
560 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
564 lprintf(9, "SSL_read got error %ld\n", errval);
568 StrBufAppendBufPlain(buf, sbuf, rlen, 0);
574 #endif /* HAVE_OPENSSL */