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.)
15 /* Copied from or.h */
16 #define LEGAL_NICKNAME_CHARACTERS "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
19 #include <openssl/ssl.h>
20 #include <openssl/err.h>
21 #include <openssl/tls1.h>
22 #include <openssl/asn1.h>
23 #include <openssl/bio.h>
25 /* How long do certificates live? (sec) */
26 #define CERT_LIFETIME (365*24*60*60)
27 /* How much clock skew do we tolerate when checking certificates? (sec) */
28 #define CERT_ALLOW_SKEW (30*60)
30 struct tor_tls_context_st
{
38 TOR_TLS_ST_HANDSHAKE
, TOR_TLS_ST_OPEN
, TOR_TLS_ST_GOTCLOSE
,
39 TOR_TLS_ST_SENTCLOSE
, TOR_TLS_ST_CLOSED
42 int wantwrite_n
; /* 0 normally, >0 if we returned wantwrite last time */
45 static X509
* tor_tls_create_certificate(crypto_pk_env_t
*rsa
,
46 const char *nickname
);
48 /* global tls context, keep it here because nobody else needs to touch it */
49 static tor_tls_context
*global_tls_context
= NULL
;
50 static int tls_library_is_initialized
= 0;
52 #define _TOR_TLS_SYSCALL -6
53 #define _TOR_TLS_ZERORETURN -5
55 /* These functions are declared in crypto.c but not exported. */
56 EVP_PKEY
*_crypto_pk_env_get_evp_pkey(crypto_pk_env_t
*env
);
57 crypto_pk_env_t
*_crypto_new_pk_env_rsa(RSA
*rsa
);
60 tls_log_errors(int severity
, const char *doing
)
63 const char *msg
, *lib
, *func
;
64 while ((err
= ERR_get_error()) != 0) {
65 msg
= (const char*)ERR_reason_error_string(err
);
66 lib
= (const char*)ERR_lib_error_string(err
);
67 func
= (const char*)ERR_func_error_string(err
);
68 if (!msg
) msg
= "(null)";
70 log(severity
, "TLS error while %s: %s (in %s:%s)", doing
, msg
, lib
,func
);
72 log(severity
, "TLS error: %s (in %s:%s)", msg
, lib
, func
);
77 #define CATCH_SYSCALL 1
81 tor_tls_get_error(tor_tls
*tls
, int r
, int extra
,
82 const char *doing
, int severity
)
84 int err
= SSL_get_error(tls
->ssl
, r
);
88 case SSL_ERROR_WANT_READ
:
89 return TOR_TLS_WANTREAD
;
90 case SSL_ERROR_WANT_WRITE
:
91 return TOR_TLS_WANTWRITE
;
92 case SSL_ERROR_SYSCALL
:
93 if (extra
&CATCH_SYSCALL
)
94 return _TOR_TLS_SYSCALL
;
95 log(severity
, "TLS error: <syscall error> (errno=%d)",errno
);
96 tls_log_errors(severity
, doing
);
98 case SSL_ERROR_ZERO_RETURN
:
100 return _TOR_TLS_ZERORETURN
;
101 log(severity
, "TLS error: Zero return");
102 tls_log_errors(severity
, doing
);
103 return TOR_TLS_ERROR
;
105 tls_log_errors(severity
, doing
);
106 return TOR_TLS_ERROR
;
112 if (!tls_library_is_initialized
) {
114 SSL_load_error_strings();
115 crypto_global_init();
116 OpenSSL_add_all_algorithms();
117 tls_library_is_initialized
= 1;
121 static int always_accept_verify_cb(int preverify_ok
,
122 X509_STORE_CTX
*x509_ctx
)
124 /* We always accept peer certs and complete the handshake. We don't validate
125 * them until later. */
129 /* Generate a self-signed certificate with the private key 'rsa' and
130 * commonName 'nickname', and write it, PEM-encoded, to the file named
131 * by 'certfile'. Return 0 on success, -1 for failure.
134 tor_tls_create_certificate(crypto_pk_env_t
*rsa
,
135 const char *nickname
)
137 time_t start_time
, end_time
;
138 EVP_PKEY
*pkey
= NULL
;
140 X509_NAME
*name
= NULL
;
145 start_time
= time(NULL
);
147 assert(rsa
&& nickname
);
148 if (!(pkey
= _crypto_pk_env_get_evp_pkey(rsa
)))
150 if (!(x509
= X509_new()))
152 if (!(X509_set_version(x509
, 2)))
154 if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509
), (long)start_time
)))
157 if (!(name
= X509_NAME_new()))
159 if ((nid
= OBJ_txt2nid("organizationName")) == NID_undef
) goto error
;
160 if (!(X509_NAME_add_entry_by_NID(name
, nid
, MBSTRING_ASC
,
161 "TOR", -1, -1, 0))) goto error
;
162 if ((nid
= OBJ_txt2nid("commonName")) == NID_undef
) goto error
;
163 if (!(X509_NAME_add_entry_by_NID(name
, nid
, MBSTRING_ASC
,
164 (char*)nickname
, -1, -1, 0))) goto error
;
166 if (!(X509_set_issuer_name(x509
, name
)))
168 if (!(X509_set_subject_name(x509
, name
)))
170 if (!X509_time_adj(X509_get_notBefore(x509
),0,&start_time
))
172 end_time
= start_time
+ CERT_LIFETIME
;
173 if (!X509_time_adj(X509_get_notAfter(x509
),0,&end_time
))
175 if (!X509_set_pubkey(x509
, pkey
))
177 if (!X509_sign(x509
, pkey
, EVP_sha1()))
190 X509_NAME_free(name
);
195 #ifdef EVERYONE_HAS_AES
196 /* Everybody is running OpenSSL 0.9.7 or later, so no backward compatibility
198 #define CIPHER_LIST TLS1_TXT_DHE_RSA_WITH_AES_128_SHA
199 #elif defined(TLS1_TXT_DHE_RSA_WITH_AES_128_SHA)
200 /* Some people are running OpenSSL before 0.9.7, but we aren't.
201 * We can support AES and 3DES.
203 #define CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
204 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
206 /* We're running OpenSSL before 0.9.7. We only support 3DES. */
207 #define CIPHER_LIST SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA
210 /* Create a new TLS context. If we are going to be using it as a
211 * server, it must have isServer set to true, certfile set to a
212 * filename for a certificate file, and RSA set to the private key
213 * used for that certificate. Return -1 if failure, else 0.
216 tor_tls_context_new(crypto_pk_env_t
*rsa
,
217 int isServer
, const char *nickname
)
219 crypto_dh_env_t
*dh
= NULL
;
220 EVP_PKEY
*pkey
= NULL
;
221 tor_tls_context
*result
;
227 cert
= tor_tls_create_certificate(rsa
, nickname
);
229 log(LOG_WARN
, "Error creating certificate");
234 result
= tor_malloc(sizeof(tor_tls_context
));
236 #ifdef EVERYONE_HAS_AES
237 /* Tell OpenSSL to only use TLS1 */
238 if (!(result
->ctx
= SSL_CTX_new(TLSv1_method())))
241 /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
242 if (!(result
->ctx
= SSL_CTX_new(SSLv23_method())))
244 SSL_CTX_set_options(result
->ctx
, SSL_OP_NO_SSLv2
);
246 if (!SSL_CTX_set_cipher_list(result
->ctx
, CIPHER_LIST
))
248 if (cert
&& !SSL_CTX_use_certificate(result
->ctx
,cert
))
250 SSL_CTX_set_session_cache_mode(result
->ctx
, SSL_SESS_CACHE_OFF
);
252 if (!(pkey
= _crypto_pk_env_get_evp_pkey(rsa
)))
254 if (!SSL_CTX_use_PrivateKey(result
->ctx
, pkey
))
259 if (!SSL_CTX_check_private_key(result
->ctx
))
263 dh
= crypto_dh_new();
264 SSL_CTX_set_tmp_dh(result
->ctx
, dh
->dh
);
266 SSL_CTX_set_verify(result
->ctx
, SSL_VERIFY_PEER
,
267 always_accept_verify_cb
);
268 /* let us realloc bufs that we're writing from */
269 SSL_CTX_set_mode(result
->ctx
, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER
);
271 /* Free the old context if one exists. */
272 if (global_tls_context
) {
273 /* This is safe even if there are open connections: OpenSSL does
274 * reference counting with SSL and SSL_CTX objects. */
275 SSL_CTX_free(global_tls_context
->ctx
);
276 free(global_tls_context
);
278 global_tls_context
= result
;
286 if (result
&& result
->ctx
)
287 SSL_CTX_free(result
->ctx
);
294 /* Create a new TLS object from a TLS context, a filedescriptor, and
295 * a flag to determine whether it is functioning as a server.
298 tor_tls_new(int sock
, int isServer
)
300 tor_tls
*result
= tor_malloc(sizeof(tor_tls
));
301 assert(global_tls_context
); /* make sure somebody made it first */
302 if (!(result
->ssl
= SSL_new(global_tls_context
->ctx
)))
304 result
->socket
= sock
;
305 SSL_set_fd(result
->ssl
, sock
);
306 result
->state
= TOR_TLS_ST_HANDSHAKE
;
307 result
->isServer
= isServer
;
308 result
->wantwrite_n
= 0;
312 /* Release resources associated with a TLS object. Does not close the
313 * underlying file descriptor.
316 tor_tls_free(tor_tls
*tls
)
322 /* Underlying function for TLS reading. Reads up to 'len' characters
323 * from 'tls' into 'cp'. On success, returns the number of characters
324 * read. On failure, returns TOR_TLS_ERROR, TOR_TLS_CLOSE,
325 * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
328 tor_tls_read(tor_tls
*tls
, char *cp
, int len
)
331 assert(tls
&& tls
->ssl
);
332 assert(tls
->state
== TOR_TLS_ST_OPEN
);
333 r
= SSL_read(tls
->ssl
, cp
, len
);
336 err
= tor_tls_get_error(tls
, r
, CATCH_ZERO
, "reading", LOG_INFO
);
337 if (err
== _TOR_TLS_ZERORETURN
) {
338 tls
->state
= TOR_TLS_ST_CLOSED
;
339 return TOR_TLS_CLOSE
;
341 assert(err
!= TOR_TLS_DONE
);
346 /* Underlying function for TLS writing. Write up to 'n' characters
347 * from 'cp' onto 'tls'. On success, returns the number of characters
348 * written. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
349 * or TOR_TLS_WANTWRITE.
352 tor_tls_write(tor_tls
*tls
, char *cp
, int n
)
355 assert(tls
&& tls
->ssl
);
356 assert(tls
->state
== TOR_TLS_ST_OPEN
);
359 if(tls
->wantwrite_n
) {
360 /* if WANTWRITE last time, we must use the _same_ n as before */
361 assert(n
>= tls
->wantwrite_n
);
362 log_fn(LOG_INFO
,"resuming pending-write, (%d to flush, reusing %d)",
363 n
, tls
->wantwrite_n
);
364 n
= tls
->wantwrite_n
;
365 tls
->wantwrite_n
= 0;
367 r
= SSL_write(tls
->ssl
, cp
, n
);
368 err
= tor_tls_get_error(tls
, r
, 0, "writing", LOG_INFO
);
369 if (err
== TOR_TLS_DONE
) {
372 if (err
== TOR_TLS_WANTWRITE
|| err
== TOR_TLS_WANTREAD
) {
373 log_fn(LOG_INFO
,"wantwrite or wantread. remembering the number %d.",n
);
374 tls
->wantwrite_n
= n
;
379 /* Perform initial handshake on 'tls'. When finished, returns
380 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
381 * or TOR_TLS_WANTWRITE.
384 tor_tls_handshake(tor_tls
*tls
)
387 assert(tls
&& tls
->ssl
);
388 assert(tls
->state
== TOR_TLS_ST_HANDSHAKE
);
390 r
= SSL_accept(tls
->ssl
);
392 r
= SSL_connect(tls
->ssl
);
394 r
= tor_tls_get_error(tls
,r
,0, "handshaking", LOG_INFO
);
395 if (r
== TOR_TLS_DONE
) {
396 tls
->state
= TOR_TLS_ST_OPEN
;
401 /* Shut down an open tls connection 'tls'. When finished, returns
402 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
403 * or TOR_TLS_WANTWRITE.
406 tor_tls_shutdown(tor_tls
*tls
)
410 assert(tls
&& tls
->ssl
);
413 if (tls
->state
== TOR_TLS_ST_SENTCLOSE
) {
414 /* If we've already called shutdown once to send a close message,
415 * we read until the other side has closed too.
418 r
= SSL_read(tls
->ssl
, buf
, 128);
420 err
= tor_tls_get_error(tls
, r
, CATCH_ZERO
, "reading to shut down",
422 if (err
== _TOR_TLS_ZERORETURN
) {
423 tls
->state
= TOR_TLS_ST_GOTCLOSE
;
424 /* fall through... */
430 r
= SSL_shutdown(tls
->ssl
);
432 /* If shutdown returns 1, the connection is entirely closed. */
433 tls
->state
= TOR_TLS_ST_CLOSED
;
436 err
= tor_tls_get_error(tls
, r
, CATCH_SYSCALL
|CATCH_ZERO
, "shutting down",
438 if (err
== _TOR_TLS_SYSCALL
) {
439 /* The underlying TCP connection closed while we were shutting down. */
440 tls
->state
= TOR_TLS_ST_CLOSED
;
442 } else if (err
== _TOR_TLS_ZERORETURN
) {
443 /* The TLS connection says that it sent a shutdown record, but
444 * isn't done shutting down yet. Make sure that this hasn't
445 * happened before, then go back to the start of the function
448 if (tls
->state
== TOR_TLS_ST_GOTCLOSE
||
449 tls
->state
== TOR_TLS_ST_SENTCLOSE
) {
451 "TLS returned \"half-closed\" value while already half-closed");
452 return TOR_TLS_ERROR
;
454 tls
->state
= TOR_TLS_ST_SENTCLOSE
;
455 /* fall through ... */
462 /* Return true iff this TLS connection is authenticated.
465 tor_tls_peer_has_cert(tor_tls
*tls
)
468 if (!(cert
= SSL_get_peer_certificate(tls
->ssl
)))
475 tor_tls_get_peer_cert_nickname(tor_tls
*tls
, char *buf
, int buflen
)
478 X509_NAME
*name
= NULL
;
482 if (!(cert
= SSL_get_peer_certificate(tls
->ssl
))) {
483 log_fn(LOG_WARN
, "Peer has no certificate");
486 if (!(name
= X509_get_subject_name(cert
))) {
487 log_fn(LOG_WARN
, "Peer certificate has no subject name");
490 if ((nid
= OBJ_txt2nid("commonName")) == NID_undef
)
493 lenout
= X509_NAME_get_text_by_NID(name
, nid
, buf
, buflen
);
496 if (strspn(buf
, LEGAL_NICKNAME_CHARACTERS
) != lenout
) {
497 log_fn(LOG_WARN
, "Peer certificate nickname has illegal characters.");
505 X509_NAME_free(name
);
509 /* If the provided tls connection is authenticated and has a
510 * certificate that is currently valid and is correctly self-signed,
511 * return its public key. Otherwise return NULL.
514 tor_tls_verify(tor_tls
*tls
)
517 EVP_PKEY
*pkey
= NULL
;
520 crypto_pk_env_t
*r
= NULL
;
521 if (!(cert
= SSL_get_peer_certificate(tls
->ssl
)))
525 t
= now
+ CERT_ALLOW_SKEW
;
526 if (X509_cmp_time(X509_get_notBefore(cert
), &t
) > 0) {
527 log_fn(LOG_WARN
,"Certificate becomes valid in the future: possible clock skew.");
530 t
= now
- CERT_ALLOW_SKEW
;
531 if (X509_cmp_time(X509_get_notAfter(cert
), &t
) < 0) {
532 log_fn(LOG_WARN
,"Certificate already expired; possible clock skew.");
536 /* Get the public key. */
537 if (!(pkey
= X509_get_pubkey(cert
))) {
538 log_fn(LOG_WARN
,"X509_get_pubkey returned null");
541 if (X509_verify(cert
, pkey
) <= 0) {
542 log_fn(LOG_WARN
,"X509_verify on cert and pkey returned <= 0");
546 rsa
= EVP_PKEY_get1_RSA(pkey
);
550 log_fn(LOG_WARN
,"EVP_PKEY_get1_RSA(pkey) returned null");
554 r
= _crypto_new_pk_env_rsa(rsa
);
568 tor_tls_get_pending_bytes(tor_tls
*tls
)
571 return SSL_pending(tls
->ssl
);
574 /* Return the number of bytes read across the underlying socket. */
575 unsigned long tor_tls_get_n_bytes_read(tor_tls
*tls
)
578 return BIO_number_read(SSL_get_rbio(tls
->ssl
));
580 unsigned long tor_tls_get_n_bytes_written(tor_tls
*tls
)
583 return BIO_number_written(SSL_get_wbio(tls
->ssl
));