Log pending TLS errors in a couple more places, in case they are possible.
[tor.git] / src / common / tortls.c
blobe3078a7563a240b305afd7d0df85f988897e15d9
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)",errno);
101 tls_log_errors(severity, doing);
102 return TOR_TLS_ERROR;
103 case SSL_ERROR_ZERO_RETURN:
104 if (extra&CATCH_ZERO)
105 return _TOR_TLS_ZERORETURN;
106 log(severity, "TLS error: Zero return");
107 tls_log_errors(severity, doing);
108 return TOR_TLS_ERROR;
109 default:
110 tls_log_errors(severity, doing);
111 return TOR_TLS_ERROR;
115 static void
116 tor_tls_init() {
117 if (!tls_library_is_initialized) {
118 SSL_library_init();
119 SSL_load_error_strings();
120 crypto_global_init();
121 OpenSSL_add_all_algorithms();
122 tls_library_is_initialized = 1;
126 static int always_accept_verify_cb(int preverify_ok,
127 X509_STORE_CTX *x509_ctx)
129 /* We always accept peer certs and complete the handshake. We don't validate
130 * them until later. */
131 return 1;
134 /* Generate a self-signed certificate with the private key 'rsa' and
135 * identity key 'identity and commonName 'nickname'. Return a certificate
136 * on success, NULL on failure.
137 * DOCDOC
139 X509 *
140 tor_tls_create_certificate(crypto_pk_env_t *rsa,
141 crypto_pk_env_t *rsa_sign,
142 const char *cname,
143 const char *cname_sign,
144 unsigned int cert_lifetime)
146 time_t start_time, end_time;
147 EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
148 X509 *x509 = NULL;
149 X509_NAME *name = NULL, *name_issuer=NULL;
150 int nid;
152 tor_tls_init();
154 start_time = time(NULL);
156 tor_assert(rsa && cname && rsa_sign && cname_sign);
157 if (!(sign_pkey = _crypto_pk_env_get_evp_pkey(rsa_sign,1)))
158 goto error;
159 if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,0)))
160 goto error;
161 if (!(x509 = X509_new()))
162 goto error;
163 if (!(X509_set_version(x509, 2)))
164 goto error;
165 if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509), (long)start_time)))
166 goto error;
168 if (!(name = X509_NAME_new()))
169 goto error;
170 if ((nid = OBJ_txt2nid("organizationName")) == NID_undef) goto error;
171 if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
172 "TOR", -1, -1, 0))) goto error;
173 if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
174 if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
175 (char*)cname, -1, -1, 0))) goto error;
176 if (!(X509_set_subject_name(x509, name)))
177 goto error;
179 if (!(name_issuer = X509_NAME_new()))
180 goto error;
181 if ((nid = OBJ_txt2nid("organizationName")) == NID_undef) goto error;
182 if (!(X509_NAME_add_entry_by_NID(name_issuer, nid, MBSTRING_ASC,
183 "TOR", -1, -1, 0))) goto error;
184 if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
185 if (!(X509_NAME_add_entry_by_NID(name_issuer, nid, MBSTRING_ASC,
186 (char*)cname_sign, -1, -1, 0))) goto error;
187 if (!(X509_set_issuer_name(x509, name_issuer)))
188 goto error;
190 if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
191 goto error;
192 end_time = start_time + cert_lifetime;
193 if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
194 goto error;
195 if (!X509_set_pubkey(x509, pkey))
196 goto error;
197 if (!X509_sign(x509, sign_pkey, EVP_sha1()))
198 goto error;
200 goto done;
201 error:
202 tls_log_errors(LOG_WARN, "generating certificate");
203 if (x509) {
204 X509_free(x509);
205 x509 = NULL;
207 done:
208 if (sign_pkey)
209 EVP_PKEY_free(sign_pkey);
210 if (pkey)
211 EVP_PKEY_free(pkey);
212 if (name)
213 X509_NAME_free(name);
214 if (name_issuer)
215 X509_NAME_free(name_issuer);
216 return x509;
220 #ifdef EVERYONE_HAS_AES
221 /* Everybody is running OpenSSL 0.9.7 or later, so no backward compatibility
222 * is needed. */
223 #define CIPHER_LIST TLS1_TXT_DHE_RSA_WITH_AES_128_SHA
224 #elif defined(TLS1_TXT_DHE_RSA_WITH_AES_128_SHA)
225 /* Some people are running OpenSSL before 0.9.7, but we aren't.
226 * We can support AES and 3DES.
228 #define CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
229 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
230 #else
231 /* We're running OpenSSL before 0.9.7. We only support 3DES. */
232 #define CIPHER_LIST SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA
233 #endif
235 /* Create a new TLS context. If we are going to be using it as a
236 * server, it must have isServer set to true, 'identity' set to the
237 * identity key used to sign that certificate, and 'nickname' set to
238 * the server's nickname. Return -1 if failure, else 0.
241 tor_tls_context_new(crypto_pk_env_t *identity,
242 int isServer, const char *nickname,
243 unsigned int key_lifetime)
245 crypto_pk_env_t *rsa = NULL;
246 crypto_dh_env_t *dh = NULL;
247 EVP_PKEY *pkey = NULL;
248 tor_tls_context *result = NULL;
249 X509 *cert = NULL, *idcert = NULL;
250 char nn2[1024];
251 sprintf(nn2, "%s <identity>", nickname);
253 tor_tls_init();
255 if (isServer) {
256 if (!(rsa = crypto_new_pk_env()))
257 goto error;
258 if (crypto_pk_generate_key(rsa)<0)
259 goto error;
260 cert = tor_tls_create_certificate(rsa, identity, nickname, nn2,
261 key_lifetime);
262 idcert = tor_tls_create_certificate(identity, identity, nn2, nn2,
263 IDENTITY_CERT_LIFETIME);
264 if (!cert || !idcert) {
265 log(LOG_WARN, "Error creating certificate");
266 goto error;
270 result = tor_malloc(sizeof(tor_tls_context));
271 result->ctx = NULL;
272 #ifdef EVERYONE_HAS_AES
273 /* Tell OpenSSL to only use TLS1 */
274 if (!(result->ctx = SSL_CTX_new(TLSv1_method())))
275 goto error;
276 #else
277 /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
278 if (!(result->ctx = SSL_CTX_new(SSLv23_method())))
279 goto error;
280 SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2);
281 #endif
282 if (!SSL_CTX_set_cipher_list(result->ctx, CIPHER_LIST))
283 goto error;
284 if (cert && !SSL_CTX_use_certificate(result->ctx,cert))
285 goto error;
286 if (idcert && !SSL_CTX_add_extra_chain_cert(result->ctx,idcert))
287 goto error;
288 SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
289 if (isServer) {
290 tor_assert(rsa);
291 if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,1)))
292 goto error;
293 if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
294 goto error;
295 EVP_PKEY_free(pkey);
296 pkey = NULL;
297 if (cert) {
298 if (!SSL_CTX_check_private_key(result->ctx))
299 goto error;
302 dh = crypto_dh_new();
303 SSL_CTX_set_tmp_dh(result->ctx, _crypto_dh_env_get_dh(dh));
304 crypto_dh_free(dh);
305 SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
306 always_accept_verify_cb);
307 /* let us realloc bufs that we're writing from */
308 SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
310 /* Free the old context if one exists. */
311 if (global_tls_context) {
312 /* This is safe even if there are open connections: OpenSSL does
313 * reference counting with SSL and SSL_CTX objects. */
314 SSL_CTX_free(global_tls_context->ctx);
315 free(global_tls_context);
317 global_tls_context = result;
318 return 0;
320 error:
321 tls_log_errors(LOG_WARN, "creating TLS context");
322 if (pkey)
323 EVP_PKEY_free(pkey);
324 if (rsa)
325 crypto_free_pk_env(rsa);
326 if (dh)
327 crypto_dh_free(dh);
328 if (result && result->ctx)
329 SSL_CTX_free(result->ctx);
330 if (result)
331 free(result);
332 /* leak certs XXXX ? */
333 return -1;
336 /* Create a new TLS object from a TLS context, a filedescriptor, and
337 * a flag to determine whether it is functioning as a server.
339 tor_tls *
340 tor_tls_new(int sock, int isServer)
342 tor_tls *result = tor_malloc(sizeof(tor_tls));
343 tor_assert(global_tls_context); /* make sure somebody made it first */
344 if (!(result->ssl = SSL_new(global_tls_context->ctx)))
345 return NULL;
346 result->socket = sock;
347 SSL_set_fd(result->ssl, sock);
348 result->state = TOR_TLS_ST_HANDSHAKE;
349 result->isServer = isServer;
350 result->wantwrite_n = 0;
351 return result;
354 /* Release resources associated with a TLS object. Does not close the
355 * underlying file descriptor.
357 void
358 tor_tls_free(tor_tls *tls)
360 SSL_free(tls->ssl);
361 free(tls);
364 /* Underlying function for TLS reading. Reads up to 'len' characters
365 * from 'tls' into 'cp'. On success, returns the number of characters
366 * read. On failure, returns TOR_TLS_ERROR, TOR_TLS_CLOSE,
367 * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
370 tor_tls_read(tor_tls *tls, char *cp, int len)
372 int r, err;
373 tor_assert(tls && tls->ssl);
374 tor_assert(tls->state == TOR_TLS_ST_OPEN);
375 r = SSL_read(tls->ssl, cp, len);
376 if (r > 0)
377 return r;
378 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_INFO);
379 if (err == _TOR_TLS_ZERORETURN) {
380 tls->state = TOR_TLS_ST_CLOSED;
381 return TOR_TLS_CLOSE;
382 } else {
383 tor_assert(err != TOR_TLS_DONE);
384 return err;
388 /* Underlying function for TLS writing. Write up to 'n' characters
389 * from 'cp' onto 'tls'. On success, returns the number of characters
390 * written. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
391 * or TOR_TLS_WANTWRITE.
394 tor_tls_write(tor_tls *tls, char *cp, int n)
396 int r, err;
397 tor_assert(tls && tls->ssl);
398 tor_assert(tls->state == TOR_TLS_ST_OPEN);
399 if (n == 0)
400 return 0;
401 if(tls->wantwrite_n) {
402 /* if WANTWRITE last time, we must use the _same_ n as before */
403 tor_assert(n >= tls->wantwrite_n);
404 log_fn(LOG_DEBUG,"resuming pending-write, (%d to flush, reusing %d)",
405 n, tls->wantwrite_n);
406 n = tls->wantwrite_n;
407 tls->wantwrite_n = 0;
409 r = SSL_write(tls->ssl, cp, n);
410 err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO);
411 if (err == TOR_TLS_DONE) {
412 return r;
414 if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
415 // log_fn(LOG_INFO,"wantwrite or wantread. remembering the number %d.",n);
416 tls->wantwrite_n = n;
418 return err;
421 /* Perform initial handshake on 'tls'. When finished, returns
422 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
423 * or TOR_TLS_WANTWRITE.
426 tor_tls_handshake(tor_tls *tls)
428 int r;
429 tor_assert(tls && tls->ssl);
430 tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
431 if (tls->isServer) {
432 r = SSL_accept(tls->ssl);
433 } else {
434 r = SSL_connect(tls->ssl);
436 r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO);
437 if (r == TOR_TLS_DONE) {
438 tls->state = TOR_TLS_ST_OPEN;
440 return r;
443 /* Shut down an open tls connection 'tls'. When finished, returns
444 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
445 * or TOR_TLS_WANTWRITE.
448 tor_tls_shutdown(tor_tls *tls)
450 int r, err;
451 char buf[128];
452 tor_assert(tls && tls->ssl);
454 while (1) {
455 if (tls->state == TOR_TLS_ST_SENTCLOSE) {
456 /* If we've already called shutdown once to send a close message,
457 * we read until the other side has closed too.
459 do {
460 r = SSL_read(tls->ssl, buf, 128);
461 } while (r>0);
462 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
463 LOG_INFO);
464 if (err == _TOR_TLS_ZERORETURN) {
465 tls->state = TOR_TLS_ST_GOTCLOSE;
466 /* fall through... */
467 } else {
468 return err;
472 r = SSL_shutdown(tls->ssl);
473 if (r == 1) {
474 /* If shutdown returns 1, the connection is entirely closed. */
475 tls->state = TOR_TLS_ST_CLOSED;
476 return TOR_TLS_DONE;
478 err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
479 LOG_INFO);
480 if (err == _TOR_TLS_SYSCALL) {
481 /* The underlying TCP connection closed while we were shutting down. */
482 tls->state = TOR_TLS_ST_CLOSED;
483 return TOR_TLS_DONE;
484 } else if (err == _TOR_TLS_ZERORETURN) {
485 /* The TLS connection says that it sent a shutdown record, but
486 * isn't done shutting down yet. Make sure that this hasn't
487 * happened before, then go back to the start of the function
488 * and try to read.
490 if (tls->state == TOR_TLS_ST_GOTCLOSE ||
491 tls->state == TOR_TLS_ST_SENTCLOSE) {
492 log(LOG_WARN,
493 "TLS returned \"half-closed\" value while already half-closed");
494 return TOR_TLS_ERROR;
496 tls->state = TOR_TLS_ST_SENTCLOSE;
497 /* fall through ... */
498 } else {
499 return err;
501 } /* end loop */
504 /* Return true iff this TLS connection is authenticated.
507 tor_tls_peer_has_cert(tor_tls *tls)
509 X509 *cert;
510 if (!(cert = SSL_get_peer_certificate(tls->ssl)))
511 return 0;
512 X509_free(cert);
513 return 1;
517 tor_tls_get_peer_cert_nickname(tor_tls *tls, char *buf, int buflen)
519 X509 *cert = NULL;
520 X509_NAME *name = NULL;
521 int nid;
522 int lenout;
524 if (!(cert = SSL_get_peer_certificate(tls->ssl))) {
525 log_fn(LOG_WARN, "Peer has no certificate");
526 goto error;
528 if (!(name = X509_get_subject_name(cert))) {
529 log_fn(LOG_WARN, "Peer certificate has no subject name");
530 goto error;
532 if ((nid = OBJ_txt2nid("commonName")) == NID_undef)
533 goto error;
535 lenout = X509_NAME_get_text_by_NID(name, nid, buf, buflen);
536 if (lenout == -1)
537 goto error;
538 if (((int)strspn(buf, LEGAL_NICKNAME_CHARACTERS)) < lenout) {
539 log_fn(LOG_WARN, "Peer certificate nickname has illegal characters.");
540 goto error;
542 return 0;
543 error:
544 if (cert)
545 X509_free(cert);
546 if (name)
547 X509_NAME_free(name);
548 return -1;
551 /* If the provided tls connection is authenticated and has a
552 * certificate that is currently valid and is correctly signed by
553 * identity_key, return 0. Else, return -1.
556 tor_tls_verify(tor_tls *tls, crypto_pk_env_t *identity_key)
558 X509 *cert = NULL;
559 EVP_PKEY *id_pkey = NULL;
560 time_t now, t;
561 int r = -1;
563 if (!(cert = SSL_get_peer_certificate(tls->ssl)))
564 return -1;
566 now = time(NULL);
567 t = now + CERT_ALLOW_SKEW;
568 if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
569 log_fn(LOG_WARN,"Certificate becomes valid in the future: possible clock skew.");
570 goto done;
572 t = now - CERT_ALLOW_SKEW;
573 if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
574 log_fn(LOG_WARN,"Certificate already expired; possible clock skew.");
575 goto done;
578 /* Get the public key. */
579 if (!(id_pkey = _crypto_pk_env_get_evp_pkey(identity_key,0)) ||
580 X509_verify(cert, id_pkey) <= 0) {
581 log_fn(LOG_WARN,"X509_verify on cert and pkey returned <= 0");
582 tls_log_errors(LOG_WARN,"verifying certificate");
583 goto done;
586 r = 0;
588 done:
589 if (cert)
590 X509_free(cert);
591 if (id_pkey)
592 EVP_PKEY_free(id_pkey);
594 /* XXXX */
595 tls_log_errors(LOG_WARN, "finishing tor_tls_verify");
597 return r;
601 tor_tls_get_pending_bytes(tor_tls *tls)
603 tor_assert(tls);
604 return SSL_pending(tls->ssl);
607 /* Return the number of bytes read across the underlying socket. */
608 unsigned long tor_tls_get_n_bytes_read(tor_tls *tls)
610 tor_assert(tls);
611 return BIO_number_read(SSL_get_rbio(tls->ssl));
613 unsigned long tor_tls_get_n_bytes_written(tor_tls *tls)
615 tor_assert(tls);
616 return BIO_number_written(SSL_get_wbio(tls->ssl));
620 Local Variables:
621 mode:c
622 indent-tabs-mode:nil
623 c-basic-offset:2
624 End: