5 * \defgroup https Provides HTTPS, when the OpenSSL library is available.
6 * \ingroup WebcitHttpServer
14 #include "webserver.h"
16 /** where to find the keys */
17 #define CTDL_CRYPTO_DIR ctdl_key_dir
18 #define CTDL_KEY_PATH file_crpt_file_key /**< the key */
19 #define CTDL_CSR_PATH file_crpt_file_csr /**< the csr file */
20 #define CTDL_CER_PATH file_crpt_file_cer /**< the cer file */
21 #define SIGN_DAYS 365 /**< how long our certificate should live */
23 SSL_CTX *ssl_ctx; /**< SSL context */
24 pthread_mutex_t **SSLCritters; /**< Things needing locking */
26 pthread_key_t ThreadSSL; /**< Per-thread SSL context */
30 * \return thread id???
32 static unsigned long id_callback(void)
34 return (unsigned long) pthread_self();
38 * \brief initialize ssl engine
39 * load certs and initialize openssl internals
43 SSL_METHOD *ssl_method;
48 EVP_PKEY *req_pkey = NULL;
49 X509_NAME *name = NULL;
53 if (!access("/var/run/egd-pool", F_OK))
54 RAND_egd("/var/run/egd-pool");
58 "PRNG not adequately seeded, won't do SSL/TLS\n");
62 malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t *));
64 lprintf(1, "citserver: can't allocate memory!!\n");
65 /* Nothing's been initialized, just die */
70 for (a = 0; a < CRYPTO_num_locks(); a++) {
71 SSLCritters[a] = malloc(sizeof(pthread_mutex_t));
72 if (!SSLCritters[a]) {
74 "citserver: can't allocate memory!!\n");
75 /** Nothing's been initialized, just die */
78 pthread_mutex_init(SSLCritters[a], NULL);
83 * Initialize SSL transport layer
86 SSL_load_error_strings();
87 ssl_method = SSLv23_server_method();
88 if (!(ssl_ctx = SSL_CTX_new(ssl_method))) {
89 lprintf(3, "SSL_CTX_new failed: %s\n",
90 ERR_reason_error_string(ERR_get_error()));
94 CRYPTO_set_locking_callback(ssl_lock);
95 CRYPTO_set_id_callback(id_callback);
98 * Get our certificates in order. \todo dirify. this is a setup job.
99 * First, create the key/cert directory if it's not there already...
101 mkdir(CTDL_CRYPTO_DIR, 0700);
104 * Before attempting to generate keys/certificates, first try
105 * link to them from the Citadel server if it's on the same host.
106 * We ignore any error return because it either meant that there
107 * was nothing in Citadel to link from (in which case we just
108 * generate new files) or the target files already exist (which
109 * is not fatal either). \todo dirify
111 if (!strcasecmp(ctdlhost, "uds")) {
112 sprintf(buf, "%s/keys/citadel.key", ctdlport);
113 symlink(buf, CTDL_KEY_PATH);
114 sprintf(buf, "%s/keys/citadel.csr", ctdlport);
115 symlink(buf, CTDL_CSR_PATH);
116 sprintf(buf, "%s/keys/citadel.cer", ctdlport);
117 symlink(buf, CTDL_CER_PATH);
121 * If we still don't have a private key, generate one.
123 if (access(CTDL_KEY_PATH, R_OK) != 0) {
124 lprintf(5, "Generating RSA key pair.\n");
125 rsa = RSA_generate_key(1024, /**< modulus size */
126 65537, /**< exponent */
127 NULL, /**< no callback */
128 NULL); /**< no callback */
130 lprintf(3, "Key generation failed: %s\n",
131 ERR_reason_error_string(ERR_get_error()));
134 fp = fopen(CTDL_KEY_PATH, "w");
136 chmod(CTDL_KEY_PATH, 0600);
137 if (PEM_write_RSAPrivateKey(fp, /**< the file */
140 NULL, /**< no passphr */
141 0, /**< no passphr */
142 NULL, /**< no callbk */
143 NULL /**< no callbk */
145 lprintf(3, "Cannot write key: %s\n",
146 ERR_reason_error_string(ERR_get_error()));
147 unlink(CTDL_KEY_PATH);
152 lprintf(3, "Cannot write key: %s\n", CTDL_KEY_PATH);
160 * If there is no certificate file on disk, we will be generating a self-signed certificate
161 * in the next step. Therefore, if we have neither a CSR nor a certificate, generate
162 * the CSR in this step so that the next step may commence.
164 if ( (access(CTDL_CER_PATH, R_OK) != 0) && (access(CTDL_CSR_PATH, R_OK) != 0) ) {
165 lprintf(5, "Generating a certificate signing request.\n");
168 * Read our key from the file. No, we don't just keep this
169 * in memory from the above key-generation function, because
170 * there is the possibility that the key was already on disk
171 * and we didn't just generate it now.
173 fp = fopen(CTDL_KEY_PATH, "r");
175 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
181 /** Create a public key from the private key */
182 if (pk=EVP_PKEY_new(), pk != NULL) {
183 EVP_PKEY_assign_RSA(pk, rsa);
184 if (req = X509_REQ_new(), req != NULL) {
186 /** Set the public key */
187 X509_REQ_set_pubkey(req, pk);
188 X509_REQ_set_version(req, 0L);
190 name = X509_REQ_get_subject_name(req);
192 /** Tell it who we are */
195 X509_NAME_add_entry_by_txt(name, "C",
196 MBSTRING_ASC, "US", -1, -1, 0);
198 X509_NAME_add_entry_by_txt(name, "ST",
199 MBSTRING_ASC, "New York", -1, -1, 0);
201 X509_NAME_add_entry_by_txt(name, "L",
202 MBSTRING_ASC, "Mount Kisco", -1, -1, 0);
205 X509_NAME_add_entry_by_txt(name, "O",
206 MBSTRING_ASC, "Organization name", -1, -1, 0);
208 X509_NAME_add_entry_by_txt(name, "OU",
209 MBSTRING_ASC, "Citadel server", -1, -1, 0);
211 X509_NAME_add_entry_by_txt(name, "CN",
212 MBSTRING_ASC, "*", -1, -1, 0);
214 X509_REQ_set_subject_name(req, name);
217 if (!X509_REQ_sign(req, pk, EVP_md5())) {
218 lprintf(3, "X509_REQ_sign(): error\n");
221 /** Write it to disk. */
222 fp = fopen(CTDL_CSR_PATH, "w");
224 chmod(CTDL_CSR_PATH, 0600);
225 PEM_write_X509_REQ(fp, req);
229 lprintf(3, "Cannot write key: %s\n", CTDL_CSR_PATH);
242 lprintf(3, "Unable to read private key.\n");
249 * Generate a self-signed certificate if we don't have one.
251 if (access(CTDL_CER_PATH, R_OK) != 0) {
252 lprintf(5, "Generating a self-signed certificate.\n");
254 /** Same deal as before: always read the key from disk because
255 * it may or may not have just been generated.
257 fp = fopen(CTDL_KEY_PATH, "r");
259 rsa = PEM_read_RSAPrivateKey(fp, NULL, NULL, NULL);
263 /** This also holds true for the CSR. */
268 if (pk=EVP_PKEY_new(), pk != NULL) {
269 EVP_PKEY_assign_RSA(pk, rsa);
272 fp = fopen(CTDL_CSR_PATH, "r");
274 req = PEM_read_X509_REQ(fp, NULL, NULL, NULL);
279 if (cer = X509_new(), cer != NULL) {
281 ASN1_INTEGER_set(X509_get_serialNumber(cer), 0);
282 X509_set_issuer_name(cer, req->req_info->subject);
283 X509_set_subject_name(cer, req->req_info->subject);
284 X509_gmtime_adj(X509_get_notBefore(cer), 0);
285 X509_gmtime_adj(X509_get_notAfter(cer),(long)60*60*24*SIGN_DAYS);
287 req_pkey = X509_REQ_get_pubkey(req);
288 X509_set_pubkey(cer, req_pkey);
289 EVP_PKEY_free(req_pkey);
292 if (!X509_sign(cer, pk, EVP_md5())) {
293 lprintf(3, "X509_sign(): error\n");
296 /** Write it to disk. */
297 fp = fopen(CTDL_CER_PATH, "w");
299 chmod(CTDL_CER_PATH, 0600);
300 PEM_write_X509(fp, cer);
304 lprintf(3, "Cannot write key: %s\n", CTDL_CER_PATH);
317 * Now try to bind to the key and certificate.
318 * Note that we use SSL_CTX_use_certificate_chain_file() which allows
319 * the certificate file to contain intermediate certificates.
321 SSL_CTX_use_certificate_chain_file(ssl_ctx, CTDL_CER_PATH);
322 SSL_CTX_use_PrivateKey_file(ssl_ctx, CTDL_KEY_PATH, SSL_FILETYPE_PEM);
323 if ( !SSL_CTX_check_private_key(ssl_ctx) ) {
324 lprintf(3, "Cannot install certificate: %s\n",
325 ERR_reason_error_string(ERR_get_error()));
332 * \brief starts SSL/TLS encryption for the current session.
333 * \param sock the socket connection
334 * \return Zero if the SSL/TLS handshake succeeded, non-zero otherwise.
336 int starttls(int sock) {
337 int retval, bits, alg_bits;
340 pthread_setspecific(ThreadSSL, NULL);
345 if (!(newssl = SSL_new(ssl_ctx))) {
346 lprintf(3, "SSL_new failed: %s\n",
347 ERR_reason_error_string(ERR_get_error()));
350 if (!(SSL_set_fd(newssl, sock))) {
351 lprintf(3, "SSL_set_fd failed: %s\n",
352 ERR_reason_error_string(ERR_get_error()));
356 retval = SSL_accept(newssl);
359 * Can't notify the client of an error here; they will
360 * discover the problem at the SSL layer and should
361 * revert to unencrypted communications.
365 errval = SSL_get_error(newssl, retval);
366 lprintf(3, "SSL_accept failed: %s\n",
367 ERR_reason_error_string(ERR_get_error()));
372 BIO_set_close(newssl->rbio, BIO_NOCLOSE);
373 bits = SSL_CIPHER_get_bits(SSL_get_current_cipher(newssl), &alg_bits);
374 lprintf(5, "SSL/TLS using %s on %s (%d of %d bits)\n",
375 SSL_CIPHER_get_name(SSL_get_current_cipher(newssl)),
376 SSL_CIPHER_get_version(SSL_get_current_cipher(newssl)),
379 pthread_setspecific(ThreadSSL, newssl);
386 * \brief shuts down the TLS connection
388 * WARNING: This may make your session vulnerable to a known plaintext
389 * attack in the current implmentation.
395 if (THREADSSL == NULL) return;
397 lprintf(5, "Ending SSL/TLS\n");
398 SSL_shutdown(THREADSSL);
399 ctx = SSL_get_SSL_CTX(THREADSSL);
401 /** I don't think this is needed, and it crashes the server anyway
404 * lprintf(9, "Freeing CTX at %x\n", (int)ctx );
410 pthread_setspecific(ThreadSSL, NULL);
415 * \brief callback for OpenSSL mutex locks
416 * \param mode which mode??????
417 * \param n how many???
418 * \param file which filename ???
419 * \param line what line????
421 void ssl_lock(int mode, int n, const char *file, int line)
423 if (mode & CRYPTO_LOCK)
424 pthread_mutex_lock(SSLCritters[n]);
426 pthread_mutex_unlock(SSLCritters[n]);
430 * \brief Send binary data to the client encrypted.
431 * \param buf chars to send to the client
432 * \param nbytes how many chars
434 void client_write_ssl(char *buf, int nbytes)
440 if (THREADSSL == NULL) return;
444 while (nremain > 0) {
445 if (SSL_want_write(THREADSSL)) {
446 if ((SSL_read(THREADSSL, junk, 0)) < 1) {
447 lprintf(9, "SSL_read in client_write: %s\n",
448 ERR_reason_error_string(ERR_get_error()));
451 retval = SSL_write(THREADSSL, &buf[nbytes - nremain], nremain);
455 errval = SSL_get_error(THREADSSL, retval);
456 if (errval == SSL_ERROR_WANT_READ ||
457 errval == SSL_ERROR_WANT_WRITE) {
461 lprintf(9, "SSL_write got error %ld, ret %d\n", errval, retval);
463 lprintf(9, "errno is %d\n", errno);
474 * \brief read data from the encrypted layer.
475 * \param buf charbuffer to read to
476 * \param bytes how many
477 * \param timeout how long should we wait?
480 int client_read_ssl(char *buf, int bytes, int timeout)
491 if (THREADSSL == NULL) return(0);
494 while (len < bytes) {
497 * This code is disabled because we don't need it when
498 * using blocking reads (which we are). -IO
501 s = BIO_get_fd(THREADSSL->rbio, NULL);
506 retval = select(s + 1, &rfds, NULL, NULL, &tv);
508 if (FD_ISSET(s, &rfds) == 0) {
513 if (SSL_want_read(THREADSSL)) {
514 if ((SSL_write(THREADSSL, junk, 0)) < 1) {
515 lprintf(9, "SSL_write in client_read: %s\n", ERR_reason_error_string(ERR_get_error()));
518 rlen = SSL_read(THREADSSL, &buf[len], bytes - len);
522 errval = SSL_get_error(THREADSSL, rlen);
523 if (errval == SSL_ERROR_WANT_READ ||
524 errval == SSL_ERROR_WANT_WRITE) {
528 lprintf(9, "SSL_read got error %ld\n", errval);
538 #endif /* HAVE_OPENSSL */