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)",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
;
110 tls_log_errors(severity
, doing
);
111 return TOR_TLS_ERROR
;
117 if (!tls_library_is_initialized
) {
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. */
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.
140 tor_tls_create_certificate(crypto_pk_env_t
*rsa
,
141 crypto_pk_env_t
*rsa_sign
,
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
;
149 X509_NAME
*name
= NULL
, *name_issuer
=NULL
;
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)))
159 if (!(pkey
= _crypto_pk_env_get_evp_pkey(rsa
,0)))
161 if (!(x509
= X509_new()))
163 if (!(X509_set_version(x509
, 2)))
165 if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509
), (long)start_time
)))
168 if (!(name
= X509_NAME_new()))
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
)))
179 if (!(name_issuer
= X509_NAME_new()))
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
)))
190 if (!X509_time_adj(X509_get_notBefore(x509
),0,&start_time
))
192 end_time
= start_time
+ cert_lifetime
;
193 if (!X509_time_adj(X509_get_notAfter(x509
),0,&end_time
))
195 if (!X509_set_pubkey(x509
, pkey
))
197 if (!X509_sign(x509
, sign_pkey
, EVP_sha1()))
202 tls_log_errors(LOG_WARN
, "generating certificate");
209 EVP_PKEY_free(sign_pkey
);
213 X509_NAME_free(name
);
215 X509_NAME_free(name_issuer
);
220 #ifdef EVERYONE_HAS_AES
221 /* Everybody is running OpenSSL 0.9.7 or later, so no backward compatibility
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)
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
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
;
251 sprintf(nn2
, "%s <identity>", nickname
);
256 if (!(rsa
= crypto_new_pk_env()))
258 if (crypto_pk_generate_key(rsa
)<0)
260 cert
= tor_tls_create_certificate(rsa
, identity
, nickname
, nn2
,
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");
270 result
= tor_malloc(sizeof(tor_tls_context
));
272 #ifdef EVERYONE_HAS_AES
273 /* Tell OpenSSL to only use TLS1 */
274 if (!(result
->ctx
= SSL_CTX_new(TLSv1_method())))
277 /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
278 if (!(result
->ctx
= SSL_CTX_new(SSLv23_method())))
280 SSL_CTX_set_options(result
->ctx
, SSL_OP_NO_SSLv2
);
282 if (!SSL_CTX_set_cipher_list(result
->ctx
, CIPHER_LIST
))
284 if (cert
&& !SSL_CTX_use_certificate(result
->ctx
,cert
))
286 if (idcert
&& !SSL_CTX_add_extra_chain_cert(result
->ctx
,idcert
))
288 SSL_CTX_set_session_cache_mode(result
->ctx
, SSL_SESS_CACHE_OFF
);
291 if (!(pkey
= _crypto_pk_env_get_evp_pkey(rsa
,1)))
293 if (!SSL_CTX_use_PrivateKey(result
->ctx
, pkey
))
298 if (!SSL_CTX_check_private_key(result
->ctx
))
302 dh
= crypto_dh_new();
303 SSL_CTX_set_tmp_dh(result
->ctx
, _crypto_dh_env_get_dh(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
;
321 tls_log_errors(LOG_WARN
, "creating TLS context");
325 crypto_free_pk_env(rsa
);
328 if (result
&& result
->ctx
)
329 SSL_CTX_free(result
->ctx
);
332 /* leak certs XXXX ? */
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.
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
)))
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;
354 /* Release resources associated with a TLS object. Does not close the
355 * underlying file descriptor.
358 tor_tls_free(tor_tls
*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
)
373 tor_assert(tls
&& tls
->ssl
);
374 tor_assert(tls
->state
== TOR_TLS_ST_OPEN
);
375 r
= SSL_read(tls
->ssl
, cp
, len
);
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
;
383 tor_assert(err
!= TOR_TLS_DONE
);
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
)
397 tor_assert(tls
&& tls
->ssl
);
398 tor_assert(tls
->state
== TOR_TLS_ST_OPEN
);
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
) {
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
;
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
)
429 tor_assert(tls
&& tls
->ssl
);
430 tor_assert(tls
->state
== TOR_TLS_ST_HANDSHAKE
);
432 r
= SSL_accept(tls
->ssl
);
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
;
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
)
452 tor_assert(tls
&& tls
->ssl
);
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.
460 r
= SSL_read(tls
->ssl
, buf
, 128);
462 err
= tor_tls_get_error(tls
, r
, CATCH_ZERO
, "reading to shut down",
464 if (err
== _TOR_TLS_ZERORETURN
) {
465 tls
->state
= TOR_TLS_ST_GOTCLOSE
;
466 /* fall through... */
472 r
= SSL_shutdown(tls
->ssl
);
474 /* If shutdown returns 1, the connection is entirely closed. */
475 tls
->state
= TOR_TLS_ST_CLOSED
;
478 err
= tor_tls_get_error(tls
, r
, CATCH_SYSCALL
|CATCH_ZERO
, "shutting down",
480 if (err
== _TOR_TLS_SYSCALL
) {
481 /* The underlying TCP connection closed while we were shutting down. */
482 tls
->state
= TOR_TLS_ST_CLOSED
;
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
490 if (tls
->state
== TOR_TLS_ST_GOTCLOSE
||
491 tls
->state
== TOR_TLS_ST_SENTCLOSE
) {
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 ... */
504 /* Return true iff this TLS connection is authenticated.
507 tor_tls_peer_has_cert(tor_tls
*tls
)
510 if (!(cert
= SSL_get_peer_certificate(tls
->ssl
)))
517 tor_tls_get_peer_cert_nickname(tor_tls
*tls
, char *buf
, int buflen
)
520 X509_NAME
*name
= NULL
;
524 if (!(cert
= SSL_get_peer_certificate(tls
->ssl
))) {
525 log_fn(LOG_WARN
, "Peer has no certificate");
528 if (!(name
= X509_get_subject_name(cert
))) {
529 log_fn(LOG_WARN
, "Peer certificate has no subject name");
532 if ((nid
= OBJ_txt2nid("commonName")) == NID_undef
)
535 lenout
= X509_NAME_get_text_by_NID(name
, nid
, buf
, buflen
);
538 if (((int)strspn(buf
, LEGAL_NICKNAME_CHARACTERS
)) < lenout
) {
539 log_fn(LOG_WARN
, "Peer certificate nickname has illegal characters.");
547 X509_NAME_free(name
);
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
)
559 EVP_PKEY
*id_pkey
= NULL
;
563 if (!(cert
= SSL_get_peer_certificate(tls
->ssl
)))
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.");
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.");
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");
592 EVP_PKEY_free(id_pkey
);
595 tls_log_errors(LOG_WARN
, "finishing tor_tls_verify");
601 tor_tls_get_pending_bytes(tor_tls
*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
)
611 return BIO_number_read(SSL_get_rbio(tls
->ssl
));
613 unsigned long tor_tls_get_n_bytes_written(tor_tls
*tls
)
616 return BIO_number_written(SSL_get_wbio(tls
->ssl
));