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 SSL_CTX_set_options(*ctx
, SSL_OP_SINGLE_DH_USE
);
356 if (!SSL_CTX_set_cipher_list(*ctx
, CIPHER_LIST
))
359 if (cert
&& !SSL_CTX_use_certificate(*ctx
,cert
))
361 X509_free(cert
); /* We just added a reference to cert. */
363 if (idcert
&& !SSL_CTX_add_extra_chain_cert(*ctx
,idcert
))
365 idcert
=NULL
; /* The context now owns the reference to idcert */
367 SSL_CTX_set_session_cache_mode(*ctx
, SSL_SESS_CACHE_OFF
);
368 if (isServer
&& !client_only
) {
370 if (!(pkey
= _crypto_pk_env_get_evp_pkey(rsa
,1)))
372 if (!SSL_CTX_use_PrivateKey(*ctx
, pkey
))
376 if (!SSL_CTX_check_private_key(*ctx
))
379 dh
= crypto_dh_new();
380 SSL_CTX_set_tmp_dh(*ctx
, _crypto_dh_env_get_dh(dh
));
382 SSL_CTX_set_verify(*ctx
, SSL_VERIFY_PEER
,
383 always_accept_verify_cb
);
384 /* let us realloc bufs that we're writing from */
385 SSL_CTX_set_mode(*ctx
, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER
);
387 /* Free the old context if one exists. */
388 if (global_tls_context
) {
389 /* This is safe even if there are open connections: OpenSSL does
390 * reference counting with SSL and SSL_CTX objects. */
391 SSL_CTX_free(global_tls_context
->ctx
);
392 SSL_CTX_free(global_tls_context
->client_only_ctx
);
393 tor_free(global_tls_context
);
395 global_tls_context
= result
;
397 crypto_free_pk_env(rsa
);
401 tls_log_errors(LOG_WARN
, "creating TLS context");
405 crypto_free_pk_env(rsa
);
408 if (result
&& result
->ctx
)
409 SSL_CTX_free(result
->ctx
);
410 if (result
&& result
->client_only_ctx
)
411 SSL_CTX_free(result
->client_only_ctx
);
421 /** Create a new TLS object from a file descriptor, and a flag to
422 * determine whether it is functioning as a server.
425 tor_tls_new(int sock
, int isServer
, int use_no_cert
)
427 tor_tls_t
*result
= tor_malloc(sizeof(tor_tls_t
));
429 tor_assert(global_tls_context
); /* make sure somebody made it first */
430 ctx
= use_no_cert
? global_tls_context
->client_only_ctx
431 : global_tls_context
->ctx
;
432 if (!(result
->ssl
= SSL_new(ctx
))) {
433 tls_log_errors(LOG_WARN
, "generating TLS context");
437 result
->socket
= sock
;
438 SSL_set_fd(result
->ssl
, sock
);
439 result
->state
= TOR_TLS_ST_HANDSHAKE
;
440 result
->isServer
= isServer
;
441 result
->wantwrite_n
= 0;
442 /* Not expected to get called. */
443 tls_log_errors(LOG_WARN
, "generating TLS context");
447 /** Return whether this tls initiated the connect (client) or
448 * received it (server). */
450 tor_tls_is_server(tor_tls_t
*tls
)
453 return tls
->isServer
;
456 /** Release resources associated with a TLS object. Does not close the
457 * underlying file descriptor.
460 tor_tls_free(tor_tls_t
*tls
)
462 tor_assert(tls
&& tls
->ssl
);
468 /** Underlying function for TLS reading. Reads up to <b>len</b>
469 * characters from <b>tls</b> into <b>cp</b>. On success, returns the
470 * number of characters read. On failure, returns TOR_TLS_ERROR,
471 * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
474 tor_tls_read(tor_tls_t
*tls
, char *cp
, size_t len
)
478 tor_assert(tls
->ssl
);
479 tor_assert(tls
->state
== TOR_TLS_ST_OPEN
);
480 r
= SSL_read(tls
->ssl
, cp
, len
);
483 err
= tor_tls_get_error(tls
, r
, CATCH_ZERO
, "reading", LOG_DEBUG
);
484 if (err
== _TOR_TLS_ZERORETURN
) {
485 debug(LD_NET
,"read returned r=%d; TLS is closed",r
);
486 tls
->state
= TOR_TLS_ST_CLOSED
;
487 return TOR_TLS_CLOSE
;
489 tor_assert(err
!= TOR_TLS_DONE
);
490 debug(LD_NET
,"read returned r=%d, err=%d",r
,err
);
495 /** Underlying function for TLS writing. Write up to <b>n</b>
496 * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
497 * number of characters written. On failure, returns TOR_TLS_ERROR,
498 * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
501 tor_tls_write(tor_tls_t
*tls
, char *cp
, size_t n
)
505 tor_assert(tls
->ssl
);
506 tor_assert(tls
->state
== TOR_TLS_ST_OPEN
);
509 if (tls
->wantwrite_n
) {
510 /* if WANTWRITE last time, we must use the _same_ n as before */
511 tor_assert(n
>= tls
->wantwrite_n
);
512 debug(LD_NET
,"resuming pending-write, (%d to flush, reusing %d)",
513 (int)n
, (int)tls
->wantwrite_n
);
514 n
= tls
->wantwrite_n
;
515 tls
->wantwrite_n
= 0;
517 r
= SSL_write(tls
->ssl
, cp
, n
);
518 err
= tor_tls_get_error(tls
, r
, 0, "writing", LOG_INFO
);
519 if (err
== TOR_TLS_DONE
) {
522 if (err
== TOR_TLS_WANTWRITE
|| err
== TOR_TLS_WANTREAD
) {
523 tls
->wantwrite_n
= n
;
528 /** Perform initial handshake on <b>tls</b>. When finished, returns
529 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
530 * or TOR_TLS_WANTWRITE.
533 tor_tls_handshake(tor_tls_t
*tls
)
537 tor_assert(tls
->ssl
);
538 tor_assert(tls
->state
== TOR_TLS_ST_HANDSHAKE
);
539 check_no_tls_errors();
541 r
= SSL_accept(tls
->ssl
);
543 r
= SSL_connect(tls
->ssl
);
545 r
= tor_tls_get_error(tls
,r
,0, "handshaking", LOG_INFO
);
546 if (ERR_peek_error() != 0) {
547 tls_log_errors(LOG_WARN
, "handshaking");
548 return TOR_TLS_ERROR
;
550 if (r
== TOR_TLS_DONE
) {
551 tls
->state
= TOR_TLS_ST_OPEN
;
556 /** Shut down an open tls connection <b>tls</b>. When finished, returns
557 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
558 * or TOR_TLS_WANTWRITE.
561 tor_tls_shutdown(tor_tls_t
*tls
)
566 tor_assert(tls
->ssl
);
569 if (tls
->state
== TOR_TLS_ST_SENTCLOSE
) {
570 /* If we've already called shutdown once to send a close message,
571 * we read until the other side has closed too.
574 r
= SSL_read(tls
->ssl
, buf
, 128);
576 err
= tor_tls_get_error(tls
, r
, CATCH_ZERO
, "reading to shut down",
578 if (err
== _TOR_TLS_ZERORETURN
) {
579 tls
->state
= TOR_TLS_ST_GOTCLOSE
;
580 /* fall through... */
586 r
= SSL_shutdown(tls
->ssl
);
588 /* If shutdown returns 1, the connection is entirely closed. */
589 tls
->state
= TOR_TLS_ST_CLOSED
;
592 err
= tor_tls_get_error(tls
, r
, CATCH_SYSCALL
|CATCH_ZERO
, "shutting down",
594 if (err
== _TOR_TLS_SYSCALL
) {
595 /* The underlying TCP connection closed while we were shutting down. */
596 tls
->state
= TOR_TLS_ST_CLOSED
;
598 } else if (err
== _TOR_TLS_ZERORETURN
) {
599 /* The TLS connection says that it sent a shutdown record, but
600 * isn't done shutting down yet. Make sure that this hasn't
601 * happened before, then go back to the start of the function
604 if (tls
->state
== TOR_TLS_ST_GOTCLOSE
||
605 tls
->state
== TOR_TLS_ST_SENTCLOSE
) {
606 log(LOG_WARN
, LD_NET
,
607 "TLS returned \"half-closed\" value while already half-closed");
608 return TOR_TLS_ERROR
;
610 tls
->state
= TOR_TLS_ST_SENTCLOSE
;
611 /* fall through ... */
618 /** Return true iff this TLS connection is authenticated.
621 tor_tls_peer_has_cert(tor_tls_t
*tls
)
624 cert
= SSL_get_peer_certificate(tls
->ssl
);
625 tls_log_errors(LOG_WARN
, "getting peer certificate");
632 /** Write the nickname (if any) that the peer connected on <b>tls</b>
633 * claims to have into the first <b>buflen</b> characters of <b>buf</b>.
634 * Truncate the nickname if it is longer than buflen-1 characters. Always
635 * NUL-terminate. Return 0 on success, -1 on failure.
638 tor_tls_get_peer_cert_nickname(tor_tls_t
*tls
, char *buf
, size_t buflen
)
641 X509_NAME
*name
= NULL
;
646 if (!(cert
= SSL_get_peer_certificate(tls
->ssl
))) {
647 warn(LD_PROTOCOL
, "Peer has no certificate");
650 if (!(name
= X509_get_subject_name(cert
))) {
651 warn(LD_PROTOCOL
, "Peer certificate has no subject name");
654 if ((nid
= OBJ_txt2nid("commonName")) == NID_undef
)
657 lenout
= X509_NAME_get_text_by_NID(name
, nid
, buf
, buflen
);
660 if (((int)strspn(buf
, LEGAL_NICKNAME_CHARACTERS
)) < lenout
) {
661 warn(LD_PROTOCOL
, "Peer certificate nickname \"%s\" has illegal characters.",
663 if (strchr(buf
, '.'))
664 warn(LD_PROTOCOL
, " (Maybe it is not really running Tor at its advertised OR port.)");
674 tls_log_errors(LOG_WARN
, "getting peer certificate nickname");
679 log_cert_lifetime(X509
*cert
, const char *problem
)
683 char *s1
=NULL
, *s2
=NULL
;
685 time_t now
= time(NULL
);
689 warn(LD_GENERAL
,"Certificate %s: is your system clock set incorrectly?",
692 if (!(bio
= BIO_new(BIO_s_mem()))) {
693 warn(LD_GENERAL
, "Couldn't allocate BIO!"); goto end
;
695 if (!(ASN1_TIME_print(bio
, X509_get_notBefore(cert
)))) {
696 tls_log_errors(LOG_WARN
, "printing certificate lifetime");
699 BIO_get_mem_ptr(bio
, &buf
);
700 s1
= tor_strndup(buf
->data
, buf
->length
);
703 if (!(ASN1_TIME_print(bio
, X509_get_notAfter(cert
)))) {
704 tls_log_errors(LOG_WARN
, "printing certificate lifetime");
707 BIO_get_mem_ptr(bio
, &buf
);
708 s2
= tor_strndup(buf
->data
, buf
->length
);
710 strftime(mytime
, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now
, &tm
));
712 warn(LD_GENERAL
, "(certificate lifetime runs from %s through %s. Your time is %s.)",s1
,s2
,mytime
);
715 /* Not expected to get invoked */
716 tls_log_errors(LOG_WARN
, "getting certificate lifetime");
725 /** If the provided tls connection is authenticated and has a
726 * certificate that is currently valid and signed, then set
727 * *<b>identity_key</b> to the identity certificate's key and return
728 * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
731 tor_tls_verify(int severity
, tor_tls_t
*tls
, crypto_pk_env_t
**identity_key
)
733 X509
*cert
= NULL
, *id_cert
= NULL
;
734 STACK_OF(X509
) *chain
= NULL
;
735 EVP_PKEY
*id_pkey
= NULL
;
740 *identity_key
= NULL
;
742 if (!(cert
= SSL_get_peer_certificate(tls
->ssl
)))
744 if (!(chain
= SSL_get_peer_cert_chain(tls
->ssl
)))
746 num_in_chain
= sk_X509_num(chain
);
747 /* 1 means we're receiving (server-side), and it's just the id_cert.
748 * 2 means we're connecting (client-side), and it's both the link
749 * cert and the id_cert.
751 if (num_in_chain
< 1) {
752 log_fn(severity
,LD_PROTOCOL
,"Unexpected number of certificates in chain (%d)",
756 for (i
=0; i
<num_in_chain
; ++i
) {
757 id_cert
= sk_X509_value(chain
, i
);
758 if (X509_cmp(id_cert
, cert
) != 0)
762 log_fn(severity
,LD_PROTOCOL
,"No distinct identity certificate found");
766 if (!(id_pkey
= X509_get_pubkey(id_cert
)) ||
767 X509_verify(cert
, id_pkey
) <= 0) {
768 log_fn(severity
,LD_PROTOCOL
,"X509_verify on cert and pkey returned <= 0");
769 tls_log_errors(severity
,"verifying certificate");
773 rsa
= EVP_PKEY_get1_RSA(id_pkey
);
776 *identity_key
= _crypto_new_pk_env_rsa(rsa
);
784 EVP_PKEY_free(id_pkey
);
786 /* This should never get invoked, but let's make sure in case OpenSSL
787 * acts unexpectedly. */
788 tls_log_errors(LOG_WARN
, "finishing tor_tls_verify");
793 /** Check whether the certificate set on the connection <b>tls</b> is
794 * expired or not-yet-valid, give or take <b>tolerance</b>
795 * seconds. Return 0 for valid, -1 for failure.
797 * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
800 tor_tls_check_lifetime(tor_tls_t
*tls
, int tolerance
)
808 if (!(cert
= SSL_get_peer_certificate(tls
->ssl
)))
812 if (X509_cmp_time(X509_get_notBefore(cert
), &t
) > 0) {
813 log_cert_lifetime(cert
, "not yet valid");
817 if (X509_cmp_time(X509_get_notAfter(cert
), &t
) < 0) {
818 log_cert_lifetime(cert
, "already expired");
826 /* Not expected to get invoked */
827 tls_log_errors(LOG_WARN
, "checking certificate lifetime");
832 /** Return the number of bytes available for reading from <b>tls</b>.
835 tor_tls_get_pending_bytes(tor_tls_t
*tls
)
838 #if OPENSSL_VERSION_NUMBER < 0x0090700fl
839 if (tls
->ssl
->rstate
== SSL_ST_READ_BODY
)
841 if (tls
->ssl
->s3
->rrec
.type
!= SSL3_RT_APPLICATION_DATA
)
844 return SSL_pending(tls
->ssl
);
848 /** Return the number of bytes read across the underlying socket. */
850 tor_tls_get_n_bytes_read(tor_tls_t
*tls
)
853 return BIO_number_read(SSL_get_rbio(tls
->ssl
));
855 /** Return the number of bytes written across the underlying socket. */
857 tor_tls_get_n_bytes_written(tor_tls_t
*tls
)
860 return BIO_number_written(SSL_get_wbio(tls
->ssl
));
863 /** Implement check_no_tls_errors: If there are any pending OpenSSL
864 * errors, log an error message and assert(0). */
866 _check_no_tls_errors(const char *fname
, int line
)
868 if (ERR_peek_error() == 0)
870 log(LOG_WARN
, LD_CRYPTO
, "Unhandled OpenSSL errors found at %s:%d: ",
871 tor_fix_source_file(fname
), line
);
872 tls_log_errors(LOG_WARN
, NULL
);