if we rotate our onion key, publish a new descriptor, and
[tor.git] / src / common / tortls.c
blob51c4abe247903dd1eb593cdd7c3d37df991518b3
1 /* Copyright 2003 Roger Dingledine.
2 * Copyright 2004-2006 Roger Dingledine, Nick Mathewson */
3 /* See LICENSE for licensing information */
4 /* $Id$ */
5 const char tortls_c_id[] =
6 "$Id$";
8 /**
9 * \file tortls.c
10 * \brief Wrapper functions to present a consistent interface to
11 * TLS, SSL, and X.509 functions from OpenSSL.
12 **/
14 /* (Unlike other tor functions, these
15 * are prefixed with tor_ in order to avoid conflicting with OpenSSL
16 * functions and variables.)
19 #include "orconfig.h"
20 #include "./crypto.h"
21 #include "./tortls.h"
22 #include "./util.h"
23 #include "./log.h"
24 #include <string.h>
26 /* Copied from or.h */
27 #define LEGAL_NICKNAME_CHARACTERS \
28 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
30 #include <assert.h>
31 #include <openssl/ssl.h>
32 #include <openssl/err.h>
33 #include <openssl/tls1.h>
34 #include <openssl/asn1.h>
35 #include <openssl/bio.h>
37 /** How long do identity certificates live? (sec) */
38 #define IDENTITY_CERT_LIFETIME (365*24*60*60)
40 /** Structure holding the TLS state for a single connection. */
41 typedef struct tor_tls_context_t {
42 SSL_CTX *ctx;
43 } tor_tls_context_t;
45 /** Holds a SSL object and its associated data. Members are only
46 * accessed from within tortls.c.
48 struct tor_tls_t {
49 SSL *ssl; /**< An OpenSSL SSL object. */
50 int socket; /**< The underlying file descriptor for this TLS connection. */
51 enum {
52 TOR_TLS_ST_HANDSHAKE, TOR_TLS_ST_OPEN, TOR_TLS_ST_GOTCLOSE,
53 TOR_TLS_ST_SENTCLOSE, TOR_TLS_ST_CLOSED
54 } state; /**< The current SSL state, depending on which operations have
55 * completed successfully. */
56 int isServer;
57 size_t wantwrite_n; /**< 0 normally, >0 if we returned wantwrite last
58 * time. */
61 static X509* tor_tls_create_certificate(crypto_pk_env_t *rsa,
62 crypto_pk_env_t *rsa_sign,
63 const char *cname,
64 const char *cname_sign,
65 unsigned int lifetime);
67 /** Global tls context. We keep it here because nobody else needs to
68 * touch it. */
69 static tor_tls_context_t *global_tls_context = NULL;
70 /** True iff tor_tls_init() has been called. */
71 static int tls_library_is_initialized = 0;
73 /* Module-internal error codes. */
74 #define _TOR_TLS_SYSCALL -6
75 #define _TOR_TLS_ZERORETURN -5
77 /* These functions are declared in crypto.c but not exported. */
78 EVP_PKEY *_crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private);
79 crypto_pk_env_t *_crypto_new_pk_env_rsa(RSA *rsa);
80 DH *_crypto_dh_env_get_dh(crypto_dh_env_t *dh);
82 /** Log all pending tls errors at level <b>severity</b>. Use
83 * <b>doing</b> to describe our current activities.
85 static void
86 tls_log_errors(int severity, const char *doing)
88 int err;
89 const char *msg, *lib, *func;
90 while ((err = ERR_get_error()) != 0) {
91 msg = (const char*)ERR_reason_error_string(err);
92 lib = (const char*)ERR_lib_error_string(err);
93 func = (const char*)ERR_func_error_string(err);
94 if (!msg) msg = "(null)";
95 if (doing) {
96 log(severity, LD_NET, "TLS error while %s: %s (in %s:%s)",
97 doing, msg, lib,func);
98 } else {
99 log(severity, LD_NET, "TLS error: %s (in %s:%s)", msg, lib, func);
104 #define CATCH_SYSCALL 1
105 #define CATCH_ZERO 2
107 /** Given a TLS object and the result of an SSL_* call, use
108 * SSL_get_error to determine whether an error has occurred, and if so
109 * which one. Return one of TOR_TLS_{DONE|WANTREAD|WANTWRITE|ERROR}.
110 * If extra&CATCH_SYSCALL is true, return _TOR_TLS_SYSCALL instead of
111 * reporting syscall errors. If extra&CATCH_ZERO is true, return
112 * _TOR_TLS_ZERORETURN instead of reporting zero-return errors.
114 * If an error has occurred, log it at level <b>severity</b> and describe the
115 * current action as <b>doing</b>.
117 static int
118 tor_tls_get_error(tor_tls_t *tls, int r, int extra,
119 const char *doing, int severity)
121 int err = SSL_get_error(tls->ssl, r);
122 switch (err) {
123 case SSL_ERROR_NONE:
124 return TOR_TLS_DONE;
125 case SSL_ERROR_WANT_READ:
126 return TOR_TLS_WANTREAD;
127 case SSL_ERROR_WANT_WRITE:
128 return TOR_TLS_WANTWRITE;
129 case SSL_ERROR_SYSCALL:
130 if (extra&CATCH_SYSCALL)
131 return _TOR_TLS_SYSCALL;
132 if (r == 0)
133 log(severity, LD_NET, "TLS error: unexpected close while %s", doing);
134 else {
135 int e = tor_socket_errno(tls->socket);
136 log(severity, LD_NET,
137 "TLS error: <syscall error while %s> (errno=%d: %s)",
138 doing, e, tor_socket_strerror(e));
140 tls_log_errors(severity, doing);
141 return TOR_TLS_ERROR;
142 case SSL_ERROR_ZERO_RETURN:
143 if (extra&CATCH_ZERO)
144 return _TOR_TLS_ZERORETURN;
145 log(severity, LD_NET, "TLS error: Zero return");
146 tls_log_errors(severity, doing);
147 return TOR_TLS_ERROR;
148 default:
149 tls_log_errors(severity, doing);
150 return TOR_TLS_ERROR;
154 /** Initialize OpenSSL, unless it has already been initialized.
156 static void
157 tor_tls_init(void)
159 if (!tls_library_is_initialized) {
160 SSL_library_init();
161 SSL_load_error_strings();
162 crypto_global_init(-1);
163 tls_library_is_initialized = 1;
167 void
168 tor_tls_free_all(void)
170 if (global_tls_context) {
171 SSL_CTX_free(global_tls_context->ctx);
172 tor_free(global_tls_context);
173 global_tls_context = NULL;
177 /** We need to give OpenSSL a callback to verify certificates. This is
178 * it: We always accept peer certs and complete the handshake. We
179 * don't validate them until later.
181 static int
182 always_accept_verify_cb(int preverify_ok,
183 X509_STORE_CTX *x509_ctx)
185 /* avoid "unused parameter" warning. */
186 preverify_ok = 0;
187 x509_ctx = NULL;
188 return 1;
191 /** Generate and sign an X509 certificate with the public key <b>rsa</b>,
192 * signed by the private key <b>rsa_sign</b>. The commonName of the
193 * certificate will be <b>cname</b>; the commonName of the issuer will be
194 * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b> seconds
195 * starting from now. Return a certificate on success, NULL on
196 * failure.
198 static X509 *
199 tor_tls_create_certificate(crypto_pk_env_t *rsa,
200 crypto_pk_env_t *rsa_sign,
201 const char *cname,
202 const char *cname_sign,
203 unsigned int cert_lifetime)
205 time_t start_time, end_time;
206 EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
207 X509 *x509 = NULL;
208 X509_NAME *name = NULL, *name_issuer=NULL;
209 int nid;
211 tor_tls_init();
213 start_time = time(NULL);
215 tor_assert(rsa);
216 tor_assert(cname);
217 tor_assert(rsa_sign);
218 tor_assert(cname_sign);
219 if (!(sign_pkey = _crypto_pk_env_get_evp_pkey(rsa_sign,1)))
220 goto error;
221 if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,0)))
222 goto error;
223 if (!(x509 = X509_new()))
224 goto error;
225 if (!(X509_set_version(x509, 2)))
226 goto error;
227 if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509), (long)start_time)))
228 goto error;
230 if (!(name = X509_NAME_new()))
231 goto error;
232 if ((nid = OBJ_txt2nid("organizationName")) == NID_undef)
233 goto error;
234 if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
235 (unsigned char*)"Tor", -1, -1, 0)))
236 goto error;
237 if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
238 if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
239 (unsigned char*)cname, -1, -1, 0)))
240 goto error;
241 if (!(X509_set_subject_name(x509, name)))
242 goto error;
244 if (!(name_issuer = X509_NAME_new()))
245 goto error;
246 if ((nid = OBJ_txt2nid("organizationName")) == NID_undef)
247 goto error;
248 if (!(X509_NAME_add_entry_by_NID(name_issuer, nid, MBSTRING_ASC,
249 (unsigned char*)"Tor", -1, -1, 0)))
250 goto error;
251 if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
252 if (!(X509_NAME_add_entry_by_NID(name_issuer, nid, MBSTRING_ASC,
253 (unsigned char*)cname_sign, -1, -1, 0)))
254 goto error;
255 if (!(X509_set_issuer_name(x509, name_issuer)))
256 goto error;
258 if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
259 goto error;
260 end_time = start_time + cert_lifetime;
261 if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
262 goto error;
263 if (!X509_set_pubkey(x509, pkey))
264 goto error;
265 if (!X509_sign(x509, sign_pkey, EVP_sha1()))
266 goto error;
268 goto done;
269 error:
270 if (x509) {
271 X509_free(x509);
272 x509 = NULL;
274 done:
275 tls_log_errors(LOG_WARN, "generating certificate");
276 if (sign_pkey)
277 EVP_PKEY_free(sign_pkey);
278 if (pkey)
279 EVP_PKEY_free(pkey);
280 if (name)
281 X509_NAME_free(name);
282 if (name_issuer)
283 X509_NAME_free(name_issuer);
284 return x509;
287 #ifdef EVERYONE_HAS_AES
288 /* Everybody is running OpenSSL 0.9.7 or later, so no backward compatibility
289 * is needed. */
290 #define CIPHER_LIST TLS1_TXT_DHE_RSA_WITH_AES_128_SHA
291 #elif defined(TLS1_TXT_DHE_RSA_WITH_AES_128_SHA)
292 /* Some people are running OpenSSL before 0.9.7, but we aren't.
293 * We can support AES and 3DES.
295 #define CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
296 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
297 #else
298 /* We're running OpenSSL before 0.9.7. We only support 3DES. */
299 #define CIPHER_LIST SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA
300 #endif
302 /** Create a new TLS context for use with Tor TLS handshakes.
303 * <b>identity</b> should be set to the identity key used to sign the
304 * certificate, and <b>nickname</b> set to the nickname to use.
306 * You can call this function multiple times. Each time you call it,
307 * it generates new certificates; all new connections will use
308 * the new SSL context.
311 tor_tls_context_new(crypto_pk_env_t *identity, const char *nickname,
312 unsigned int key_lifetime)
314 crypto_pk_env_t *rsa = NULL;
315 crypto_dh_env_t *dh = NULL;
316 EVP_PKEY *pkey = NULL;
317 tor_tls_context_t *result = NULL;
318 X509 *cert = NULL, *idcert = NULL;
319 char nn2[128];
320 if (!nickname)
321 nickname = "null";
322 tor_snprintf(nn2, sizeof(nn2), "%s <identity>", nickname);
324 tor_tls_init();
326 /* Generate short-term RSA key. */
327 if (!(rsa = crypto_new_pk_env()))
328 goto error;
329 if (crypto_pk_generate_key(rsa)<0)
330 goto error;
331 /* Create certificate signed by identity key. */
332 cert = tor_tls_create_certificate(rsa, identity, nickname, nn2,
333 key_lifetime);
334 /* Create self-signed certificate for identity key. */
335 idcert = tor_tls_create_certificate(identity, identity, nn2, nn2,
336 IDENTITY_CERT_LIFETIME);
337 if (!cert || !idcert) {
338 log(LOG_WARN, LD_CRYPTO, "Error creating certificate");
339 goto error;
342 result = tor_malloc(sizeof(tor_tls_context_t));
343 #ifdef EVERYONE_HAS_AES
344 /* Tell OpenSSL to only use TLS1 */
345 if (!(result->ctx = SSL_CTX_new(TLSv1_method())))
346 goto error;
347 #else
348 /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
349 if (!(result->ctx = SSL_CTX_new(SSLv23_method())))
350 goto error;
351 SSL_CTX_set_options(result->ctx, SSL_OP_NO_SSLv2);
352 #endif
353 SSL_CTX_set_options(result->ctx, SSL_OP_SINGLE_DH_USE);
354 if (!SSL_CTX_set_cipher_list(result->ctx, CIPHER_LIST))
355 goto error;
356 if (cert && !SSL_CTX_use_certificate(result->ctx,cert))
357 goto error;
358 X509_free(cert); /* We just added a reference to cert. */
359 cert=NULL;
360 if (idcert && !SSL_CTX_add_extra_chain_cert(result->ctx,idcert))
361 goto error;
362 idcert=NULL; /* The context now owns the reference to idcert */
363 SSL_CTX_set_session_cache_mode(result->ctx, SSL_SESS_CACHE_OFF);
364 tor_assert(rsa);
365 if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,1)))
366 goto error;
367 if (!SSL_CTX_use_PrivateKey(result->ctx, pkey))
368 goto error;
369 EVP_PKEY_free(pkey);
370 pkey = NULL;
371 if (!SSL_CTX_check_private_key(result->ctx))
372 goto error;
373 dh = crypto_dh_new();
374 SSL_CTX_set_tmp_dh(result->ctx, _crypto_dh_env_get_dh(dh));
375 crypto_dh_free(dh);
376 SSL_CTX_set_verify(result->ctx, SSL_VERIFY_PEER,
377 always_accept_verify_cb);
378 /* let us realloc bufs that we're writing from */
379 SSL_CTX_set_mode(result->ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
380 /* Free the old context if one exists. */
381 if (global_tls_context) {
382 /* This is safe even if there are open connections: OpenSSL does
383 * reference counting with SSL and SSL_CTX objects. */
384 SSL_CTX_free(global_tls_context->ctx);
385 tor_free(global_tls_context);
387 global_tls_context = result;
388 if (rsa)
389 crypto_free_pk_env(rsa);
390 return 0;
392 error:
393 tls_log_errors(LOG_WARN, "creating TLS context");
394 if (pkey)
395 EVP_PKEY_free(pkey);
396 if (rsa)
397 crypto_free_pk_env(rsa);
398 if (dh)
399 crypto_dh_free(dh);
400 if (result && result->ctx)
401 SSL_CTX_free(result->ctx);
402 if (result)
403 tor_free(result);
404 if (cert)
405 X509_free(cert);
406 if (idcert)
407 X509_free(idcert);
408 return -1;
411 /** Create a new TLS object from a file descriptor, and a flag to
412 * determine whether it is functioning as a server.
414 tor_tls_t *
415 tor_tls_new(int sock, int isServer)
417 BIO *bio = NULL;
418 tor_tls_t *result = tor_malloc(sizeof(tor_tls_t));
420 tor_assert(global_tls_context); /* make sure somebody made it first */
421 if (!(result->ssl = SSL_new(global_tls_context->ctx))) {
422 tls_log_errors(LOG_WARN, "generating TLS context");
423 tor_free(result);
424 return NULL;
426 result->socket = sock;
427 #ifdef USE_BSOCKETS
428 bio = BIO_new_bsocket(sock, BIO_NOCLOSE);
429 #else
430 bio = BIO_new_socket(sock, BIO_NOCLOSE);
431 #endif
432 if (! bio) {
433 tls_log_errors(LOG_WARN, "opening BIO");
434 tor_free(result);
435 return NULL;
437 SSL_set_bio(result->ssl, bio, bio);
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");
443 return result;
446 /** Return whether this tls initiated the connect (client) or
447 * received it (server). */
449 tor_tls_is_server(tor_tls_t *tls)
451 tor_assert(tls);
452 return tls->isServer;
455 /** Release resources associated with a TLS object. Does not close the
456 * underlying file descriptor.
458 void
459 tor_tls_free(tor_tls_t *tls)
461 tor_assert(tls && tls->ssl);
462 SSL_free(tls->ssl);
463 tls->ssl = NULL;
464 tor_free(tls);
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)
475 int r, err;
476 tor_assert(tls);
477 tor_assert(tls->ssl);
478 tor_assert(tls->state == TOR_TLS_ST_OPEN);
479 r = SSL_read(tls->ssl, cp, len);
480 if (r > 0)
481 return r;
482 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_DEBUG);
483 if (err == _TOR_TLS_ZERORETURN) {
484 log_debug(LD_NET,"read returned r=%d; TLS is closed",r);
485 tls->state = TOR_TLS_ST_CLOSED;
486 return TOR_TLS_CLOSE;
487 } else {
488 tor_assert(err != TOR_TLS_DONE);
489 log_debug(LD_NET,"read returned r=%d, err=%d",r,err);
490 return 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)
502 int r, err;
503 tor_assert(tls);
504 tor_assert(tls->ssl);
505 tor_assert(tls->state == TOR_TLS_ST_OPEN);
506 if (n == 0)
507 return 0;
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 log_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) {
519 return r;
521 if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
522 tls->wantwrite_n = n;
524 return err;
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)
534 int r;
535 tor_assert(tls);
536 tor_assert(tls->ssl);
537 tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
538 check_no_tls_errors();
539 if (tls->isServer) {
540 r = SSL_accept(tls->ssl);
541 } else {
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(tls->isServer ? LOG_INFO : LOG_WARN,
547 "handshaking");
548 return TOR_TLS_ERROR;
550 if (r == TOR_TLS_DONE) {
551 tls->state = TOR_TLS_ST_OPEN;
553 return r;
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)
563 int r, err;
564 char buf[128];
565 tor_assert(tls);
566 tor_assert(tls->ssl);
568 while (1) {
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.
573 do {
574 r = SSL_read(tls->ssl, buf, 128);
575 } while (r>0);
576 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
577 LOG_INFO);
578 if (err == _TOR_TLS_ZERORETURN) {
579 tls->state = TOR_TLS_ST_GOTCLOSE;
580 /* fall through... */
581 } else {
582 return err;
586 r = SSL_shutdown(tls->ssl);
587 if (r == 1) {
588 /* If shutdown returns 1, the connection is entirely closed. */
589 tls->state = TOR_TLS_ST_CLOSED;
590 return TOR_TLS_DONE;
592 err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
593 LOG_INFO);
594 if (err == _TOR_TLS_SYSCALL) {
595 /* The underlying TCP connection closed while we were shutting down. */
596 tls->state = TOR_TLS_ST_CLOSED;
597 return TOR_TLS_DONE;
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
602 * and try to read.
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 ... */
612 } else {
613 return err;
615 } /* end loop */
618 /** Return true iff this TLS connection is authenticated.
621 tor_tls_peer_has_cert(tor_tls_t *tls)
623 X509 *cert;
624 cert = SSL_get_peer_certificate(tls->ssl);
625 tls_log_errors(LOG_WARN, "getting peer certificate");
626 if (!cert)
627 return 0;
628 X509_free(cert);
629 return 1;
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(int severity, tor_tls_t *tls,
639 char *buf, size_t buflen)
641 X509 *cert = NULL;
642 X509_NAME *name = NULL;
643 int nid;
644 int lenout;
645 int r = -1;
647 if (!(cert = SSL_get_peer_certificate(tls->ssl))) {
648 log_fn(severity, LD_PROTOCOL, "Peer has no certificate");
649 goto error;
651 if (!(name = X509_get_subject_name(cert))) {
652 log_fn(severity, LD_PROTOCOL, "Peer certificate has no subject name");
653 goto error;
655 if ((nid = OBJ_txt2nid("commonName")) == NID_undef)
656 goto error;
658 lenout = X509_NAME_get_text_by_NID(name, nid, buf, buflen);
659 if (lenout == -1)
660 goto error;
661 if (((int)strspn(buf, LEGAL_NICKNAME_CHARACTERS)) < lenout) {
662 log_fn(severity, LD_PROTOCOL,
663 "Peer certificate nickname %s has illegal characters.",
664 escaped(buf));
665 if (strchr(buf, '.'))
666 log_fn(severity, LD_PROTOCOL,
667 " (Maybe it is not really running Tor at its "
668 "advertised OR port.)");
669 goto error;
672 r = 0;
674 error:
675 if (cert)
676 X509_free(cert);
678 tls_log_errors(severity, "getting peer certificate nickname");
679 return r;
682 static void
683 log_cert_lifetime(X509 *cert, const char *problem)
685 BIO *bio = NULL;
686 BUF_MEM *buf;
687 char *s1=NULL, *s2=NULL;
688 char mytime[33];
689 time_t now = time(NULL);
690 struct tm tm;
692 if (problem)
693 log_warn(LD_GENERAL,
694 "Certificate %s: is your system clock set incorrectly?",
695 problem);
697 if (!(bio = BIO_new(BIO_s_mem()))) {
698 log_warn(LD_GENERAL, "Couldn't allocate BIO!"); goto end;
700 if (!(ASN1_TIME_print(bio, X509_get_notBefore(cert)))) {
701 tls_log_errors(LOG_WARN, "printing certificate lifetime");
702 goto end;
704 BIO_get_mem_ptr(bio, &buf);
705 s1 = tor_strndup(buf->data, buf->length);
707 (void)BIO_reset(bio);
708 if (!(ASN1_TIME_print(bio, X509_get_notAfter(cert)))) {
709 tls_log_errors(LOG_WARN, "printing certificate lifetime");
710 goto end;
712 BIO_get_mem_ptr(bio, &buf);
713 s2 = tor_strndup(buf->data, buf->length);
715 strftime(mytime, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now, &tm));
717 log_warn(LD_GENERAL,
718 "(certificate lifetime runs from %s through %s. Your time is %s.)",
719 s1,s2,mytime);
721 end:
722 /* Not expected to get invoked */
723 tls_log_errors(LOG_WARN, "getting certificate lifetime");
724 if (bio)
725 BIO_free(bio);
726 if (s1)
727 tor_free(s1);
728 if (s2)
729 tor_free(s2);
732 /** If the provided tls connection is authenticated and has a
733 * certificate that is currently valid and signed, then set
734 * *<b>identity_key</b> to the identity certificate's key and return
735 * 0. Else, return -1 and log complaints with log-level <b>severity</b>.
738 tor_tls_verify(int severity, tor_tls_t *tls, crypto_pk_env_t **identity_key)
740 X509 *cert = NULL, *id_cert = NULL;
741 STACK_OF(X509) *chain = NULL;
742 EVP_PKEY *id_pkey = NULL;
743 RSA *rsa;
744 int num_in_chain;
745 int r = -1, i;
747 *identity_key = NULL;
749 if (!(cert = SSL_get_peer_certificate(tls->ssl)))
750 goto done;
751 if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
752 goto done;
753 num_in_chain = sk_X509_num(chain);
754 /* 1 means we're receiving (server-side), and it's just the id_cert.
755 * 2 means we're connecting (client-side), and it's both the link
756 * cert and the id_cert.
758 if (num_in_chain < 1) {
759 log_fn(severity,LD_PROTOCOL,
760 "Unexpected number of certificates in chain (%d)",
761 num_in_chain);
762 goto done;
764 for (i=0; i<num_in_chain; ++i) {
765 id_cert = sk_X509_value(chain, i);
766 if (X509_cmp(id_cert, cert) != 0)
767 break;
769 if (!id_cert) {
770 log_fn(severity,LD_PROTOCOL,"No distinct identity certificate found");
771 goto done;
774 if (!(id_pkey = X509_get_pubkey(id_cert)) ||
775 X509_verify(cert, id_pkey) <= 0) {
776 log_fn(severity,LD_PROTOCOL,"X509_verify on cert and pkey returned <= 0");
777 tls_log_errors(severity,"verifying certificate");
778 goto done;
781 rsa = EVP_PKEY_get1_RSA(id_pkey);
782 if (!rsa)
783 goto done;
784 *identity_key = _crypto_new_pk_env_rsa(rsa);
786 r = 0;
788 done:
789 if (cert)
790 X509_free(cert);
791 if (id_pkey)
792 EVP_PKEY_free(id_pkey);
794 /* This should never get invoked, but let's make sure in case OpenSSL
795 * acts unexpectedly. */
796 tls_log_errors(LOG_WARN, "finishing tor_tls_verify");
798 return r;
801 /** Check whether the certificate set on the connection <b>tls</b> is
802 * expired or not-yet-valid, give or take <b>tolerance</b>
803 * seconds. Return 0 for valid, -1 for failure.
805 * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
808 tor_tls_check_lifetime(tor_tls_t *tls, int tolerance)
810 time_t now, t;
811 X509 *cert;
812 int r = -1;
814 now = time(NULL);
816 if (!(cert = SSL_get_peer_certificate(tls->ssl)))
817 goto done;
819 t = now + tolerance;
820 if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
821 log_cert_lifetime(cert, "not yet valid");
822 goto done;
824 t = now - tolerance;
825 if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
826 log_cert_lifetime(cert, "already expired");
827 goto done;
830 r = 0;
831 done:
832 if (cert)
833 X509_free(cert);
834 /* Not expected to get invoked */
835 tls_log_errors(LOG_WARN, "checking certificate lifetime");
837 return r;
840 /** Return the number of bytes available for reading from <b>tls</b>.
843 tor_tls_get_pending_bytes(tor_tls_t *tls)
845 tor_assert(tls);
846 #if OPENSSL_VERSION_NUMBER < 0x0090700fl
847 if (tls->ssl->rstate == SSL_ST_READ_BODY)
848 return 0;
849 if (tls->ssl->s3->rrec.type != SSL3_RT_APPLICATION_DATA)
850 return 0;
851 #endif
852 return SSL_pending(tls->ssl);
855 /** If <b>tls</b> requires that the next write be of a particular size,
856 * return that size. Otherwise, return 0. */
857 size_t
858 tor_tls_get_forced_write_size(tor_tls_t *tls)
860 return tls->wantwrite_n;
863 /** Return the number of bytes read across the underlying socket. */
864 unsigned long
865 tor_tls_get_n_bytes_read(tor_tls_t *tls)
867 tor_assert(tls);
868 return BIO_number_read(SSL_get_rbio(tls->ssl));
870 /** Return the number of bytes written across the underlying socket. */
871 unsigned long
872 tor_tls_get_n_bytes_written(tor_tls_t *tls)
874 tor_assert(tls);
875 return BIO_number_written(SSL_get_wbio(tls->ssl));
878 /** Implement check_no_tls_errors: If there are any pending OpenSSL
879 * errors, log an error message. */
880 void
881 _check_no_tls_errors(const char *fname, int line)
883 if (ERR_peek_error() == 0)
884 return;
885 log(LOG_WARN, LD_CRYPTO, "Unhandled OpenSSL errors found at %s:%d: ",
886 tor_fix_source_file(fname), line);
887 tls_log_errors(LOG_WARN, NULL);