1 /* Copyright 2003 Roger Dingledine. */
2 /* See LICENSE for licensing information */
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.)
16 /* Copied from or.h */
17 #define LEGAL_NICKNAME_CHARACTERS "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
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
{
39 TOR_TLS_ST_HANDSHAKE
, TOR_TLS_ST_OPEN
, TOR_TLS_ST_GOTCLOSE
,
40 TOR_TLS_ST_SENTCLOSE
, TOR_TLS_ST_CLOSED
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
,
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
);
65 tls_log_errors(int severity
, const char *doing
)
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)";
75 log(severity
, "TLS error while %s: %s (in %s:%s)", doing
, msg
, lib
,func
);
77 log(severity
, "TLS error: %s (in %s:%s)", msg
, lib
, func
);
82 #define CATCH_SYSCALL 1
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
);
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
,
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
;
111 tls_log_errors(severity
, doing
);
112 return TOR_TLS_ERROR
;
118 if (!tls_library_is_initialized
) {
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. */
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.
141 tor_tls_create_certificate(crypto_pk_env_t
*rsa
,
142 crypto_pk_env_t
*rsa_sign
,
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
;
150 X509_NAME
*name
= NULL
, *name_issuer
=NULL
;
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)))
160 if (!(pkey
= _crypto_pk_env_get_evp_pkey(rsa
,0)))
162 if (!(x509
= X509_new()))
164 if (!(X509_set_version(x509
, 2)))
166 if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509
), (long)start_time
)))
169 if (!(name
= X509_NAME_new()))
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
)))
180 if (!(name_issuer
= X509_NAME_new()))
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
)))
191 if (!X509_time_adj(X509_get_notBefore(x509
),0,&start_time
))
193 end_time
= start_time
+ cert_lifetime
;
194 if (!X509_time_adj(X509_get_notAfter(x509
),0,&end_time
))
196 if (!X509_set_pubkey(x509
, pkey
))
198 if (!X509_sign(x509
, sign_pkey
, EVP_sha1()))
203 tls_log_errors(LOG_WARN
, "generating certificate");
210 EVP_PKEY_free(sign_pkey
);
214 X509_NAME_free(name
);
216 X509_NAME_free(name_issuer
);
221 #ifdef EVERYONE_HAS_AES
222 /* Everybody is running OpenSSL 0.9.7 or later, so no backward compatibility
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)
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
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
;
252 sprintf(nn2
, "%s <identity>", nickname
);
257 if (!(rsa
= crypto_new_pk_env()))
259 if (crypto_pk_generate_key(rsa
)<0)
261 cert
= tor_tls_create_certificate(rsa
, identity
, nickname
, nn2
,
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");
271 result
= tor_malloc(sizeof(tor_tls_context
));
273 #ifdef EVERYONE_HAS_AES
274 /* Tell OpenSSL to only use TLS1 */
275 if (!(result
->ctx
= SSL_CTX_new(TLSv1_method())))
278 /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
279 if (!(result
->ctx
= SSL_CTX_new(SSLv23_method())))
281 SSL_CTX_set_options(result
->ctx
, SSL_OP_NO_SSLv2
);
283 if (!SSL_CTX_set_cipher_list(result
->ctx
, CIPHER_LIST
))
285 if (cert
&& !SSL_CTX_use_certificate(result
->ctx
,cert
))
287 if (idcert
&& !SSL_CTX_add_extra_chain_cert(result
->ctx
,idcert
))
289 SSL_CTX_set_session_cache_mode(result
->ctx
, SSL_SESS_CACHE_OFF
);
292 if (!(pkey
= _crypto_pk_env_get_evp_pkey(rsa
,1)))
294 if (!SSL_CTX_use_PrivateKey(result
->ctx
, pkey
))
299 if (!SSL_CTX_check_private_key(result
->ctx
))
303 dh
= crypto_dh_new();
304 SSL_CTX_set_tmp_dh(result
->ctx
, _crypto_dh_env_get_dh(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
;
322 tls_log_errors(LOG_WARN
, "creating TLS context");
326 crypto_free_pk_env(rsa
);
329 if (result
&& result
->ctx
)
330 SSL_CTX_free(result
->ctx
);
333 /* leak certs XXXX ? */
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.
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
)))
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;
355 /* Release resources associated with a TLS object. Does not close the
356 * underlying file descriptor.
359 tor_tls_free(tor_tls
*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
)
374 tor_assert(tls
&& tls
->ssl
);
375 tor_assert(tls
->state
== TOR_TLS_ST_OPEN
);
376 r
= SSL_read(tls
->ssl
, cp
, len
);
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
;
385 tor_assert(err
!= TOR_TLS_DONE
);
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
)
399 tor_assert(tls
&& tls
->ssl
);
400 tor_assert(tls
->state
== TOR_TLS_ST_OPEN
);
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
) {
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
;
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
)
431 tor_assert(tls
&& tls
->ssl
);
432 tor_assert(tls
->state
== TOR_TLS_ST_HANDSHAKE
);
434 r
= SSL_accept(tls
->ssl
);
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
;
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
)
454 tor_assert(tls
&& tls
->ssl
);
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.
462 r
= SSL_read(tls
->ssl
, buf
, 128);
464 err
= tor_tls_get_error(tls
, r
, CATCH_ZERO
, "reading to shut down",
466 if (err
== _TOR_TLS_ZERORETURN
) {
467 tls
->state
= TOR_TLS_ST_GOTCLOSE
;
468 /* fall through... */
474 r
= SSL_shutdown(tls
->ssl
);
476 /* If shutdown returns 1, the connection is entirely closed. */
477 tls
->state
= TOR_TLS_ST_CLOSED
;
480 err
= tor_tls_get_error(tls
, r
, CATCH_SYSCALL
|CATCH_ZERO
, "shutting down",
482 if (err
== _TOR_TLS_SYSCALL
) {
483 /* The underlying TCP connection closed while we were shutting down. */
484 tls
->state
= TOR_TLS_ST_CLOSED
;
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
492 if (tls
->state
== TOR_TLS_ST_GOTCLOSE
||
493 tls
->state
== TOR_TLS_ST_SENTCLOSE
) {
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 ... */
506 /* Return true iff this TLS connection is authenticated.
509 tor_tls_peer_has_cert(tor_tls
*tls
)
512 if (!(cert
= SSL_get_peer_certificate(tls
->ssl
)))
519 tor_tls_get_peer_cert_nickname(tor_tls
*tls
, char *buf
, int buflen
)
522 X509_NAME
*name
= NULL
;
526 if (!(cert
= SSL_get_peer_certificate(tls
->ssl
))) {
527 log_fn(LOG_WARN
, "Peer has no certificate");
530 if (!(name
= X509_get_subject_name(cert
))) {
531 log_fn(LOG_WARN
, "Peer certificate has no subject name");
534 if ((nid
= OBJ_txt2nid("commonName")) == NID_undef
)
537 lenout
= X509_NAME_get_text_by_NID(name
, nid
, buf
, buflen
);
540 if (((int)strspn(buf
, LEGAL_NICKNAME_CHARACTERS
)) < lenout
) {
541 log_fn(LOG_WARN
, "Peer certificate nickname has illegal characters.");
549 X509_NAME_free(name
);
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
)
561 EVP_PKEY
*id_pkey
= NULL
;
565 if (!(cert
= SSL_get_peer_certificate(tls
->ssl
)))
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.");
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.");
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");
594 EVP_PKEY_free(id_pkey
);
597 tls_log_errors(LOG_WARN
, "finishing tor_tls_verify");
603 tor_tls_get_pending_bytes(tor_tls
*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
)
613 return BIO_number_read(SSL_get_rbio(tls
->ssl
));
615 unsigned long tor_tls_get_n_bytes_written(tor_tls
*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)
625 log_fn(LOG_ERR
, "Unhandled OpenSSL errors found at %s:%d: ",
627 tls_log_errors(LOG_ERR
, NULL
);