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 */
21 pthread_key_t ThreadSSL; /* Per-thread SSL context */
23 static unsigned long id_callback(void)
25 return (unsigned long) pthread_self();
28 void shutdown_ssl(void)
32 /* Openssl requires these while shutdown.
33 * Didn't find a way to get out of this clean.
34 * int i, n = CRYPTO_num_locks();
35 * for (i = 0; i < n; i++)
36 * free(SSLCritters[i]);
42 * initialize ssl engine, load certs and initialize openssl internals
46 SSL_METHOD *ssl_method;
51 EVP_PKEY *req_pkey = NULL;
52 X509_NAME *name = NULL;
57 if (!access("/var/run/egd-pool", F_OK)) {
58 RAND_egd("/var/run/egd-pool");
62 lprintf(3, "PRNG not adequately seeded, won't do SSL/TLS\n");
65 SSLCritters = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
67 lprintf(1, "citserver: can't allocate memory!!\n");
68 /* Nothing's been initialized, just die */
74 for (a = 0; a < CRYPTO_num_locks(); a++) {
75 SSLCritters[a] = malloc(sizeof(pthread_mutex_t));
76 if (!SSLCritters[a]) {
78 "citserver: can't allocate memory!!\n");
79 /** Nothing's been initialized, just die */
83 pthread_mutex_init(SSLCritters[a], NULL);
88 * Initialize SSL transport layer
91 SSL_load_error_strings();
92 ssl_method = SSLv23_server_method();
93 if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
94 lprintf(3, "SSL_CTX_new failed: %s\n",
95 ERR_reason_error_string(ERR_get_error()));
99 CRYPTO_set_locking_callback(ssl_lock);
100 CRYPTO_set_id_callback(id_callback);
103 * Get our certificates in order. (FIXME: dirify. this is a setup job.)
104 * First, create the key/cert directory if it's not there already...
106 mkdir(CTDL_CRYPTO_DIR, 0700);
109 * Before attempting to generate keys/certificates, first try
110 * link to them from the Citadel server if it's on the same host.
111 * We ignore any error return because it either meant that there
112 * was nothing in Citadel to link from (in which case we just
113 * generate new files) or the target files already exist (which
114 * is not fatal either).
116 if (!strcasecmp(ctdlhost, "uds")) {
117 sprintf(buf, "%s/keys/citadel.key", ctdlport);
118 rv = symlink(buf, CTDL_KEY_PATH);
119 if (!rv) lprintf(1, "%s\n", strerror(errno));
120 sprintf(buf, "%s/keys/citadel.csr", ctdlport);
121 rv = symlink(buf, CTDL_CSR_PATH);
122 if (!rv) lprintf(1, "%s\n", strerror(errno));
123 sprintf(buf, "%s/keys/citadel.cer", ctdlport);
124 rv = symlink(buf, CTDL_CER_PATH);
125 if (!rv) lprintf(1, "%s\n", strerror(errno));
129 * If we still don't have a private key, generate one.
131 if (access(CTDL_KEY_PATH, R_OK) != 0) {
132 lprintf(5, "Generating RSA key pair.\n");
133 rsa = RSA_generate_key(1024, /* modulus size */
134 65537, /* exponent */
135 NULL, /* no callback */
136 NULL /* no callback */
139 lprintf(3, "Key generation failed: %s\n", ERR_reason_error_string(ERR_get_error()));
142 fp = fopen(CTDL_KEY_PATH, "w");
144 chmod(CTDL_KEY_PATH, 0600);
145 if (PEM_write_RSAPrivateKey(fp, /* the file */
148 NULL, /* no passphr */
150 NULL, /* no callbk */
153 lprintf(3, "Cannot write key: %s\n",
154 ERR_reason_error_string(ERR_get_error()));
155 unlink(CTDL_KEY_PATH);
160 lprintf(3, "Cannot write key: %s\n", CTDL_KEY_PATH);
169 * If there is no certificate file on disk, we will be generating a self-signed certificate
170 * in the next step. Therefore, if we have neither a CSR nor a certificate, generate
171 * the CSR in this step so that the next step may commence.
173 if ( (access(CTDL_CER_PATH, R_OK) != 0) && (access(CTDL_CSR_PATH, R_OK) != 0) ) {
174 lprintf(5, "Generating a certificate signing request.\n");
177 * Read our key from the file. No, we don't just keep this
178 * in memory from the above key-generation function, because
179 * there is the possibility that the key was already on disk
180 * and we didn't just generate it now.
182 fp = fopen(CTDL_KEY_PATH, "r");
184 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
190 /** Create a public key from the private key */
191 if (pk=EVP_PKEY_new(), pk != NULL) {
192 EVP_PKEY_assign_RSA(pk, rsa);
193 if (req = X509_REQ_new(), req != NULL) {
195 /* Set the public key */
196 X509_REQ_set_pubkey(req, pk);
197 X509_REQ_set_version(req, 0L);
199 name = X509_REQ_get_subject_name(req);
201 /* Tell it who we are */
204 * We used to add these fields to the subject, but
205 * now we don't. Someone doing this for real isn't
206 * going to use the webcit-generated CSR anyway.
208 X509_NAME_add_entry_by_txt(name, "C",
209 MBSTRING_ASC, "US", -1, -1, 0);
211 X509_NAME_add_entry_by_txt(name, "ST",
212 MBSTRING_ASC, "New York", -1, -1, 0);
214 X509_NAME_add_entry_by_txt(name, "L",
215 MBSTRING_ASC, "Mount Kisco", -1, -1, 0);
220 env = "Organization name",
222 X509_NAME_add_entry_by_txt(
231 env = "Citadel server";
233 X509_NAME_add_entry_by_txt(
244 X509_NAME_add_entry_by_txt(
251 X509_REQ_set_subject_name(req, name);
254 if (!X509_REQ_sign(req, pk, EVP_md5())) {
255 lprintf(3, "X509_REQ_sign(): error\n");
258 /* Write it to disk. */
259 fp = fopen(CTDL_CSR_PATH, "w");
261 chmod(CTDL_CSR_PATH, 0600);
262 PEM_write_X509_REQ(fp, req);
266 lprintf(3, "Cannot write key: %s\n", CTDL_CSR_PATH);
280 lprintf(3, "Unable to read private key.\n");
287 * Generate a self-signed certificate if we don't have one.
289 if (access(CTDL_CER_PATH, R_OK) != 0) {
290 lprintf(5, "Generating a self-signed certificate.\n");
292 /* Same deal as before: always read the key from disk because
293 * it may or may not have just been generated.
295 fp = fopen(CTDL_KEY_PATH, "r");
297 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
301 /* This also holds true for the CSR. */
306 if (pk=EVP_PKEY_new(), pk != NULL) {
307 EVP_PKEY_assign_RSA(pk, rsa);
310 fp = fopen(CTDL_CSR_PATH, "r");
312 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
317 if (cer = X509_new(), cer != NULL) {
319 ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
320 X509_set_issuer_name(cer, req->req_info->subject);
321 X509_set_subject_name(cer, req->req_info->subject);
322 X509_gmtime_adj(X509_get_notBefore(cer), 0);
323 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(3, "X509_sign(): error\n");
334 /* Write it to disk. */
335 fp = fopen(CTDL_CER_PATH, "w");
337 chmod(CTDL_CER_PATH, 0600);
338 PEM_write_X509(fp, cer);
342 lprintf(3, "Cannot write key: %s\n", CTDL_CER_PATH);
356 * Now try to bind to the key and certificate.
357 * Note that we use SSL_CTX_use_certificate_chain_file() which allows
358 * the certificate file to contain intermediate certificates.
360 SSL_CTX_use_certificate_chain_file(ssl_ctx, CTDL_CER_PATH);
361 SSL_CTX_use_PrivateKey_file(ssl_ctx, CTDL_KEY_PATH, SSL_FILETYPE_PEM);
362 if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
363 lprintf(3, "Cannot install certificate: %s\n",
364 ERR_reason_error_string(ERR_get_error()));
371 * starts SSL/TLS encryption for the current session.
373 int starttls(int sock) {
374 int retval, bits, alg_bits, r;
377 pthread_setspecific(ThreadSSL, NULL);
382 if (!(newssl = SSL_new(ssl_ctx))) {
383 lprintf(3, "SSL_new failed: %s\n", ERR_reason_error_string(ERR_get_error()));
386 if (!(SSL_set_fd(newssl, sock))) {
387 lprintf(3, "SSL_set_fd failed: %s\n", ERR_reason_error_string(ERR_get_error()));
391 retval = SSL_accept(newssl);
394 * Can't notify the client of an error here; they will
395 * discover the problem at the SSL layer and should
396 * revert to unencrypted communications.
399 const char *ssl_error_reason = NULL;
401 errval = SSL_get_error(newssl, retval);
402 ssl_error_reason = ERR_reason_error_string(ERR_get_error());
403 if (ssl_error_reason == NULL) {
404 lprintf(3, "SSL_accept failed: errval=%i, retval=%i %s\n", errval, retval, strerror(errval));
407 lprintf(3, "SSL_accept failed: %s\n", ssl_error_reason);
410 retval = SSL_accept(newssl);
414 const char *ssl_error_reason = NULL;
416 errval = SSL_get_error(newssl, retval);
417 ssl_error_reason = ERR_reason_error_string(ERR_get_error());
418 if (ssl_error_reason == NULL) {
419 lprintf(3, "SSL_accept failed: errval=%i, retval=%i (%s)\n", errval, retval, strerror(errval));
422 lprintf(3, "SSL_accept failed: %s\n", ssl_error_reason);
429 lprintf(15, "SSL_accept success\n");
431 r = BIO_set_close(newssl->rbio, BIO_NOCLOSE);
432 bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(newssl), &alg_bits);
433 lprintf(15, "SSL/TLS using %s on %s (%d of %d bits)\n",
434 SSL_CIPHER_get_name(SSL_get_current_cipher(newssl)),
435 SSL_CIPHER_get_version(SSL_get_current_cipher(newssl)),
438 pthread_setspecific(ThreadSSL, newssl);
439 lprintf(15, "SSL started\n");
446 * shuts down the TLS connection
448 * WARNING: This may make your session vulnerable to a known plaintext
449 * attack in the current implmentation.
455 if (THREADSSL == NULL) return;
457 lprintf(15, "Ending SSL/TLS\n");
458 SSL_shutdown(THREADSSL);
459 ctx = SSL_get_SSL_CTX(THREADSSL);
461 /* I don't think this is needed, and it crashes the server anyway
464 * lprintf(9, "Freeing CTX at %x\n", (int)ctx );
470 pthread_setspecific(ThreadSSL, NULL);
475 * callback for OpenSSL mutex locks
477 void ssl_lock(int mode, int n, const char *file, int line)
479 if (mode & CRYPTO_LOCK) {
480 pthread_mutex_lock(SSLCritters[n]);
483 pthread_mutex_unlock(SSLCritters[n]);
488 * Send binary data to the client encrypted.
490 void client_write_ssl(const StrBuf *Buf)
498 if (THREADSSL == NULL) return;
500 nbytes = nremain = StrLength(Buf);
503 while (nremain > 0) {
504 if (SSL_want_write(THREADSSL)) {
505 if ((SSL_read(THREADSSL, junk, 0)) < 1) {
506 lprintf(9, "SSL_read in client_write: %s\n",
507 ERR_reason_error_string(ERR_get_error()));
510 retval = SSL_write(THREADSSL, &buf[nbytes - nremain], nremain);
514 errval = SSL_get_error(THREADSSL, retval);
515 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
519 lprintf(9, "SSL_write got error %ld, ret %d\n", errval, retval);
521 lprintf(9, "errno is %d\n", errno);
532 * read data from the encrypted layer.
534 int client_read_sslbuffer(StrBuf *buf, int timeout)
536 char sbuf[16384]; /* OpenSSL communicates in 16k blocks, so let's speak its native tongue. */
539 SSL *pssl = THREADSSL;
541 if (pssl == NULL) return(-1);
544 if (SSL_want_read(pssl)) {
545 if ((SSL_write(pssl, junk, 0)) < 1) {
546 lprintf(9, "SSL_write in client_read\n");
549 rlen = SSL_read(pssl, sbuf, sizeof(sbuf));
553 errval = SSL_get_error(pssl, rlen);
554 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
558 lprintf(9, "SSL_read got error %ld\n", errval);
562 StrBufAppendBufPlain(buf, sbuf, rlen, 0);
568 #endif /* HAVE_OPENSSL */