1 /* Copyright 2003 Roger Dingledine.
2 * Copyright 2004-2005 Roger Dingledine, Nick Mathewson */
3 /* See LICENSE for licensing information */
5 const char tortls_c_id
[] = "$Id$";
9 * \brief Wrapper functions to present a consistent interface to
10 * TLS, SSL, and X.509 functions from OpenSSL.
13 /* (Unlike other tor functions, these
14 * are prefixed with tor_ in order to avoid conflicting with OpenSSL
15 * functions and variables.)
25 /* Copied from or.h */
26 #define LEGAL_NICKNAME_CHARACTERS "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
29 #include <openssl/ssl.h>
30 #include <openssl/err.h>
31 #include <openssl/tls1.h>
32 #include <openssl/asn1.h>
33 #include <openssl/bio.h>
35 /** How long do identity certificates live? (sec) */
36 #define IDENTITY_CERT_LIFETIME (365*24*60*60)
39 typedef struct tor_tls_context_t
{
41 SSL_CTX
*client_only_ctx
;
44 /** Holds a SSL object and its associated data. Members are only
45 * accessed from within tortls.c.
48 SSL
*ssl
; /**< An OpenSSL SSL object. */
49 int socket
; /**< The underlying file descriptor for this TLS connection. */
51 TOR_TLS_ST_HANDSHAKE
, TOR_TLS_ST_OPEN
, TOR_TLS_ST_GOTCLOSE
,
52 TOR_TLS_ST_SENTCLOSE
, TOR_TLS_ST_CLOSED
53 } state
; /**< The current SSL state, depending on which operations have
54 * completed successfully. */
56 size_t wantwrite_n
; /**< 0 normally, >0 if we returned wantwrite last time. */
59 static X509
* tor_tls_create_certificate(crypto_pk_env_t
*rsa
,
60 crypto_pk_env_t
*rsa_sign
,
62 const char *cname_sign
,
63 unsigned int lifetime
);
65 /** Global tls context. We keep it here because nobody else needs to
67 static tor_tls_context_t
*global_tls_context
= NULL
;
68 /** True iff tor_tls_init() has been called. */
69 static int tls_library_is_initialized
= 0;
71 /* Module-internal error codes. */
72 #define _TOR_TLS_SYSCALL -6
73 #define _TOR_TLS_ZERORETURN -5
75 /* These functions are declared in crypto.c but not exported. */
76 EVP_PKEY
*_crypto_pk_env_get_evp_pkey(crypto_pk_env_t
*env
, int private);
77 crypto_pk_env_t
*_crypto_new_pk_env_rsa(RSA
*rsa
);
78 DH
*_crypto_dh_env_get_dh(crypto_dh_env_t
*dh
);
80 /** Log all pending tls errors at level <b>severity</b>. Use
81 * <b>doing</b> to describe our current activities.
84 tls_log_errors(int severity
, const char *doing
)
87 const char *msg
, *lib
, *func
;
88 while ((err
= ERR_get_error()) != 0) {
89 msg
= (const char*)ERR_reason_error_string(err
);
90 lib
= (const char*)ERR_lib_error_string(err
);
91 func
= (const char*)ERR_func_error_string(err
);
92 if (!msg
) msg
= "(null)";
94 log(severity
, LD_NET
, "TLS error while %s: %s (in %s:%s)", doing
, msg
, lib
,func
);
96 log(severity
, LD_NET
, "TLS error: %s (in %s:%s)", msg
, lib
, func
);
101 #define CATCH_SYSCALL 1
104 /** Given a TLS object and the result of an SSL_* call, use
105 * SSL_get_error to determine whether an error has occurred, and if so
106 * which one. Return one of TOR_TLS_{DONE|WANTREAD|WANTWRITE|ERROR}.
107 * If extra&CATCH_SYSCALL is true, return _TOR_TLS_SYSCALL instead of
108 * reporting syscall errors. If extra&CATCH_ZERO is true, return
109 * _TOR_TLS_ZERORETURN instead of reporting zero-return errors.
111 * If an error has occurred, log it at level <b>severity</b> and describe the
112 * current action as <b>doing</b>.
115 tor_tls_get_error(tor_tls_t
*tls
, int r
, int extra
,
116 const char *doing
, int severity
)
118 int err
= SSL_get_error(tls
->ssl
, r
);
122 case SSL_ERROR_WANT_READ
:
123 return TOR_TLS_WANTREAD
;
124 case SSL_ERROR_WANT_WRITE
:
125 return TOR_TLS_WANTWRITE
;
126 case SSL_ERROR_SYSCALL
:
127 if (extra
&CATCH_SYSCALL
)
128 return _TOR_TLS_SYSCALL
;
130 log(severity
, LD_NET
, "TLS error: unexpected close while %s", doing
);
132 int e
= tor_socket_errno(tls
->socket
);
133 log(severity
, LD_NET
, "TLS error: <syscall error while %s> (errno=%d: %s)",
134 doing
, e
, tor_socket_strerror(e
));
136 tls_log_errors(severity
, doing
);
137 return TOR_TLS_ERROR
;
138 case SSL_ERROR_ZERO_RETURN
:
139 if (extra
&CATCH_ZERO
)
140 return _TOR_TLS_ZERORETURN
;
141 log(severity
, LD_NET
, "TLS error: Zero return");
142 tls_log_errors(severity
, doing
);
143 return TOR_TLS_ERROR
;
145 tls_log_errors(severity
, doing
);
146 return TOR_TLS_ERROR
;
150 /** Initialize OpenSSL, unless it has already been initialized.
155 if (!tls_library_is_initialized
) {
157 SSL_load_error_strings();
158 crypto_global_init(-1);
159 tls_library_is_initialized
= 1;
164 tor_tls_free_all(void)
166 if (global_tls_context
) {
167 SSL_CTX_free(global_tls_context
->ctx
);
168 SSL_CTX_free(global_tls_context
->client_only_ctx
);
169 tor_free(global_tls_context
);
170 global_tls_context
= NULL
;
174 /** We need to give OpenSSL a callback to verify certificates. This is
175 * it: We always accept peer certs and complete the handshake. We
176 * don't validate them until later.
179 always_accept_verify_cb(int preverify_ok
,
180 X509_STORE_CTX
*x509_ctx
)
182 /* avoid "unused parameter" warning. */
188 /** Generate and sign an X509 certificate with the public key <b>rsa</b>,
189 * signed by the private key <b>rsa_sign</b>. The commonName of the
190 * certificate will be <b>cname</b>; the commonName of the issuer will be
191 * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b> seconds
192 * starting from now. Return a certificate on success, NULL on
196 tor_tls_create_certificate(crypto_pk_env_t
*rsa
,
197 crypto_pk_env_t
*rsa_sign
,
199 const char *cname_sign
,
200 unsigned int cert_lifetime
)
202 time_t start_time
, end_time
;
203 EVP_PKEY
*sign_pkey
= NULL
, *pkey
=NULL
;
205 X509_NAME
*name
= NULL
, *name_issuer
=NULL
;
210 start_time
= time(NULL
);
214 tor_assert(rsa_sign
);
215 tor_assert(cname_sign
);
216 if (!(sign_pkey
= _crypto_pk_env_get_evp_pkey(rsa_sign
,1)))
218 if (!(pkey
= _crypto_pk_env_get_evp_pkey(rsa
,0)))
220 if (!(x509
= X509_new()))
222 if (!(X509_set_version(x509
, 2)))
224 if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509
), (long)start_time
)))
227 if (!(name
= X509_NAME_new()))
229 if ((nid
= OBJ_txt2nid("organizationName")) == NID_undef
) goto error
;
230 if (!(X509_NAME_add_entry_by_NID(name
, nid
, MBSTRING_ASC
,
231 (unsigned char*)"TOR", -1, -1, 0))) goto error
;
232 if ((nid
= OBJ_txt2nid("commonName")) == NID_undef
) goto error
;
233 if (!(X509_NAME_add_entry_by_NID(name
, nid
, MBSTRING_ASC
,
234 (unsigned char*)cname
, -1, -1, 0))) goto error
;
235 if (!(X509_set_subject_name(x509
, name
)))
238 if (!(name_issuer
= X509_NAME_new()))
240 if ((nid
= OBJ_txt2nid("organizationName")) == NID_undef
) goto error
;
241 if (!(X509_NAME_add_entry_by_NID(name_issuer
, nid
, MBSTRING_ASC
,
242 (unsigned char*)"TOR", -1, -1, 0))) goto error
;
243 if ((nid
= OBJ_txt2nid("commonName")) == NID_undef
) goto error
;
244 if (!(X509_NAME_add_entry_by_NID(name_issuer
, nid
, MBSTRING_ASC
,
245 (unsigned char*)cname_sign
, -1, -1, 0))) goto error
;
246 if (!(X509_set_issuer_name(x509
, name_issuer
)))
249 if (!X509_time_adj(X509_get_notBefore(x509
),0,&start_time
))
251 end_time
= start_time
+ cert_lifetime
;
252 if (!X509_time_adj(X509_get_notAfter(x509
),0,&end_time
))
254 if (!X509_set_pubkey(x509
, pkey
))
256 if (!X509_sign(x509
, sign_pkey
, EVP_sha1()))
266 tls_log_errors(LOG_WARN
, "generating certificate");
268 EVP_PKEY_free(sign_pkey
);
272 X509_NAME_free(name
);
274 X509_NAME_free(name_issuer
);
278 #ifdef EVERYONE_HAS_AES
279 /* Everybody is running OpenSSL 0.9.7 or later, so no backward compatibility
281 #define CIPHER_LIST TLS1_TXT_DHE_RSA_WITH_AES_128_SHA
282 #elif defined(TLS1_TXT_DHE_RSA_WITH_AES_128_SHA)
283 /* Some people are running OpenSSL before 0.9.7, but we aren't.
284 * We can support AES and 3DES.
286 #define CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
287 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
289 /* We're running OpenSSL before 0.9.7. We only support 3DES. */
290 #define CIPHER_LIST SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA
293 /** Create a new TLS context. If we are going to be using it as a
294 * server, it must have isServer set to true, <b>identity</b> set to the
295 * identity key used to sign that certificate, and <b>nickname</b> set to
296 * the server's nickname. If we're only going to be a client,
297 * isServer should be false, identity should be NULL, and nickname
298 * should be NULL. Return -1 if failure, else 0.
300 * You can call this function multiple times. Each time you call it,
301 * it generates new certificates; all new connections will use
302 * the new SSL context.
305 tor_tls_context_new(crypto_pk_env_t
*identity
,
306 int isServer
, const char *nickname
,
307 unsigned int key_lifetime
)
309 crypto_pk_env_t
*rsa
= NULL
;
310 crypto_dh_env_t
*dh
= NULL
;
311 EVP_PKEY
*pkey
= NULL
;
312 tor_tls_context_t
*result
= NULL
;
313 X509
*cert
= NULL
, *idcert
= NULL
;
319 tor_snprintf(nn2
, sizeof(nn2
), "%s <identity>", nickname
);
324 /* Generate short-term RSA key. */
325 if (!(rsa
= crypto_new_pk_env()))
327 if (crypto_pk_generate_key(rsa
)<0)
329 /* Create certificate signed by identity key. */
330 cert
= tor_tls_create_certificate(rsa
, identity
, nickname
, nn2
,
332 /* Create self-signed certificate for identity key. */
333 idcert
= tor_tls_create_certificate(identity
, identity
, nn2
, nn2
,
334 IDENTITY_CERT_LIFETIME
);
335 if (!cert
|| !idcert
) {
336 log(LOG_WARN
, LD_CRYPTO
, "Error creating certificate");
341 result
= tor_malloc(sizeof(tor_tls_context_t
));
342 result
->ctx
= result
->client_only_ctx
= NULL
;
343 for (client_only
=0; client_only
<= 1; ++client_only
) {
344 ctx
= client_only
? &result
->client_only_ctx
: &result
->ctx
;
345 #ifdef EVERYONE_HAS_AES
346 /* Tell OpenSSL to only use TLS1 */
347 if (!(*ctx
= SSL_CTX_new(TLSv1_method())))
350 /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
351 if (!(*ctx
= SSL_CTX_new(SSLv23_method())))
353 SSL_CTX_set_options(*ctx
, SSL_OP_NO_SSLv2
);
355 if (!SSL_CTX_set_cipher_list(*ctx
, CIPHER_LIST
))
358 if (cert
&& !SSL_CTX_use_certificate(*ctx
,cert
))
360 X509_free(cert
); /* We just added a reference to cert. */
362 if (idcert
&& !SSL_CTX_add_extra_chain_cert(*ctx
,idcert
))
364 idcert
=NULL
; /* The context now owns the reference to idcert */
366 SSL_CTX_set_session_cache_mode(*ctx
, SSL_SESS_CACHE_OFF
);
367 if (isServer
&& !client_only
) {
369 if (!(pkey
= _crypto_pk_env_get_evp_pkey(rsa
,1)))
371 if (!SSL_CTX_use_PrivateKey(*ctx
, pkey
))
375 if (!SSL_CTX_check_private_key(*ctx
))
378 dh
= crypto_dh_new();
379 SSL_CTX_set_tmp_dh(*ctx
, _crypto_dh_env_get_dh(dh
));
381 SSL_CTX_set_verify(*ctx
, SSL_VERIFY_PEER
,
382 always_accept_verify_cb
);
383 /* let us realloc bufs that we're writing from */
384 SSL_CTX_set_mode(*ctx
, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER
);
386 /* Free the old context if one exists. */
387 if (global_tls_context
) {
388 /* This is safe even if there are open connections: OpenSSL does
389 * reference counting with SSL and SSL_CTX objects. */
390 SSL_CTX_free(global_tls_context
->ctx
);
391 SSL_CTX_free(global_tls_context
->client_only_ctx
);
392 tor_free(global_tls_context
);
394 global_tls_context
= result
;
396 crypto_free_pk_env(rsa
);
400 tls_log_errors(LOG_WARN
, "creating TLS context");
404 crypto_free_pk_env(rsa
);
407 if (result
&& result
->ctx
)
408 SSL_CTX_free(result
->ctx
);
409 if (result
&& result
->client_only_ctx
)
410 SSL_CTX_free(result
->client_only_ctx
);
420 /** Create a new TLS object from a file descriptor, and a flag to
421 * determine whether it is functioning as a server.
424 tor_tls_new(int sock
, int isServer
, int use_no_cert
)
426 tor_tls_t
*result
= tor_malloc(sizeof(tor_tls_t
));
428 tor_assert(global_tls_context
); /* make sure somebody made it first */
429 ctx
= use_no_cert
? global_tls_context
->client_only_ctx
430 : global_tls_context
->ctx
;
431 if (!(result
->ssl
= SSL_new(ctx
))) {
432 tls_log_errors(LOG_WARN
, "generating TLS context");
436 result
->socket
= sock
;
437 SSL_set_fd(result
->ssl
, sock
);
438 result
->state
= TOR_TLS_ST_HANDSHAKE
;
439 result
->isServer
= isServer
;
440 result
->wantwrite_n
= 0;
441 /* Not expected to get called. */
442 tls_log_errors(LOG_WARN
, "generating TLS context");
446 /** Return whether this tls initiated the connect (client) or
447 * received it (server). */
449 tor_tls_is_server(tor_tls_t
*tls
)
452 return tls
->isServer
;
455 /** Release resources associated with a TLS object. Does not close the
456 * underlying file descriptor.
459 tor_tls_free(tor_tls_t
*tls
)
461 tor_assert(tls
&& tls
->ssl
);
467 /** Underlying function for TLS reading. Reads up to <b>len</b>
468 * characters from <b>tls</b> into <b>cp</b>. On success, returns the
469 * number of characters read. On failure, returns TOR_TLS_ERROR,
470 * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
473 tor_tls_read(tor_tls_t
*tls
, char *cp
, size_t len
)
477 tor_assert(tls
->ssl
);
478 tor_assert(tls
->state
== TOR_TLS_ST_OPEN
);
479 r
= SSL_read(tls
->ssl
, cp
, len
);
482 err
= tor_tls_get_error(tls
, r
, CATCH_ZERO
, "reading", LOG_DEBUG
);
483 if (err
== _TOR_TLS_ZERORETURN
) {
484 debug(LD_NET
,"read returned r=%d; TLS is closed",r
);
485 tls
->state
= TOR_TLS_ST_CLOSED
;
486 return TOR_TLS_CLOSE
;
488 tor_assert(err
!= TOR_TLS_DONE
);
489 debug(LD_NET
,"read returned r=%d, err=%d",r
,err
);
494 /** Underlying function for TLS writing. Write up to <b>n</b>
495 * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
496 * number of characters written. On failure, returns TOR_TLS_ERROR,
497 * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
500 tor_tls_write(tor_tls_t
*tls
, char *cp
, size_t n
)
504 tor_assert(tls
->ssl
);
505 tor_assert(tls
->state
== TOR_TLS_ST_OPEN
);
508 if (tls
->wantwrite_n
) {
509 /* if WANTWRITE last time, we must use the _same_ n as before */
510 tor_assert(n
>= tls
->wantwrite_n
);
511 debug(LD_NET
,"resuming pending-write, (%d to flush, reusing %d)",
512 (int)n
, (int)tls
->wantwrite_n
);
513 n
= tls
->wantwrite_n
;
514 tls
->wantwrite_n
= 0;
516 r
= SSL_write(tls
->ssl
, cp
, n
);
517 err
= tor_tls_get_error(tls
, r
, 0, "writing", LOG_INFO
);
518 if (err
== TOR_TLS_DONE
) {
521 if (err
== TOR_TLS_WANTWRITE
|| err
== TOR_TLS_WANTREAD
) {
522 tls
->wantwrite_n
= n
;
527 /** Perform initial handshake on <b>tls</b>. When finished, returns
528 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
529 * or TOR_TLS_WANTWRITE.
532 tor_tls_handshake(tor_tls_t
*tls
)
536 tor_assert(tls
->ssl
);
537 tor_assert(tls
->state
== TOR_TLS_ST_HANDSHAKE
);
538 check_no_tls_errors();
540 r
= SSL_accept(tls
->ssl
);
542 r
= SSL_connect(tls
->ssl
);
544 r
= tor_tls_get_error(tls
,r
,0, "handshaking", LOG_INFO
);
545 if (ERR_peek_error() != 0) {
546 tls_log_errors(LOG_WARN
, "handshaking");
547 return TOR_TLS_ERROR
;
549 if (r
== TOR_TLS_DONE
) {
550 tls
->state
= TOR_TLS_ST_OPEN
;
555 /** Shut down an open tls connection <b>tls</b>. When finished, returns
556 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
557 * or TOR_TLS_WANTWRITE.
560 tor_tls_shutdown(tor_tls_t
*tls
)
565 tor_assert(tls
->ssl
);
568 if (tls
->state
== TOR_TLS_ST_SENTCLOSE
) {
569 /* If we've already called shutdown once to send a close message,
570 * we read until the other side has closed too.
573 r
= SSL_read(tls
->ssl
, buf
, 128);
575 err
= tor_tls_get_error(tls
, r
, CATCH_ZERO
, "reading to shut down",
577 if (err
== _TOR_TLS_ZERORETURN
) {
578 tls
->state
= TOR_TLS_ST_GOTCLOSE
;
579 /* fall through... */
585 r
= SSL_shutdown(tls
->ssl
);
587 /* If shutdown returns 1, the connection is entirely closed. */
588 tls
->state
= TOR_TLS_ST_CLOSED
;
591 err
= tor_tls_get_error(tls
, r
, CATCH_SYSCALL
|CATCH_ZERO
, "shutting down",
593 if (err
== _TOR_TLS_SYSCALL
) {
594 /* The underlying TCP connection closed while we were shutting down. */
595 tls
->state
= TOR_TLS_ST_CLOSED
;
597 } else if (err
== _TOR_TLS_ZERORETURN
) {
598 /* The TLS connection says that it sent a shutdown record, but
599 * isn't done shutting down yet. Make sure that this hasn't
600 * happened before, then go back to the start of the function
603 if (tls
->state
== TOR_TLS_ST_GOTCLOSE
||
604 tls
->state
== TOR_TLS_ST_SENTCLOSE
) {
605 log(LOG_WARN
, LD_NET
,
606 "TLS returned \"half-closed\" value while already half-closed");
607 return TOR_TLS_ERROR
;
609 tls
->state
= TOR_TLS_ST_SENTCLOSE
;
610 /* fall through ... */
617 /** Return true iff this TLS connection is authenticated.
620 tor_tls_peer_has_cert(tor_tls_t
*tls
)
623 cert
= SSL_get_peer_certificate(tls
->ssl
);
624 tls_log_errors(LOG_WARN
, "getting peer certificate");
631 /** Write the nickname (if any) that the peer connected on <b>tls</b>
632 * claims to have into the first <b>buflen</b> characters of <b>buf</b>.
633 * Truncate the nickname if it is longer than buflen-1 characters. Always
634 * NUL-terminate. Return 0 on success, -1 on failure.
637 tor_tls_get_peer_cert_nickname(tor_tls_t
*tls
, char *buf
, size_t buflen
)
640 X509_NAME
*name
= NULL
;
645 if (!(cert
= SSL_get_peer_certificate(tls
->ssl
))) {
646 warn(LD_PROTOCOL
, "Peer has no certificate");
649 if (!(name
= X509_get_subject_name(cert
))) {
650 warn(LD_PROTOCOL
, "Peer certificate has no subject name");
653 if ((nid
= OBJ_txt2nid("commonName")) == NID_undef
)
656 lenout
= X509_NAME_get_text_by_NID(name
, nid
, buf
, buflen
);
659 if (((int)strspn(buf
, LEGAL_NICKNAME_CHARACTERS
)) < lenout
) {
660 warn(LD_PROTOCOL
, "Peer certificate nickname \"%s\" has illegal characters.",
662 if (strchr(buf
, '.'))
663 warn(LD_PROTOCOL
, " (Maybe it is not really running Tor at its advertised OR port.)");
673 tls_log_errors(LOG_WARN
, "getting peer certificate nickname");
678 log_cert_lifetime(X509
*cert
, const char *problem
)
682 char *s1
=NULL
, *s2
=NULL
;
684 time_t now
= time(NULL
);
688 warn(LD_GENERAL
,"Certificate %s: is your system clock set incorrectly?",
691 if (!(bio
= BIO_new(BIO_s_mem()))) {
692 warn(LD_GENERAL
, "Couldn't allocate BIO!"); goto end
;
694 if (!(ASN1_TIME_print(bio
, X509_get_notBefore(cert
)))) {
695 tls_log_errors(LOG_WARN
, "printing certificate lifetime");
698 BIO_get_mem_ptr(bio
, &buf
);
699 s1
= tor_strndup(buf
->data
, buf
->length
);
702 if (!(ASN1_TIME_print(bio
, X509_get_notAfter(cert
)))) {
703 tls_log_errors(LOG_WARN
, "printing certificate lifetime");
706 BIO_get_mem_ptr(bio
, &buf
);
707 s2
= tor_strndup(buf
->data
, buf
->length
);
709 strftime(mytime
, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now
, &tm
));
711 warn(LD_GENERAL
, "(certificate lifetime runs from %s through %s. Your time is %s.)",s1
,s2
,mytime
);
714 /* Not expected to get invoked */
715 tls_log_errors(LOG_WARN
, "getting certificate lifetime");
724 /** If the provided tls connection is authenticated and has a
725 * certificate that is currently valid and signed, then set
726 * *<b>identity_key</b> to the identity certificate's key and return
727 * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
730 tor_tls_verify(int severity
, tor_tls_t
*tls
, crypto_pk_env_t
**identity_key
)
732 X509
*cert
= NULL
, *id_cert
= NULL
;
733 STACK_OF(X509
) *chain
= NULL
;
734 EVP_PKEY
*id_pkey
= NULL
;
739 *identity_key
= NULL
;
741 if (!(cert
= SSL_get_peer_certificate(tls
->ssl
)))
743 if (!(chain
= SSL_get_peer_cert_chain(tls
->ssl
)))
745 num_in_chain
= sk_X509_num(chain
);
746 /* 1 means we're receiving (server-side), and it's just the id_cert.
747 * 2 means we're connecting (client-side), and it's both the link
748 * cert and the id_cert.
750 if (num_in_chain
< 1) {
751 log_fn(severity
,LD_PROTOCOL
,"Unexpected number of certificates in chain (%d)",
755 for (i
=0; i
<num_in_chain
; ++i
) {
756 id_cert
= sk_X509_value(chain
, i
);
757 if (X509_cmp(id_cert
, cert
) != 0)
761 log_fn(severity
,LD_PROTOCOL
,"No distinct identity certificate found");
765 if (!(id_pkey
= X509_get_pubkey(id_cert
)) ||
766 X509_verify(cert
, id_pkey
) <= 0) {
767 log_fn(severity
,LD_PROTOCOL
,"X509_verify on cert and pkey returned <= 0");
768 tls_log_errors(severity
,"verifying certificate");
772 rsa
= EVP_PKEY_get1_RSA(id_pkey
);
775 *identity_key
= _crypto_new_pk_env_rsa(rsa
);
783 EVP_PKEY_free(id_pkey
);
785 /* This should never get invoked, but let's make sure in case OpenSSL
786 * acts unexpectedly. */
787 tls_log_errors(LOG_WARN
, "finishing tor_tls_verify");
792 /** Check whether the certificate set on the connection <b>tls</b> is
793 * expired or not-yet-valid, give or take <b>tolerance</b>
794 * seconds. Return 0 for valid, -1 for failure.
796 * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
799 tor_tls_check_lifetime(tor_tls_t
*tls
, int tolerance
)
807 if (!(cert
= SSL_get_peer_certificate(tls
->ssl
)))
811 if (X509_cmp_time(X509_get_notBefore(cert
), &t
) > 0) {
812 log_cert_lifetime(cert
, "not yet valid");
816 if (X509_cmp_time(X509_get_notAfter(cert
), &t
) < 0) {
817 log_cert_lifetime(cert
, "already expired");
825 /* Not expected to get invoked */
826 tls_log_errors(LOG_WARN
, "checking certificate lifetime");
831 /** Return the number of bytes available for reading from <b>tls</b>.
834 tor_tls_get_pending_bytes(tor_tls_t
*tls
)
837 #if OPENSSL_VERSION_NUMBER < 0x0090700fl
838 if (tls
->ssl
->rstate
== SSL_ST_READ_BODY
)
840 if (tls
->ssl
->s3
->rrec
.type
!= SSL3_RT_APPLICATION_DATA
)
843 return SSL_pending(tls
->ssl
);
847 /** Return the number of bytes read across the underlying socket. */
849 tor_tls_get_n_bytes_read(tor_tls_t
*tls
)
852 return BIO_number_read(SSL_get_rbio(tls
->ssl
));
854 /** Return the number of bytes written across the underlying socket. */
856 tor_tls_get_n_bytes_written(tor_tls_t
*tls
)
859 return BIO_number_written(SSL_get_wbio(tls
->ssl
));
862 /** Implement check_no_tls_errors: If there are any pending OpenSSL
863 * errors, log an error message and assert(0). */
865 _check_no_tls_errors(const char *fname
, int line
)
867 if (ERR_peek_error() == 0)
869 log_fn(LOG_WARN
, LD_CRYPTO
, "Unhandled OpenSSL errors found at %s:%d: ",
871 tls_log_errors(LOG_WARN
, NULL
);