Add a macro to catch unhandled openssl errors.
[tor.git] / src / common / tortls.c
blob738556d24704223cee9ff5f53e9fcc9ff20bab52
1 /* Copyright 2003 Roger Dingledine. */
2 /* See LICENSE for licensing information */
3 /* $Id$ */
5 /* TLS wrappers for The Onion Router. (Unlike other tor functions, these
6 * are prefixed with tor_ in order to avoid conflicting with OpenSSL
7 * functions and variables.)
8 */
10 #include "./crypto.h"
11 #include "./tortls.h"
12 #include "./util.h"
13 #include "./log.h"
14 #include <string.h>
16 /* Copied from or.h */
17 #define LEGAL_NICKNAME_CHARACTERS "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
19 #include <assert.h>
20 #include <openssl/ssl.h>
21 #include <openssl/err.h>
22 #include <openssl/tls1.h>
23 #include <openssl/asn1.h>
24 #include <openssl/bio.h>
26 /* How long do identity certificates live? (sec) */
27 #define IDENTITY_CERT_LIFETIME (365*24*60*60)
28 /* How much clock skew do we tolerate when checking certificates? (sec) */
29 #define CERT_ALLOW_SKEW (90*60)
31 struct tor_tls_context_st {
32 SSL_CTX *ctx;
35 struct tor_tls_st {
36 SSL *ssl;
37 int socket;
38 enum {
39 TOR_TLS_ST_HANDSHAKE, TOR_TLS_ST_OPEN, TOR_TLS_ST_GOTCLOSE,
40 TOR_TLS_ST_SENTCLOSE, TOR_TLS_ST_CLOSED
41 } state;
42 int isServer;
43 int wantwrite_n; /* 0 normally, >0 if we returned wantwrite last time */
46 static X509* tor_tls_create_certificate(crypto_pk_env_t *rsa,
47 crypto_pk_env_t *rsa_sign,
48 const char *cname,
49 const char *cname_sign,
50 unsigned int lifetime);
52 /* global tls context, keep it here because nobody else needs to touch it */
53 static tor_tls_context *global_tls_context = NULL;
54 static int tls_library_is_initialized = 0;
56 #define _TOR_TLS_SYSCALL -6
57 #define _TOR_TLS_ZERORETURN -5
59 /* These functions are declared in crypto.c but not exported. */
60 EVP_PKEY *_crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private);
61 crypto_pk_env_t *_crypto_new_pk_env_rsa(RSA *rsa);
62 DH *_crypto_dh_env_get_dh(crypto_dh_env_t *dh);
64 static void
65 tls_log_errors(int severity, const char *doing)
67 int err;
68 const char *msg, *lib, *func;
69 while ((err = ERR_get_error()) != 0) {
70 msg = (const char*)ERR_reason_error_string(err);
71 lib = (const char*)ERR_lib_error_string(err);
72 func = (const char*)ERR_func_error_string(err);
73 if (!msg) msg = "(null)";
74 if (doing) {
75 log(severity, "TLS error while %s: %s (in %s:%s)", doing, msg, lib,func);
76 } else {
77 log(severity, "TLS error: %s (in %s:%s)", msg, lib, func);
82 #define CATCH_SYSCALL 1
83 #define CATCH_ZERO 2
85 static int
86 tor_tls_get_error(tor_tls *tls, int r, int extra,
87 const char *doing, int severity)
89 int err = SSL_get_error(tls->ssl, r);
90 switch (err) {
91 case SSL_ERROR_NONE:
92 return TOR_TLS_DONE;
93 case SSL_ERROR_WANT_READ:
94 return TOR_TLS_WANTREAD;
95 case SSL_ERROR_WANT_WRITE:
96 return TOR_TLS_WANTWRITE;
97 case SSL_ERROR_SYSCALL:
98 if (extra&CATCH_SYSCALL)
99 return _TOR_TLS_SYSCALL;
100 log(severity, "TLS error: <syscall error> (errno=%d: %s)",errno,
101 strerror(errno));
102 tls_log_errors(severity, doing);
103 return TOR_TLS_ERROR;
104 case SSL_ERROR_ZERO_RETURN:
105 if (extra&CATCH_ZERO)
106 return _TOR_TLS_ZERORETURN;
107 log(severity, "TLS error: Zero return");
108 tls_log_errors(severity, doing);
109 return TOR_TLS_ERROR;
110 default:
111 tls_log_errors(severity, doing);
112 return TOR_TLS_ERROR;
116 static void
117 tor_tls_init() {
118 if (!tls_library_is_initialized) {
119 SSL_library_init();
120 SSL_load_error_strings();
121 crypto_global_init();
122 OpenSSL_add_all_algorithms();
123 tls_library_is_initialized = 1;
127 static int always_accept_verify_cb(int preverify_ok,
128 X509_STORE_CTX *x509_ctx)
130 /* We always accept peer certs and complete the handshake. We don't validate
131 * them until later. */
132 return 1;
135 /* Generate a self-signed certificate with the private key 'rsa' and
136 * identity key 'identity and commonName 'nickname'. Return a certificate
137 * on success, NULL on failure.
138 * DOCDOC
140 X509 *
141 tor_tls_create_certificate(crypto_pk_env_t *rsa,
142 crypto_pk_env_t *rsa_sign,
143 const char *cname,
144 const char *cname_sign,
145 unsigned int cert_lifetime)
147 time_t start_time, end_time;
148 EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
149 X509 *x509 = NULL;
150 X509_NAME *name = NULL, *name_issuer=NULL;
151 int nid;
153 tor_tls_init();
155 start_time = time(NULL);
157 tor_assert(rsa && cname && rsa_sign && cname_sign);
158 if (!(sign_pkey = _crypto_pk_env_get_evp_pkey(rsa_sign,1)))
159 goto error;
160 if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,0)))
161 goto error;
162 if (!(x509 = X509_new()))
163 goto error;
164 if (!(X509_set_version(x509, 2)))
165 goto error;
166 if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509), (long)start_time)))
167 goto error;
169 if (!(name = X509_NAME_new()))
170 goto error;
171 if ((nid = OBJ_txt2nid("organizationName")) == NID_undef) goto error;
172 if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
173 "TOR", -1, -1, 0))) goto error;
174 if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
175 if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
176 (char*)cname, -1, -1, 0))) goto error;
177 if (!(X509_set_subject_name(x509, name)))
178 goto error;
180 if (!(name_issuer = X509_NAME_new()))
181 goto error;
182 if ((nid = OBJ_txt2nid("organizationName")) == NID_undef) goto error;
183 if (!(X509_NAME_add_entry_by_NID(name_issuer, nid, MBSTRING_ASC,
184 "TOR", -1, -1, 0))) goto error;
185 if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
186 if (!(X509_NAME_add_entry_by_NID(name_issuer, nid, MBSTRING_ASC,
187 (char*)cname_sign, -1, -1, 0))) goto error;
188 if (!(X509_set_issuer_name(x509, name_issuer)))
189 goto error;
191 if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
192 goto error;
193 end_time = start_time + cert_lifetime;
194 if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
195 goto error;
196 if (!X509_set_pubkey(x509, pkey))
197 goto error;
198 if (!X509_sign(x509, sign_pkey, EVP_sha1()))
199 goto error;
201 goto done;
202 error:
203 tls_log_errors(LOG_WARN, "generating certificate");
204 if (x509) {
205 X509_free(x509);
206 x509 = NULL;
208 done:
209 if (sign_pkey)
210 EVP_PKEY_free(sign_pkey);
211 if (pkey)
212 EVP_PKEY_free(pkey);
213 if (name)
214 X509_NAME_free(name);
215 if (name_issuer)
216 X509_NAME_free(name_issuer);
217 return x509;
221 #ifdef EVERYONE_HAS_AES
222 /* Everybody is running OpenSSL 0.9.7 or later, so no backward compatibility
223 * is needed. */
224 #define CIPHER_LIST TLS1_TXT_DHE_RSA_WITH_AES_128_SHA
225 #elif defined(TLS1_TXT_DHE_RSA_WITH_AES_128_SHA)
226 /* Some people are running OpenSSL before 0.9.7, but we aren't.
227 * We can support AES and 3DES.
229 #define CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
230 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
231 #else
232 /* We're running OpenSSL before 0.9.7. We only support 3DES. */
233 #define CIPHER_LIST SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA
234 #endif
236 /* Create a new TLS context. If we are going to be using it as a
237 * server, it must have isServer set to true, 'identity' set to the
238 * identity key used to sign that certificate, and 'nickname' set to
239 * the server's nickname. Return -1 if failure, else 0.
242 tor_tls_context_new(crypto_pk_env_t *identity,
243 int isServer, const char *nickname,
244 unsigned int key_lifetime)
246 crypto_pk_env_t *rsa = NULL;
247 crypto_dh_env_t *dh = NULL;
248 EVP_PKEY *pkey = NULL;
249 tor_tls_context *result = NULL;
250 X509 *cert = NULL, *idcert = NULL;
251 char nn2[1024];
252 sprintf(nn2, "%s <identity>", nickname);
254 tor_tls_init();
256 if (isServer) {
257 if (!(rsa = crypto_new_pk_env()))
258 goto error;
259 if (crypto_pk_generate_key(rsa)<0)
260 goto error;
261 cert = tor_tls_create_certificate(rsa, identity, nickname, nn2,
262 key_lifetime);
263 idcert = tor_tls_create_certificate(identity, identity, nn2, nn2,
264 IDENTITY_CERT_LIFETIME);
265 if (!cert || !idcert) {
266 log(LOG_WARN, "Error creating certificate");
267 goto error;
271 result = tor_malloc(sizeof(tor_tls_context));
272 result->ctx = NULL;
273 #ifdef EVERYONE_HAS_AES
274 /* Tell OpenSSL to only use TLS1 */
275 if (!(result->ctx = SSL_CTX_new(TLSv1_method())))
276 goto error;
277 #else
278 /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
279 if (!(result->ctx = SSL_CTX_new(SSLv23_method())))
280 goto error;
281 SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2);
282 #endif
283 if (!SSL_CTX_set_cipher_list(result->ctx, CIPHER_LIST))
284 goto error;
285 if (cert && !SSL_CTX_use_certificate(result->ctx,cert))
286 goto error;
287 if (idcert && !SSL_CTX_add_extra_chain_cert(result->ctx,idcert))
288 goto error;
289 SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
290 if (isServer) {
291 tor_assert(rsa);
292 if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,1)))
293 goto error;
294 if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
295 goto error;
296 EVP_PKEY_free(pkey);
297 pkey = NULL;
298 if (cert) {
299 if (!SSL_CTX_check_private_key(result->ctx))
300 goto error;
303 dh = crypto_dh_new();
304 SSL_CTX_set_tmp_dh(result->ctx, _crypto_dh_env_get_dh(dh));
305 crypto_dh_free(dh);
306 SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
307 always_accept_verify_cb);
308 /* let us realloc bufs that we're writing from */
309 SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
311 /* Free the old context if one exists. */
312 if (global_tls_context) {
313 /* This is safe even if there are open connections: OpenSSL does
314 * reference counting with SSL and SSL_CTX objects. */
315 SSL_CTX_free(global_tls_context->ctx);
316 free(global_tls_context);
318 global_tls_context = result;
319 return 0;
321 error:
322 tls_log_errors(LOG_WARN, "creating TLS context");
323 if (pkey)
324 EVP_PKEY_free(pkey);
325 if (rsa)
326 crypto_free_pk_env(rsa);
327 if (dh)
328 crypto_dh_free(dh);
329 if (result && result->ctx)
330 SSL_CTX_free(result->ctx);
331 if (result)
332 free(result);
333 /* leak certs XXXX ? */
334 return -1;
337 /* Create a new TLS object from a TLS context, a filedescriptor, and
338 * a flag to determine whether it is functioning as a server.
340 tor_tls *
341 tor_tls_new(int sock, int isServer)
343 tor_tls *result = tor_malloc(sizeof(tor_tls));
344 tor_assert(global_tls_context); /* make sure somebody made it first */
345 if (!(result->ssl = SSL_new(global_tls_context->ctx)))
346 return NULL;
347 result->socket = sock;
348 SSL_set_fd(result->ssl, sock);
349 result->state = TOR_TLS_ST_HANDSHAKE;
350 result->isServer = isServer;
351 result->wantwrite_n = 0;
352 return result;
355 /* Release resources associated with a TLS object. Does not close the
356 * underlying file descriptor.
358 void
359 tor_tls_free(tor_tls *tls)
361 SSL_free(tls->ssl);
362 free(tls);
365 /* Underlying function for TLS reading. Reads up to 'len' characters
366 * from 'tls' into 'cp'. On success, returns the number of characters
367 * read. On failure, returns TOR_TLS_ERROR, TOR_TLS_CLOSE,
368 * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
371 tor_tls_read(tor_tls *tls, char *cp, int len)
373 int r, err;
374 tor_assert(tls && tls->ssl);
375 tor_assert(tls->state == TOR_TLS_ST_OPEN);
376 r = SSL_read(tls->ssl, cp, len);
377 if (r > 0)
378 return r;
379 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_INFO);
380 log_fn(LOG_DEBUG,"returned r=%d, err=%d",r,err);
381 if (err == _TOR_TLS_ZERORETURN) {
382 tls->state = TOR_TLS_ST_CLOSED;
383 return TOR_TLS_CLOSE;
384 } else {
385 tor_assert(err != TOR_TLS_DONE);
386 return err;
390 /* Underlying function for TLS writing. Write up to 'n' characters
391 * from 'cp' onto 'tls'. On success, returns the number of characters
392 * written. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
393 * or TOR_TLS_WANTWRITE.
396 tor_tls_write(tor_tls *tls, char *cp, int n)
398 int r, err;
399 tor_assert(tls && tls->ssl);
400 tor_assert(tls->state == TOR_TLS_ST_OPEN);
401 if (n == 0)
402 return 0;
403 if(tls->wantwrite_n) {
404 /* if WANTWRITE last time, we must use the _same_ n as before */
405 tor_assert(n >= tls->wantwrite_n);
406 log_fn(LOG_DEBUG,"resuming pending-write, (%d to flush, reusing %d)",
407 n, tls->wantwrite_n);
408 n = tls->wantwrite_n;
409 tls->wantwrite_n = 0;
411 r = SSL_write(tls->ssl, cp, n);
412 err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO);
413 if (err == TOR_TLS_DONE) {
414 return r;
416 if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
417 // log_fn(LOG_INFO,"wantwrite or wantread. remembering the number %d.",n);
418 tls->wantwrite_n = n;
420 return err;
423 /* Perform initial handshake on 'tls'. When finished, returns
424 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
425 * or TOR_TLS_WANTWRITE.
428 tor_tls_handshake(tor_tls *tls)
430 int r;
431 tor_assert(tls && tls->ssl);
432 tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
433 if (tls->isServer) {
434 r = SSL_accept(tls->ssl);
435 } else {
436 r = SSL_connect(tls->ssl);
438 r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO);
439 if (r == TOR_TLS_DONE) {
440 tls->state = TOR_TLS_ST_OPEN;
442 return r;
445 /* Shut down an open tls connection 'tls'. When finished, returns
446 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
447 * or TOR_TLS_WANTWRITE.
450 tor_tls_shutdown(tor_tls *tls)
452 int r, err;
453 char buf[128];
454 tor_assert(tls && tls->ssl);
456 while (1) {
457 if (tls->state == TOR_TLS_ST_SENTCLOSE) {
458 /* If we've already called shutdown once to send a close message,
459 * we read until the other side has closed too.
461 do {
462 r = SSL_read(tls->ssl, buf, 128);
463 } while (r>0);
464 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
465 LOG_INFO);
466 if (err == _TOR_TLS_ZERORETURN) {
467 tls->state = TOR_TLS_ST_GOTCLOSE;
468 /* fall through... */
469 } else {
470 return err;
474 r = SSL_shutdown(tls->ssl);
475 if (r == 1) {
476 /* If shutdown returns 1, the connection is entirely closed. */
477 tls->state = TOR_TLS_ST_CLOSED;
478 return TOR_TLS_DONE;
480 err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
481 LOG_INFO);
482 if (err == _TOR_TLS_SYSCALL) {
483 /* The underlying TCP connection closed while we were shutting down. */
484 tls->state = TOR_TLS_ST_CLOSED;
485 return TOR_TLS_DONE;
486 } else if (err == _TOR_TLS_ZERORETURN) {
487 /* The TLS connection says that it sent a shutdown record, but
488 * isn't done shutting down yet. Make sure that this hasn't
489 * happened before, then go back to the start of the function
490 * and try to read.
492 if (tls->state == TOR_TLS_ST_GOTCLOSE ||
493 tls->state == TOR_TLS_ST_SENTCLOSE) {
494 log(LOG_WARN,
495 "TLS returned \"half-closed\" value while already half-closed");
496 return TOR_TLS_ERROR;
498 tls->state = TOR_TLS_ST_SENTCLOSE;
499 /* fall through ... */
500 } else {
501 return err;
503 } /* end loop */
506 /* Return true iff this TLS connection is authenticated.
509 tor_tls_peer_has_cert(tor_tls *tls)
511 X509 *cert;
512 if (!(cert = SSL_get_peer_certificate(tls->ssl)))
513 return 0;
514 X509_free(cert);
515 return 1;
519 tor_tls_get_peer_cert_nickname(tor_tls *tls, char *buf, int buflen)
521 X509 *cert = NULL;
522 X509_NAME *name = NULL;
523 int nid;
524 int lenout;
526 if (!(cert = SSL_get_peer_certificate(tls->ssl))) {
527 log_fn(LOG_WARN, "Peer has no certificate");
528 goto error;
530 if (!(name = X509_get_subject_name(cert))) {
531 log_fn(LOG_WARN, "Peer certificate has no subject name");
532 goto error;
534 if ((nid = OBJ_txt2nid("commonName")) == NID_undef)
535 goto error;
537 lenout = X509_NAME_get_text_by_NID(name, nid, buf, buflen);
538 if (lenout == -1)
539 goto error;
540 if (((int)strspn(buf, LEGAL_NICKNAME_CHARACTERS)) < lenout) {
541 log_fn(LOG_WARN, "Peer certificate nickname has illegal characters.");
542 goto error;
544 return 0;
545 error:
546 if (cert)
547 X509_free(cert);
548 if (name)
549 X509_NAME_free(name);
550 return -1;
553 /* If the provided tls connection is authenticated and has a
554 * certificate that is currently valid and is correctly signed by
555 * identity_key, return 0. Else, return -1.
558 tor_tls_verify(tor_tls *tls, crypto_pk_env_t *identity_key)
560 X509 *cert = NULL;
561 EVP_PKEY *id_pkey = NULL;
562 time_t now, t;
563 int r = -1;
565 if (!(cert = SSL_get_peer_certificate(tls->ssl)))
566 return -1;
568 now = time(NULL);
569 t = now + CERT_ALLOW_SKEW;
570 if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
571 log_fn(LOG_WARN,"Certificate becomes valid in the future: possible clock skew.");
572 goto done;
574 t = now - CERT_ALLOW_SKEW;
575 if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
576 log_fn(LOG_WARN,"Certificate already expired; possible clock skew.");
577 goto done;
580 /* Get the public key. */
581 if (!(id_pkey = _crypto_pk_env_get_evp_pkey(identity_key,0)) ||
582 X509_verify(cert, id_pkey) <= 0) {
583 log_fn(LOG_WARN,"X509_verify on cert and pkey returned <= 0");
584 tls_log_errors(LOG_WARN,"verifying certificate");
585 goto done;
588 r = 0;
590 done:
591 if (cert)
592 X509_free(cert);
593 if (id_pkey)
594 EVP_PKEY_free(id_pkey);
596 /* XXXX */
597 tls_log_errors(LOG_WARN, "finishing tor_tls_verify");
599 return r;
603 tor_tls_get_pending_bytes(tor_tls *tls)
605 tor_assert(tls);
606 return SSL_pending(tls->ssl);
609 /* Return the number of bytes read across the underlying socket. */
610 unsigned long tor_tls_get_n_bytes_read(tor_tls *tls)
612 tor_assert(tls);
613 return BIO_number_read(SSL_get_rbio(tls->ssl));
615 unsigned long tor_tls_get_n_bytes_written(tor_tls *tls)
617 tor_assert(tls);
618 return BIO_number_written(SSL_get_wbio(tls->ssl));
621 void _assert_no_tls_errors(const char *fname, int line)
623 if (ERR_peek_error() == 0)
624 return;
625 log_fn(LOG_ERR, "Unhandled OpenSSL errors found at %s:%d: ",
626 fname, line);
627 tls_log_errors(LOG_ERR, NULL);
629 tor_assert(0);
634 Local Variables:
635 mode:c
636 indent-tabs-mode:nil
637 c-basic-offset:2
638 End: