Fix "JAP-client" hideous ASN1 bug, twice. (Fix1: check more thoroughly for TLS errors...
[tor.git] / src / common / tortls.c
blobf0e57e5455ec394bb1c17dbc27705cd26b5cb1c8
1 /* Copyright 2003 Roger Dingledine.
2 * Copyright 2004-2005 Roger Dingledine, Nick Mathewson */
3 /* See LICENSE for licensing information */
4 /* $Id$ */
5 const char tortls_c_id[] = "$Id$";
7 /**
8 * \file tortls.c
10 * \brief TLS wrappers for Tor.
11 **/
12 /* (Unlike other tor functions, these
13 * are prefixed with tor_ in order to avoid conflicting with OpenSSL
14 * functions and variables.)
17 #include "./crypto.h"
18 #include "./tortls.h"
19 #include "./util.h"
20 #include "./log.h"
21 #include <string.h>
23 /* Copied from or.h */
24 #define LEGAL_NICKNAME_CHARACTERS "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
26 #include <assert.h>
27 #include <openssl/ssl.h>
28 #include <openssl/err.h>
29 #include <openssl/tls1.h>
30 #include <openssl/asn1.h>
31 #include <openssl/bio.h>
33 /** How long do identity certificates live? (sec) */
34 #define IDENTITY_CERT_LIFETIME (365*24*60*60)
36 typedef struct tor_tls_context_st {
37 SSL_CTX *ctx;
38 SSL_CTX *client_only_ctx;
39 } tor_tls_context;
41 /** Holds a SSL object and its associated data. Members are only
42 * accessed from within tortls.c.
44 struct tor_tls_st {
45 SSL *ssl; /**< An OpenSSL SSL object. */
46 int socket; /**< The underlying file descriptor for this TLS connection. */
47 enum {
48 TOR_TLS_ST_HANDSHAKE, TOR_TLS_ST_OPEN, TOR_TLS_ST_GOTCLOSE,
49 TOR_TLS_ST_SENTCLOSE, TOR_TLS_ST_CLOSED
50 } state; /**< The current SSL state, depending on which operations have
51 * completed successfully. */
52 int isServer;
53 size_t wantwrite_n; /**< 0 normally, >0 if we returned wantwrite last time. */
56 static X509* tor_tls_create_certificate(crypto_pk_env_t *rsa,
57 crypto_pk_env_t *rsa_sign,
58 const char *cname,
59 const char *cname_sign,
60 unsigned int lifetime);
62 /** Global tls context. We keep it here because nobody else needs to
63 * touch it. */
64 static tor_tls_context *global_tls_context = NULL;
65 /** True iff tor_tls_init() has been called. */
66 static int tls_library_is_initialized = 0;
68 /* Module-internal error codes. */
69 #define _TOR_TLS_SYSCALL -6
70 #define _TOR_TLS_ZERORETURN -5
72 /* These functions are declared in crypto.c but not exported. */
73 EVP_PKEY *_crypto_pk_env_get_evp_pkey(crypto_pk_env_t *env, int private);
74 crypto_pk_env_t *_crypto_new_pk_env_rsa(RSA *rsa);
75 DH *_crypto_dh_env_get_dh(crypto_dh_env_t *dh);
77 /** Log all pending tls errors at level <b>severity</b>. Use
78 * <b>doing</b> to describe our current activities.
80 static void
81 tls_log_errors(int severity, const char *doing)
83 int err;
84 const char *msg, *lib, *func;
85 while ((err = ERR_get_error()) != 0) {
86 msg = (const char*)ERR_reason_error_string(err);
87 lib = (const char*)ERR_lib_error_string(err);
88 func = (const char*)ERR_func_error_string(err);
89 if (!msg) msg = "(null)";
90 if (doing) {
91 log(severity, "TLS error while %s: %s (in %s:%s)", doing, msg, lib,func);
92 } else {
93 log(severity, "TLS error: %s (in %s:%s)", msg, lib, func);
98 #define CATCH_SYSCALL 1
99 #define CATCH_ZERO 2
101 /** Given a TLS object and the result of an SSL_* call, use
102 * SSL_get_error to determine whether an error has occurred, and if so
103 * which one. Return one of TOR_TLS_{DONE|WANTREAD|WANTWRITE|ERROR}.
104 * If extra&CATCH_SYSCALL is true, return _TOR_TLS_SYSCALL instead of
105 * reporting syscall errors. If extra&CATCH_ZERO is true, return
106 * _TOR_TLS_ZERORETURN instead of reporting zero-return errors.
108 * If an error has occurred, log it at level <b>severity</b> and describe the
109 * current action as <b>doing</b>.
111 static int
112 tor_tls_get_error(tor_tls *tls, int r, int extra,
113 const char *doing, int severity)
115 int err = SSL_get_error(tls->ssl, r);
116 switch (err) {
117 case SSL_ERROR_NONE:
118 return TOR_TLS_DONE;
119 case SSL_ERROR_WANT_READ:
120 return TOR_TLS_WANTREAD;
121 case SSL_ERROR_WANT_WRITE:
122 return TOR_TLS_WANTWRITE;
123 case SSL_ERROR_SYSCALL:
124 if (extra&CATCH_SYSCALL)
125 return _TOR_TLS_SYSCALL;
126 if (r == 0)
127 log(severity, "TLS error: unexpected close while %s", doing);
128 else {
129 int e = tor_socket_errno(tls->socket);
130 log(severity, "TLS error: <syscall error while %s> (errno=%d: %s)",
131 doing, e, tor_socket_strerror(e));
133 tls_log_errors(severity, doing);
134 return TOR_TLS_ERROR;
135 case SSL_ERROR_ZERO_RETURN:
136 if (extra&CATCH_ZERO)
137 return _TOR_TLS_ZERORETURN;
138 log(severity, "TLS error: Zero return");
139 tls_log_errors(severity, doing);
140 return TOR_TLS_ERROR;
141 default:
142 tls_log_errors(severity, doing);
143 return TOR_TLS_ERROR;
147 /** Initialize OpenSSL, unless it has already been initialized.
149 static void
150 tor_tls_init(void) {
151 if (!tls_library_is_initialized) {
152 SSL_library_init();
153 SSL_load_error_strings();
154 crypto_global_init();
155 OpenSSL_add_all_algorithms();
156 tls_library_is_initialized = 1;
160 void
161 tor_tls_free_all(void)
163 if (global_tls_context) {
164 SSL_CTX_free(global_tls_context->ctx);
165 SSL_CTX_free(global_tls_context->client_only_ctx);
166 tor_free(global_tls_context);
167 global_tls_context = NULL;
171 /** We need to give OpenSSL a callback to verify certificates. This is
172 * it: We always accept peer certs and complete the handshake. We
173 * don't validate them until later.
175 static int always_accept_verify_cb(int preverify_ok,
176 X509_STORE_CTX *x509_ctx)
178 return 1;
181 /** Generate and sign an X509 certificate with the public key <b>rsa</b>,
182 * signed by the private key <b>rsa_sign</b>. The commonName of the
183 * certificate will be <b>cname</b>; the commonName of the issuer will be
184 * <b>cname_sign</b>. The cert will be valid for <b>cert_lifetime</b> seconds
185 * starting from now. Return a certificate on success, NULL on
186 * failure.
188 static X509 *
189 tor_tls_create_certificate(crypto_pk_env_t *rsa,
190 crypto_pk_env_t *rsa_sign,
191 const char *cname,
192 const char *cname_sign,
193 unsigned int cert_lifetime)
195 time_t start_time, end_time;
196 EVP_PKEY *sign_pkey = NULL, *pkey=NULL;
197 X509 *x509 = NULL;
198 X509_NAME *name = NULL, *name_issuer=NULL;
199 int nid;
201 tor_tls_init();
203 start_time = time(NULL);
205 tor_assert(rsa);
206 tor_assert(cname);
207 tor_assert(rsa_sign);
208 tor_assert(cname_sign);
209 if (!(sign_pkey = _crypto_pk_env_get_evp_pkey(rsa_sign,1)))
210 goto error;
211 if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,0)))
212 goto error;
213 if (!(x509 = X509_new()))
214 goto error;
215 if (!(X509_set_version(x509, 2)))
216 goto error;
217 if (!(ASN1_INTEGER_set(X509_get_serialNumber(x509), (long)start_time)))
218 goto error;
220 if (!(name = X509_NAME_new()))
221 goto error;
222 if ((nid = OBJ_txt2nid("organizationName")) == NID_undef) goto error;
223 if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
224 (char*)"TOR", -1, -1, 0))) goto error;
225 if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
226 if (!(X509_NAME_add_entry_by_NID(name, nid, MBSTRING_ASC,
227 (char*)cname, -1, -1, 0))) goto error;
228 if (!(X509_set_subject_name(x509, name)))
229 goto error;
231 if (!(name_issuer = X509_NAME_new()))
232 goto error;
233 if ((nid = OBJ_txt2nid("organizationName")) == NID_undef) goto error;
234 if (!(X509_NAME_add_entry_by_NID(name_issuer, nid, MBSTRING_ASC,
235 (char*)"TOR", -1, -1, 0))) goto error;
236 if ((nid = OBJ_txt2nid("commonName")) == NID_undef) goto error;
237 if (!(X509_NAME_add_entry_by_NID(name_issuer, nid, MBSTRING_ASC,
238 (char*)cname_sign, -1, -1, 0))) goto error;
239 if (!(X509_set_issuer_name(x509, name_issuer)))
240 goto error;
242 if (!X509_time_adj(X509_get_notBefore(x509),0,&start_time))
243 goto error;
244 end_time = start_time + cert_lifetime;
245 if (!X509_time_adj(X509_get_notAfter(x509),0,&end_time))
246 goto error;
247 if (!X509_set_pubkey(x509, pkey))
248 goto error;
249 if (!X509_sign(x509, sign_pkey, EVP_sha1()))
250 goto error;
252 goto done;
253 error:
254 if (x509) {
255 X509_free(x509);
256 x509 = NULL;
258 done:
259 tls_log_errors(LOG_WARN, "generating certificate");
260 if (sign_pkey)
261 EVP_PKEY_free(sign_pkey);
262 if (pkey)
263 EVP_PKEY_free(pkey);
264 if (name)
265 X509_NAME_free(name);
266 if (name_issuer)
267 X509_NAME_free(name_issuer);
268 return x509;
271 #ifdef EVERYONE_HAS_AES
272 /* Everybody is running OpenSSL 0.9.7 or later, so no backward compatibility
273 * is needed. */
274 #define CIPHER_LIST TLS1_TXT_DHE_RSA_WITH_AES_128_SHA
275 #elif defined(TLS1_TXT_DHE_RSA_WITH_AES_128_SHA)
276 /* Some people are running OpenSSL before 0.9.7, but we aren't.
277 * We can support AES and 3DES.
279 #define CIPHER_LIST (TLS1_TXT_DHE_RSA_WITH_AES_128_SHA ":" \
280 SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA)
281 #else
282 /* We're running OpenSSL before 0.9.7. We only support 3DES. */
283 #define CIPHER_LIST SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA
284 #endif
286 /** Create a new TLS context. If we are going to be using it as a
287 * server, it must have isServer set to true, <b>identity</b> set to the
288 * identity key used to sign that certificate, and <b>nickname</b> set to
289 * the server's nickname. If we're only going to be a client,
290 * isServer should be false, identity should be NULL, and nickname
291 * should be NULL. Return -1 if failure, else 0.
293 * You can call this function multiple times. Each time you call it,
294 * it generates new certificates; all new connections will use
295 * the new SSL context.
298 tor_tls_context_new(crypto_pk_env_t *identity,
299 int isServer, const char *nickname,
300 unsigned int key_lifetime)
302 crypto_pk_env_t *rsa = NULL;
303 crypto_dh_env_t *dh = NULL;
304 EVP_PKEY *pkey = NULL;
305 tor_tls_context *result = NULL;
306 X509 *cert = NULL, *idcert = NULL;
307 char nn2[128];
308 int client_only;
309 SSL_CTX **ctx;
310 if (!nickname)
311 nickname = "null";
312 tor_snprintf(nn2, sizeof(nn2), "%s <identity>", nickname);
314 tor_tls_init();
316 if (isServer) {
317 /* Generate short-term RSA key. */
318 if (!(rsa = crypto_new_pk_env()))
319 goto error;
320 if (crypto_pk_generate_key(rsa)<0)
321 goto error;
322 /* Create certificate signed by identity key. */
323 cert = tor_tls_create_certificate(rsa, identity, nickname, nn2,
324 key_lifetime);
325 /* Create self-signed certificate for identity key. */
326 idcert = tor_tls_create_certificate(identity, identity, nn2, nn2,
327 IDENTITY_CERT_LIFETIME);
328 if (!cert || !idcert) {
329 log(LOG_WARN, "Error creating certificate");
330 goto error;
334 result = tor_malloc(sizeof(tor_tls_context));
335 result->ctx = result->client_only_ctx = NULL;
336 for (client_only=0; client_only <= 1; ++client_only) {
337 ctx = client_only ? &result->client_only_ctx : &result->ctx;
338 #ifdef EVERYONE_HAS_AES
339 /* Tell OpenSSL to only use TLS1 */
340 if (!(*ctx = SSL_CTX_new(TLSv1_method())))
341 goto error;
342 #else
343 /* Tell OpenSSL to use SSL3 or TLS1 but not SSL2. */
344 if (!(*ctx = SSL_CTX_new(SSLv23_method())))
345 goto error;
346 SSL_CTX_set_options(*ctx, SSL_OP_NO_SSLv2);
347 #endif
348 if (!SSL_CTX_set_cipher_list(*ctx, CIPHER_LIST))
349 goto error;
350 if (!client_only) {
351 if (cert && !SSL_CTX_use_certificate(*ctx,cert))
352 goto error;
353 X509_free(cert); /* We just added a reference to cert. */
354 cert=NULL;
355 if (idcert && !SSL_CTX_add_extra_chain_cert(*ctx,idcert))
356 goto error;
357 idcert=NULL; /* The context now owns the reference to idcert */
359 SSL_CTX_set_session_cache_mode(*ctx, SSL_SESS_CACHE_OFF);
360 if (isServer && !client_only) {
361 tor_assert(rsa);
362 if (!(pkey = _crypto_pk_env_get_evp_pkey(rsa,1)))
363 goto error;
364 if (!SSL_CTX_use_PrivateKey(*ctx, pkey))
365 goto error;
366 EVP_PKEY_free(pkey);
367 pkey = NULL;
368 if (!SSL_CTX_check_private_key(*ctx))
369 goto error;
371 dh = crypto_dh_new();
372 SSL_CTX_set_tmp_dh(*ctx, _crypto_dh_env_get_dh(dh));
373 crypto_dh_free(dh);
374 SSL_CTX_set_verify(*ctx, SSL_VERIFY_PEER,
375 always_accept_verify_cb);
376 /* let us realloc bufs that we're writing from */
377 SSL_CTX_set_mode(*ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
379 /* Free the old context if one exists. */
380 if (global_tls_context) {
381 /* This is safe even if there are open connections: OpenSSL does
382 * reference counting with SSL and SSL_CTX objects. */
383 SSL_CTX_free(global_tls_context->ctx);
384 SSL_CTX_free(global_tls_context->client_only_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 && result->client_only_ctx)
403 SSL_CTX_free(result->client_only_ctx);
404 if (result)
405 free(result);
406 if (cert)
407 X509_free(cert);
408 if (idcert)
409 X509_free(idcert);
410 return -1;
413 /** Create a new TLS object from a file descriptor, and a flag to
414 * determine whether it is functioning as a server.
416 tor_tls *
417 tor_tls_new(int sock, int isServer, int use_no_cert)
419 tor_tls *result = tor_malloc(sizeof(tor_tls));
420 SSL_CTX *ctx;
421 tor_assert(global_tls_context); /* make sure somebody made it first */
422 ctx = use_no_cert ? global_tls_context->client_only_ctx
423 : global_tls_context->ctx;
424 if (!(result->ssl = SSL_new(ctx))) {
425 tls_log_errors(LOG_WARN, "generating TLS context");
426 tor_free(result);
427 return NULL;
429 result->socket = sock;
430 SSL_set_fd(result->ssl, sock);
431 result->state = TOR_TLS_ST_HANDSHAKE;
432 result->isServer = isServer;
433 result->wantwrite_n = 0;
434 /* Not expected to get called. */
435 tls_log_errors(LOG_WARN, "generating TLS context");
436 return result;
439 /** Return whether this tls initiated the connect (client) or
440 * received it (server). */
442 tor_tls_is_server(tor_tls *tls)
444 tor_assert(tls);
445 return tls->isServer;
448 /** Release resources associated with a TLS object. Does not close the
449 * underlying file descriptor.
451 void
452 tor_tls_free(tor_tls *tls)
454 tor_assert(tls && tls->ssl);
455 SSL_free(tls->ssl);
456 tls->ssl = NULL;
457 tor_free(tls);
460 /** Underlying function for TLS reading. Reads up to <b>len</b>
461 * characters from <b>tls</b> into <b>cp</b>. On success, returns the
462 * number of characters read. On failure, returns TOR_TLS_ERROR,
463 * TOR_TLS_CLOSE, TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
466 tor_tls_read(tor_tls *tls, char *cp, size_t len)
468 int r, err;
469 tor_assert(tls);
470 tor_assert(tls->ssl);
471 tor_assert(tls->state == TOR_TLS_ST_OPEN);
472 r = SSL_read(tls->ssl, cp, len);
473 if (r > 0)
474 return r;
475 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading", LOG_INFO);
476 if (err == _TOR_TLS_ZERORETURN) {
477 log_fn(LOG_DEBUG,"read returned r=%d; TLS is closed",r);
478 tls->state = TOR_TLS_ST_CLOSED;
479 return TOR_TLS_CLOSE;
480 } else {
481 tor_assert(err != TOR_TLS_DONE);
482 log_fn(LOG_DEBUG,"read returned r=%d, err=%d",r,err);
483 return err;
487 /** Underlying function for TLS writing. Write up to <b>n</b>
488 * characters from <b>cp</b> onto <b>tls</b>. On success, returns the
489 * number of characters written. On failure, returns TOR_TLS_ERROR,
490 * TOR_TLS_WANTREAD, or TOR_TLS_WANTWRITE.
493 tor_tls_write(tor_tls *tls, char *cp, size_t n)
495 int r, err;
496 tor_assert(tls);
497 tor_assert(tls->ssl);
498 tor_assert(tls->state == TOR_TLS_ST_OPEN);
499 if (n == 0)
500 return 0;
501 if (tls->wantwrite_n) {
502 /* if WANTWRITE last time, we must use the _same_ n as before */
503 tor_assert(n >= tls->wantwrite_n);
504 log_fn(LOG_DEBUG,"resuming pending-write, (%d to flush, reusing %d)",
505 (int)n, (int)tls->wantwrite_n);
506 n = tls->wantwrite_n;
507 tls->wantwrite_n = 0;
509 r = SSL_write(tls->ssl, cp, n);
510 err = tor_tls_get_error(tls, r, 0, "writing", LOG_INFO);
511 if (err == TOR_TLS_DONE) {
512 return r;
514 if (err == TOR_TLS_WANTWRITE || err == TOR_TLS_WANTREAD) {
515 tls->wantwrite_n = n;
517 return err;
520 /** Perform initial handshake on <b>tls</b>. When finished, returns
521 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
522 * or TOR_TLS_WANTWRITE.
525 tor_tls_handshake(tor_tls *tls)
527 int r;
528 tor_assert(tls);
529 tor_assert(tls->ssl);
530 tor_assert(tls->state == TOR_TLS_ST_HANDSHAKE);
531 if (tls->isServer) {
532 r = SSL_accept(tls->ssl);
533 } else {
534 r = SSL_connect(tls->ssl);
536 r = tor_tls_get_error(tls,r,0, "handshaking", LOG_INFO);
537 if (r == TOR_TLS_DONE) {
538 tls->state = TOR_TLS_ST_OPEN;
540 return r;
543 /** Shut down an open tls connection <b>tls</b>. When finished, returns
544 * TOR_TLS_DONE. On failure, returns TOR_TLS_ERROR, TOR_TLS_WANTREAD,
545 * or TOR_TLS_WANTWRITE.
548 tor_tls_shutdown(tor_tls *tls)
550 int r, err;
551 char buf[128];
552 tor_assert(tls);
553 tor_assert(tls->ssl);
555 while (1) {
556 if (tls->state == TOR_TLS_ST_SENTCLOSE) {
557 /* If we've already called shutdown once to send a close message,
558 * we read until the other side has closed too.
560 do {
561 r = SSL_read(tls->ssl, buf, 128);
562 } while (r>0);
563 err = tor_tls_get_error(tls, r, CATCH_ZERO, "reading to shut down",
564 LOG_INFO);
565 if (err == _TOR_TLS_ZERORETURN) {
566 tls->state = TOR_TLS_ST_GOTCLOSE;
567 /* fall through... */
568 } else {
569 return err;
573 r = SSL_shutdown(tls->ssl);
574 if (r == 1) {
575 /* If shutdown returns 1, the connection is entirely closed. */
576 tls->state = TOR_TLS_ST_CLOSED;
577 return TOR_TLS_DONE;
579 err = tor_tls_get_error(tls, r, CATCH_SYSCALL|CATCH_ZERO, "shutting down",
580 LOG_INFO);
581 if (err == _TOR_TLS_SYSCALL) {
582 /* The underlying TCP connection closed while we were shutting down. */
583 tls->state = TOR_TLS_ST_CLOSED;
584 return TOR_TLS_DONE;
585 } else if (err == _TOR_TLS_ZERORETURN) {
586 /* The TLS connection says that it sent a shutdown record, but
587 * isn't done shutting down yet. Make sure that this hasn't
588 * happened before, then go back to the start of the function
589 * and try to read.
591 if (tls->state == TOR_TLS_ST_GOTCLOSE ||
592 tls->state == TOR_TLS_ST_SENTCLOSE) {
593 log(LOG_WARN,
594 "TLS returned \"half-closed\" value while already half-closed");
595 return TOR_TLS_ERROR;
597 tls->state = TOR_TLS_ST_SENTCLOSE;
598 /* fall through ... */
599 } else {
600 return err;
602 } /* end loop */
605 /** Return true iff this TLS connection is authenticated.
608 tor_tls_peer_has_cert(tor_tls *tls)
610 X509 *cert;
611 cert = SSL_get_peer_certificate(tls->ssl);
612 tls_log_errors(LOG_WARN, "getting peer certificate");
613 if (!cert)
614 return 0;
615 X509_free(cert);
616 return 1;
619 /** Write the nickname (if any) that the peer connected on <b>tls</b>
620 * claims to have into the first <b>buflen</b> characters of <b>buf</b>.
621 * Truncate the nickname if it is longer than buflen-1 characters. Always
622 * NUL-terminate. Return 0 on success, -1 on failure.
625 tor_tls_get_peer_cert_nickname(tor_tls *tls, char *buf, size_t buflen)
627 X509 *cert = NULL;
628 X509_NAME *name = NULL;
629 int nid;
630 int lenout;
631 int r = -1;
633 if (!(cert = SSL_get_peer_certificate(tls->ssl))) {
634 log_fn(LOG_WARN, "Peer has no certificate");
635 goto error;
637 if (!(name = X509_get_subject_name(cert))) {
638 log_fn(LOG_WARN, "Peer certificate has no subject name");
639 goto error;
641 if ((nid = OBJ_txt2nid("commonName")) == NID_undef)
642 goto error;
644 lenout = X509_NAME_get_text_by_NID(name, nid, buf, buflen);
645 if (lenout == -1)
646 goto error;
647 if (((int)strspn(buf, LEGAL_NICKNAME_CHARACTERS)) < lenout) {
648 log_fn(LOG_WARN, "Peer certificate nickname '%s' has illegal characters.",
649 buf);
650 if (strchr(buf, '.'))
651 log_fn(LOG_WARN, " (Maybe it is not really running Tor at its advertised OR port.)");
652 goto error;
655 r = 0;
657 error:
658 if (cert)
659 X509_free(cert);
661 tls_log_errors(LOG_WARN, "getting peer certificate nickname");
662 return r;
665 static void log_cert_lifetime(X509 *cert, const char *problem)
667 BIO *bio = NULL;
668 BUF_MEM *buf;
669 char *s1=NULL, *s2=NULL;
670 char mytime[33];
671 time_t now = time(NULL);
672 struct tm tm;
674 if (problem)
675 log_fn(LOG_WARN,"Certificate %s: is your system clock set incorrectly?",
676 problem);
678 if (!(bio = BIO_new(BIO_s_mem()))) {
679 log_fn(LOG_WARN, "Couldn't allocate BIO!"); goto end;
681 if (!(ASN1_TIME_print(bio, X509_get_notBefore(cert)))) {
682 tls_log_errors(LOG_WARN, "printing certificate lifetime");
683 goto end;
685 BIO_get_mem_ptr(bio, &buf);
686 s1 = tor_strndup(buf->data, buf->length);
688 BIO_reset(bio);
689 if (!(ASN1_TIME_print(bio, X509_get_notAfter(cert)))) {
690 tls_log_errors(LOG_WARN, "printing certificate lifetime");
691 goto end;
693 BIO_get_mem_ptr(bio, &buf);
694 s2 = tor_strndup(buf->data, buf->length);
696 strftime(mytime, 32, "%b %d %H:%M:%S %Y GMT", tor_gmtime_r(&now, &tm));
698 log_fn(LOG_WARN, "(certificate lifetime runs from %s through %s. Your time is %s.)",s1,s2,mytime);
700 end:
701 /* Not expected to get invoked */
702 tls_log_errors(LOG_WARN, "getting certificate lifetime");
703 if (bio)
704 BIO_free(bio);
705 if (s1)
706 tor_free(s1);
707 if (s2)
708 tor_free(s2);
711 /** If the provided tls connection is authenticated and has a
712 * certificate that is currently valid and signed, then set
713 * *<b>identity_key</b> to the identity certificate's key and return
714 * 0. Else, return -1.
717 tor_tls_verify(tor_tls *tls, crypto_pk_env_t **identity_key)
719 X509 *cert = NULL, *id_cert = NULL;
720 STACK_OF(X509) *chain = NULL;
721 EVP_PKEY *id_pkey = NULL;
722 RSA *rsa;
723 int num_in_chain;
724 int r = -1, i;
726 *identity_key = NULL;
728 if (!(cert = SSL_get_peer_certificate(tls->ssl)))
729 goto done;
730 if (!(chain = SSL_get_peer_cert_chain(tls->ssl)))
731 goto done;
732 num_in_chain = sk_X509_num(chain);
733 /* 1 means we're receiving (server-side), and it's just the id_cert.
734 * 2 means we're connecting (client-side), and it's both the link
735 * cert and the id_cert.
737 if (num_in_chain < 1) {
738 log_fn(LOG_WARN,"Unexpected number of certificates in chain (%d)",
739 num_in_chain);
740 goto done;
742 for (i=0; i<num_in_chain; ++i) {
743 id_cert = sk_X509_value(chain, i);
744 if (X509_cmp(id_cert, cert) != 0)
745 break;
747 if (!id_cert) {
748 log_fn(LOG_WARN,"No distinct identity certificate found");
749 goto done;
752 if (!(id_pkey = X509_get_pubkey(id_cert)) ||
753 X509_verify(cert, id_pkey) <= 0) {
754 log_fn(LOG_WARN,"X509_verify on cert and pkey returned <= 0");
755 tls_log_errors(LOG_WARN,"verifying certificate");
756 goto done;
759 rsa = EVP_PKEY_get1_RSA(id_pkey);
760 if (!rsa)
761 goto done;
762 *identity_key = _crypto_new_pk_env_rsa(rsa);
764 r = 0;
766 done:
767 if (cert)
768 X509_free(cert);
769 if (id_pkey)
770 EVP_PKEY_free(id_pkey);
772 /* This should never get invoked, but let's make sure in case OpenSSL
773 * acts unexpectedly. */
774 tls_log_errors(LOG_WARN, "finishing tor_tls_verify");
776 return r;
779 /** Check whether the certificate set on the connection <b>tls</b> is
780 * expired or not-yet-valid, give or take <b>tolerance</b>
781 * seconds. Return 0 for valid, -1 for failure.
783 * NOTE: you should call tor_tls_verify before tor_tls_check_lifetime.
786 tor_tls_check_lifetime(tor_tls *tls, int tolerance)
788 time_t now, t;
789 X509 *cert;
790 int r = -1;
792 now = time(NULL);
794 if (!(cert = SSL_get_peer_certificate(tls->ssl)))
795 goto done;
797 t = now + tolerance;
798 if (X509_cmp_time(X509_get_notBefore(cert), &t) > 0) {
799 log_cert_lifetime(cert, "not yet valid");
800 goto done;
802 t = now - tolerance;
803 if (X509_cmp_time(X509_get_notAfter(cert), &t) < 0) {
804 log_cert_lifetime(cert, "already expired");
805 goto done;
808 r = 0;
809 done:
810 if (cert)
811 X509_free(cert);
812 /* Not expected to get invoked */
813 tls_log_errors(LOG_WARN, "checking certificate lifetime");
815 return r;
818 /** Return the number of bytes available for reading from <b>tls</b>.
821 tor_tls_get_pending_bytes(tor_tls *tls)
823 tor_assert(tls);
824 #if OPENSSL_VERSION_NUMBER < 0x0090700fl
825 if (tls->ssl->rstate == SSL_ST_READ_BODY)
826 return 0;
827 if (tls->ssl->s3->rrec.type != SSL3_RT_APPLICATION_DATA)
828 return 0;
829 #endif
830 return SSL_pending(tls->ssl);
834 /** Return the number of bytes read across the underlying socket. */
835 unsigned long tor_tls_get_n_bytes_read(tor_tls *tls)
837 tor_assert(tls);
838 return BIO_number_read(SSL_get_rbio(tls->ssl));
840 /** Return the number of bytes written across the underlying socket. */
841 unsigned long tor_tls_get_n_bytes_written(tor_tls *tls)
843 tor_assert(tls);
844 return BIO_number_written(SSL_get_wbio(tls->ssl));
847 /** Implement check_no_tls_errors: If there are any pending OpenSSL
848 * errors, log an error message and assert(0). */
849 void _check_no_tls_errors(const char *fname, int line)
851 if (ERR_peek_error() == 0)
852 return;
853 log_fn(LOG_ERR, "Unhandled OpenSSL errors found at %s:%d: ",
854 fname, line);
855 tls_log_errors(LOG_ERR, NULL);