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;
56 if (!access("/var/run/egd-pool", F_OK)) {
57 RAND_egd("/var/run/egd-pool");
61 lprintf(3, "PRNG not adequately seeded, won't do SSL/TLS\n");
64 SSLCritters = malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
66 lprintf(1, "citserver: can't allocate memory!!\n");
67 /* Nothing's been initialized, just die */
73 for (a = 0; a < CRYPTO_num_locks(); a++) {
74 SSLCritters[a] = malloc(sizeof(pthread_mutex_t));
75 if (!SSLCritters[a]) {
77 "citserver: can't allocate memory!!\n");
78 /** Nothing's been initialized, just die */
82 pthread_mutex_init(SSLCritters[a], NULL);
87 * Initialize SSL transport layer
90 SSL_load_error_strings();
91 ssl_method = SSLv23_server_method();
92 if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
93 lprintf(3, "SSL_CTX_new failed: %s\n",
94 ERR_reason_error_string(ERR_get_error()));
98 CRYPTO_set_locking_callback(ssl_lock);
99 CRYPTO_set_id_callback(id_callback);
102 * Get our certificates in order. (FIXME: dirify. this is a setup job.)
103 * First, create the key/cert directory if it's not there already...
105 mkdir(CTDL_CRYPTO_DIR, 0700);
108 * Before attempting to generate keys/certificates, first try
109 * link to them from the Citadel server if it's on the same host.
110 * We ignore any error return because it either meant that there
111 * was nothing in Citadel to link from (in which case we just
112 * generate new files) or the target files already exist (which
113 * is not fatal either).
115 if (!strcasecmp(ctdlhost, "uds")) {
116 sprintf(buf, "%s/keys/citadel.key", ctdlport);
117 symlink(buf, CTDL_KEY_PATH);
118 sprintf(buf, "%s/keys/citadel.csr", ctdlport);
119 symlink(buf, CTDL_CSR_PATH);
120 sprintf(buf, "%s/keys/citadel.cer", ctdlport);
121 symlink(buf, CTDL_CER_PATH);
125 * If we still don't have a private key, generate one.
127 if (access(CTDL_KEY_PATH, R_OK) != 0) {
128 lprintf(5, "Generating RSA key pair.\n");
129 rsa = RSA_generate_key(1024, /* modulus size */
130 65537, /* exponent */
131 NULL, /* no callback */
132 NULL /* no callback */
135 lprintf(3, "Key generation failed: %s\n", ERR_reason_error_string(ERR_get_error()));
138 fp = fopen(CTDL_KEY_PATH, "w");
140 chmod(CTDL_KEY_PATH, 0600);
141 if (PEM_write_RSAPrivateKey(fp, /* the file */
144 NULL, /* no passphr */
146 NULL, /* no callbk */
149 lprintf(3, "Cannot write key: %s\n",
150 ERR_reason_error_string(ERR_get_error()));
151 unlink(CTDL_KEY_PATH);
156 lprintf(3, "Cannot write key: %s\n", CTDL_KEY_PATH);
165 * If there is no certificate file on disk, we will be generating a self-signed certificate
166 * in the next step. Therefore, if we have neither a CSR nor a certificate, generate
167 * the CSR in this step so that the next step may commence.
169 if ( (access(CTDL_CER_PATH, R_OK) != 0) && (access(CTDL_CSR_PATH, R_OK) != 0) ) {
170 lprintf(5, "Generating a certificate signing request.\n");
173 * Read our key from the file. No, we don't just keep this
174 * in memory from the above key-generation function, because
175 * there is the possibility that the key was already on disk
176 * and we didn't just generate it now.
178 fp = fopen(CTDL_KEY_PATH, "r");
180 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
186 /** Create a public key from the private key */
187 if (pk=EVP_PKEY_new(), pk != NULL) {
188 EVP_PKEY_assign_RSA(pk, rsa);
189 if (req = X509_REQ_new(), req != NULL) {
191 /* Set the public key */
192 X509_REQ_set_pubkey(req, pk);
193 X509_REQ_set_version(req, 0L);
195 name = X509_REQ_get_subject_name(req);
197 /* Tell it who we are */
200 * We used to add these fields to the subject, but
201 * now we don't. Someone doing this for real isn't
202 * going to use the webcit-generated CSR anyway.
204 X509_NAME_add_entry_by_txt(name, "C",
205 MBSTRING_ASC, "US", -1, -1, 0);
207 X509_NAME_add_entry_by_txt(name, "ST",
208 MBSTRING_ASC, "New York", -1, -1, 0);
210 X509_NAME_add_entry_by_txt(name, "L",
211 MBSTRING_ASC, "Mount Kisco", -1, -1, 0);
216 env = "Organization name",
218 X509_NAME_add_entry_by_txt(
227 env = "Citadel server";
229 X509_NAME_add_entry_by_txt(
240 X509_NAME_add_entry_by_txt(
247 X509_REQ_set_subject_name(req, name);
250 if (!X509_REQ_sign(req, pk, EVP_md5())) {
251 lprintf(3, "X509_REQ_sign(): error\n");
254 /* Write it to disk. */
255 fp = fopen(CTDL_CSR_PATH, "w");
257 chmod(CTDL_CSR_PATH, 0600);
258 PEM_write_X509_REQ(fp, req);
262 lprintf(3, "Cannot write key: %s\n", CTDL_CSR_PATH);
276 lprintf(3, "Unable to read private key.\n");
283 * Generate a self-signed certificate if we don't have one.
285 if (access(CTDL_CER_PATH, R_OK) != 0) {
286 lprintf(5, "Generating a self-signed certificate.\n");
288 /* Same deal as before: always read the key from disk because
289 * it may or may not have just been generated.
291 fp = fopen(CTDL_KEY_PATH, "r");
293 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
297 /* This also holds true for the CSR. */
302 if (pk=EVP_PKEY_new(), pk != NULL) {
303 EVP_PKEY_assign_RSA(pk, rsa);
306 fp = fopen(CTDL_CSR_PATH, "r");
308 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
313 if (cer = X509_new(), cer != NULL) {
315 ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
316 X509_set_issuer_name(cer, req->req_info->subject);
317 X509_set_subject_name(cer, req->req_info->subject);
318 X509_gmtime_adj(X509_get_notBefore(cer), 0);
319 X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
321 req_pkey = X509_REQ_get_pubkey(req);
322 X509_set_pubkey(cer, req_pkey);
323 EVP_PKEY_free(req_pkey);
326 if (!X509_sign(cer, pk, EVP_md5())) {
327 lprintf(3, "X509_sign(): error\n");
330 /* Write it to disk. */
331 fp = fopen(CTDL_CER_PATH, "w");
333 chmod(CTDL_CER_PATH, 0600);
334 PEM_write_X509(fp, cer);
338 lprintf(3, "Cannot write key: %s\n", CTDL_CER_PATH);
352 * Now try to bind to the key and certificate.
353 * Note that we use SSL_CTX_use_certificate_chain_file() which allows
354 * the certificate file to contain intermediate certificates.
356 SSL_CTX_use_certificate_chain_file(ssl_ctx, CTDL_CER_PATH);
357 SSL_CTX_use_PrivateKey_file(ssl_ctx, CTDL_KEY_PATH, SSL_FILETYPE_PEM);
358 if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
359 lprintf(3, "Cannot install certificate: %s\n",
360 ERR_reason_error_string(ERR_get_error()));
367 * starts SSL/TLS encryption for the current session.
369 int starttls(int sock) {
370 int retval, bits, alg_bits, r;
373 pthread_setspecific(ThreadSSL, NULL);
378 if (!(newssl = SSL_new(ssl_ctx))) {
379 lprintf(3, "SSL_new failed: %s\n", ERR_reason_error_string(ERR_get_error()));
382 if (!(SSL_set_fd(newssl, sock))) {
383 lprintf(3, "SSL_set_fd failed: %s\n", ERR_reason_error_string(ERR_get_error()));
387 retval = SSL_accept(newssl);
390 * Can't notify the client of an error here; they will
391 * discover the problem at the SSL layer and should
392 * revert to unencrypted communications.
395 const char *ssl_error_reason = NULL;
397 errval = SSL_get_error(newssl, retval);
398 ssl_error_reason = ERR_reason_error_string(ERR_get_error());
399 if (ssl_error_reason == NULL) {
400 lprintf(3, "SSL_accept failed: errval=%i, retval=%i %s\n", errval, retval, strerror(errval));
403 lprintf(3, "SSL_accept failed: %s\n", ssl_error_reason);
406 retval = SSL_accept(newssl);
410 const char *ssl_error_reason = NULL;
412 errval = SSL_get_error(newssl, retval);
413 ssl_error_reason = ERR_reason_error_string(ERR_get_error());
414 if (ssl_error_reason == NULL) {
415 lprintf(3, "SSL_accept failed: errval=%i, retval=%i (%s)\n", errval, retval, strerror(errval));
418 lprintf(3, "SSL_accept failed: %s\n", ssl_error_reason);
425 lprintf(15, "SSL_accept success\n");
427 r = BIO_set_close(newssl->rbio, BIO_NOCLOSE);
428 bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(newssl), &alg_bits);
429 lprintf(15, "SSL/TLS using %s on %s (%d of %d bits)\n",
430 SSL_CIPHER_get_name(SSL_get_current_cipher(newssl)),
431 SSL_CIPHER_get_version(SSL_get_current_cipher(newssl)),
434 pthread_setspecific(ThreadSSL, newssl);
435 lprintf(15, "SSL started\n");
442 * shuts down the TLS connection
444 * WARNING: This may make your session vulnerable to a known plaintext
445 * attack in the current implmentation.
451 if (THREADSSL == NULL) return;
453 lprintf(15, "Ending SSL/TLS\n");
454 SSL_shutdown(THREADSSL);
455 ctx = SSL_get_SSL_CTX(THREADSSL);
457 /* I don't think this is needed, and it crashes the server anyway
460 * lprintf(9, "Freeing CTX at %x\n", (int)ctx );
466 pthread_setspecific(ThreadSSL, NULL);
471 * callback for OpenSSL mutex locks
473 void ssl_lock(int mode, int n, const char *file, int line)
475 if (mode & CRYPTO_LOCK) {
476 pthread_mutex_lock(SSLCritters[n]);
479 pthread_mutex_unlock(SSLCritters[n]);
484 * Send binary data to the client encrypted.
486 void client_write_ssl(const StrBuf *Buf)
494 if (THREADSSL == NULL) return;
496 nbytes = nremain = StrLength(Buf);
499 while (nremain > 0) {
500 if (SSL_want_write(THREADSSL)) {
501 if ((SSL_read(THREADSSL, junk, 0)) < 1) {
502 lprintf(9, "SSL_read in client_write: %s\n",
503 ERR_reason_error_string(ERR_get_error()));
506 retval = SSL_write(THREADSSL, &buf[nbytes - nremain], nremain);
510 errval = SSL_get_error(THREADSSL, retval);
511 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
515 lprintf(9, "SSL_write got error %ld, ret %d\n", errval, retval);
517 lprintf(9, "errno is %d\n", errno);
528 * read data from the encrypted layer.
530 int client_read_sslbuffer(StrBuf *buf, int timeout)
532 char sbuf[16384]; /* OpenSSL communicates in 16k blocks, so let's speak its native tongue. */
535 SSL *pssl = THREADSSL;
537 if (pssl == NULL) return(-1);
540 if (SSL_want_read(pssl)) {
541 if ((SSL_write(pssl, junk, 0)) < 1) {
542 lprintf(9, "SSL_write in client_read\n");
545 rlen = SSL_read(pssl, sbuf, sizeof(sbuf));
549 errval = SSL_get_error(pssl, rlen);
550 if (errval == SSL_ERROR_WANT_READ || errval == SSL_ERROR_WANT_WRITE) {
554 lprintf(9, "SSL_read got error %ld\n", errval);
558 StrBufAppendBufPlain(buf, sbuf, rlen, 0);
564 #endif /* HAVE_OPENSSL */