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();
37 void shutdown_ssl(void)
41 /* Openssl requires these while shutdown.
42 * Didn't find a way to get out of this clean.
43 * int i, n = CRYPTO_num_locks();
44 * for (i = 0; i < n; i++)
45 * free(SSLCritters[i]);
51 * \brief initialize ssl engine
52 * load certs and initialize openssl internals
56 SSL_METHOD
*ssl_method
;
61 EVP_PKEY
*req_pkey
= NULL
;
62 X509_NAME
*name
= NULL
;
66 if (!access("/var/run/egd-pool", F_OK
))
67 RAND_egd("/var/run/egd-pool");
71 "PRNG not adequately seeded, won't do SSL/TLS\n");
75 malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t
*));
77 lprintf(1, "citserver: can't allocate memory!!\n");
78 /* Nothing's been initialized, just die */
84 for (a
= 0; a
< CRYPTO_num_locks(); a
++) {
85 SSLCritters
[a
] = malloc(sizeof(pthread_mutex_t
));
86 if (!SSLCritters
[a
]) {
88 "citserver: can't allocate memory!!\n");
89 /** Nothing's been initialized, just die */
93 pthread_mutex_init(SSLCritters
[a
], NULL
);
98 * Initialize SSL transport layer
101 SSL_load_error_strings();
102 ssl_method
= SSLv23_server_method();
103 if (!(ssl_ctx
= SSL_CTX_new(ssl_method
))) {
104 lprintf(3, "SSL_CTX_new failed: %s\n",
105 ERR_reason_error_string(ERR_get_error()));
109 CRYPTO_set_locking_callback(ssl_lock
);
110 CRYPTO_set_id_callback(id_callback
);
113 * Get our certificates in order. \todo dirify. this is a setup job.
114 * First, create the key/cert directory if it's not there already...
116 mkdir(CTDL_CRYPTO_DIR
, 0700);
119 * Before attempting to generate keys/certificates, first try
120 * link to them from the Citadel server if it's on the same host.
121 * We ignore any error return because it either meant that there
122 * was nothing in Citadel to link from (in which case we just
123 * generate new files) or the target files already exist (which
124 * is not fatal either). \todo dirify
126 if (!strcasecmp(ctdlhost
, "uds")) {
127 sprintf(buf
, "%s/keys/citadel.key", ctdlport
);
128 symlink(buf
, CTDL_KEY_PATH
);
129 sprintf(buf
, "%s/keys/citadel.csr", ctdlport
);
130 symlink(buf
, CTDL_CSR_PATH
);
131 sprintf(buf
, "%s/keys/citadel.cer", ctdlport
);
132 symlink(buf
, CTDL_CER_PATH
);
136 * If we still don't have a private key, generate one.
138 if (access(CTDL_KEY_PATH
, R_OK
) != 0) {
139 lprintf(5, "Generating RSA key pair.\n");
140 rsa
= RSA_generate_key(1024, /**< modulus size */
141 65537, /**< exponent */
142 NULL
, /**< no callback */
143 NULL
); /**< no callback */
145 lprintf(3, "Key generation failed: %s\n",
146 ERR_reason_error_string(ERR_get_error()));
149 fp
= fopen(CTDL_KEY_PATH
, "w");
151 chmod(CTDL_KEY_PATH
, 0600);
152 if (PEM_write_RSAPrivateKey(fp
, /**< the file */
155 NULL
, /**< no passphr */
156 0, /**< no passphr */
157 NULL
, /**< no callbk */
158 NULL
/**< no callbk */
160 lprintf(3, "Cannot write key: %s\n",
161 ERR_reason_error_string(ERR_get_error()));
162 unlink(CTDL_KEY_PATH
);
167 lprintf(3, "Cannot write key: %s\n", CTDL_KEY_PATH
);
176 * If there is no certificate file on disk, we will be generating a self-signed certificate
177 * in the next step. Therefore, if we have neither a CSR nor a certificate, generate
178 * the CSR in this step so that the next step may commence.
180 if ( (access(CTDL_CER_PATH
, R_OK
) != 0) && (access(CTDL_CSR_PATH
, R_OK
) != 0) ) {
181 lprintf(5, "Generating a certificate signing request.\n");
184 * Read our key from the file. No, we don't just keep this
185 * in memory from the above key-generation function, because
186 * there is the possibility that the key was already on disk
187 * and we didn't just generate it now.
189 fp
= fopen(CTDL_KEY_PATH
, "r");
191 rsa
= PEM_read_RSAPrivateKey(fp
, NULL
, NULL
, NULL
);
197 /** Create a public key from the private key */
198 if (pk
=EVP_PKEY_new(), pk
!= NULL
) {
199 EVP_PKEY_assign_RSA(pk
, rsa
);
200 if (req
= X509_REQ_new(), req
!= NULL
) {
202 /** Set the public key */
203 X509_REQ_set_pubkey(req
, pk
);
204 X509_REQ_set_version(req
, 0L);
206 name
= X509_REQ_get_subject_name(req
);
208 /** Tell it who we are */
211 X509_NAME_add_entry_by_txt(name, "C",
212 MBSTRING_ASC, "US", -1, -1, 0);
214 X509_NAME_add_entry_by_txt(name, "ST",
215 MBSTRING_ASC, "New York", -1, -1, 0);
217 X509_NAME_add_entry_by_txt(name, "L",
218 MBSTRING_ASC, "Mount Kisco", -1, -1, 0);
221 X509_NAME_add_entry_by_txt(
224 (unsigned char*)"Organization name",
227 X509_NAME_add_entry_by_txt(
230 (unsigned char*)"Citadel server1",
233 X509_NAME_add_entry_by_txt(
236 (unsigned char*)"*", -1, -1, 0);
238 X509_REQ_set_subject_name(req
, name
);
241 if (!X509_REQ_sign(req
, pk
, EVP_md5())) {
242 lprintf(3, "X509_REQ_sign(): error\n");
245 /** Write it to disk. */
246 fp
= fopen(CTDL_CSR_PATH
, "w");
248 chmod(CTDL_CSR_PATH
, 0600);
249 PEM_write_X509_REQ(fp
, req
);
253 lprintf(3, "Cannot write key: %s\n", CTDL_CSR_PATH
);
267 lprintf(3, "Unable to read private key.\n");
274 * Generate a self-signed certificate if we don't have one.
276 if (access(CTDL_CER_PATH
, R_OK
) != 0) {
277 lprintf(5, "Generating a self-signed certificate.\n");
279 /** Same deal as before: always read the key from disk because
280 * it may or may not have just been generated.
282 fp
= fopen(CTDL_KEY_PATH
, "r");
284 rsa
= PEM_read_RSAPrivateKey(fp
, NULL
, NULL
, NULL
);
288 /** This also holds true for the CSR. */
293 if (pk
=EVP_PKEY_new(), pk
!= NULL
) {
294 EVP_PKEY_assign_RSA(pk
, rsa
);
297 fp
= fopen(CTDL_CSR_PATH
, "r");
299 req
= PEM_read_X509_REQ(fp
, NULL
, NULL
, NULL
);
304 if (cer
= X509_new(), cer
!= NULL
) {
306 ASN1_INTEGER_set(X509_get_serialNumber(cer
), 0);
307 X509_set_issuer_name(cer
, req
->req_info
->subject
);
308 X509_set_subject_name(cer
, req
->req_info
->subject
);
309 X509_gmtime_adj(X509_get_notBefore(cer
), 0);
310 X509_gmtime_adj(X509_get_notAfter(cer
),(long)60*60*24*SIGN_DAYS
);
312 req_pkey
= X509_REQ_get_pubkey(req
);
313 X509_set_pubkey(cer
, req_pkey
);
314 EVP_PKEY_free(req_pkey
);
317 if (!X509_sign(cer
, pk
, EVP_md5())) {
318 lprintf(3, "X509_sign(): error\n");
321 /** Write it to disk. */
322 fp
= fopen(CTDL_CER_PATH
, "w");
324 chmod(CTDL_CER_PATH
, 0600);
325 PEM_write_X509(fp
, cer
);
329 lprintf(3, "Cannot write key: %s\n", CTDL_CER_PATH
);
343 * Now try to bind to the key and certificate.
344 * Note that we use SSL_CTX_use_certificate_chain_file() which allows
345 * the certificate file to contain intermediate certificates.
347 SSL_CTX_use_certificate_chain_file(ssl_ctx
, CTDL_CER_PATH
);
348 SSL_CTX_use_PrivateKey_file(ssl_ctx
, CTDL_KEY_PATH
, SSL_FILETYPE_PEM
);
349 if ( !SSL_CTX_check_private_key(ssl_ctx
) ) {
350 lprintf(3, "Cannot install certificate: %s\n",
351 ERR_reason_error_string(ERR_get_error()));
358 * \brief starts SSL/TLS encryption for the current session.
359 * \param sock the socket connection
360 * \return Zero if the SSL/TLS handshake succeeded, non-zero otherwise.
362 int starttls(int sock
) {
363 int retval
, bits
, alg_bits
, r
;
366 pthread_setspecific(ThreadSSL
, NULL
);
371 if (!(newssl
= SSL_new(ssl_ctx
))) {
372 lprintf(3, "SSL_new failed: %s\n",
373 ERR_reason_error_string(ERR_get_error()));
376 if (!(SSL_set_fd(newssl
, sock
))) {
377 lprintf(3, "SSL_set_fd failed: %s\n",
378 ERR_reason_error_string(ERR_get_error()));
382 retval
= SSL_accept(newssl
);
385 * Can't notify the client of an error here; they will
386 * discover the problem at the SSL layer and should
387 * revert to unencrypted communications.
390 const char *ssl_error_reason
= NULL
;
392 errval
= SSL_get_error(newssl
, retval
);
393 ssl_error_reason
= ERR_reason_error_string(ERR_get_error());
394 if (ssl_error_reason
== NULL
)
395 lprintf(3, "SSL_accept failed: errval=%i, retval=%i\n", errval
, retval
);
397 lprintf(3, "SSL_accept failed: %s\n", ssl_error_reason
);
399 retval
= SSL_accept(newssl
);
403 const char *ssl_error_reason
= NULL
;
405 errval
= SSL_get_error(newssl
, retval
);
406 ssl_error_reason
= ERR_reason_error_string(ERR_get_error());
407 if (ssl_error_reason
== NULL
)
408 lprintf(3, "SSL_accept failed: errval=%i, retval=%i\n", errval
, retval
);
410 lprintf(3, "SSL_accept failed: %s\n", ssl_error_reason
);
414 } else lprintf(15, "SSL_accept success\n");
415 r
= BIO_set_close(newssl
->rbio
, BIO_NOCLOSE
);
416 bits
= SSL_CIPHER_get_bits(SSL_get_current_cipher(newssl
), &alg_bits
);
417 lprintf(15, "SSL/TLS using %s on %s (%d of %d bits)\n",
418 SSL_CIPHER_get_name(SSL_get_current_cipher(newssl
)),
419 SSL_CIPHER_get_version(SSL_get_current_cipher(newssl
)),
422 pthread_setspecific(ThreadSSL
, newssl
);
423 lprintf(15, "SSL started\n");
430 * \brief shuts down the TLS connection
432 * WARNING: This may make your session vulnerable to a known plaintext
433 * attack in the current implmentation.
439 if (THREADSSL
== NULL
) return;
441 lprintf(15, "Ending SSL/TLS\n");
442 SSL_shutdown(THREADSSL
);
443 ctx
= SSL_get_SSL_CTX(THREADSSL
);
445 /** I don't think this is needed, and it crashes the server anyway
448 * lprintf(9, "Freeing CTX at %x\n", (int)ctx );
454 pthread_setspecific(ThreadSSL
, NULL
);
459 * \brief callback for OpenSSL mutex locks
460 * \param mode which mode??????
461 * \param n how many???
462 * \param file which filename ???
463 * \param line what line????
465 void ssl_lock(int mode
, int n
, const char *file
, int line
)
467 if (mode
& CRYPTO_LOCK
)
468 pthread_mutex_lock(SSLCritters
[n
]);
470 pthread_mutex_unlock(SSLCritters
[n
]);
474 * \brief Send binary data to the client encrypted.
475 * \param buf chars to send to the client
476 * \param nbytes how many chars
478 void client_write_ssl(const StrBuf
*Buf
)
486 if (THREADSSL
== NULL
) return;
488 nbytes
= nremain
= StrLength(Buf
);
491 while (nremain
> 0) {
492 if (SSL_want_write(THREADSSL
)) {
493 if ((SSL_read(THREADSSL
, junk
, 0)) < 1) {
494 lprintf(9, "SSL_read in client_write: %s\n",
495 ERR_reason_error_string(ERR_get_error()));
498 retval
= SSL_write(THREADSSL
, &buf
[nbytes
- nremain
], nremain
);
502 errval
= SSL_get_error(THREADSSL
, retval
);
503 if (errval
== SSL_ERROR_WANT_READ
||
504 errval
== SSL_ERROR_WANT_WRITE
) {
508 lprintf(9, "SSL_write got error %ld, ret %d\n", errval
, retval
);
510 lprintf(9, "errno is %d\n", errno
);
521 * \brief read data from the encrypted layer.
522 * \param buf charbuffer to read to
523 * \param bytes how many
524 * \param timeout how long should we wait?
527 int client_read_sslbuffer(StrBuf
*buf
, int timeout
)
535 char sbuf
[16384]; /**< Openssl communicates in 16k blocks, so lets speak its native tongue. */
538 SSL
*pssl
= THREADSSL
;
540 if (pssl
== NULL
) return(-1);
545 * This code is disabled because we don't need it when
546 * using blocking reads (which we are). -IO
549 s
= BIO_get_fd(pssl
->rbio
, NULL
);
554 retval
= select(s
+ 1, &rfds
, NULL
, NULL
, &tv
);
556 if (FD_ISSET(s
, &rfds
) == 0) {
561 if (SSL_want_read(pssl
)) {
562 if ((SSL_write(pssl
, junk
, 0)) < 1) {
563 lprintf(9, "SSL_write in client_read\n");
566 rlen
= SSL_read(pssl
, sbuf
, sizeof(sbuf
));
570 errval
= SSL_get_error(pssl
, rlen
);
571 if (errval
== SSL_ERROR_WANT_READ
||
572 errval
== SSL_ERROR_WANT_WRITE
) {
576 lprintf(9, "SSL_read got error %ld\n", errval
);
580 StrBufAppendBufPlain(buf
, sbuf
, rlen
, 0);
587 #endif /* HAVE_OPENSSL */