Remove false positives from channel_is_client()
[tor.git] / src / or / connection_or.c
blobfcd281da2605b92f1f854d906160083cc2b3683d
1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2017, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
7 /**
8 * \file connection_or.c
9 * \brief Functions to handle OR connections, TLS handshaking, and
10 * cells on the network.
12 * An or_connection_t is a subtype of connection_t (as implemented in
13 * connection.c) that uses a TLS connection to send and receive cells on the
14 * Tor network. (By sending and receiving cells connection_or.c, it cooperates
15 * with channeltls.c to implement a the channel interface of channel.c.)
17 * Every OR connection has an underlying tortls_t object (as implemented in
18 * tortls.c) which it uses as its TLS stream. It is responsible for
19 * sending and receiving cells over that TLS.
21 * This module also implements the client side of the v3 Tor link handshake,
22 **/
23 #include "or.h"
24 #include "bridges.h"
25 #include "buffers.h"
27 * Define this so we get channel internal functions, since we're implementing
28 * part of a subclass (channel_tls_t).
30 #define TOR_CHANNEL_INTERNAL_
31 #include "channel.h"
32 #include "channeltls.h"
33 #include "circuitbuild.h"
34 #include "circuitlist.h"
35 #include "circuitstats.h"
36 #include "command.h"
37 #include "config.h"
38 #include "connection.h"
39 #include "connection_or.h"
40 #include "control.h"
41 #include "dirserv.h"
42 #include "entrynodes.h"
43 #include "geoip.h"
44 #include "main.h"
45 #include "link_handshake.h"
46 #include "microdesc.h"
47 #include "networkstatus.h"
48 #include "nodelist.h"
49 #include "reasons.h"
50 #include "relay.h"
51 #include "rephist.h"
52 #include "router.h"
53 #include "routerkeys.h"
54 #include "routerlist.h"
55 #include "ext_orport.h"
56 #include "scheduler.h"
57 #include "torcert.h"
58 #include "channelpadding.h"
60 static int connection_tls_finish_handshake(or_connection_t *conn);
61 static int connection_or_launch_v3_or_handshake(or_connection_t *conn);
62 static int connection_or_process_cells_from_inbuf(or_connection_t *conn);
63 static int connection_or_check_valid_tls_handshake(or_connection_t *conn,
64 int started_here,
65 char *digest_rcvd_out);
67 static void connection_or_tls_renegotiated_cb(tor_tls_t *tls, void *_conn);
69 static unsigned int
70 connection_or_is_bad_for_new_circs(or_connection_t *or_conn);
71 static void connection_or_mark_bad_for_new_circs(or_connection_t *or_conn);
74 * Call this when changing connection state, so notifications to the owning
75 * channel can be handled.
78 static void connection_or_change_state(or_connection_t *conn, uint8_t state);
80 static void connection_or_check_canonicity(or_connection_t *conn,
81 int started_here);
83 /**************************************************************/
85 /** Global map between Extended ORPort identifiers and OR
86 * connections. */
87 static digestmap_t *orconn_ext_or_id_map = NULL;
89 /** Clear clear conn->identity_digest and update other data
90 * structures as appropriate.*/
91 void
92 connection_or_clear_identity(or_connection_t *conn)
94 tor_assert(conn);
95 memset(conn->identity_digest, 0, DIGEST_LEN);
98 /** Clear all identities in OR conns.*/
99 void
100 connection_or_clear_identity_map(void)
102 smartlist_t *conns = get_connection_array();
103 SMARTLIST_FOREACH(conns, connection_t *, conn,
105 if (conn->type == CONN_TYPE_OR) {
106 connection_or_clear_identity(TO_OR_CONN(conn));
111 /** Change conn->identity_digest to digest, and add conn into
112 * the appropriate digest maps.
114 * NOTE that this function only allows two kinds of transitions: from
115 * unset identity to set identity, and from idempotent re-settings
116 * of the same identity. It's not allowed to clear an identity or to
117 * change an identity. Return 0 on success, and -1 if the transition
118 * is not allowed.
120 static void
121 connection_or_set_identity_digest(or_connection_t *conn,
122 const char *rsa_digest,
123 const ed25519_public_key_t *ed_id)
125 channel_t *chan = NULL;
126 tor_assert(conn);
127 tor_assert(rsa_digest);
129 if (conn->chan)
130 chan = TLS_CHAN_TO_BASE(conn->chan);
132 log_info(LD_HANDSHAKE, "Set identity digest for %p (%s): %s %s.",
133 conn,
134 escaped_safe_str(conn->base_.address),
135 hex_str(rsa_digest, DIGEST_LEN),
136 ed25519_fmt(ed_id));
137 log_info(LD_HANDSHAKE, " (Previously: %s %s)",
138 hex_str(conn->identity_digest, DIGEST_LEN),
139 chan ? ed25519_fmt(&chan->ed25519_identity) : "<null>");
141 const int rsa_id_was_set = ! tor_digest_is_zero(conn->identity_digest);
142 const int ed_id_was_set =
143 chan && !ed25519_public_key_is_zero(&chan->ed25519_identity);
144 const int rsa_changed =
145 tor_memneq(conn->identity_digest, rsa_digest, DIGEST_LEN);
146 const int ed_changed = ed_id_was_set &&
147 (!ed_id || !ed25519_pubkey_eq(ed_id, &chan->ed25519_identity));
149 tor_assert(!rsa_changed || !rsa_id_was_set);
150 tor_assert(!ed_changed || !ed_id_was_set);
152 if (!rsa_changed && !ed_changed)
153 return;
155 /* If the identity was set previously, remove the old mapping. */
156 if (rsa_id_was_set) {
157 connection_or_clear_identity(conn);
158 if (chan)
159 channel_clear_identity_digest(chan);
162 memcpy(conn->identity_digest, rsa_digest, DIGEST_LEN);
164 /* If we're initializing the IDs to zero, don't add a mapping yet. */
165 if (tor_digest_is_zero(rsa_digest) &&
166 (!ed_id || ed25519_public_key_is_zero(ed_id)))
167 return;
169 /* Deal with channels */
170 if (chan)
171 channel_set_identity_digest(chan, rsa_digest, ed_id);
174 /** Remove the Extended ORPort identifier of <b>conn</b> from the
175 * global identifier list. Also, clear the identifier from the
176 * connection itself. */
177 void
178 connection_or_remove_from_ext_or_id_map(or_connection_t *conn)
180 or_connection_t *tmp;
181 if (!orconn_ext_or_id_map)
182 return;
183 if (!conn->ext_or_conn_id)
184 return;
186 tmp = digestmap_remove(orconn_ext_or_id_map, conn->ext_or_conn_id);
187 if (!tor_digest_is_zero(conn->ext_or_conn_id))
188 tor_assert(tmp == conn);
190 memset(conn->ext_or_conn_id, 0, EXT_OR_CONN_ID_LEN);
193 /** Return the connection whose ext_or_id is <b>id</b>. Return NULL if no such
194 * connection is found. */
195 or_connection_t *
196 connection_or_get_by_ext_or_id(const char *id)
198 if (!orconn_ext_or_id_map)
199 return NULL;
200 return digestmap_get(orconn_ext_or_id_map, id);
203 /** Deallocate the global Extended ORPort identifier list */
204 void
205 connection_or_clear_ext_or_id_map(void)
207 digestmap_free(orconn_ext_or_id_map, NULL);
208 orconn_ext_or_id_map = NULL;
211 /** Creates an Extended ORPort identifier for <b>conn</b> and deposits
212 * it into the global list of identifiers. */
213 void
214 connection_or_set_ext_or_identifier(or_connection_t *conn)
216 char random_id[EXT_OR_CONN_ID_LEN];
217 or_connection_t *tmp;
219 if (!orconn_ext_or_id_map)
220 orconn_ext_or_id_map = digestmap_new();
222 /* Remove any previous identifiers: */
223 if (conn->ext_or_conn_id && !tor_digest_is_zero(conn->ext_or_conn_id))
224 connection_or_remove_from_ext_or_id_map(conn);
226 do {
227 crypto_rand(random_id, sizeof(random_id));
228 } while (digestmap_get(orconn_ext_or_id_map, random_id));
230 if (!conn->ext_or_conn_id)
231 conn->ext_or_conn_id = tor_malloc_zero(EXT_OR_CONN_ID_LEN);
233 memcpy(conn->ext_or_conn_id, random_id, EXT_OR_CONN_ID_LEN);
235 tmp = digestmap_set(orconn_ext_or_id_map, random_id, conn);
236 tor_assert(!tmp);
239 /**************************************************************/
241 /** Map from a string describing what a non-open OR connection was doing when
242 * failed, to an intptr_t describing the count of connections that failed that
243 * way. Note that the count is stored _as_ the pointer.
245 static strmap_t *broken_connection_counts;
247 /** If true, do not record information in <b>broken_connection_counts</b>. */
248 static int disable_broken_connection_counts = 0;
250 /** Record that an OR connection failed in <b>state</b>. */
251 static void
252 note_broken_connection(const char *state)
254 void *ptr;
255 intptr_t val;
256 if (disable_broken_connection_counts)
257 return;
259 if (!broken_connection_counts)
260 broken_connection_counts = strmap_new();
262 ptr = strmap_get(broken_connection_counts, state);
263 val = (intptr_t)ptr;
264 val++;
265 ptr = (void*)val;
266 strmap_set(broken_connection_counts, state, ptr);
269 /** Forget all recorded states for failed connections. If
270 * <b>stop_recording</b> is true, don't record any more. */
271 void
272 clear_broken_connection_map(int stop_recording)
274 if (broken_connection_counts)
275 strmap_free(broken_connection_counts, NULL);
276 broken_connection_counts = NULL;
277 if (stop_recording)
278 disable_broken_connection_counts = 1;
281 /** Write a detailed description the state of <b>orconn</b> into the
282 * <b>buflen</b>-byte buffer at <b>buf</b>. This description includes not
283 * only the OR-conn level state but also the TLS state. It's useful for
284 * diagnosing broken handshakes. */
285 static void
286 connection_or_get_state_description(or_connection_t *orconn,
287 char *buf, size_t buflen)
289 connection_t *conn = TO_CONN(orconn);
290 const char *conn_state;
291 char tls_state[256];
293 tor_assert(conn->type == CONN_TYPE_OR || conn->type == CONN_TYPE_EXT_OR);
295 conn_state = conn_state_to_string(conn->type, conn->state);
296 tor_tls_get_state_description(orconn->tls, tls_state, sizeof(tls_state));
298 tor_snprintf(buf, buflen, "%s with SSL state %s", conn_state, tls_state);
301 /** Record the current state of <b>orconn</b> as the state of a broken
302 * connection. */
303 static void
304 connection_or_note_state_when_broken(or_connection_t *orconn)
306 char buf[256];
307 if (disable_broken_connection_counts)
308 return;
309 connection_or_get_state_description(orconn, buf, sizeof(buf));
310 log_info(LD_HANDSHAKE,"Connection died in state '%s'", buf);
311 note_broken_connection(buf);
314 /** Helper type used to sort connection states and find the most frequent. */
315 typedef struct broken_state_count_t {
316 intptr_t count;
317 const char *state;
318 } broken_state_count_t;
320 /** Helper function used to sort broken_state_count_t by frequency. */
321 static int
322 broken_state_count_compare(const void **a_ptr, const void **b_ptr)
324 const broken_state_count_t *a = *a_ptr, *b = *b_ptr;
325 if (b->count < a->count)
326 return -1;
327 else if (b->count == a->count)
328 return 0;
329 else
330 return 1;
333 /** Upper limit on the number of different states to report for connection
334 * failure. */
335 #define MAX_REASONS_TO_REPORT 10
337 /** Report a list of the top states for failed OR connections at log level
338 * <b>severity</b>, in log domain <b>domain</b>. */
339 void
340 connection_or_report_broken_states(int severity, int domain)
342 int total = 0;
343 smartlist_t *items;
345 if (!broken_connection_counts || disable_broken_connection_counts)
346 return;
348 items = smartlist_new();
349 STRMAP_FOREACH(broken_connection_counts, state, void *, countptr) {
350 broken_state_count_t *c = tor_malloc(sizeof(broken_state_count_t));
351 c->count = (intptr_t)countptr;
352 total += (int)c->count;
353 c->state = state;
354 smartlist_add(items, c);
355 } STRMAP_FOREACH_END;
357 smartlist_sort(items, broken_state_count_compare);
359 tor_log(severity, domain, "%d connections have failed%s", total,
360 smartlist_len(items) > MAX_REASONS_TO_REPORT ? ". Top reasons:" : ":");
362 SMARTLIST_FOREACH_BEGIN(items, const broken_state_count_t *, c) {
363 if (c_sl_idx > MAX_REASONS_TO_REPORT)
364 break;
365 tor_log(severity, domain,
366 " %d connections died in state %s", (int)c->count, c->state);
367 } SMARTLIST_FOREACH_END(c);
369 SMARTLIST_FOREACH(items, broken_state_count_t *, c, tor_free(c));
370 smartlist_free(items);
373 /** Call this to change or_connection_t states, so the owning channel_tls_t can
374 * be notified.
377 static void
378 connection_or_change_state(or_connection_t *conn, uint8_t state)
380 uint8_t old_state;
382 tor_assert(conn);
384 old_state = conn->base_.state;
385 conn->base_.state = state;
387 if (conn->chan)
388 channel_tls_handle_state_change_on_orconn(conn->chan, conn,
389 old_state, state);
392 /** Return the number of circuits using an or_connection_t; this used to
393 * be an or_connection_t field, but it got moved to channel_t and we
394 * shouldn't maintain two copies. */
396 MOCK_IMPL(int,
397 connection_or_get_num_circuits, (or_connection_t *conn))
399 tor_assert(conn);
401 if (conn->chan) {
402 return channel_num_circuits(TLS_CHAN_TO_BASE(conn->chan));
403 } else return 0;
406 /**************************************************************/
408 /** Pack the cell_t host-order structure <b>src</b> into network-order
409 * in the buffer <b>dest</b>. See tor-spec.txt for details about the
410 * wire format.
412 * Note that this function doesn't touch <b>dst</b>-\>next: the caller
413 * should set it or clear it as appropriate.
415 void
416 cell_pack(packed_cell_t *dst, const cell_t *src, int wide_circ_ids)
418 char *dest = dst->body;
419 if (wide_circ_ids) {
420 set_uint32(dest, htonl(src->circ_id));
421 dest += 4;
422 } else {
423 /* Clear the last two bytes of dest, in case we can accidentally
424 * send them to the network somehow. */
425 memset(dest+CELL_MAX_NETWORK_SIZE-2, 0, 2);
426 set_uint16(dest, htons(src->circ_id));
427 dest += 2;
429 set_uint8(dest, src->command);
430 memcpy(dest+1, src->payload, CELL_PAYLOAD_SIZE);
433 /** Unpack the network-order buffer <b>src</b> into a host-order
434 * cell_t structure <b>dest</b>.
436 static void
437 cell_unpack(cell_t *dest, const char *src, int wide_circ_ids)
439 if (wide_circ_ids) {
440 dest->circ_id = ntohl(get_uint32(src));
441 src += 4;
442 } else {
443 dest->circ_id = ntohs(get_uint16(src));
444 src += 2;
446 dest->command = get_uint8(src);
447 memcpy(dest->payload, src+1, CELL_PAYLOAD_SIZE);
450 /** Write the header of <b>cell</b> into the first VAR_CELL_MAX_HEADER_SIZE
451 * bytes of <b>hdr_out</b>. Returns number of bytes used. */
453 var_cell_pack_header(const var_cell_t *cell, char *hdr_out, int wide_circ_ids)
455 int r;
456 if (wide_circ_ids) {
457 set_uint32(hdr_out, htonl(cell->circ_id));
458 hdr_out += 4;
459 r = VAR_CELL_MAX_HEADER_SIZE;
460 } else {
461 set_uint16(hdr_out, htons(cell->circ_id));
462 hdr_out += 2;
463 r = VAR_CELL_MAX_HEADER_SIZE - 2;
465 set_uint8(hdr_out, cell->command);
466 set_uint16(hdr_out+1, htons(cell->payload_len));
467 return r;
470 /** Allocate and return a new var_cell_t with <b>payload_len</b> bytes of
471 * payload space. */
472 var_cell_t *
473 var_cell_new(uint16_t payload_len)
475 size_t size = STRUCT_OFFSET(var_cell_t, payload) + payload_len;
476 var_cell_t *cell = tor_malloc_zero(size);
477 cell->payload_len = payload_len;
478 cell->command = 0;
479 cell->circ_id = 0;
480 return cell;
484 * Copy a var_cell_t
487 var_cell_t *
488 var_cell_copy(const var_cell_t *src)
490 var_cell_t *copy = NULL;
491 size_t size = 0;
493 if (src != NULL) {
494 size = STRUCT_OFFSET(var_cell_t, payload) + src->payload_len;
495 copy = tor_malloc_zero(size);
496 copy->payload_len = src->payload_len;
497 copy->command = src->command;
498 copy->circ_id = src->circ_id;
499 memcpy(copy->payload, src->payload, copy->payload_len);
502 return copy;
505 /** Release all space held by <b>cell</b>. */
506 void
507 var_cell_free(var_cell_t *cell)
509 tor_free(cell);
512 /** We've received an EOF from <b>conn</b>. Mark it for close and return. */
514 connection_or_reached_eof(or_connection_t *conn)
516 tor_assert(conn);
518 log_info(LD_OR,"OR connection reached EOF. Closing.");
519 connection_or_close_normally(conn, 1);
521 return 0;
524 /** Handle any new bytes that have come in on connection <b>conn</b>.
525 * If conn is in 'open' state, hand it to
526 * connection_or_process_cells_from_inbuf()
527 * (else do nothing).
530 connection_or_process_inbuf(or_connection_t *conn)
532 /** Don't let the inbuf of a nonopen OR connection grow beyond this many
533 * bytes: it's either a broken client, a non-Tor client, or a DOS
534 * attempt. */
535 #define MAX_OR_INBUF_WHEN_NONOPEN 0
537 int ret = 0;
538 tor_assert(conn);
540 switch (conn->base_.state) {
541 case OR_CONN_STATE_PROXY_HANDSHAKING:
542 ret = connection_read_proxy_handshake(TO_CONN(conn));
544 /* start TLS after handshake completion, or deal with error */
545 if (ret == 1) {
546 tor_assert(TO_CONN(conn)->proxy_state == PROXY_CONNECTED);
547 if (connection_tls_start_handshake(conn, 0) < 0)
548 ret = -1;
549 /* Touch the channel's active timestamp if there is one */
550 if (conn->chan)
551 channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
553 if (ret < 0) {
554 connection_or_close_for_error(conn, 0);
557 return ret;
558 case OR_CONN_STATE_TLS_SERVER_RENEGOTIATING:
559 case OR_CONN_STATE_OPEN:
560 case OR_CONN_STATE_OR_HANDSHAKING_V2:
561 case OR_CONN_STATE_OR_HANDSHAKING_V3:
562 return connection_or_process_cells_from_inbuf(conn);
563 default:
564 break; /* don't do anything */
567 /* This check was necessary with 0.2.2, when the TLS_SERVER_RENEGOTIATING
568 * check would otherwise just let data accumulate. It serves no purpose
569 * in 0.2.3.
571 * XXXX Remove this check once we verify that the above paragraph is
572 * 100% true. */
573 if (buf_datalen(conn->base_.inbuf) > MAX_OR_INBUF_WHEN_NONOPEN) {
574 log_fn(LOG_PROTOCOL_WARN, LD_NET, "Accumulated too much data (%d bytes) "
575 "on nonopen OR connection %s %s:%u in state %s; closing.",
576 (int)buf_datalen(conn->base_.inbuf),
577 connection_or_nonopen_was_started_here(conn) ? "to" : "from",
578 conn->base_.address, conn->base_.port,
579 conn_state_to_string(conn->base_.type, conn->base_.state));
580 connection_or_close_for_error(conn, 0);
581 ret = -1;
584 return ret;
587 /** Called whenever we have flushed some data on an or_conn: add more data
588 * from active circuits. */
590 connection_or_flushed_some(or_connection_t *conn)
592 size_t datalen;
594 /* The channel will want to update its estimated queue size */
595 channel_update_xmit_queue_size(TLS_CHAN_TO_BASE(conn->chan));
597 /* If we're under the low water mark, add cells until we're just over the
598 * high water mark. */
599 datalen = connection_get_outbuf_len(TO_CONN(conn));
600 if (datalen < OR_CONN_LOWWATER) {
601 /* Let the scheduler know */
602 scheduler_channel_wants_writes(TLS_CHAN_TO_BASE(conn->chan));
605 return 0;
608 /** This is for channeltls.c to ask how many cells we could accept if
609 * they were available. */
610 ssize_t
611 connection_or_num_cells_writeable(or_connection_t *conn)
613 size_t datalen, cell_network_size;
614 ssize_t n = 0;
616 tor_assert(conn);
619 * If we're under the high water mark, we're potentially
620 * writeable; note this is different from the calculation above
621 * used to trigger when to start writing after we've stopped.
623 datalen = connection_get_outbuf_len(TO_CONN(conn));
624 if (datalen < OR_CONN_HIGHWATER) {
625 cell_network_size = get_cell_network_size(conn->wide_circ_ids);
626 n = CEIL_DIV(OR_CONN_HIGHWATER - datalen, cell_network_size);
629 return n;
632 /** Connection <b>conn</b> has finished writing and has no bytes left on
633 * its outbuf.
635 * Otherwise it's in state "open": stop writing and return.
637 * If <b>conn</b> is broken, mark it for close and return -1, else
638 * return 0.
641 connection_or_finished_flushing(or_connection_t *conn)
643 tor_assert(conn);
644 assert_connection_ok(TO_CONN(conn),0);
646 switch (conn->base_.state) {
647 case OR_CONN_STATE_PROXY_HANDSHAKING:
648 case OR_CONN_STATE_OPEN:
649 case OR_CONN_STATE_OR_HANDSHAKING_V2:
650 case OR_CONN_STATE_OR_HANDSHAKING_V3:
651 break;
652 default:
653 log_err(LD_BUG,"Called in unexpected state %d.", conn->base_.state);
654 tor_fragile_assert();
655 return -1;
657 return 0;
660 /** Connected handler for OR connections: begin the TLS handshake.
663 connection_or_finished_connecting(or_connection_t *or_conn)
665 const int proxy_type = or_conn->proxy_type;
666 connection_t *conn;
668 tor_assert(or_conn);
669 conn = TO_CONN(or_conn);
670 tor_assert(conn->state == OR_CONN_STATE_CONNECTING);
672 log_debug(LD_HANDSHAKE,"OR connect() to router at %s:%u finished.",
673 conn->address,conn->port);
674 control_event_bootstrap(BOOTSTRAP_STATUS_HANDSHAKE, 0);
676 if (proxy_type != PROXY_NONE) {
677 /* start proxy handshake */
678 if (connection_proxy_connect(conn, proxy_type) < 0) {
679 connection_or_close_for_error(or_conn, 0);
680 return -1;
683 connection_start_reading(conn);
684 connection_or_change_state(or_conn, OR_CONN_STATE_PROXY_HANDSHAKING);
685 return 0;
688 if (connection_tls_start_handshake(or_conn, 0) < 0) {
689 /* TLS handshaking error of some kind. */
690 connection_or_close_for_error(or_conn, 0);
691 return -1;
693 return 0;
696 /** Called when we're about to finally unlink and free an OR connection:
697 * perform necessary accounting and cleanup */
698 void
699 connection_or_about_to_close(or_connection_t *or_conn)
701 time_t now = time(NULL);
702 connection_t *conn = TO_CONN(or_conn);
704 /* Tell the controlling channel we're closed */
705 if (or_conn->chan) {
706 channel_closed(TLS_CHAN_TO_BASE(or_conn->chan));
708 * NULL this out because the channel might hang around a little
709 * longer before channel_run_cleanup() gets it.
711 or_conn->chan->conn = NULL;
712 or_conn->chan = NULL;
715 /* Remember why we're closing this connection. */
716 if (conn->state != OR_CONN_STATE_OPEN) {
717 /* now mark things down as needed */
718 if (connection_or_nonopen_was_started_here(or_conn)) {
719 const or_options_t *options = get_options();
720 connection_or_note_state_when_broken(or_conn);
721 rep_hist_note_connect_failed(or_conn->identity_digest, now);
722 /* Tell the new guard API about the channel failure */
723 entry_guard_chan_failed(TLS_CHAN_TO_BASE(or_conn->chan));
724 if (conn->state >= OR_CONN_STATE_TLS_HANDSHAKING) {
725 int reason = tls_error_to_orconn_end_reason(or_conn->tls_error);
726 control_event_or_conn_status(or_conn, OR_CONN_EVENT_FAILED,
727 reason);
728 if (!authdir_mode_tests_reachability(options))
729 control_event_bootstrap_problem(
730 orconn_end_reason_to_control_string(reason),
731 reason, or_conn);
734 } else if (conn->hold_open_until_flushed) {
735 /* We only set hold_open_until_flushed when we're intentionally
736 * closing a connection. */
737 rep_hist_note_disconnect(or_conn->identity_digest, now);
738 control_event_or_conn_status(or_conn, OR_CONN_EVENT_CLOSED,
739 tls_error_to_orconn_end_reason(or_conn->tls_error));
740 } else if (!tor_digest_is_zero(or_conn->identity_digest)) {
741 rep_hist_note_connection_died(or_conn->identity_digest, now);
742 control_event_or_conn_status(or_conn, OR_CONN_EVENT_CLOSED,
743 tls_error_to_orconn_end_reason(or_conn->tls_error));
747 /** Return 1 if identity digest <b>id_digest</b> is known to be a
748 * currently or recently running relay. Otherwise return 0. */
750 connection_or_digest_is_known_relay(const char *id_digest)
752 if (router_get_consensus_status_by_id(id_digest))
753 return 1; /* It's in the consensus: "yes" */
754 if (router_get_by_id_digest(id_digest))
755 return 1; /* Not in the consensus, but we have a descriptor for
756 * it. Probably it was in a recent consensus. "Yes". */
757 return 0;
760 /** Set the per-conn read and write limits for <b>conn</b>. If it's a known
761 * relay, we will rely on the global read and write buckets, so give it
762 * per-conn limits that are big enough they'll never matter. But if it's
763 * not a known relay, first check if we set PerConnBwRate/Burst, then
764 * check if the consensus sets them, else default to 'big enough'.
766 * If <b>reset</b> is true, set the bucket to be full. Otherwise, just
767 * clip the bucket if it happens to be <em>too</em> full.
769 static void
770 connection_or_update_token_buckets_helper(or_connection_t *conn, int reset,
771 const or_options_t *options)
773 int rate, burst; /* per-connection rate limiting params */
774 if (connection_or_digest_is_known_relay(conn->identity_digest)) {
775 /* It's in the consensus, or we have a descriptor for it meaning it
776 * was probably in a recent consensus. It's a recognized relay:
777 * give it full bandwidth. */
778 rate = (int)options->BandwidthRate;
779 burst = (int)options->BandwidthBurst;
780 } else {
781 /* Not a recognized relay. Squeeze it down based on the suggested
782 * bandwidth parameters in the consensus, but allow local config
783 * options to override. */
784 rate = options->PerConnBWRate ? (int)options->PerConnBWRate :
785 networkstatus_get_param(NULL, "perconnbwrate",
786 (int)options->BandwidthRate, 1, INT32_MAX);
787 burst = options->PerConnBWBurst ? (int)options->PerConnBWBurst :
788 networkstatus_get_param(NULL, "perconnbwburst",
789 (int)options->BandwidthBurst, 1, INT32_MAX);
792 conn->bandwidthrate = rate;
793 conn->bandwidthburst = burst;
794 if (reset) { /* set up the token buckets to be full */
795 conn->read_bucket = conn->write_bucket = burst;
796 return;
798 /* If the new token bucket is smaller, take out the extra tokens.
799 * (If it's larger, don't -- the buckets can grow to reach the cap.) */
800 if (conn->read_bucket > burst)
801 conn->read_bucket = burst;
802 if (conn->write_bucket > burst)
803 conn->write_bucket = burst;
806 /** Either our set of relays or our per-conn rate limits have changed.
807 * Go through all the OR connections and update their token buckets to make
808 * sure they don't exceed their maximum values. */
809 void
810 connection_or_update_token_buckets(smartlist_t *conns,
811 const or_options_t *options)
813 SMARTLIST_FOREACH(conns, connection_t *, conn,
815 if (connection_speaks_cells(conn))
816 connection_or_update_token_buckets_helper(TO_OR_CONN(conn), 0, options);
820 /* Mark <b>or_conn</b> as canonical if <b>is_canonical</b> is set, and
821 * non-canonical otherwise. Adjust idle_timeout accordingly.
823 void
824 connection_or_set_canonical(or_connection_t *or_conn,
825 int is_canonical)
827 if (bool_eq(is_canonical, or_conn->is_canonical) &&
828 or_conn->idle_timeout != 0) {
829 /* Don't recalculate an existing idle_timeout unless the canonical
830 * status changed. */
831 return;
834 or_conn->is_canonical = !! is_canonical; /* force to a 1-bit boolean */
835 or_conn->idle_timeout = channelpadding_get_channel_idle_timeout(
836 TLS_CHAN_TO_BASE(or_conn->chan), is_canonical);
838 log_info(LD_CIRC,
839 "Channel " U64_FORMAT " chose an idle timeout of %d.",
840 or_conn->chan ?
841 U64_PRINTF_ARG(TLS_CHAN_TO_BASE(or_conn->chan)->global_identifier):0,
842 or_conn->idle_timeout);
845 /** If we don't necessarily know the router we're connecting to, but we
846 * have an addr/port/id_digest, then fill in as much as we can. Start
847 * by checking to see if this describes a router we know.
848 * <b>started_here</b> is 1 if we are the initiator of <b>conn</b> and
849 * 0 if it's an incoming connection. */
850 void
851 connection_or_init_conn_from_address(or_connection_t *conn,
852 const tor_addr_t *addr, uint16_t port,
853 const char *id_digest,
854 const ed25519_public_key_t *ed_id,
855 int started_here)
857 log_debug(LD_HANDSHAKE, "init conn from address %s: %s, %s (%d)",
858 fmt_addr(addr),
859 hex_str((const char*)id_digest, DIGEST_LEN),
860 ed25519_fmt(ed_id),
861 started_here);
863 connection_or_set_identity_digest(conn, id_digest, ed_id);
864 connection_or_update_token_buckets_helper(conn, 1, get_options());
866 conn->base_.port = port;
867 tor_addr_copy(&conn->base_.addr, addr);
868 tor_addr_copy(&conn->real_addr, addr);
870 connection_or_check_canonicity(conn, started_here);
873 /** Check whether the identity of <b>conn</b> matches a known node. If it
874 * does, check whether the address of conn matches the expected address, and
875 * update the connection's is_canonical flag, nickname, and address fields as
876 * appropriate. */
877 static void
878 connection_or_check_canonicity(or_connection_t *conn, int started_here)
880 const char *id_digest = conn->identity_digest;
881 const ed25519_public_key_t *ed_id = NULL;
882 const tor_addr_t *addr = &conn->real_addr;
883 if (conn->chan)
884 ed_id = & TLS_CHAN_TO_BASE(conn->chan)->ed25519_identity;
886 const node_t *r = node_get_by_id(id_digest);
887 if (r &&
888 node_supports_ed25519_link_authentication(r) &&
889 ! node_ed25519_id_matches(r, ed_id)) {
890 /* If this node is capable of proving an ed25519 ID,
891 * we can't call this a canonical connection unless both IDs match. */
892 r = NULL;
895 if (r) {
896 tor_addr_port_t node_ap;
897 node_get_pref_orport(r, &node_ap);
898 /* XXXX proposal 186 is making this more complex. For now, a conn
899 is canonical when it uses the _preferred_ address. */
900 if (tor_addr_eq(&conn->base_.addr, &node_ap.addr))
901 connection_or_set_canonical(conn, 1);
902 if (!started_here) {
903 /* Override the addr/port, so our log messages will make sense.
904 * This is dangerous, since if we ever try looking up a conn by
905 * its actual addr/port, we won't remember. Careful! */
906 /* XXXX arma: this is stupid, and it's the reason we need real_addr
907 * to track is_canonical properly. What requires it? */
908 /* XXXX <arma> i believe the reason we did this, originally, is because
909 * we wanted to log what OR a connection was to, and if we logged the
910 * right IP address and port 56244, that wouldn't be as helpful. now we
911 * log the "right" port too, so we know if it's moria1 or moria2.
913 tor_addr_copy(&conn->base_.addr, &node_ap.addr);
914 conn->base_.port = node_ap.port;
916 tor_free(conn->nickname);
917 conn->nickname = tor_strdup(node_get_nickname(r));
918 tor_free(conn->base_.address);
919 conn->base_.address = tor_addr_to_str_dup(&node_ap.addr);
920 } else {
921 tor_free(conn->nickname);
922 conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
923 conn->nickname[0] = '$';
924 base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
925 conn->identity_digest, DIGEST_LEN);
927 tor_free(conn->base_.address);
928 conn->base_.address = tor_addr_to_str_dup(addr);
932 * We have to tell channeltls.c to update the channel marks (local, in
933 * particular), since we may have changed the address.
936 if (conn->chan) {
937 channel_tls_update_marks(conn);
941 /** These just pass all the is_bad_for_new_circs manipulation on to
942 * channel_t */
944 static unsigned int
945 connection_or_is_bad_for_new_circs(or_connection_t *or_conn)
947 tor_assert(or_conn);
949 if (or_conn->chan)
950 return channel_is_bad_for_new_circs(TLS_CHAN_TO_BASE(or_conn->chan));
951 else return 0;
954 static void
955 connection_or_mark_bad_for_new_circs(or_connection_t *or_conn)
957 tor_assert(or_conn);
959 if (or_conn->chan)
960 channel_mark_bad_for_new_circs(TLS_CHAN_TO_BASE(or_conn->chan));
963 /** How old do we let a connection to an OR get before deciding it's
964 * too old for new circuits? */
965 #define TIME_BEFORE_OR_CONN_IS_TOO_OLD (60*60*24*7)
967 /** Given a list of all the or_connections with a given
968 * identity, set elements of that list as is_bad_for_new_circs as
969 * appropriate. Helper for connection_or_set_bad_connections().
971 * Specifically, we set the is_bad_for_new_circs flag on:
972 * - all connections if <b>force</b> is true.
973 * - all connections that are too old.
974 * - all open non-canonical connections for which a canonical connection
975 * exists to the same router.
976 * - all open canonical connections for which a 'better' canonical
977 * connection exists to the same router.
978 * - all open non-canonical connections for which a 'better' non-canonical
979 * connection exists to the same router at the same address.
981 * See channel_is_better() in channel.c for our idea of what makes one OR
982 * connection better than another.
984 void
985 connection_or_group_set_badness_(smartlist_t *group, int force)
987 /* XXXX this function should be entirely about channels, not OR
988 * XXXX connections. */
990 or_connection_t *best = NULL;
991 int n_old = 0, n_inprogress = 0, n_canonical = 0, n_other = 0;
992 time_t now = time(NULL);
994 /* Pass 1: expire everything that's old, and see what the status of
995 * everything else is. */
996 SMARTLIST_FOREACH_BEGIN(group, or_connection_t *, or_conn) {
997 if (or_conn->base_.marked_for_close ||
998 connection_or_is_bad_for_new_circs(or_conn))
999 continue;
1000 if (force ||
1001 or_conn->base_.timestamp_created + TIME_BEFORE_OR_CONN_IS_TOO_OLD
1002 < now) {
1003 log_info(LD_OR,
1004 "Marking OR conn to %s:%d as too old for new circuits "
1005 "(fd "TOR_SOCKET_T_FORMAT", %d secs old).",
1006 or_conn->base_.address, or_conn->base_.port, or_conn->base_.s,
1007 (int)(now - or_conn->base_.timestamp_created));
1008 connection_or_mark_bad_for_new_circs(or_conn);
1011 if (connection_or_is_bad_for_new_circs(or_conn)) {
1012 ++n_old;
1013 } else if (or_conn->base_.state != OR_CONN_STATE_OPEN) {
1014 ++n_inprogress;
1015 } else if (or_conn->is_canonical) {
1016 ++n_canonical;
1017 } else {
1018 ++n_other;
1020 } SMARTLIST_FOREACH_END(or_conn);
1022 /* Pass 2: We know how about how good the best connection is.
1023 * expire everything that's worse, and find the very best if we can. */
1024 SMARTLIST_FOREACH_BEGIN(group, or_connection_t *, or_conn) {
1025 if (or_conn->base_.marked_for_close ||
1026 connection_or_is_bad_for_new_circs(or_conn))
1027 continue; /* This one doesn't need to be marked bad. */
1028 if (or_conn->base_.state != OR_CONN_STATE_OPEN)
1029 continue; /* Don't mark anything bad until we have seen what happens
1030 * when the connection finishes. */
1031 if (n_canonical && !or_conn->is_canonical) {
1032 /* We have at least one open canonical connection to this router,
1033 * and this one is open but not canonical. Mark it bad. */
1034 log_info(LD_OR,
1035 "Marking OR conn to %s:%d as unsuitable for new circuits: "
1036 "(fd "TOR_SOCKET_T_FORMAT", %d secs old). It is not "
1037 "canonical, and we have another connection to that OR that is.",
1038 or_conn->base_.address, or_conn->base_.port, or_conn->base_.s,
1039 (int)(now - or_conn->base_.timestamp_created));
1040 connection_or_mark_bad_for_new_circs(or_conn);
1041 continue;
1044 if (!best ||
1045 channel_is_better(TLS_CHAN_TO_BASE(or_conn->chan),
1046 TLS_CHAN_TO_BASE(best->chan))) {
1047 best = or_conn;
1049 } SMARTLIST_FOREACH_END(or_conn);
1051 if (!best)
1052 return;
1054 /* Pass 3: One connection to OR is best. If it's canonical, mark as bad
1055 * every other open connection. If it's non-canonical, mark as bad
1056 * every other open connection to the same address.
1058 * XXXX This isn't optimal; if we have connections to an OR at multiple
1059 * addresses, we'd like to pick the best _for each address_, and mark as
1060 * bad every open connection that isn't best for its address. But this
1061 * can only occur in cases where the other OR is old (so we have no
1062 * canonical connection to it), or where all the connections to the OR are
1063 * at noncanonical addresses and we have no good direct connection (which
1064 * means we aren't at risk of attaching circuits to it anyway). As
1065 * 0.1.2.x dies out, the first case will go away, and the second one is
1066 * "mostly harmless", so a fix can wait until somebody is bored.
1068 SMARTLIST_FOREACH_BEGIN(group, or_connection_t *, or_conn) {
1069 if (or_conn->base_.marked_for_close ||
1070 connection_or_is_bad_for_new_circs(or_conn) ||
1071 or_conn->base_.state != OR_CONN_STATE_OPEN)
1072 continue;
1073 if (or_conn != best &&
1074 channel_is_better(TLS_CHAN_TO_BASE(best->chan),
1075 TLS_CHAN_TO_BASE(or_conn->chan))) {
1076 /* This isn't the best conn, _and_ the best conn is better than it */
1077 if (best->is_canonical) {
1078 log_info(LD_OR,
1079 "Marking OR conn to %s:%d as unsuitable for new circuits: "
1080 "(fd "TOR_SOCKET_T_FORMAT", %d secs old). "
1081 "We have a better canonical one "
1082 "(fd "TOR_SOCKET_T_FORMAT"; %d secs old).",
1083 or_conn->base_.address, or_conn->base_.port, or_conn->base_.s,
1084 (int)(now - or_conn->base_.timestamp_created),
1085 best->base_.s, (int)(now - best->base_.timestamp_created));
1086 connection_or_mark_bad_for_new_circs(or_conn);
1087 } else if (!tor_addr_compare(&or_conn->real_addr,
1088 &best->real_addr, CMP_EXACT)) {
1089 log_info(LD_OR,
1090 "Marking OR conn to %s:%d as unsuitable for new circuits: "
1091 "(fd "TOR_SOCKET_T_FORMAT", %d secs old). We have a better "
1092 "one with the "
1093 "same address (fd "TOR_SOCKET_T_FORMAT"; %d secs old).",
1094 or_conn->base_.address, or_conn->base_.port, or_conn->base_.s,
1095 (int)(now - or_conn->base_.timestamp_created),
1096 best->base_.s, (int)(now - best->base_.timestamp_created));
1097 connection_or_mark_bad_for_new_circs(or_conn);
1100 } SMARTLIST_FOREACH_END(or_conn);
1103 /** <b>conn</b> is in the 'connecting' state, and it failed to complete
1104 * a TCP connection. Send notifications appropriately.
1106 * <b>reason</b> specifies the or_conn_end_reason for the failure;
1107 * <b>msg</b> specifies the strerror-style error message.
1109 void
1110 connection_or_connect_failed(or_connection_t *conn,
1111 int reason, const char *msg)
1113 control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED, reason);
1114 if (!authdir_mode_tests_reachability(get_options()))
1115 control_event_bootstrap_problem(msg, reason, conn);
1118 /** <b>conn</b> got an error in connection_handle_read_impl() or
1119 * connection_handle_write_impl() and is going to die soon.
1121 * <b>reason</b> specifies the or_conn_end_reason for the failure;
1122 * <b>msg</b> specifies the strerror-style error message.
1124 void
1125 connection_or_notify_error(or_connection_t *conn,
1126 int reason, const char *msg)
1128 channel_t *chan;
1130 tor_assert(conn);
1132 /* If we're connecting, call connect_failed() too */
1133 if (TO_CONN(conn)->state == OR_CONN_STATE_CONNECTING)
1134 connection_or_connect_failed(conn, reason, msg);
1136 /* Tell the controlling channel if we have one */
1137 if (conn->chan) {
1138 chan = TLS_CHAN_TO_BASE(conn->chan);
1139 /* Don't transition if we're already in closing, closed or error */
1140 if (!CHANNEL_CONDEMNED(chan)) {
1141 channel_close_for_error(chan);
1145 /* No need to mark for error because connection.c is about to do that */
1148 /** Launch a new OR connection to <b>addr</b>:<b>port</b> and expect to
1149 * handshake with an OR with identity digest <b>id_digest</b>. Optionally,
1150 * pass in a pointer to a channel using this connection.
1152 * If <b>id_digest</b> is me, do nothing. If we're already connected to it,
1153 * return that connection. If the connect() is in progress, set the
1154 * new conn's state to 'connecting' and return it. If connect() succeeds,
1155 * call connection_tls_start_handshake() on it.
1157 * This function is called from router_retry_connections(), for
1158 * ORs connecting to ORs, and circuit_establish_circuit(), for
1159 * OPs connecting to ORs.
1161 * Return the launched conn, or NULL if it failed.
1164 MOCK_IMPL(or_connection_t *,
1165 connection_or_connect, (const tor_addr_t *_addr, uint16_t port,
1166 const char *id_digest,
1167 const ed25519_public_key_t *ed_id,
1168 channel_tls_t *chan))
1170 or_connection_t *conn;
1171 const or_options_t *options = get_options();
1172 int socket_error = 0;
1173 tor_addr_t addr;
1175 int r;
1176 tor_addr_t proxy_addr;
1177 uint16_t proxy_port;
1178 int proxy_type;
1180 tor_assert(_addr);
1181 tor_assert(id_digest);
1182 tor_addr_copy(&addr, _addr);
1184 if (server_mode(options) && router_digest_is_me(id_digest)) {
1185 log_info(LD_PROTOCOL,"Client asked me to connect to myself. Refusing.");
1186 return NULL;
1188 if (server_mode(options) && router_ed25519_id_is_me(ed_id)) {
1189 log_info(LD_PROTOCOL,"Client asked me to connect to myself by Ed25519 "
1190 "identity. Refusing.");
1191 return NULL;
1194 conn = or_connection_new(CONN_TYPE_OR, tor_addr_family(&addr));
1197 * Set up conn so it's got all the data we need to remember for channels
1199 * This stuff needs to happen before connection_or_init_conn_from_address()
1200 * so connection_or_set_identity_digest() and such know where to look to
1201 * keep the channel up to date.
1203 conn->chan = chan;
1204 chan->conn = conn;
1205 connection_or_init_conn_from_address(conn, &addr, port, id_digest, ed_id, 1);
1206 connection_or_change_state(conn, OR_CONN_STATE_CONNECTING);
1207 control_event_or_conn_status(conn, OR_CONN_EVENT_LAUNCHED, 0);
1209 conn->is_outgoing = 1;
1211 /* If we are using a proxy server, find it and use it. */
1212 r = get_proxy_addrport(&proxy_addr, &proxy_port, &proxy_type, TO_CONN(conn));
1213 if (r == 0) {
1214 conn->proxy_type = proxy_type;
1215 if (proxy_type != PROXY_NONE) {
1216 tor_addr_copy(&addr, &proxy_addr);
1217 port = proxy_port;
1218 conn->base_.proxy_state = PROXY_INFANT;
1220 } else {
1221 /* get_proxy_addrport() might fail if we have a Bridge line that
1222 references a transport, but no ClientTransportPlugin lines
1223 defining its transport proxy. If this is the case, let's try to
1224 output a useful log message to the user. */
1225 const char *transport_name =
1226 find_transport_name_by_bridge_addrport(&TO_CONN(conn)->addr,
1227 TO_CONN(conn)->port);
1229 if (transport_name) {
1230 log_warn(LD_GENERAL, "We were supposed to connect to bridge '%s' "
1231 "using pluggable transport '%s', but we can't find a pluggable "
1232 "transport proxy supporting '%s'. This can happen if you "
1233 "haven't provided a ClientTransportPlugin line, or if "
1234 "your pluggable transport proxy stopped running.",
1235 fmt_addrport(&TO_CONN(conn)->addr, TO_CONN(conn)->port),
1236 transport_name, transport_name);
1238 control_event_bootstrap_problem(
1239 "Can't connect to bridge",
1240 END_OR_CONN_REASON_PT_MISSING,
1241 conn);
1243 } else {
1244 log_warn(LD_GENERAL, "Tried to connect to '%s' through a proxy, but "
1245 "the proxy address could not be found.",
1246 fmt_addrport(&TO_CONN(conn)->addr, TO_CONN(conn)->port));
1249 connection_free(TO_CONN(conn));
1250 return NULL;
1253 switch (connection_connect(TO_CONN(conn), conn->base_.address,
1254 &addr, port, &socket_error)) {
1255 case -1:
1256 /* We failed to establish a connection probably because of a local
1257 * error. No need to blame the guard in this case. Notify the networking
1258 * system of this failure. */
1259 connection_or_connect_failed(conn,
1260 errno_to_orconn_end_reason(socket_error),
1261 tor_socket_strerror(socket_error));
1262 connection_free(TO_CONN(conn));
1263 return NULL;
1264 case 0:
1265 connection_watch_events(TO_CONN(conn), READ_EVENT | WRITE_EVENT);
1266 /* writable indicates finish, readable indicates broken link,
1267 error indicates broken link on windows */
1268 return conn;
1269 /* case 1: fall through */
1272 if (connection_or_finished_connecting(conn) < 0) {
1273 /* already marked for close */
1274 return NULL;
1276 return conn;
1279 /** Mark orconn for close and transition the associated channel, if any, to
1280 * the closing state.
1282 * It's safe to call this and connection_or_close_for_error() any time, and
1283 * channel layer will treat it as a connection closing for reasons outside
1284 * its control, like the remote end closing it. It can also be a local
1285 * reason that's specific to connection_t/or_connection_t rather than
1286 * the channel mechanism, such as expiration of old connections in
1287 * run_connection_housekeeping(). If you want to close a channel_t
1288 * from somewhere that logically works in terms of generic channels
1289 * rather than connections, use channel_mark_for_close(); see also
1290 * the comment on that function in channel.c.
1293 void
1294 connection_or_close_normally(or_connection_t *orconn, int flush)
1296 channel_t *chan = NULL;
1298 tor_assert(orconn);
1299 if (flush) connection_mark_and_flush_internal(TO_CONN(orconn));
1300 else connection_mark_for_close_internal(TO_CONN(orconn));
1301 if (orconn->chan) {
1302 chan = TLS_CHAN_TO_BASE(orconn->chan);
1303 /* Don't transition if we're already in closing, closed or error */
1304 if (!CHANNEL_CONDEMNED(chan)) {
1305 channel_close_from_lower_layer(chan);
1310 /** Mark orconn for close and transition the associated channel, if any, to
1311 * the error state.
1314 MOCK_IMPL(void,
1315 connection_or_close_for_error,(or_connection_t *orconn, int flush))
1317 channel_t *chan = NULL;
1319 tor_assert(orconn);
1320 if (flush) connection_mark_and_flush_internal(TO_CONN(orconn));
1321 else connection_mark_for_close_internal(TO_CONN(orconn));
1322 if (orconn->chan) {
1323 chan = TLS_CHAN_TO_BASE(orconn->chan);
1324 /* Don't transition if we're already in closing, closed or error */
1325 if (!CHANNEL_CONDEMNED(chan)) {
1326 channel_close_for_error(chan);
1331 /** Begin the tls handshake with <b>conn</b>. <b>receiving</b> is 0 if
1332 * we initiated the connection, else it's 1.
1334 * Assign a new tls object to conn->tls, begin reading on <b>conn</b>, and
1335 * pass <b>conn</b> to connection_tls_continue_handshake().
1337 * Return -1 if <b>conn</b> is broken, else return 0.
1339 MOCK_IMPL(int,
1340 connection_tls_start_handshake,(or_connection_t *conn, int receiving))
1342 channel_listener_t *chan_listener;
1343 channel_t *chan;
1345 /* Incoming connections will need a new channel passed to the
1346 * channel_tls_listener */
1347 if (receiving) {
1348 /* It shouldn't already be set */
1349 tor_assert(!(conn->chan));
1350 chan_listener = channel_tls_get_listener();
1351 if (!chan_listener) {
1352 chan_listener = channel_tls_start_listener();
1353 command_setup_listener(chan_listener);
1355 chan = channel_tls_handle_incoming(conn);
1356 channel_listener_queue_incoming(chan_listener, chan);
1359 connection_or_change_state(conn, OR_CONN_STATE_TLS_HANDSHAKING);
1360 tor_assert(!conn->tls);
1361 conn->tls = tor_tls_new(conn->base_.s, receiving);
1362 if (!conn->tls) {
1363 log_warn(LD_BUG,"tor_tls_new failed. Closing.");
1364 return -1;
1366 tor_tls_set_logged_address(conn->tls, // XXX client and relay?
1367 escaped_safe_str(conn->base_.address));
1369 connection_start_reading(TO_CONN(conn));
1370 log_debug(LD_HANDSHAKE,"starting TLS handshake on fd "TOR_SOCKET_T_FORMAT,
1371 conn->base_.s);
1372 note_crypto_pk_op(receiving ? TLS_HANDSHAKE_S : TLS_HANDSHAKE_C);
1374 if (connection_tls_continue_handshake(conn) < 0)
1375 return -1;
1377 return 0;
1380 /** Block all future attempts to renegotiate on 'conn' */
1381 void
1382 connection_or_block_renegotiation(or_connection_t *conn)
1384 tor_tls_t *tls = conn->tls;
1385 if (!tls)
1386 return;
1387 tor_tls_set_renegotiate_callback(tls, NULL, NULL);
1388 tor_tls_block_renegotiation(tls);
1391 /** Invoked on the server side from inside tor_tls_read() when the server
1392 * gets a successful TLS renegotiation from the client. */
1393 static void
1394 connection_or_tls_renegotiated_cb(tor_tls_t *tls, void *_conn)
1396 or_connection_t *conn = _conn;
1397 (void)tls;
1399 /* Don't invoke this again. */
1400 connection_or_block_renegotiation(conn);
1402 if (connection_tls_finish_handshake(conn) < 0) {
1403 /* XXXX_TLS double-check that it's ok to do this from inside read. */
1404 /* XXXX_TLS double-check that this verifies certificates. */
1405 connection_or_close_for_error(conn, 0);
1409 /** Move forward with the tls handshake. If it finishes, hand
1410 * <b>conn</b> to connection_tls_finish_handshake().
1412 * Return -1 if <b>conn</b> is broken, else return 0.
1415 connection_tls_continue_handshake(or_connection_t *conn)
1417 int result;
1418 check_no_tls_errors();
1420 tor_assert(conn->base_.state == OR_CONN_STATE_TLS_HANDSHAKING);
1421 // log_notice(LD_OR, "Continue handshake with %p", conn->tls);
1422 result = tor_tls_handshake(conn->tls);
1423 // log_notice(LD_OR, "Result: %d", result);
1425 switch (result) {
1426 CASE_TOR_TLS_ERROR_ANY:
1427 log_info(LD_OR,"tls error [%s]. breaking connection.",
1428 tor_tls_err_to_string(result));
1429 return -1;
1430 case TOR_TLS_DONE:
1431 if (! tor_tls_used_v1_handshake(conn->tls)) {
1432 if (!tor_tls_is_server(conn->tls)) {
1433 tor_assert(conn->base_.state == OR_CONN_STATE_TLS_HANDSHAKING);
1434 return connection_or_launch_v3_or_handshake(conn);
1435 } else {
1436 /* v2/v3 handshake, but we are not a client. */
1437 log_debug(LD_OR, "Done with initial SSL handshake (server-side). "
1438 "Expecting renegotiation or VERSIONS cell");
1439 tor_tls_set_renegotiate_callback(conn->tls,
1440 connection_or_tls_renegotiated_cb,
1441 conn);
1442 connection_or_change_state(conn,
1443 OR_CONN_STATE_TLS_SERVER_RENEGOTIATING);
1444 connection_stop_writing(TO_CONN(conn));
1445 connection_start_reading(TO_CONN(conn));
1446 return 0;
1449 tor_assert(tor_tls_is_server(conn->tls));
1450 return connection_tls_finish_handshake(conn);
1451 case TOR_TLS_WANTWRITE:
1452 connection_start_writing(TO_CONN(conn));
1453 log_debug(LD_OR,"wanted write");
1454 return 0;
1455 case TOR_TLS_WANTREAD: /* handshaking conns are *always* reading */
1456 log_debug(LD_OR,"wanted read");
1457 return 0;
1458 case TOR_TLS_CLOSE:
1459 log_info(LD_OR,"tls closed. breaking connection.");
1460 return -1;
1462 return 0;
1465 /** Return 1 if we initiated this connection, or 0 if it started
1466 * out as an incoming connection.
1469 connection_or_nonopen_was_started_here(or_connection_t *conn)
1471 tor_assert(conn->base_.type == CONN_TYPE_OR ||
1472 conn->base_.type == CONN_TYPE_EXT_OR);
1473 if (!conn->tls)
1474 return 1; /* it's still in proxy states or something */
1475 if (conn->handshake_state)
1476 return conn->handshake_state->started_here;
1477 return !tor_tls_is_server(conn->tls);
1480 /** <b>Conn</b> just completed its handshake. Return 0 if all is well, and
1481 * return -1 if they are lying, broken, or otherwise something is wrong.
1483 * If we initiated this connection (<b>started_here</b> is true), make sure
1484 * the other side sent a correctly formed certificate. If I initiated the
1485 * connection, make sure it's the right relay by checking the certificate.
1487 * Otherwise (if we _didn't_ initiate this connection), it's okay for
1488 * the certificate to be weird or absent.
1490 * If we return 0, and the certificate is as expected, write a hash of the
1491 * identity key into <b>digest_rcvd_out</b>, which must have DIGEST_LEN
1492 * space in it.
1493 * If the certificate is invalid or missing on an incoming connection,
1494 * we return 0 and set <b>digest_rcvd_out</b> to DIGEST_LEN NUL bytes.
1495 * (If we return -1, the contents of this buffer are undefined.)
1497 * As side effects,
1498 * 1) Set conn->circ_id_type according to tor-spec.txt.
1499 * 2) If we're an authdirserver and we initiated the connection: drop all
1500 * descriptors that claim to be on that IP/port but that aren't
1501 * this relay; and note that this relay is reachable.
1502 * 3) If this is a bridge and we didn't configure its identity
1503 * fingerprint, remember the keyid we just learned.
1505 static int
1506 connection_or_check_valid_tls_handshake(or_connection_t *conn,
1507 int started_here,
1508 char *digest_rcvd_out)
1510 crypto_pk_t *identity_rcvd=NULL;
1511 const or_options_t *options = get_options();
1512 int severity = server_mode(options) ? LOG_PROTOCOL_WARN : LOG_WARN;
1513 const char *safe_address =
1514 started_here ? conn->base_.address :
1515 safe_str_client(conn->base_.address);
1516 const char *conn_type = started_here ? "outgoing" : "incoming";
1517 int has_cert = 0;
1519 check_no_tls_errors();
1520 has_cert = tor_tls_peer_has_cert(conn->tls);
1521 if (started_here && !has_cert) {
1522 log_info(LD_HANDSHAKE,"Tried connecting to router at %s:%d, but it didn't "
1523 "send a cert! Closing.",
1524 safe_address, conn->base_.port);
1525 return -1;
1526 } else if (!has_cert) {
1527 log_debug(LD_HANDSHAKE,"Got incoming connection with no certificate. "
1528 "That's ok.");
1530 check_no_tls_errors();
1532 if (has_cert) {
1533 int v = tor_tls_verify(started_here?severity:LOG_INFO,
1534 conn->tls, &identity_rcvd);
1535 if (started_here && v<0) {
1536 log_fn(severity,LD_HANDSHAKE,"Tried connecting to router at %s:%d: It"
1537 " has a cert but it's invalid. Closing.",
1538 safe_address, conn->base_.port);
1539 return -1;
1540 } else if (v<0) {
1541 log_info(LD_HANDSHAKE,"Incoming connection gave us an invalid cert "
1542 "chain; ignoring.");
1543 } else {
1544 log_debug(LD_HANDSHAKE,
1545 "The certificate seems to be valid on %s connection "
1546 "with %s:%d", conn_type, safe_address, conn->base_.port);
1548 check_no_tls_errors();
1551 if (identity_rcvd) {
1552 if (crypto_pk_get_digest(identity_rcvd, digest_rcvd_out) < 0) {
1553 return -1;
1555 } else {
1556 memset(digest_rcvd_out, 0, DIGEST_LEN);
1559 tor_assert(conn->chan);
1560 channel_set_circid_type(TLS_CHAN_TO_BASE(conn->chan), identity_rcvd, 1);
1562 crypto_pk_free(identity_rcvd);
1564 if (started_here) {
1565 /* A TLS handshake can't teach us an Ed25519 ID, so we set it to NULL
1566 * here. */
1567 log_debug(LD_HANDSHAKE, "Calling client_learned_peer_id from "
1568 "check_valid_tls_handshake");
1569 return connection_or_client_learned_peer_id(conn,
1570 (const uint8_t*)digest_rcvd_out,
1571 NULL);
1574 return 0;
1577 /** Called when we (as a connection initiator) have definitively,
1578 * authenticatedly, learned that ID of the Tor instance on the other
1579 * side of <b>conn</b> is <b>rsa_peer_id</b> and optionally <b>ed_peer_id</b>.
1580 * For v1 and v2 handshakes,
1581 * this is right after we get a certificate chain in a TLS handshake
1582 * or renegotiation. For v3+ handshakes, this is right after we get a
1583 * certificate chain in a CERTS cell.
1585 * If we did not know the ID before, record the one we got.
1587 * If we wanted an ID, but we didn't get the one we expected, log a message
1588 * and return -1.
1589 * On relays:
1590 * - log a protocol warning whenever the fingerprints don't match;
1591 * On clients:
1592 * - if a relay's fingerprint doesn't match, log a warning;
1593 * - if we don't have updated relay fingerprints from a recent consensus, and
1594 * a fallback directory mirror's hard-coded fingerprint has changed, log an
1595 * info explaining that we will try another fallback.
1597 * If we're testing reachability, remember what we learned.
1599 * Return 0 on success, -1 on failure.
1602 connection_or_client_learned_peer_id(or_connection_t *conn,
1603 const uint8_t *rsa_peer_id,
1604 const ed25519_public_key_t *ed_peer_id)
1606 const or_options_t *options = get_options();
1607 channel_tls_t *chan_tls = conn->chan;
1608 channel_t *chan = channel_tls_to_base(chan_tls);
1609 int changed_identity = 0;
1610 tor_assert(chan);
1612 const int expected_rsa_key =
1613 ! tor_digest_is_zero(conn->identity_digest);
1614 const int expected_ed_key =
1615 ! ed25519_public_key_is_zero(&chan->ed25519_identity);
1617 log_info(LD_HANDSHAKE, "learned peer id for %p (%s): %s, %s",
1618 conn,
1619 safe_str_client(conn->base_.address),
1620 hex_str((const char*)rsa_peer_id, DIGEST_LEN),
1621 ed25519_fmt(ed_peer_id));
1623 if (! expected_rsa_key && ! expected_ed_key) {
1624 log_info(LD_HANDSHAKE, "(we had no ID in mind when we made this "
1625 "connection.");
1626 connection_or_set_identity_digest(conn,
1627 (const char*)rsa_peer_id, ed_peer_id);
1628 tor_free(conn->nickname);
1629 conn->nickname = tor_malloc(HEX_DIGEST_LEN+2);
1630 conn->nickname[0] = '$';
1631 base16_encode(conn->nickname+1, HEX_DIGEST_LEN+1,
1632 conn->identity_digest, DIGEST_LEN);
1633 log_info(LD_HANDSHAKE, "Connected to router %s at %s:%d without knowing "
1634 "its key. Hoping for the best.",
1635 conn->nickname, conn->base_.address, conn->base_.port);
1636 /* if it's a bridge and we didn't know its identity fingerprint, now
1637 * we do -- remember it for future attempts. */
1638 learned_router_identity(&conn->base_.addr, conn->base_.port,
1639 (const char*)rsa_peer_id, ed_peer_id);
1640 changed_identity = 1;
1643 const int rsa_mismatch = expected_rsa_key &&
1644 tor_memneq(rsa_peer_id, conn->identity_digest, DIGEST_LEN);
1645 /* It only counts as an ed25519 mismatch if we wanted an ed25519 identity
1646 * and didn't get it. It's okay if we get one that we didn't ask for. */
1647 const int ed25519_mismatch =
1648 expected_ed_key &&
1649 (ed_peer_id == NULL ||
1650 ! ed25519_pubkey_eq(&chan->ed25519_identity, ed_peer_id));
1652 if (rsa_mismatch || ed25519_mismatch) {
1653 /* I was aiming for a particular digest. I didn't get it! */
1654 char seen_rsa[HEX_DIGEST_LEN+1];
1655 char expected_rsa[HEX_DIGEST_LEN+1];
1656 char seen_ed[ED25519_BASE64_LEN+1];
1657 char expected_ed[ED25519_BASE64_LEN+1];
1658 base16_encode(seen_rsa, sizeof(seen_rsa),
1659 (const char*)rsa_peer_id, DIGEST_LEN);
1660 base16_encode(expected_rsa, sizeof(expected_rsa), conn->identity_digest,
1661 DIGEST_LEN);
1662 if (ed_peer_id) {
1663 ed25519_public_to_base64(seen_ed, ed_peer_id);
1664 } else {
1665 strlcpy(seen_ed, "no ed25519 key", sizeof(seen_ed));
1667 if (! ed25519_public_key_is_zero(&chan->ed25519_identity)) {
1668 ed25519_public_to_base64(expected_ed, &chan->ed25519_identity);
1669 } else {
1670 strlcpy(expected_ed, "no ed25519 key", sizeof(expected_ed));
1672 const int using_hardcoded_fingerprints =
1673 !networkstatus_get_reasonably_live_consensus(time(NULL),
1674 usable_consensus_flavor());
1675 const int is_fallback_fingerprint = router_digest_is_fallback_dir(
1676 conn->identity_digest);
1677 const int is_authority_fingerprint = router_digest_is_trusted_dir(
1678 conn->identity_digest);
1679 int severity;
1680 const char *extra_log = "";
1682 if (server_mode(options)) {
1683 severity = LOG_PROTOCOL_WARN;
1684 } else {
1685 if (using_hardcoded_fingerprints) {
1686 /* We need to do the checks in this order, because the list of
1687 * fallbacks includes the list of authorities */
1688 if (is_authority_fingerprint) {
1689 severity = LOG_WARN;
1690 } else if (is_fallback_fingerprint) {
1691 /* we expect a small number of fallbacks to change from their
1692 * hard-coded fingerprints over the life of a release */
1693 severity = LOG_INFO;
1694 extra_log = " Tor will try a different fallback.";
1695 } else {
1696 /* it's a bridge, it's either a misconfiguration, or unexpected */
1697 severity = LOG_WARN;
1699 } else {
1700 /* a relay has changed its fingerprint from the one in the consensus */
1701 severity = LOG_WARN;
1705 log_fn(severity, LD_HANDSHAKE,
1706 "Tried connecting to router at %s:%d, but RSA identity key was not "
1707 "as expected: wanted %s + %s but got %s + %s.%s",
1708 conn->base_.address, conn->base_.port,
1709 expected_rsa, expected_ed, seen_rsa, seen_ed, extra_log);
1711 /* Tell the new guard API about the channel failure */
1712 entry_guard_chan_failed(TLS_CHAN_TO_BASE(conn->chan));
1713 control_event_or_conn_status(conn, OR_CONN_EVENT_FAILED,
1714 END_OR_CONN_REASON_OR_IDENTITY);
1715 if (!authdir_mode_tests_reachability(options))
1716 control_event_bootstrap_problem(
1717 "Unexpected identity in router certificate",
1718 END_OR_CONN_REASON_OR_IDENTITY,
1719 conn);
1720 return -1;
1723 if (!expected_ed_key && ed_peer_id) {
1724 log_info(LD_HANDSHAKE, "(we had no Ed25519 ID in mind when we made this "
1725 "connection.");
1726 connection_or_set_identity_digest(conn,
1727 (const char*)rsa_peer_id, ed_peer_id);
1728 changed_identity = 1;
1731 if (changed_identity) {
1732 /* If we learned an identity for this connection, then we might have
1733 * just discovered it to be canonical. */
1734 connection_or_check_canonicity(conn, conn->handshake_state->started_here);
1737 if (authdir_mode_tests_reachability(options)) {
1738 dirserv_orconn_tls_done(&conn->base_.addr, conn->base_.port,
1739 (const char*)rsa_peer_id, ed_peer_id);
1742 return 0;
1745 /** Return when a client used this, for connection.c, since client_used
1746 * is now one of the timestamps of channel_t */
1748 time_t
1749 connection_or_client_used(or_connection_t *conn)
1751 tor_assert(conn);
1753 if (conn->chan) {
1754 return channel_when_last_client(TLS_CHAN_TO_BASE(conn->chan));
1755 } else return 0;
1758 /** The v1/v2 TLS handshake is finished.
1760 * Make sure we are happy with the person we just handshaked with.
1762 * If they initiated the connection, make sure they're not already connected,
1763 * then initialize conn from the information in router.
1765 * If all is successful, call circuit_n_conn_done() to handle events
1766 * that have been pending on the <tls handshake completion. Also set the
1767 * directory to be dirty (only matters if I'm an authdirserver).
1769 * If this is a v2 TLS handshake, send a versions cell.
1771 static int
1772 connection_tls_finish_handshake(or_connection_t *conn)
1774 char digest_rcvd[DIGEST_LEN];
1775 int started_here = connection_or_nonopen_was_started_here(conn);
1777 tor_assert(!started_here);
1779 log_debug(LD_HANDSHAKE,"%s tls handshake on %p with %s done, using "
1780 "ciphersuite %s. verifying.",
1781 started_here?"outgoing":"incoming",
1782 conn,
1783 safe_str_client(conn->base_.address),
1784 tor_tls_get_ciphersuite_name(conn->tls));
1786 if (connection_or_check_valid_tls_handshake(conn, started_here,
1787 digest_rcvd) < 0)
1788 return -1;
1790 circuit_build_times_network_is_live(get_circuit_build_times_mutable());
1792 if (tor_tls_used_v1_handshake(conn->tls)) {
1793 conn->link_proto = 1;
1794 connection_or_init_conn_from_address(conn, &conn->base_.addr,
1795 conn->base_.port, digest_rcvd,
1796 NULL, 0);
1797 tor_tls_block_renegotiation(conn->tls);
1798 rep_hist_note_negotiated_link_proto(1, started_here);
1799 return connection_or_set_state_open(conn);
1800 } else {
1801 connection_or_change_state(conn, OR_CONN_STATE_OR_HANDSHAKING_V2);
1802 if (connection_init_or_handshake_state(conn, started_here) < 0)
1803 return -1;
1804 connection_or_init_conn_from_address(conn, &conn->base_.addr,
1805 conn->base_.port, digest_rcvd,
1806 NULL, 0);
1807 return connection_or_send_versions(conn, 0);
1812 * Called as client when initial TLS handshake is done, and we notice
1813 * that we got a v3-handshake signalling certificate from the server.
1814 * Set up structures, do bookkeeping, and send the versions cell.
1815 * Return 0 on success and -1 on failure.
1817 static int
1818 connection_or_launch_v3_or_handshake(or_connection_t *conn)
1820 tor_assert(connection_or_nonopen_was_started_here(conn));
1822 circuit_build_times_network_is_live(get_circuit_build_times_mutable());
1824 connection_or_change_state(conn, OR_CONN_STATE_OR_HANDSHAKING_V3);
1825 if (connection_init_or_handshake_state(conn, 1) < 0)
1826 return -1;
1828 return connection_or_send_versions(conn, 1);
1831 /** Allocate a new connection handshake state for the connection
1832 * <b>conn</b>. Return 0 on success, -1 on failure. */
1834 connection_init_or_handshake_state(or_connection_t *conn, int started_here)
1836 or_handshake_state_t *s;
1837 if (conn->handshake_state) {
1838 log_warn(LD_BUG, "Duplicate call to connection_init_or_handshake_state!");
1839 return 0;
1841 s = conn->handshake_state = tor_malloc_zero(sizeof(or_handshake_state_t));
1842 s->started_here = started_here ? 1 : 0;
1843 s->digest_sent_data = 1;
1844 s->digest_received_data = 1;
1845 if (! started_here && get_current_link_cert_cert()) {
1846 s->own_link_cert = tor_cert_dup(get_current_link_cert_cert());
1848 s->certs = or_handshake_certs_new();
1849 s->certs->started_here = s->started_here;
1850 return 0;
1853 /** Free all storage held by <b>state</b>. */
1854 void
1855 or_handshake_state_free(or_handshake_state_t *state)
1857 if (!state)
1858 return;
1859 crypto_digest_free(state->digest_sent);
1860 crypto_digest_free(state->digest_received);
1861 or_handshake_certs_free(state->certs);
1862 tor_cert_free(state->own_link_cert);
1863 memwipe(state, 0xBE, sizeof(or_handshake_state_t));
1864 tor_free(state);
1868 * Remember that <b>cell</b> has been transmitted (if <b>incoming</b> is
1869 * false) or received (if <b>incoming</b> is true) during a V3 handshake using
1870 * <b>state</b>.
1872 * (We don't record the cell, but we keep a digest of everything sent or
1873 * received during the v3 handshake, and the client signs it in an
1874 * authenticate cell.)
1876 void
1877 or_handshake_state_record_cell(or_connection_t *conn,
1878 or_handshake_state_t *state,
1879 const cell_t *cell,
1880 int incoming)
1882 size_t cell_network_size = get_cell_network_size(conn->wide_circ_ids);
1883 crypto_digest_t *d, **dptr;
1884 packed_cell_t packed;
1885 if (incoming) {
1886 if (!state->digest_received_data)
1887 return;
1888 } else {
1889 if (!state->digest_sent_data)
1890 return;
1892 if (!incoming) {
1893 log_warn(LD_BUG, "We shouldn't be sending any non-variable-length cells "
1894 "while making a handshake digest. But we think we are sending "
1895 "one with type %d.", (int)cell->command);
1897 dptr = incoming ? &state->digest_received : &state->digest_sent;
1898 if (! *dptr)
1899 *dptr = crypto_digest256_new(DIGEST_SHA256);
1901 d = *dptr;
1902 /* Re-packing like this is a little inefficient, but we don't have to do
1903 this very often at all. */
1904 cell_pack(&packed, cell, conn->wide_circ_ids);
1905 crypto_digest_add_bytes(d, packed.body, cell_network_size);
1906 memwipe(&packed, 0, sizeof(packed));
1909 /** Remember that a variable-length <b>cell</b> has been transmitted (if
1910 * <b>incoming</b> is false) or received (if <b>incoming</b> is true) during a
1911 * V3 handshake using <b>state</b>.
1913 * (We don't record the cell, but we keep a digest of everything sent or
1914 * received during the v3 handshake, and the client signs it in an
1915 * authenticate cell.)
1917 void
1918 or_handshake_state_record_var_cell(or_connection_t *conn,
1919 or_handshake_state_t *state,
1920 const var_cell_t *cell,
1921 int incoming)
1923 crypto_digest_t *d, **dptr;
1924 int n;
1925 char buf[VAR_CELL_MAX_HEADER_SIZE];
1926 if (incoming) {
1927 if (!state->digest_received_data)
1928 return;
1929 } else {
1930 if (!state->digest_sent_data)
1931 return;
1933 dptr = incoming ? &state->digest_received : &state->digest_sent;
1934 if (! *dptr)
1935 *dptr = crypto_digest256_new(DIGEST_SHA256);
1937 d = *dptr;
1939 n = var_cell_pack_header(cell, buf, conn->wide_circ_ids);
1940 crypto_digest_add_bytes(d, buf, n);
1941 crypto_digest_add_bytes(d, (const char *)cell->payload, cell->payload_len);
1943 memwipe(buf, 0, sizeof(buf));
1946 /** Set <b>conn</b>'s state to OR_CONN_STATE_OPEN, and tell other subsystems
1947 * as appropriate. Called when we are done with all TLS and OR handshaking.
1950 connection_or_set_state_open(or_connection_t *conn)
1952 connection_or_change_state(conn, OR_CONN_STATE_OPEN);
1953 control_event_or_conn_status(conn, OR_CONN_EVENT_CONNECTED, 0);
1955 /* Link protocol 3 appeared in Tor 0.2.3.6-alpha, so any connection
1956 * that uses an earlier link protocol should not be treated as a relay. */
1957 if (conn->link_proto < 3) {
1958 channel_mark_client(TLS_CHAN_TO_BASE(conn->chan));
1961 or_handshake_state_free(conn->handshake_state);
1962 conn->handshake_state = NULL;
1963 connection_start_reading(TO_CONN(conn));
1965 return 0;
1968 /** Pack <b>cell</b> into wire-format, and write it onto <b>conn</b>'s outbuf.
1969 * For cells that use or affect a circuit, this should only be called by
1970 * connection_or_flush_from_first_active_circuit().
1972 void
1973 connection_or_write_cell_to_buf(const cell_t *cell, or_connection_t *conn)
1975 packed_cell_t networkcell;
1976 size_t cell_network_size = get_cell_network_size(conn->wide_circ_ids);
1978 tor_assert(cell);
1979 tor_assert(conn);
1981 cell_pack(&networkcell, cell, conn->wide_circ_ids);
1983 rep_hist_padding_count_write(PADDING_TYPE_TOTAL);
1984 if (cell->command == CELL_PADDING)
1985 rep_hist_padding_count_write(PADDING_TYPE_CELL);
1987 connection_write_to_buf(networkcell.body, cell_network_size, TO_CONN(conn));
1989 /* Touch the channel's active timestamp if there is one */
1990 if (conn->chan) {
1991 channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
1993 if (TLS_CHAN_TO_BASE(conn->chan)->currently_padding) {
1994 rep_hist_padding_count_write(PADDING_TYPE_ENABLED_TOTAL);
1995 if (cell->command == CELL_PADDING)
1996 rep_hist_padding_count_write(PADDING_TYPE_ENABLED_CELL);
2000 if (conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3)
2001 or_handshake_state_record_cell(conn, conn->handshake_state, cell, 0);
2004 /** Pack a variable-length <b>cell</b> into wire-format, and write it onto
2005 * <b>conn</b>'s outbuf. Right now, this <em>DOES NOT</em> support cells that
2006 * affect a circuit.
2008 MOCK_IMPL(void,
2009 connection_or_write_var_cell_to_buf,(const var_cell_t *cell,
2010 or_connection_t *conn))
2012 int n;
2013 char hdr[VAR_CELL_MAX_HEADER_SIZE];
2014 tor_assert(cell);
2015 tor_assert(conn);
2016 n = var_cell_pack_header(cell, hdr, conn->wide_circ_ids);
2017 connection_write_to_buf(hdr, n, TO_CONN(conn));
2018 connection_write_to_buf((char*)cell->payload,
2019 cell->payload_len, TO_CONN(conn));
2020 if (conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3)
2021 or_handshake_state_record_var_cell(conn, conn->handshake_state, cell, 0);
2023 /* Touch the channel's active timestamp if there is one */
2024 if (conn->chan)
2025 channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
2028 /** See whether there's a variable-length cell waiting on <b>or_conn</b>'s
2029 * inbuf. Return values as for fetch_var_cell_from_buf(). */
2030 static int
2031 connection_fetch_var_cell_from_buf(or_connection_t *or_conn, var_cell_t **out)
2033 connection_t *conn = TO_CONN(or_conn);
2034 return fetch_var_cell_from_buf(conn->inbuf, out, or_conn->link_proto);
2037 /** Process cells from <b>conn</b>'s inbuf.
2039 * Loop: while inbuf contains a cell, pull it off the inbuf, unpack it,
2040 * and hand it to command_process_cell().
2042 * Always return 0.
2044 static int
2045 connection_or_process_cells_from_inbuf(or_connection_t *conn)
2047 var_cell_t *var_cell;
2050 * Note on memory management for incoming cells: below the channel layer,
2051 * we shouldn't need to consider its internal queueing/copying logic. It
2052 * is safe to pass cells to it on the stack or on the heap, but in the
2053 * latter case we must be sure we free them later.
2055 * The incoming cell queue code in channel.c will (in the common case)
2056 * decide it can pass them to the upper layer immediately, in which case
2057 * those functions may run directly on the cell pointers we pass here, or
2058 * it may decide to queue them, in which case it will allocate its own
2059 * buffer and copy the cell.
2062 while (1) {
2063 log_debug(LD_OR,
2064 TOR_SOCKET_T_FORMAT": starting, inbuf_datalen %d "
2065 "(%d pending in tls object).",
2066 conn->base_.s,(int)connection_get_inbuf_len(TO_CONN(conn)),
2067 tor_tls_get_pending_bytes(conn->tls));
2068 if (connection_fetch_var_cell_from_buf(conn, &var_cell)) {
2069 if (!var_cell)
2070 return 0; /* not yet. */
2072 /* Touch the channel's active timestamp if there is one */
2073 if (conn->chan)
2074 channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
2076 circuit_build_times_network_is_live(get_circuit_build_times_mutable());
2077 channel_tls_handle_var_cell(var_cell, conn);
2078 var_cell_free(var_cell);
2079 } else {
2080 const int wide_circ_ids = conn->wide_circ_ids;
2081 size_t cell_network_size = get_cell_network_size(conn->wide_circ_ids);
2082 char buf[CELL_MAX_NETWORK_SIZE];
2083 cell_t cell;
2084 if (connection_get_inbuf_len(TO_CONN(conn))
2085 < cell_network_size) /* whole response available? */
2086 return 0; /* not yet */
2088 /* Touch the channel's active timestamp if there is one */
2089 if (conn->chan)
2090 channel_timestamp_active(TLS_CHAN_TO_BASE(conn->chan));
2092 circuit_build_times_network_is_live(get_circuit_build_times_mutable());
2093 connection_fetch_from_buf(buf, cell_network_size, TO_CONN(conn));
2095 /* retrieve cell info from buf (create the host-order struct from the
2096 * network-order string) */
2097 cell_unpack(&cell, buf, wide_circ_ids);
2099 channel_tls_handle_cell(&cell, conn);
2104 /** Array of recognized link protocol versions. */
2105 static const uint16_t or_protocol_versions[] = { 1, 2, 3, 4, 5 };
2106 /** Number of versions in <b>or_protocol_versions</b>. */
2107 static const int n_or_protocol_versions =
2108 (int)( sizeof(or_protocol_versions)/sizeof(uint16_t) );
2110 /** Return true iff <b>v</b> is a link protocol version that this Tor
2111 * implementation believes it can support. */
2113 is_or_protocol_version_known(uint16_t v)
2115 int i;
2116 for (i = 0; i < n_or_protocol_versions; ++i) {
2117 if (or_protocol_versions[i] == v)
2118 return 1;
2120 return 0;
2123 /** Send a VERSIONS cell on <b>conn</b>, telling the other host about the
2124 * link protocol versions that this Tor can support.
2126 * If <b>v3_plus</b>, this is part of a V3 protocol handshake, so only
2127 * allow protocol version v3 or later. If not <b>v3_plus</b>, this is
2128 * not part of a v3 protocol handshake, so don't allow protocol v3 or
2129 * later.
2132 connection_or_send_versions(or_connection_t *conn, int v3_plus)
2134 var_cell_t *cell;
2135 int i;
2136 int n_versions = 0;
2137 const int min_version = v3_plus ? 3 : 0;
2138 const int max_version = v3_plus ? UINT16_MAX : 2;
2139 tor_assert(conn->handshake_state &&
2140 !conn->handshake_state->sent_versions_at);
2141 cell = var_cell_new(n_or_protocol_versions * 2);
2142 cell->command = CELL_VERSIONS;
2143 for (i = 0; i < n_or_protocol_versions; ++i) {
2144 uint16_t v = or_protocol_versions[i];
2145 if (v < min_version || v > max_version)
2146 continue;
2147 set_uint16(cell->payload+(2*n_versions), htons(v));
2148 ++n_versions;
2150 cell->payload_len = n_versions * 2;
2152 connection_or_write_var_cell_to_buf(cell, conn);
2153 conn->handshake_state->sent_versions_at = time(NULL);
2155 var_cell_free(cell);
2156 return 0;
2159 /** Send a NETINFO cell on <b>conn</b>, telling the other server what we know
2160 * about their address, our address, and the current time. */
2161 MOCK_IMPL(int,
2162 connection_or_send_netinfo,(or_connection_t *conn))
2164 cell_t cell;
2165 time_t now = time(NULL);
2166 const routerinfo_t *me;
2167 int len;
2168 uint8_t *out;
2170 tor_assert(conn->handshake_state);
2172 if (conn->handshake_state->sent_netinfo) {
2173 log_warn(LD_BUG, "Attempted to send an extra netinfo cell on a connection "
2174 "where we already sent one.");
2175 return 0;
2178 memset(&cell, 0, sizeof(cell_t));
2179 cell.command = CELL_NETINFO;
2181 /* Timestamp, if we're a relay. */
2182 if (public_server_mode(get_options()) || ! conn->is_outgoing)
2183 set_uint32(cell.payload, htonl((uint32_t)now));
2185 /* Their address. */
2186 out = cell.payload + 4;
2187 /* We use &conn->real_addr below, unless it hasn't yet been set. If it
2188 * hasn't yet been set, we know that base_.addr hasn't been tampered with
2189 * yet either. */
2190 len = append_address_to_payload(out, !tor_addr_is_null(&conn->real_addr)
2191 ? &conn->real_addr : &conn->base_.addr);
2192 if (len<0)
2193 return -1;
2194 out += len;
2196 /* My address -- only include it if I'm a public relay, or if I'm a
2197 * bridge and this is an incoming connection. If I'm a bridge and this
2198 * is an outgoing connection, act like a normal client and omit it. */
2199 if ((public_server_mode(get_options()) || !conn->is_outgoing) &&
2200 (me = router_get_my_routerinfo())) {
2201 tor_addr_t my_addr;
2202 *out++ = 1 + !tor_addr_is_null(&me->ipv6_addr);
2204 tor_addr_from_ipv4h(&my_addr, me->addr);
2205 len = append_address_to_payload(out, &my_addr);
2206 if (len < 0)
2207 return -1;
2208 out += len;
2210 if (!tor_addr_is_null(&me->ipv6_addr)) {
2211 len = append_address_to_payload(out, &me->ipv6_addr);
2212 if (len < 0)
2213 return -1;
2215 } else {
2216 *out = 0;
2219 conn->handshake_state->digest_sent_data = 0;
2220 conn->handshake_state->sent_netinfo = 1;
2221 connection_or_write_cell_to_buf(&cell, conn);
2223 return 0;
2226 /** Helper used to add an encoded certs to a cert cell */
2227 static void
2228 add_certs_cell_cert_helper(certs_cell_t *certs_cell,
2229 uint8_t cert_type,
2230 const uint8_t *cert_encoded,
2231 size_t cert_len)
2233 tor_assert(cert_len <= UINT16_MAX);
2234 certs_cell_cert_t *ccc = certs_cell_cert_new();
2235 ccc->cert_type = cert_type;
2236 ccc->cert_len = cert_len;
2237 certs_cell_cert_setlen_body(ccc, cert_len);
2238 memcpy(certs_cell_cert_getarray_body(ccc), cert_encoded, cert_len);
2240 certs_cell_add_certs(certs_cell, ccc);
2243 /** Add an encoded X509 cert (stored as <b>cert_len</b> bytes at
2244 * <b>cert_encoded</b>) to the trunnel certs_cell_t object that we are
2245 * building in <b>certs_cell</b>. Set its type field to <b>cert_type</b>.
2246 * (If <b>cert</b> is NULL, take no action.) */
2247 static void
2248 add_x509_cert(certs_cell_t *certs_cell,
2249 uint8_t cert_type,
2250 const tor_x509_cert_t *cert)
2252 if (NULL == cert)
2253 return;
2255 const uint8_t *cert_encoded = NULL;
2256 size_t cert_len;
2257 tor_x509_cert_get_der(cert, &cert_encoded, &cert_len);
2259 add_certs_cell_cert_helper(certs_cell, cert_type, cert_encoded, cert_len);
2262 /** Add an Ed25519 cert from <b>cert</b> to the trunnel certs_cell_t object
2263 * that we are building in <b>certs_cell</b>. Set its type field to
2264 * <b>cert_type</b>. (If <b>cert</b> is NULL, take no action.) */
2265 static void
2266 add_ed25519_cert(certs_cell_t *certs_cell,
2267 uint8_t cert_type,
2268 const tor_cert_t *cert)
2270 if (NULL == cert)
2271 return;
2273 add_certs_cell_cert_helper(certs_cell, cert_type,
2274 cert->encoded, cert->encoded_len);
2277 #ifdef TOR_UNIT_TESTS
2278 int certs_cell_ed25519_disabled_for_testing = 0;
2279 #else
2280 #define certs_cell_ed25519_disabled_for_testing 0
2281 #endif
2283 /** Send a CERTS cell on the connection <b>conn</b>. Return 0 on success, -1
2284 * on failure. */
2286 connection_or_send_certs_cell(or_connection_t *conn)
2288 const tor_x509_cert_t *global_link_cert = NULL, *id_cert = NULL;
2289 tor_x509_cert_t *own_link_cert = NULL;
2290 var_cell_t *cell;
2292 certs_cell_t *certs_cell = NULL;
2294 tor_assert(conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3);
2296 if (! conn->handshake_state)
2297 return -1;
2299 const int conn_in_server_mode = ! conn->handshake_state->started_here;
2301 /* Get the encoded values of the X509 certificates */
2302 if (tor_tls_get_my_certs(conn_in_server_mode,
2303 &global_link_cert, &id_cert) < 0)
2304 return -1;
2306 if (conn_in_server_mode) {
2307 own_link_cert = tor_tls_get_own_cert(conn->tls);
2309 tor_assert(id_cert);
2311 certs_cell = certs_cell_new();
2313 /* Start adding certs. First the link cert or auth1024 cert. */
2314 if (conn_in_server_mode) {
2315 tor_assert_nonfatal(own_link_cert);
2316 add_x509_cert(certs_cell,
2317 OR_CERT_TYPE_TLS_LINK, own_link_cert);
2318 } else {
2319 tor_assert(global_link_cert);
2320 add_x509_cert(certs_cell,
2321 OR_CERT_TYPE_AUTH_1024, global_link_cert);
2324 /* Next the RSA->RSA ID cert */
2325 add_x509_cert(certs_cell,
2326 OR_CERT_TYPE_ID_1024, id_cert);
2328 /* Next the Ed25519 certs */
2329 add_ed25519_cert(certs_cell,
2330 CERTTYPE_ED_ID_SIGN,
2331 get_master_signing_key_cert());
2332 if (conn_in_server_mode) {
2333 tor_assert_nonfatal(conn->handshake_state->own_link_cert ||
2334 certs_cell_ed25519_disabled_for_testing);
2335 add_ed25519_cert(certs_cell,
2336 CERTTYPE_ED_SIGN_LINK,
2337 conn->handshake_state->own_link_cert);
2338 } else {
2339 add_ed25519_cert(certs_cell,
2340 CERTTYPE_ED_SIGN_AUTH,
2341 get_current_auth_key_cert());
2344 /* And finally the crosscert. */
2346 const uint8_t *crosscert=NULL;
2347 size_t crosscert_len;
2348 get_master_rsa_crosscert(&crosscert, &crosscert_len);
2349 if (crosscert) {
2350 add_certs_cell_cert_helper(certs_cell,
2351 CERTTYPE_RSA1024_ID_EDID,
2352 crosscert, crosscert_len);
2356 /* We've added all the certs; make the cell. */
2357 certs_cell->n_certs = certs_cell_getlen_certs(certs_cell);
2359 ssize_t alloc_len = certs_cell_encoded_len(certs_cell);
2360 tor_assert(alloc_len >= 0 && alloc_len <= UINT16_MAX);
2361 cell = var_cell_new(alloc_len);
2362 cell->command = CELL_CERTS;
2363 ssize_t enc_len = certs_cell_encode(cell->payload, alloc_len, certs_cell);
2364 tor_assert(enc_len > 0 && enc_len <= alloc_len);
2365 cell->payload_len = enc_len;
2367 connection_or_write_var_cell_to_buf(cell, conn);
2368 var_cell_free(cell);
2369 certs_cell_free(certs_cell);
2370 tor_x509_cert_free(own_link_cert);
2372 return 0;
2375 /** Return true iff <b>challenge_type</b> is an AUTHCHALLENGE type that
2376 * we can send and receive. */
2378 authchallenge_type_is_supported(uint16_t challenge_type)
2380 switch (challenge_type) {
2381 case AUTHTYPE_RSA_SHA256_TLSSECRET:
2382 case AUTHTYPE_ED25519_SHA256_RFC5705:
2383 return 1;
2384 case AUTHTYPE_RSA_SHA256_RFC5705:
2385 default:
2386 return 0;
2390 /** Return true iff <b>challenge_type_a</b> is one that we would rather
2391 * use than <b>challenge_type_b</b>. */
2393 authchallenge_type_is_better(uint16_t challenge_type_a,
2394 uint16_t challenge_type_b)
2396 /* Any supported type is better than an unsupported one;
2397 * all unsupported types are equally bad. */
2398 if (!authchallenge_type_is_supported(challenge_type_a))
2399 return 0;
2400 if (!authchallenge_type_is_supported(challenge_type_b))
2401 return 1;
2402 /* It happens that types are superior in numerically ascending order.
2403 * If that ever changes, this must change too. */
2404 return (challenge_type_a > challenge_type_b);
2407 /** Send an AUTH_CHALLENGE cell on the connection <b>conn</b>. Return 0
2408 * on success, -1 on failure. */
2410 connection_or_send_auth_challenge_cell(or_connection_t *conn)
2412 var_cell_t *cell = NULL;
2413 int r = -1;
2414 tor_assert(conn->base_.state == OR_CONN_STATE_OR_HANDSHAKING_V3);
2416 if (! conn->handshake_state)
2417 return -1;
2419 auth_challenge_cell_t *ac = auth_challenge_cell_new();
2421 tor_assert(sizeof(ac->challenge) == 32);
2422 crypto_rand((char*)ac->challenge, sizeof(ac->challenge));
2424 auth_challenge_cell_add_methods(ac, AUTHTYPE_RSA_SHA256_TLSSECRET);
2425 /* Disabled, because everything that supports this method also supports
2426 * the much-superior ED25519_SHA256_RFC5705 */
2427 /* auth_challenge_cell_add_methods(ac, AUTHTYPE_RSA_SHA256_RFC5705); */
2428 auth_challenge_cell_add_methods(ac, AUTHTYPE_ED25519_SHA256_RFC5705);
2429 auth_challenge_cell_set_n_methods(ac,
2430 auth_challenge_cell_getlen_methods(ac));
2432 cell = var_cell_new(auth_challenge_cell_encoded_len(ac));
2433 ssize_t len = auth_challenge_cell_encode(cell->payload, cell->payload_len,
2434 ac);
2435 if (len != cell->payload_len) {
2436 /* LCOV_EXCL_START */
2437 log_warn(LD_BUG, "Encoded auth challenge cell length not as expected");
2438 goto done;
2439 /* LCOV_EXCL_STOP */
2441 cell->command = CELL_AUTH_CHALLENGE;
2443 connection_or_write_var_cell_to_buf(cell, conn);
2444 r = 0;
2446 done:
2447 var_cell_free(cell);
2448 auth_challenge_cell_free(ac);
2450 return r;
2453 /** Compute the main body of an AUTHENTICATE cell that a client can use
2454 * to authenticate itself on a v3 handshake for <b>conn</b>. Return it
2455 * in a var_cell_t.
2457 * If <b>server</b> is true, only calculate the first
2458 * V3_AUTH_FIXED_PART_LEN bytes -- the part of the authenticator that's
2459 * determined by the rest of the handshake, and which match the provided value
2460 * exactly.
2462 * If <b>server</b> is false and <b>signing_key</b> is NULL, calculate the
2463 * first V3_AUTH_BODY_LEN bytes of the authenticator (that is, everything
2464 * that should be signed), but don't actually sign it.
2466 * If <b>server</b> is false and <b>signing_key</b> is provided, calculate the
2467 * entire authenticator, signed with <b>signing_key</b>.
2469 * Return the length of the cell body on success, and -1 on failure.
2471 var_cell_t *
2472 connection_or_compute_authenticate_cell_body(or_connection_t *conn,
2473 const int authtype,
2474 crypto_pk_t *signing_key,
2475 const ed25519_keypair_t *ed_signing_key,
2476 int server)
2478 auth1_t *auth = NULL;
2479 auth_ctx_t *ctx = auth_ctx_new();
2480 var_cell_t *result = NULL;
2481 int old_tlssecrets_algorithm = 0;
2482 const char *authtype_str = NULL;
2484 int is_ed = 0;
2486 /* assert state is reasonable XXXX */
2487 switch (authtype) {
2488 case AUTHTYPE_RSA_SHA256_TLSSECRET:
2489 authtype_str = "AUTH0001";
2490 old_tlssecrets_algorithm = 1;
2491 break;
2492 case AUTHTYPE_RSA_SHA256_RFC5705:
2493 authtype_str = "AUTH0002";
2494 break;
2495 case AUTHTYPE_ED25519_SHA256_RFC5705:
2496 authtype_str = "AUTH0003";
2497 is_ed = 1;
2498 break;
2499 default:
2500 tor_assert(0);
2501 break;
2504 auth = auth1_new();
2505 ctx->is_ed = is_ed;
2507 /* Type: 8 bytes. */
2508 memcpy(auth1_getarray_type(auth), authtype_str, 8);
2511 const tor_x509_cert_t *id_cert=NULL;
2512 const common_digests_t *my_digests, *their_digests;
2513 const uint8_t *my_id, *their_id, *client_id, *server_id;
2514 if (tor_tls_get_my_certs(server, NULL, &id_cert))
2515 goto err;
2516 my_digests = tor_x509_cert_get_id_digests(id_cert);
2517 their_digests =
2518 tor_x509_cert_get_id_digests(conn->handshake_state->certs->id_cert);
2519 tor_assert(my_digests);
2520 tor_assert(their_digests);
2521 my_id = (uint8_t*)my_digests->d[DIGEST_SHA256];
2522 their_id = (uint8_t*)their_digests->d[DIGEST_SHA256];
2524 client_id = server ? their_id : my_id;
2525 server_id = server ? my_id : their_id;
2527 /* Client ID digest: 32 octets. */
2528 memcpy(auth->cid, client_id, 32);
2530 /* Server ID digest: 32 octets. */
2531 memcpy(auth->sid, server_id, 32);
2534 if (is_ed) {
2535 const ed25519_public_key_t *my_ed_id, *their_ed_id;
2536 if (!conn->handshake_state->certs->ed_id_sign) {
2537 log_warn(LD_OR, "Ed authenticate without Ed ID cert from peer.");
2538 goto err;
2540 my_ed_id = get_master_identity_key();
2541 their_ed_id = &conn->handshake_state->certs->ed_id_sign->signing_key;
2543 const uint8_t *cid_ed = (server ? their_ed_id : my_ed_id)->pubkey;
2544 const uint8_t *sid_ed = (server ? my_ed_id : their_ed_id)->pubkey;
2546 memcpy(auth->u1_cid_ed, cid_ed, ED25519_PUBKEY_LEN);
2547 memcpy(auth->u1_sid_ed, sid_ed, ED25519_PUBKEY_LEN);
2551 crypto_digest_t *server_d, *client_d;
2552 if (server) {
2553 server_d = conn->handshake_state->digest_sent;
2554 client_d = conn->handshake_state->digest_received;
2555 } else {
2556 client_d = conn->handshake_state->digest_sent;
2557 server_d = conn->handshake_state->digest_received;
2560 /* Server log digest : 32 octets */
2561 crypto_digest_get_digest(server_d, (char*)auth->slog, 32);
2563 /* Client log digest : 32 octets */
2564 crypto_digest_get_digest(client_d, (char*)auth->clog, 32);
2568 /* Digest of cert used on TLS link : 32 octets. */
2569 tor_x509_cert_t *cert = NULL;
2570 if (server) {
2571 cert = tor_tls_get_own_cert(conn->tls);
2572 } else {
2573 cert = tor_tls_get_peer_cert(conn->tls);
2575 if (!cert) {
2576 log_warn(LD_OR, "Unable to find cert when making %s data.",
2577 authtype_str);
2578 goto err;
2581 memcpy(auth->scert,
2582 tor_x509_cert_get_cert_digests(cert)->d[DIGEST_SHA256], 32);
2584 tor_x509_cert_free(cert);
2587 /* HMAC of clientrandom and serverrandom using master key : 32 octets */
2588 if (old_tlssecrets_algorithm) {
2589 tor_tls_get_tlssecrets(conn->tls, auth->tlssecrets);
2590 } else {
2591 char label[128];
2592 tor_snprintf(label, sizeof(label),
2593 "EXPORTER FOR TOR TLS CLIENT BINDING %s", authtype_str);
2594 tor_tls_export_key_material(conn->tls, auth->tlssecrets,
2595 auth->cid, sizeof(auth->cid),
2596 label);
2599 /* 8 octets were reserved for the current time, but we're trying to get out
2600 * of the habit of sending time around willynilly. Fortunately, nothing
2601 * checks it. That's followed by 16 bytes of nonce. */
2602 crypto_rand((char*)auth->rand, 24);
2604 ssize_t maxlen = auth1_encoded_len(auth, ctx);
2605 if (ed_signing_key && is_ed) {
2606 maxlen += ED25519_SIG_LEN;
2607 } else if (signing_key && !is_ed) {
2608 maxlen += crypto_pk_keysize(signing_key);
2611 const int AUTH_CELL_HEADER_LEN = 4; /* 2 bytes of type, 2 bytes of length */
2612 result = var_cell_new(AUTH_CELL_HEADER_LEN + maxlen);
2613 uint8_t *const out = result->payload + AUTH_CELL_HEADER_LEN;
2614 const size_t outlen = maxlen;
2615 ssize_t len;
2617 result->command = CELL_AUTHENTICATE;
2618 set_uint16(result->payload, htons(authtype));
2620 if ((len = auth1_encode(out, outlen, auth, ctx)) < 0) {
2621 /* LCOV_EXCL_START */
2622 log_warn(LD_BUG, "Unable to encode signed part of AUTH1 data.");
2623 goto err;
2624 /* LCOV_EXCL_STOP */
2627 if (server) {
2628 auth1_t *tmp = NULL;
2629 ssize_t len2 = auth1_parse(&tmp, out, len, ctx);
2630 if (!tmp) {
2631 /* LCOV_EXCL_START */
2632 log_warn(LD_BUG, "Unable to parse signed part of AUTH1 data that "
2633 "we just encoded");
2634 goto err;
2635 /* LCOV_EXCL_STOP */
2637 result->payload_len = (tmp->end_of_signed - result->payload);
2639 auth1_free(tmp);
2640 if (len2 != len) {
2641 /* LCOV_EXCL_START */
2642 log_warn(LD_BUG, "Mismatched length when re-parsing AUTH1 data.");
2643 goto err;
2644 /* LCOV_EXCL_STOP */
2646 goto done;
2649 if (ed_signing_key && is_ed) {
2650 ed25519_signature_t sig;
2651 if (ed25519_sign(&sig, out, len, ed_signing_key) < 0) {
2652 /* LCOV_EXCL_START */
2653 log_warn(LD_BUG, "Unable to sign ed25519 authentication data");
2654 goto err;
2655 /* LCOV_EXCL_STOP */
2657 auth1_setlen_sig(auth, ED25519_SIG_LEN);
2658 memcpy(auth1_getarray_sig(auth), sig.sig, ED25519_SIG_LEN);
2660 } else if (signing_key && !is_ed) {
2661 auth1_setlen_sig(auth, crypto_pk_keysize(signing_key));
2663 char d[32];
2664 crypto_digest256(d, (char*)out, len, DIGEST_SHA256);
2665 int siglen = crypto_pk_private_sign(signing_key,
2666 (char*)auth1_getarray_sig(auth),
2667 auth1_getlen_sig(auth),
2668 d, 32);
2669 if (siglen < 0) {
2670 log_warn(LD_OR, "Unable to sign AUTH1 data.");
2671 goto err;
2674 auth1_setlen_sig(auth, siglen);
2677 len = auth1_encode(out, outlen, auth, ctx);
2678 if (len < 0) {
2679 /* LCOV_EXCL_START */
2680 log_warn(LD_BUG, "Unable to encode signed AUTH1 data.");
2681 goto err;
2682 /* LCOV_EXCL_STOP */
2684 tor_assert(len + AUTH_CELL_HEADER_LEN <= result->payload_len);
2685 result->payload_len = len + AUTH_CELL_HEADER_LEN;
2686 set_uint16(result->payload+2, htons(len));
2688 goto done;
2690 err:
2691 var_cell_free(result);
2692 result = NULL;
2693 done:
2694 auth1_free(auth);
2695 auth_ctx_free(ctx);
2696 return result;
2699 /** Send an AUTHENTICATE cell on the connection <b>conn</b>. Return 0 on
2700 * success, -1 on failure */
2701 MOCK_IMPL(int,
2702 connection_or_send_authenticate_cell,(or_connection_t *conn, int authtype))
2704 var_cell_t *cell;
2705 crypto_pk_t *pk = tor_tls_get_my_client_auth_key();
2706 /* XXXX make sure we're actually supposed to send this! */
2708 if (!pk) {
2709 log_warn(LD_BUG, "Can't compute authenticate cell: no client auth key");
2710 return -1;
2712 if (! authchallenge_type_is_supported(authtype)) {
2713 log_warn(LD_BUG, "Tried to send authenticate cell with unknown "
2714 "authentication type %d", authtype);
2715 return -1;
2718 cell = connection_or_compute_authenticate_cell_body(conn,
2719 authtype,
2721 get_current_auth_keypair(),
2722 0 /* not server */);
2723 if (! cell) {
2724 /* LCOV_EXCL_START */
2725 log_warn(LD_BUG, "Unable to compute authenticate cell!");
2726 return -1;
2727 /* LCOV_EXCL_STOP */
2729 connection_or_write_var_cell_to_buf(cell, conn);
2730 var_cell_free(cell);
2732 return 0;