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-2021, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
8 * \file connection_edge.c
9 * \brief Handle edge streams.
11 * An edge_connection_t is a subtype of a connection_t, and represents two
12 * critical concepts in Tor: a stream, and an edge connection. From the Tor
13 * protocol's point of view, a stream is a bi-directional channel that is
14 * multiplexed on a single circuit. Each stream on a circuit is identified
15 * with a separate 16-bit stream ID, local to the (circuit,exit) pair.
16 * Streams are created in response to client requests.
18 * An edge connection is one thing that can implement a stream: it is either a
19 * TCP application socket that has arrived via (e.g.) a SOCKS request, or an
22 * Not every instance of edge_connection_t truly represents an edge connection,
23 * however. (Sorry!) We also create edge_connection_t objects for streams that
24 * we will not be handling with TCP. The types of these streams are:
26 * <li>DNS lookup streams, created on the client side in response to
27 * a UDP DNS request received on a DNSPort, or a RESOLVE command
29 * <li>DNS lookup streams, created on the exit side in response to
30 * a RELAY_RESOLVE cell from a client.
31 * <li>Tunneled directory streams, created on the directory cache side
32 * in response to a RELAY_BEGIN_DIR cell. These streams attach directly
33 * to a dir_connection_t object without ever using TCP.
36 * This module handles general-purpose functionality having to do with
37 * edge_connection_t. On the client side, it accepts various types of
38 * application requests on SocksPorts, TransPorts, and NATDPorts, and
39 * creates streams appropriately.
41 * This module is also responsible for implementing stream isolation:
42 * ensuring that streams that should not be linkable to one another are
43 * kept to different circuits.
45 * On the exit side, this module handles the various stream-creating
46 * type of RELAY cells by launching appropriate outgoing connections,
47 * DNS requests, or directory connection objects.
49 * And for all edge connections, this module is responsible for handling
50 * incoming and outdoing data as it arrives or leaves in the relay.c
51 * module. (Outgoing data will be packaged in
52 * connection_edge_process_inbuf() as it calls
53 * connection_edge_package_raw_inbuf(); incoming data from RELAY_DATA
54 * cells is applied in connection_edge_process_relay_cell().)
56 #define CONNECTION_EDGE_PRIVATE
58 #include "core/or/or.h"
60 #include "lib/err/backtrace.h"
62 #include "app/config/config.h"
63 #include "core/mainloop/connection.h"
64 #include "core/mainloop/mainloop.h"
65 #include "core/mainloop/netstatus.h"
66 #include "core/or/channel.h"
67 #include "core/or/circuitbuild.h"
68 #include "core/or/circuitlist.h"
69 #include "core/or/circuituse.h"
70 #include "core/or/circuitpadding.h"
71 #include "core/or/connection_edge.h"
72 #include "core/or/congestion_control_flow.h"
73 #include "core/or/conflux_util.h"
74 #include "core/or/circuitstats.h"
75 #include "core/or/connection_or.h"
76 #include "core/or/dos.h"
77 #include "core/or/extendinfo.h"
78 #include "core/or/policies.h"
79 #include "core/or/reasons.h"
80 #include "core/or/relay.h"
81 #include "core/or/sendme.h"
82 #include "core/proto/proto_http.h"
83 #include "core/proto/proto_socks.h"
84 #include "feature/client/addressmap.h"
85 #include "feature/client/circpathbias.h"
86 #include "feature/client/dnsserv.h"
87 #include "feature/control/control_events.h"
88 #include "feature/dircache/dirserv.h"
89 #include "feature/dircommon/directory.h"
90 #include "feature/hibernate/hibernate.h"
91 #include "feature/hs/hs_cache.h"
92 #include "feature/hs/hs_circuit.h"
93 #include "feature/hs/hs_client.h"
94 #include "feature/hs/hs_common.h"
95 #include "feature/nodelist/describe.h"
96 #include "feature/nodelist/networkstatus.h"
97 #include "feature/nodelist/nodelist.h"
98 #include "feature/nodelist/routerlist.h"
99 #include "feature/nodelist/routerset.h"
100 #include "feature/relay/dns.h"
101 #include "feature/relay/router.h"
102 #include "feature/relay/routermode.h"
103 #include "feature/rend/rendcommon.h"
104 #include "feature/stats/predict_ports.h"
105 #include "feature/stats/rephist.h"
106 #include "lib/buf/buffers.h"
107 #include "lib/crypt_ops/crypto_rand.h"
108 #include "lib/crypt_ops/crypto_util.h"
109 #include "lib/encoding/confline.h"
111 #include "core/or/cell_st.h"
112 #include "core/or/cpath_build_state_st.h"
113 #include "feature/dircommon/dir_connection_st.h"
114 #include "core/or/entry_connection_st.h"
115 #include "core/or/extend_info_st.h"
116 #include "feature/nodelist/node_st.h"
117 #include "core/or/or_circuit_st.h"
118 #include "core/or/origin_circuit_st.h"
119 #include "core/or/half_edge_st.h"
120 #include "core/or/socks_request_st.h"
121 #include "lib/evloop/compat_libevent.h"
123 #ifdef HAVE_LINUX_TYPES_H
124 #include <linux/types.h>
126 #ifdef HAVE_LINUX_NETFILTER_IPV4_H
127 #include <linux/netfilter_ipv4.h>
128 #define TRANS_NETFILTER
129 #define TRANS_NETFILTER_IPV4
132 #ifdef HAVE_LINUX_IF_H
133 #include <linux/if.h>
136 #ifdef HAVE_LINUX_NETFILTER_IPV6_IP6_TABLES_H
137 #include <linux/netfilter_ipv6/ip6_tables.h>
138 #if defined(IP6T_SO_ORIGINAL_DST)
139 #define TRANS_NETFILTER
140 #define TRANS_NETFILTER_IPV6
142 #endif /* defined(HAVE_LINUX_NETFILTER_IPV6_IP6_TABLES_H) */
147 #ifdef HAVE_SYS_IOCTL_H
148 #include <sys/ioctl.h>
150 #ifdef HAVE_SYS_PARAM_H
151 #include <sys/param.h>
154 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
156 #include <net/pfvar.h>
160 #ifdef IP_TRANSPARENT
164 #define SOCKS4_GRANTED 90
165 #define SOCKS4_REJECT 91
167 static int connection_ap_handshake_process_socks(entry_connection_t
*conn
);
168 static int connection_ap_process_natd(entry_connection_t
*conn
);
169 static int connection_exit_connect_dir(edge_connection_t
*exitconn
);
170 static int consider_plaintext_ports(entry_connection_t
*conn
, uint16_t port
);
171 static int connection_ap_supports_optimistic_data(const entry_connection_t
*);
172 static bool network_reentry_is_allowed(void);
175 * Cast a `connection_t *` to an `edge_connection_t *`.
177 * Exit with an assertion failure if the input is not an
178 * `edge_connection_t`.
181 TO_EDGE_CONN(connection_t
*c
)
183 tor_assert(c
->magic
== EDGE_CONNECTION_MAGIC
||
184 c
->magic
== ENTRY_CONNECTION_MAGIC
);
185 return DOWNCAST(edge_connection_t
, c
);
189 * Cast a `const connection_t *` to a `const edge_connection_t *`.
191 * Exit with an assertion failure if the input is not an
192 * `edge_connection_t`.
194 const edge_connection_t
*
195 CONST_TO_EDGE_CONN(const connection_t
*c
)
197 return TO_EDGE_CONN((connection_t
*)c
);
201 * Cast a `connection_t *` to an `entry_connection_t *`.
203 * Exit with an assertion failure if the input is not an
204 * `entry_connection_t`.
207 TO_ENTRY_CONN(connection_t
*c
)
209 tor_assert(c
->magic
== ENTRY_CONNECTION_MAGIC
);
210 return (entry_connection_t
*) SUBTYPE_P(c
, entry_connection_t
, edge_
.base_
);
214 * Cast a `const connection_t *` to a `const entry_connection_t *`.
216 * Exit with an assertion failure if the input is not an
217 * `entry_connection_t`.
219 const entry_connection_t
*
220 CONST_TO_ENTRY_CONN(const connection_t
*c
)
222 return TO_ENTRY_CONN((connection_t
*) c
);
226 * Cast an `edge_connection_t *` to an `entry_connection_t *`.
228 * Exit with an assertion failure if the input is not an
229 * `entry_connection_t`.
232 EDGE_TO_ENTRY_CONN(edge_connection_t
*c
)
234 tor_assert(c
->base_
.magic
== ENTRY_CONNECTION_MAGIC
);
235 return (entry_connection_t
*) SUBTYPE_P(c
, entry_connection_t
, edge_
);
239 * Cast a `const edge_connection_t *` to a `const entry_connection_t *`.
241 * Exit with an assertion failure if the input is not an
242 * `entry_connection_t`.
244 const entry_connection_t
*
245 CONST_EDGE_TO_ENTRY_CONN(const edge_connection_t
*c
)
247 return EDGE_TO_ENTRY_CONN((edge_connection_t
*)c
);
250 /** An AP stream has failed/finished. If it hasn't already sent back
251 * a socks reply, send one now (based on endreason). Also set
252 * has_sent_end to 1, and mark the conn.
255 connection_mark_unattached_ap_
,(entry_connection_t
*conn
, int endreason
,
256 int line
, const char *file
))
258 connection_t
*base_conn
= ENTRY_TO_CONN(conn
);
259 tor_assert(base_conn
->type
== CONN_TYPE_AP
);
260 ENTRY_TO_EDGE_CONN(conn
)->edge_has_sent_end
= 1; /* no circ yet */
262 if (base_conn
->marked_for_close
) {
263 /* This call will warn as appropriate. */
264 connection_mark_for_close_(base_conn
, line
, file
);
268 if (!conn
->socks_request
->has_finished
) {
269 if (endreason
& END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
)
271 "stream (marked at %s:%d) sending two socks replies?",
274 if (SOCKS_COMMAND_IS_CONNECT(conn
->socks_request
->command
))
275 connection_ap_handshake_socks_reply(conn
, NULL
, 0, endreason
);
276 else if (SOCKS_COMMAND_IS_RESOLVE(conn
->socks_request
->command
))
277 connection_ap_handshake_socks_resolved(conn
,
278 RESOLVED_TYPE_ERROR_TRANSIENT
,
280 else /* unknown or no handshake at all. send no response. */
281 conn
->socks_request
->has_finished
= 1;
284 connection_mark_and_flush_(base_conn
, line
, file
);
286 ENTRY_TO_EDGE_CONN(conn
)->end_reason
= endreason
;
289 /** There was an EOF. Send an end and mark the connection for close.
292 connection_edge_reached_eof(edge_connection_t
*conn
)
294 if (connection_get_inbuf_len(TO_CONN(conn
)) &&
295 connection_state_is_open(TO_CONN(conn
))) {
296 /* it still has stuff to process. don't let it die yet. */
299 log_info(LD_EDGE
,"conn (fd "TOR_SOCKET_T_FORMAT
") reached eof. Closing.",
301 if (!conn
->base_
.marked_for_close
) {
302 /* only mark it if not already marked. it's possible to
303 * get the 'end' right around when the client hangs up on us. */
304 connection_edge_end(conn
, END_STREAM_REASON_DONE
);
305 if (conn
->base_
.type
== CONN_TYPE_AP
) {
306 /* eof, so don't send a socks reply back */
307 if (EDGE_TO_ENTRY_CONN(conn
)->socks_request
)
308 EDGE_TO_ENTRY_CONN(conn
)->socks_request
->has_finished
= 1;
310 connection_mark_for_close(TO_CONN(conn
));
315 /** Handle new bytes on conn->inbuf based on state:
316 * - If it's waiting for socks info, try to read another step of the
317 * socks handshake out of conn->inbuf.
318 * - If it's waiting for the original destination, fetch it.
319 * - If it's open, then package more relay cells from the stream.
320 * - Else, leave the bytes on inbuf alone for now.
322 * Mark and return -1 if there was an unexpected error with the conn,
326 connection_edge_process_inbuf(edge_connection_t
*conn
, int package_partial
)
330 switch (conn
->base_
.state
) {
331 case AP_CONN_STATE_SOCKS_WAIT
:
332 if (connection_ap_handshake_process_socks(EDGE_TO_ENTRY_CONN(conn
)) <0) {
337 case AP_CONN_STATE_NATD_WAIT
:
338 if (connection_ap_process_natd(EDGE_TO_ENTRY_CONN(conn
)) < 0) {
343 case AP_CONN_STATE_HTTP_CONNECT_WAIT
:
344 if (connection_ap_process_http_connect(EDGE_TO_ENTRY_CONN(conn
)) < 0) {
348 case AP_CONN_STATE_OPEN
:
349 if (! conn
->base_
.linked
) {
350 note_user_activity(approx_time());
354 case EXIT_CONN_STATE_OPEN
:
355 if (connection_edge_package_raw_inbuf(conn
, package_partial
, NULL
) < 0) {
356 /* (We already sent an end cell if possible) */
357 connection_mark_for_close(TO_CONN(conn
));
361 case AP_CONN_STATE_CONNECT_WAIT
:
362 if (connection_ap_supports_optimistic_data(EDGE_TO_ENTRY_CONN(conn
))) {
364 "data from edge while in '%s' state. Sending it anyway. "
365 "package_partial=%d, buflen=%ld",
366 conn_state_to_string(conn
->base_
.type
, conn
->base_
.state
),
368 (long)connection_get_inbuf_len(TO_CONN(conn
)));
369 if (connection_edge_package_raw_inbuf(conn
, package_partial
, NULL
)<0) {
370 /* (We already sent an end cell if possible) */
371 connection_mark_for_close(TO_CONN(conn
));
376 /* Fall through if the connection is on a circuit without optimistic
379 case EXIT_CONN_STATE_CONNECTING
:
380 case AP_CONN_STATE_RENDDESC_WAIT
:
381 case AP_CONN_STATE_CIRCUIT_WAIT
:
382 case AP_CONN_STATE_RESOLVE_WAIT
:
383 case AP_CONN_STATE_CONTROLLER_WAIT
:
385 "data from edge while in '%s' state. Leaving it on buffer.",
386 conn_state_to_string(conn
->base_
.type
, conn
->base_
.state
));
389 log_warn(LD_BUG
,"Got unexpected state %d. Closing.",conn
->base_
.state
);
390 tor_fragile_assert();
391 connection_edge_end(conn
, END_STREAM_REASON_INTERNAL
);
392 connection_mark_for_close(TO_CONN(conn
));
396 /** This edge needs to be closed, because its circuit has closed.
397 * Mark it for close and return 0.
400 connection_edge_destroy(circid_t circ_id
, edge_connection_t
*conn
)
402 if (!conn
->base_
.marked_for_close
) {
403 log_info(LD_EDGE
, "CircID %u: At an edge. Marking connection for close.",
405 if (conn
->base_
.type
== CONN_TYPE_AP
) {
406 entry_connection_t
*entry_conn
= EDGE_TO_ENTRY_CONN(conn
);
407 connection_mark_unattached_ap(entry_conn
, END_STREAM_REASON_DESTROY
);
408 control_event_stream_bandwidth(conn
);
409 control_event_stream_status(entry_conn
, STREAM_EVENT_CLOSED
,
410 END_STREAM_REASON_DESTROY
);
411 conn
->end_reason
|= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED
;
413 /* closing the circuit, nothing to send an END to */
414 conn
->edge_has_sent_end
= 1;
415 conn
->end_reason
= END_STREAM_REASON_DESTROY
;
416 conn
->end_reason
|= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED
;
417 connection_mark_and_flush(TO_CONN(conn
));
420 conn
->cpath_layer
= NULL
;
421 conn
->on_circuit
= NULL
;
425 /** Send a raw end cell to the stream with ID <b>stream_id</b> out over the
426 * <b>circ</b> towards the hop identified with <b>cpath_layer</b>. If this
427 * is not a client connection, set the relay end cell's reason for closing
428 * as <b>reason</b> */
430 relay_send_end_cell_from_edge(streamid_t stream_id
, circuit_t
*circ
,
431 uint8_t reason
, crypt_path_t
*cpath_layer
)
435 if (CIRCUIT_PURPOSE_IS_CLIENT(circ
->purpose
)) {
436 /* Never send the server an informative reason code; it doesn't need to
437 * know why the client stream is failing. */
438 reason
= END_STREAM_REASON_MISC
;
441 payload
[0] = (char) reason
;
443 /* Note: we have to use relay_send_command_from_edge here, not
444 * connection_edge_end or connection_edge_send_command, since those require
445 * that we have a stream connected to a circuit, and we don't connect to a
446 * circuit until we have a pending/successful resolve. */
447 return relay_send_command_from_edge(stream_id
, circ
, RELAY_COMMAND_END
,
448 payload
, 1, cpath_layer
);
451 /* If the connection <b>conn</b> is attempting to connect to an external
452 * destination that is an hidden service and the reason is a connection
453 * refused or timeout, log it so the operator can take appropriate actions.
454 * The log statement is a rate limited warning. */
456 warn_if_hs_unreachable(const edge_connection_t
*conn
, uint8_t reason
)
460 if (conn
->base_
.type
== CONN_TYPE_EXIT
&&
461 connection_edge_is_rendezvous_stream(conn
) &&
462 (reason
== END_STREAM_REASON_CONNECTREFUSED
||
463 reason
== END_STREAM_REASON_TIMEOUT
)) {
464 #define WARN_FAILED_HS_CONNECTION 300
465 static ratelim_t warn_limit
= RATELIM_INIT(WARN_FAILED_HS_CONNECTION
);
467 if ((m
= rate_limit_log(&warn_limit
, approx_time()))) {
468 log_warn(LD_EDGE
, "Onion service connection to %s failed (%s)",
469 connection_describe_peer(TO_CONN(conn
)),
470 stream_end_reason_to_string(reason
));
476 /** Given a TTL (in seconds) from a DNS response or from a relay, determine
477 * what TTL clients and relays should actually use for caching it. */
479 clip_dns_ttl(uint32_t ttl
)
481 /* This logic is a defense against "DefectTor" DNS-based traffic
482 * confirmation attacks, as in https://nymity.ch/tor-dns/tor-dns.pdf .
483 * We only give two values: a "low" value and a "high" value.
485 if (ttl
< MIN_DNS_TTL
)
491 /** Given a TTL (in seconds), determine what TTL an exit relay should use by
492 * first clipping as usual and then adding some randomness which is sampled
493 * uniformly at random from [-FUZZY_DNS_TTL, FUZZY_DNS_TTL]. This facilitates
494 * fuzzy TTLs, which makes it harder to infer when a website was visited via
495 * side-channels like DNS (see "Website Fingerprinting with Website Oracles").
497 * Note that this can't underflow because FUZZY_DNS_TTL < MIN_DNS_TTL.
500 clip_dns_fuzzy_ttl(uint32_t ttl
)
502 return clip_dns_ttl(ttl
) +
503 crypto_rand_uint(1 + 2*FUZZY_DNS_TTL
) - FUZZY_DNS_TTL
;
506 /** Send a relay end cell from stream <b>conn</b> down conn's circuit, and
507 * remember that we've done so. If this is not a client connection, set the
508 * relay end cell's reason for closing as <b>reason</b>.
510 * Return -1 if this function has already been called on this conn,
514 connection_edge_end(edge_connection_t
*conn
, uint8_t reason
)
516 char payload
[RELAY_PAYLOAD_SIZE
];
517 size_t payload_len
=1;
519 uint8_t control_reason
= reason
;
521 if (conn
->edge_has_sent_end
) {
522 log_warn(LD_BUG
,"(Harmless.) Calling connection_edge_end (reason %d) "
523 "on an already ended stream?", reason
);
524 tor_fragile_assert();
528 if (conn
->base_
.marked_for_close
) {
530 "called on conn that's already marked for close at %s:%d.",
531 conn
->base_
.marked_for_close_file
, conn
->base_
.marked_for_close
);
535 circ
= circuit_get_by_edge_conn(conn
);
536 if (circ
&& CIRCUIT_PURPOSE_IS_CLIENT(circ
->purpose
)) {
537 /* If this is a client circuit, don't send the server an informative
538 * reason code; it doesn't need to know why the client stream is
540 reason
= END_STREAM_REASON_MISC
;
543 payload
[0] = (char)reason
;
544 if (reason
== END_STREAM_REASON_EXITPOLICY
&&
545 !connection_edge_is_rendezvous_stream(conn
)) {
547 if (tor_addr_family(&conn
->base_
.addr
) == AF_INET
) {
548 set_uint32(payload
+1, tor_addr_to_ipv4n(&conn
->base_
.addr
));
551 memcpy(payload
+1, tor_addr_to_in6_addr8(&conn
->base_
.addr
), 16);
554 set_uint32(payload
+1+addrlen
, htonl(conn
->address_ttl
));
555 payload_len
+= 4+addrlen
;
558 if (circ
&& !circ
->marked_for_close
) {
559 log_debug(LD_EDGE
,"Sending end on conn (fd "TOR_SOCKET_T_FORMAT
").",
562 if (CIRCUIT_IS_ORIGIN(circ
)) {
563 origin_circuit_t
*origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
564 connection_half_edge_add(conn
, origin_circ
);
567 connection_edge_send_command(conn
, RELAY_COMMAND_END
,
568 payload
, payload_len
);
569 /* We'll log warn if the connection was an hidden service and couldn't be
570 * made because the service wasn't available. */
571 warn_if_hs_unreachable(conn
, control_reason
);
573 log_debug(LD_EDGE
,"No circ to send end on conn "
574 "(fd "TOR_SOCKET_T_FORMAT
").",
578 conn
->edge_has_sent_end
= 1;
579 conn
->end_reason
= control_reason
;
584 * Helper function for bsearch.
586 * As per smartlist_bsearch, return < 0 if key precedes member,
587 * > 0 if member precedes key, and 0 if they are equal.
589 * This is equivalent to subtraction of the values of key - member
590 * (why does no one ever say that explicitly?).
593 connection_half_edge_compare_bsearch(const void *key
, const void **member
)
595 const half_edge_t
*e2
;
597 tor_assert(member
&& *(half_edge_t
**)member
);
598 e2
= *(const half_edge_t
**)member
;
600 return *(const streamid_t
*)key
- e2
->stream_id
;
603 /** Total number of half_edge_t objects allocated */
604 static size_t n_half_conns_allocated
= 0;
607 * Add a half-closed connection to the list, to watch for activity.
609 * These connections are removed from the list upon receiving an end
613 connection_half_edge_add(const edge_connection_t
*conn
,
614 origin_circuit_t
*circ
)
616 half_edge_t
*half_conn
= NULL
;
620 /* Double-check for re-insertion. This should not happen,
621 * but this check is cheap compared to the sort anyway */
622 if (connection_half_edge_find_stream_id(circ
->half_streams
,
624 log_warn(LD_BUG
, "Duplicate stream close for stream %d on circuit %d",
625 conn
->stream_id
, circ
->global_identifier
);
629 half_conn
= tor_malloc_zero(sizeof(half_edge_t
));
630 ++n_half_conns_allocated
;
632 if (!circ
->half_streams
) {
633 circ
->half_streams
= smartlist_new();
634 conflux_update_half_streams(circ
, circ
->half_streams
);
637 half_conn
->stream_id
= conn
->stream_id
;
639 // Is there a connected cell pending?
640 half_conn
->connected_pending
= conn
->base_
.state
==
641 AP_CONN_STATE_CONNECT_WAIT
;
643 if (edge_uses_flow_control(conn
)) {
644 /* If the edge uses the new congestion control flow control, we must use
645 * time-based limits on half-edge activity. */
646 uint64_t timeout_usec
= (uint64_t)(get_circuit_build_timeout_ms()*1000);
647 half_conn
->used_ccontrol
= 1;
649 /* If this is an onion service circuit, double the CBT as an approximate
650 * value for the other half of the circuit */
651 if (conn
->hs_ident
) {
655 /* The stream should stop seeing any use after the larger of the circuit
656 * RTT and the overall circuit build timeout */
657 half_conn
->end_ack_expected_usec
= MAX(timeout_usec
,
658 edge_get_max_rtt(conn
)) +
659 monotime_absolute_usec();
661 // How many sendme's should I expect?
662 half_conn
->sendmes_pending
=
663 (STREAMWINDOW_START
-conn
->package_window
)/STREAMWINDOW_INCREMENT
;
665 /* Data should only arrive if we're not waiting on a resolved cell.
666 * It can arrive after waiting on connected, because of optimistic
668 if (conn
->base_
.state
!= AP_CONN_STATE_RESOLVE_WAIT
) {
669 // How many more data cells can arrive on this id?
670 half_conn
->data_pending
= conn
->deliver_window
;
674 insert_at
= smartlist_bsearch_idx(circ
->half_streams
, &half_conn
->stream_id
,
675 connection_half_edge_compare_bsearch
,
677 smartlist_insert(circ
->half_streams
, insert_at
, half_conn
);
681 * Return true if the circuit has any half-closed connections
682 * that are still within the end_ack_expected_usec timestamp
686 connection_half_edges_waiting(const origin_circuit_t
*circ
)
688 if (!circ
->half_streams
)
691 SMARTLIST_FOREACH_BEGIN(circ
->half_streams
, const half_edge_t
*, half_conn
) {
692 if (half_conn
->end_ack_expected_usec
> monotime_absolute_usec())
694 } SMARTLIST_FOREACH_END(half_conn
);
699 /** Release space held by <b>he</b> */
701 half_edge_free_(half_edge_t
*he
)
705 --n_half_conns_allocated
;
709 /** Return the number of bytes devoted to storing info on half-open streams. */
711 half_streams_get_total_allocation(void)
713 return n_half_conns_allocated
* sizeof(half_edge_t
);
717 * Find a stream_id_t in the list in O(lg(n)).
719 * Returns NULL if the list is empty or element is not found.
720 * Returns a pointer to the element if found.
723 connection_half_edge_find_stream_id(const smartlist_t
*half_conns
,
724 streamid_t stream_id
)
729 return smartlist_bsearch(half_conns
, &stream_id
,
730 connection_half_edge_compare_bsearch
);
734 * Check if this stream_id is in a half-closed state. If so,
735 * check if it still has data cells pending, and decrement that
738 * Return 1 if the data window was not empty.
739 * Return 0 otherwise.
742 connection_half_edge_is_valid_data(const smartlist_t
*half_conns
,
743 streamid_t stream_id
)
745 half_edge_t
*half
= connection_half_edge_find_stream_id(half_conns
,
751 if (half
->used_ccontrol
) {
752 if (monotime_absolute_usec() > half
->end_ack_expected_usec
)
757 if (half
->data_pending
> 0) {
758 half
->data_pending
--;
766 * Check if this stream_id is in a half-closed state. If so,
767 * check if it still has a connected cell pending, and decrement
770 * Return 1 if the connected window was not empty.
771 * Return 0 otherwise.
774 connection_half_edge_is_valid_connected(const smartlist_t
*half_conns
,
775 streamid_t stream_id
)
777 half_edge_t
*half
= connection_half_edge_find_stream_id(half_conns
,
783 if (half
->connected_pending
) {
784 half
->connected_pending
= 0;
792 * Check if this stream_id is in a half-closed state. If so,
793 * check if it still has sendme cells pending, and decrement that
796 * Return 1 if the sendme window was not empty.
797 * Return 0 otherwise.
800 connection_half_edge_is_valid_sendme(const smartlist_t
*half_conns
,
801 streamid_t stream_id
)
803 half_edge_t
*half
= connection_half_edge_find_stream_id(half_conns
,
809 /* congestion control edges don't use sendmes */
810 if (half
->used_ccontrol
)
813 if (half
->sendmes_pending
> 0) {
814 half
->sendmes_pending
--;
822 * Check if this stream_id is in a half-closed state. If so, remove
823 * it from the list. No other data should come after the END cell.
825 * Return 1 if stream_id was in half-closed state.
826 * Return 0 otherwise.
829 connection_half_edge_is_valid_end(smartlist_t
*half_conns
,
830 streamid_t stream_id
)
833 int found
, remove_idx
;
838 remove_idx
= smartlist_bsearch_idx(half_conns
, &stream_id
,
839 connection_half_edge_compare_bsearch
,
844 half
= smartlist_get(half_conns
, remove_idx
);
845 smartlist_del_keeporder(half_conns
, remove_idx
);
846 half_edge_free(half
);
851 * Streams that were used to send a RESOLVE cell are closed
852 * when they get the RESOLVED, without an end. So treat
853 * a RESOLVED just like an end, and remove from the list.
856 connection_half_edge_is_valid_resolved(smartlist_t
*half_conns
,
857 streamid_t stream_id
)
859 return connection_half_edge_is_valid_end(half_conns
, stream_id
);
862 /** An error has just occurred on an operation on an edge connection
863 * <b>conn</b>. Extract the errno; convert it to an end reason, and send an
864 * appropriate relay end cell to the other end of the connection's circuit.
867 connection_edge_end_errno(edge_connection_t
*conn
)
871 reason
= errno_to_stream_end_reason(tor_socket_errno(conn
->base_
.s
));
872 return connection_edge_end(conn
, reason
);
875 /** We just wrote some data to <b>conn</b>; act appropriately.
877 * (That is, if it's open, consider sending a stream-level sendme cell if we
878 * have just flushed enough.)
881 connection_edge_flushed_some(edge_connection_t
*conn
)
883 switch (conn
->base_
.state
) {
884 case AP_CONN_STATE_OPEN
:
885 if (! conn
->base_
.linked
) {
886 note_user_activity(approx_time());
890 case EXIT_CONN_STATE_OPEN
:
891 sendme_connection_edge_consider_sending(conn
);
897 /** Connection <b>conn</b> has finished writing and has no bytes left on
900 * If it's in state 'open', stop writing, consider responding with a
901 * sendme, and return.
902 * Otherwise, stop writing and return.
904 * If <b>conn</b> is broken, mark it for close and return -1, else
908 connection_edge_finished_flushing(edge_connection_t
*conn
)
912 switch (conn
->base_
.state
) {
913 case AP_CONN_STATE_OPEN
:
914 case EXIT_CONN_STATE_OPEN
:
915 sendme_connection_edge_consider_sending(conn
);
917 case AP_CONN_STATE_SOCKS_WAIT
:
918 case AP_CONN_STATE_NATD_WAIT
:
919 case AP_CONN_STATE_RENDDESC_WAIT
:
920 case AP_CONN_STATE_CIRCUIT_WAIT
:
921 case AP_CONN_STATE_CONNECT_WAIT
:
922 case AP_CONN_STATE_CONTROLLER_WAIT
:
923 case AP_CONN_STATE_RESOLVE_WAIT
:
924 case AP_CONN_STATE_HTTP_CONNECT_WAIT
:
927 log_warn(LD_BUG
, "Called in unexpected state %d.",conn
->base_
.state
);
928 tor_fragile_assert();
934 /** Longest size for the relay payload of a RELAY_CONNECTED cell that we're
935 * able to generate. */
936 /* 4 zero bytes; 1 type byte; 16 byte IPv6 address; 4 byte TTL. */
937 #define MAX_CONNECTED_CELL_PAYLOAD_LEN 25
939 /** Set the buffer at <b>payload_out</b> -- which must have at least
940 * MAX_CONNECTED_CELL_PAYLOAD_LEN bytes available -- to the body of a
941 * RELAY_CONNECTED cell indicating that we have connected to <b>addr</b>, and
942 * that the name resolution that led us to <b>addr</b> will be valid for
943 * <b>ttl</b> seconds. Return -1 on error, or the number of bytes used on
946 connected_cell_format_payload(uint8_t *payload_out
,
947 const tor_addr_t
*addr
,
950 const sa_family_t family
= tor_addr_family(addr
);
951 int connected_payload_len
;
953 /* should be needless */
954 memset(payload_out
, 0, MAX_CONNECTED_CELL_PAYLOAD_LEN
);
956 if (family
== AF_INET
) {
957 set_uint32(payload_out
, tor_addr_to_ipv4n(addr
));
958 connected_payload_len
= 4;
959 } else if (family
== AF_INET6
) {
960 set_uint32(payload_out
, 0);
961 set_uint8(payload_out
+ 4, 6);
962 memcpy(payload_out
+ 5, tor_addr_to_in6_addr8(addr
), 16);
963 connected_payload_len
= 21;
968 set_uint32(payload_out
+ connected_payload_len
, htonl(ttl
));
969 connected_payload_len
+= 4;
971 tor_assert(connected_payload_len
<= MAX_CONNECTED_CELL_PAYLOAD_LEN
);
973 return connected_payload_len
;
976 /* This is an onion service client connection: Export the client circuit ID
977 * according to the HAProxy proxy protocol. */
979 export_hs_client_circuit_id(edge_connection_t
*edge_conn
,
980 hs_circuit_id_protocol_t protocol
)
982 /* We only support HAProxy right now. */
983 if (protocol
!= HS_CIRCUIT_ID_PROTOCOL_HAPROXY
)
987 const char dst_ipv6
[] = "::1";
988 /* See RFC4193 regarding fc00::/7 */
989 const char src_ipv6_prefix
[] = "fc00:dead:beef:4dad:";
990 uint16_t dst_port
= 0;
991 uint16_t src_port
= 1; /* default value */
992 uint32_t gid
= 0; /* default value */
994 /* Generate a GID and source port for this client */
995 if (edge_conn
->on_circuit
!= NULL
) {
996 gid
= TO_ORIGIN_CIRCUIT(edge_conn
->on_circuit
)->global_identifier
;
997 src_port
= gid
& 0x0000ffff;
1000 /* Grab the original dest port from the hs ident */
1001 if (edge_conn
->hs_ident
) {
1002 dst_port
= edge_conn
->hs_ident
->orig_virtual_port
;
1005 /* Build the string */
1006 tor_asprintf(&buf
, "PROXY TCP6 %s:%x:%x %s %d %d\r\n",
1008 gid
>> 16, gid
& 0x0000ffff,
1009 dst_ipv6
, src_port
, dst_port
);
1011 connection_buf_add(buf
, strlen(buf
), TO_CONN(edge_conn
));
1016 /** Connected handler for exit connections: start writing pending
1017 * data, deliver 'CONNECTED' relay cells as appropriate, and check
1018 * any pending data that may have been received. */
1020 connection_edge_finished_connecting(edge_connection_t
*edge_conn
)
1024 tor_assert(edge_conn
);
1025 tor_assert(edge_conn
->base_
.type
== CONN_TYPE_EXIT
);
1026 conn
= TO_CONN(edge_conn
);
1027 tor_assert(conn
->state
== EXIT_CONN_STATE_CONNECTING
);
1029 log_info(LD_EXIT
,"%s established.",
1030 connection_describe(conn
));
1032 rep_hist_note_exit_stream_opened(conn
->port
);
1034 conn
->state
= EXIT_CONN_STATE_OPEN
;
1036 connection_watch_events(conn
, READ_EVENT
); /* stop writing, keep reading */
1037 if (connection_get_outbuf_len(conn
)) /* in case there are any queued relay
1039 connection_start_writing(conn
);
1040 /* deliver a 'connected' relay cell back through the circuit. */
1041 if (connection_edge_is_rendezvous_stream(edge_conn
)) {
1042 if (connection_edge_send_command(edge_conn
,
1043 RELAY_COMMAND_CONNECTED
, NULL
, 0) < 0)
1044 return 0; /* circuit is closed, don't continue */
1046 uint8_t connected_payload
[MAX_CONNECTED_CELL_PAYLOAD_LEN
];
1047 int connected_payload_len
=
1048 connected_cell_format_payload(connected_payload
, &conn
->addr
,
1049 edge_conn
->address_ttl
);
1050 if (connected_payload_len
< 0)
1053 if (connection_edge_send_command(edge_conn
,
1054 RELAY_COMMAND_CONNECTED
,
1055 (char*)connected_payload
, connected_payload_len
) < 0)
1056 return 0; /* circuit is closed, don't continue */
1058 tor_assert(edge_conn
->package_window
> 0);
1059 /* in case the server has written anything */
1060 return connection_edge_process_inbuf(edge_conn
, 1);
1063 /** A list of all the entry_connection_t * objects that are not marked
1064 * for close, and are in AP_CONN_STATE_CIRCUIT_WAIT.
1066 * (Right now, we check in several places to make sure that this list is
1067 * correct. When it's incorrect, we'll fix it, and log a BUG message.)
1069 static smartlist_t
*pending_entry_connections
= NULL
;
1071 static int untried_pending_connections
= 0;
1074 * Mainloop event to tell us to scan for pending connections that can
1077 static mainloop_event_t
*attach_pending_entry_connections_ev
= NULL
;
1079 /** Common code to connection_(ap|exit)_about_to_close. */
1081 connection_edge_about_to_close(edge_connection_t
*edge_conn
)
1083 if (!edge_conn
->edge_has_sent_end
) {
1084 connection_t
*conn
= TO_CONN(edge_conn
);
1085 log_warn(LD_BUG
, "(Harmless.) Edge connection (marked at %s:%d) "
1086 "hasn't sent end yet?",
1087 conn
->marked_for_close_file
, conn
->marked_for_close
);
1088 tor_fragile_assert();
1092 /** Called when we're about to finally unlink and free an AP (client)
1093 * connection: perform necessary accounting and cleanup */
1095 connection_ap_about_to_close(entry_connection_t
*entry_conn
)
1098 edge_connection_t
*edge_conn
= ENTRY_TO_EDGE_CONN(entry_conn
);
1099 connection_t
*conn
= ENTRY_TO_CONN(entry_conn
);
1101 connection_edge_about_to_close(edge_conn
);
1103 if (entry_conn
->socks_request
->has_finished
== 0) {
1104 /* since conn gets removed right after this function finishes,
1105 * there's no point trying to send back a reply at this point. */
1106 log_warn(LD_BUG
,"Closing stream (marked at %s:%d) without sending"
1107 " back a socks reply.",
1108 conn
->marked_for_close_file
, conn
->marked_for_close
);
1110 if (!edge_conn
->end_reason
) {
1111 log_warn(LD_BUG
,"Closing stream (marked at %s:%d) without having"
1113 conn
->marked_for_close_file
, conn
->marked_for_close
);
1115 if (entry_conn
->dns_server_request
) {
1116 log_warn(LD_BUG
,"Closing stream (marked at %s:%d) without having"
1117 " replied to DNS request.",
1118 conn
->marked_for_close_file
, conn
->marked_for_close
);
1119 dnsserv_reject_request(entry_conn
);
1122 if (TO_CONN(edge_conn
)->state
== AP_CONN_STATE_CIRCUIT_WAIT
) {
1123 smartlist_remove(pending_entry_connections
, entry_conn
);
1127 /* Check to make sure that this isn't in pending_entry_connections if it
1128 * didn't actually belong there. */
1129 if (TO_CONN(edge_conn
)->type
== CONN_TYPE_AP
) {
1130 connection_ap_warn_and_unmark_if_pending_circ(entry_conn
,
1135 control_event_stream_bandwidth(edge_conn
);
1136 control_event_stream_status(entry_conn
, STREAM_EVENT_CLOSED
,
1137 edge_conn
->end_reason
);
1138 circ
= circuit_get_by_edge_conn(edge_conn
);
1140 circuit_detach_stream(circ
, edge_conn
);
1143 /** Called when we're about to finally unlink and free an exit
1144 * connection: perform necessary accounting and cleanup */
1146 connection_exit_about_to_close(edge_connection_t
*edge_conn
)
1149 connection_t
*conn
= TO_CONN(edge_conn
);
1151 connection_edge_about_to_close(edge_conn
);
1153 circ
= circuit_get_by_edge_conn(edge_conn
);
1155 circuit_detach_stream(circ
, edge_conn
);
1156 if (conn
->state
== EXIT_CONN_STATE_RESOLVING
) {
1157 connection_dns_remove(edge_conn
);
1161 /** Define a schedule for how long to wait between retrying
1162 * application connections. Rather than waiting a fixed amount of
1163 * time between each retry, we wait 10 seconds each for the first
1164 * two tries, and 15 seconds for each retry after
1165 * that. Hopefully this will improve the expected user experience. */
1167 compute_retry_timeout(entry_connection_t
*conn
)
1169 int timeout
= get_options()->CircuitStreamTimeout
;
1170 if (timeout
) /* if our config options override the default, use them */
1172 if (conn
->num_socks_retries
< 2) /* try 0 and try 1 */
1177 /** Find all general-purpose AP streams waiting for a response that sent their
1178 * begin/resolve cell too long ago. Detach from their current circuit, and
1179 * mark their current circuit as unsuitable for new streams. Then call
1180 * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
1181 * available) or launch a new one.
1183 * For rendezvous streams, simply give up after SocksTimeout seconds (with no
1187 connection_ap_expire_beginning(void)
1189 edge_connection_t
*conn
;
1190 entry_connection_t
*entry_conn
;
1192 time_t now
= time(NULL
);
1193 const or_options_t
*options
= get_options();
1196 int seconds_idle
, seconds_since_born
;
1197 smartlist_t
*conns
= get_connection_array();
1199 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, base_conn
) {
1200 if (base_conn
->type
!= CONN_TYPE_AP
|| base_conn
->marked_for_close
)
1202 entry_conn
= TO_ENTRY_CONN(base_conn
);
1203 conn
= ENTRY_TO_EDGE_CONN(entry_conn
);
1204 /* if it's an internal linked connection, don't yell its status. */
1205 severity
= (tor_addr_is_null(&base_conn
->addr
) && !base_conn
->port
)
1206 ? LOG_INFO
: LOG_NOTICE
;
1207 seconds_idle
= (int)( now
- base_conn
->timestamp_last_read_allowed
);
1208 seconds_since_born
= (int)( now
- base_conn
->timestamp_created
);
1210 if (base_conn
->state
== AP_CONN_STATE_OPEN
)
1213 /* We already consider SocksTimeout in
1214 * connection_ap_handshake_attach_circuit(), but we need to consider
1215 * it here too because controllers that put streams in controller_wait
1216 * state never ask Tor to attach the circuit. */
1217 if (AP_CONN_STATE_IS_UNATTACHED(base_conn
->state
)) {
1218 /* If this is a connection to an HS with PoW defenses enabled, we need to
1219 * wait longer than the usual Socks timeout. */
1220 if (seconds_since_born
>= options
->SocksTimeout
&&
1221 !entry_conn
->hs_with_pow_conn
) {
1222 log_fn(severity
, LD_APP
,
1223 "Tried for %d seconds to get a connection to %s:%d. "
1226 safe_str_client(entry_conn
->socks_request
->address
),
1227 entry_conn
->socks_request
->port
,
1228 conn_state_to_string(CONN_TYPE_AP
, base_conn
->state
));
1229 connection_mark_unattached_ap(entry_conn
, END_STREAM_REASON_TIMEOUT
);
1234 /* We're in state connect_wait or resolve_wait now -- waiting for a
1235 * reply to our relay cell. See if we want to retry/give up. */
1237 cutoff
= compute_retry_timeout(entry_conn
);
1238 if (seconds_idle
< cutoff
)
1240 circ
= circuit_get_by_edge_conn(conn
);
1241 if (!circ
) { /* it's vanished? */
1242 log_info(LD_APP
,"Conn is waiting (address %s), but lost its circ.",
1243 safe_str_client(entry_conn
->socks_request
->address
));
1244 connection_mark_unattached_ap(entry_conn
, END_STREAM_REASON_TIMEOUT
);
1247 if (circ
->purpose
== CIRCUIT_PURPOSE_C_REND_JOINED
) {
1248 if (seconds_idle
>= options
->SocksTimeout
) {
1249 log_fn(severity
, LD_REND
,
1250 "Rend stream is %d seconds late. Giving up on address"
1253 safe_str_client(entry_conn
->socks_request
->address
));
1254 /* Roll back path bias use state so that we probe the circuit
1255 * if nothing else succeeds on it */
1256 pathbias_mark_use_rollback(TO_ORIGIN_CIRCUIT(circ
));
1258 connection_edge_end(conn
, END_STREAM_REASON_TIMEOUT
);
1259 connection_mark_unattached_ap(entry_conn
, END_STREAM_REASON_TIMEOUT
);
1264 if (circ
->purpose
!= CIRCUIT_PURPOSE_C_GENERAL
&&
1265 circ
->purpose
!= CIRCUIT_PURPOSE_CONFLUX_LINKED
&&
1266 circ
->purpose
!= CIRCUIT_PURPOSE_CONTROLLER
&&
1267 circ
->purpose
!= CIRCUIT_PURPOSE_C_HSDIR_GET
&&
1268 circ
->purpose
!= CIRCUIT_PURPOSE_S_HSDIR_POST
&&
1269 circ
->purpose
!= CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT
&&
1270 circ
->purpose
!= CIRCUIT_PURPOSE_PATH_BIAS_TESTING
) {
1271 log_warn(LD_BUG
, "circuit->purpose == CIRCUIT_PURPOSE_C_GENERAL failed. "
1272 "The purpose on the circuit was %s; it was in state %s, "
1274 circuit_purpose_to_string(circ
->purpose
),
1275 circuit_state_to_string(circ
->state
),
1276 CIRCUIT_IS_ORIGIN(circ
) ?
1277 pathbias_state_to_string(TO_ORIGIN_CIRCUIT(circ
)->path_state
) :
1280 log_fn(cutoff
< 15 ? LOG_INFO
: severity
, LD_APP
,
1281 "We tried for %d seconds to connect to '%s' using exit %s."
1282 " Retrying on a new circuit.",
1284 safe_str_client(entry_conn
->socks_request
->address
),
1286 extend_info_describe(conn
->cpath_layer
->extend_info
):
1288 /* send an end down the circuit */
1289 connection_edge_end(conn
, END_STREAM_REASON_TIMEOUT
);
1290 /* un-mark it as ending, since we're going to reuse it */
1291 conn
->edge_has_sent_end
= 0;
1292 conn
->end_reason
= 0;
1293 /* make us not try this circuit again, but allow
1294 * current streams on it to survive if they can */
1295 mark_circuit_unusable_for_new_conns(TO_ORIGIN_CIRCUIT(circ
));
1297 /* give our stream another 'cutoff' seconds to try */
1298 conn
->base_
.timestamp_last_read_allowed
+= cutoff
;
1299 if (entry_conn
->num_socks_retries
< 250) /* avoid overflow */
1300 entry_conn
->num_socks_retries
++;
1301 /* move it back into 'pending' state, and try to attach. */
1302 if (connection_ap_detach_retriable(entry_conn
, TO_ORIGIN_CIRCUIT(circ
),
1303 END_STREAM_REASON_TIMEOUT
)<0) {
1304 if (!base_conn
->marked_for_close
)
1305 connection_mark_unattached_ap(entry_conn
,
1306 END_STREAM_REASON_CANT_ATTACH
);
1308 } SMARTLIST_FOREACH_END(base_conn
);
1312 * As connection_ap_attach_pending, but first scans the entire connection
1313 * array to see if any elements are missing.
1316 connection_ap_rescan_and_attach_pending(void)
1318 entry_connection_t
*entry_conn
;
1319 smartlist_t
*conns
= get_connection_array();
1321 if (PREDICT_UNLIKELY(NULL
== pending_entry_connections
))
1322 pending_entry_connections
= smartlist_new();
1324 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
) {
1325 if (conn
->marked_for_close
||
1326 conn
->type
!= CONN_TYPE_AP
||
1327 conn
->state
!= AP_CONN_STATE_CIRCUIT_WAIT
)
1330 entry_conn
= TO_ENTRY_CONN(conn
);
1331 tor_assert(entry_conn
);
1332 if (! smartlist_contains(pending_entry_connections
, entry_conn
)) {
1333 log_warn(LD_BUG
, "Found a connection %p that was supposed to be "
1334 "in pending_entry_connections, but wasn't. No worries; "
1336 pending_entry_connections
);
1337 untried_pending_connections
= 1;
1338 connection_ap_mark_as_pending_circuit(entry_conn
);
1341 } SMARTLIST_FOREACH_END(conn
);
1343 connection_ap_attach_pending(1);
1346 /** Tell any AP streams that are listed as waiting for a new circuit to try
1347 * again. If there is an available circuit for a stream, attach it. Otherwise,
1348 * launch a new circuit.
1350 * If <b>retry</b> is false, only check the list if it contains at least one
1351 * streams that we have not yet tried to attach to a circuit.
1354 connection_ap_attach_pending(int retry
)
1356 if (PREDICT_UNLIKELY(!pending_entry_connections
)) {
1360 if (untried_pending_connections
== 0 && !retry
)
1363 /* Don't allow any modifications to list while we are iterating over
1364 * it. We'll put streams back on this list if we can't attach them
1366 smartlist_t
*pending
= pending_entry_connections
;
1367 pending_entry_connections
= smartlist_new();
1369 SMARTLIST_FOREACH_BEGIN(pending
,
1370 entry_connection_t
*, entry_conn
) {
1371 connection_t
*conn
= ENTRY_TO_CONN(entry_conn
);
1372 tor_assert(conn
&& entry_conn
);
1373 if (conn
->marked_for_close
) {
1376 if (conn
->magic
!= ENTRY_CONNECTION_MAGIC
) {
1377 log_warn(LD_BUG
, "%p has impossible magic value %u.",
1378 entry_conn
, (unsigned)conn
->magic
);
1381 if (conn
->state
!= AP_CONN_STATE_CIRCUIT_WAIT
) {
1382 /* The connection_ap_handshake_attach_circuit() call, for onion service,
1383 * can lead to more than one connections in the "pending" list to change
1384 * state and so it is OK to get here. Ignore it because this connection
1385 * won't be in pending_entry_connections list after this point. */
1389 /* Okay, we're through the sanity checks. Try to handle this stream. */
1390 if (connection_ap_handshake_attach_circuit(entry_conn
) < 0) {
1391 if (!conn
->marked_for_close
)
1392 connection_mark_unattached_ap(entry_conn
,
1393 END_STREAM_REASON_CANT_ATTACH
);
1396 if (! conn
->marked_for_close
&&
1397 conn
->type
== CONN_TYPE_AP
&&
1398 conn
->state
== AP_CONN_STATE_CIRCUIT_WAIT
) {
1399 /* Is it still waiting for a circuit? If so, we didn't attach it,
1400 * so it's still pending. Put it back on the list.
1402 if (!smartlist_contains(pending_entry_connections
, entry_conn
)) {
1403 smartlist_add(pending_entry_connections
, entry_conn
);
1408 /* If we got here, then we either closed the connection, or
1409 * we attached it. */
1410 } SMARTLIST_FOREACH_END(entry_conn
);
1412 smartlist_free(pending
);
1413 untried_pending_connections
= 0;
1417 attach_pending_entry_connections_cb(mainloop_event_t
*ev
, void *arg
)
1421 connection_ap_attach_pending(0);
1424 /** Mark <b>entry_conn</b> as needing to get attached to a circuit.
1426 * And <b>entry_conn</b> must be in AP_CONN_STATE_CIRCUIT_WAIT,
1427 * should not already be pending a circuit. The circuit will get
1428 * launched or the connection will get attached the next time we
1429 * call connection_ap_attach_pending().
1432 connection_ap_mark_as_pending_circuit_(entry_connection_t
*entry_conn
,
1433 const char *fname
, int lineno
)
1435 connection_t
*conn
= ENTRY_TO_CONN(entry_conn
);
1436 tor_assert(conn
->state
== AP_CONN_STATE_CIRCUIT_WAIT
);
1437 tor_assert(conn
->magic
== ENTRY_CONNECTION_MAGIC
);
1438 if (conn
->marked_for_close
)
1441 if (PREDICT_UNLIKELY(NULL
== pending_entry_connections
)) {
1442 pending_entry_connections
= smartlist_new();
1444 if (PREDICT_UNLIKELY(NULL
== attach_pending_entry_connections_ev
)) {
1445 attach_pending_entry_connections_ev
= mainloop_event_postloop_new(
1446 attach_pending_entry_connections_cb
, NULL
);
1448 if (PREDICT_UNLIKELY(smartlist_contains(pending_entry_connections
,
1450 log_warn(LD_BUG
, "What?? pending_entry_connections already contains %p! "
1451 "(Called from %s:%d.)",
1452 entry_conn
, fname
, lineno
);
1453 #ifdef DEBUGGING_17659
1454 const char *f2
= entry_conn
->marked_pending_circ_file
;
1455 log_warn(LD_BUG
, "(Previously called from %s:%d.)\n",
1457 entry_conn
->marked_pending_circ_line
);
1458 #endif /* defined(DEBUGGING_17659) */
1459 log_backtrace(LOG_WARN
, LD_BUG
, "To debug, this may help");
1463 #ifdef DEBUGGING_17659
1464 entry_conn
->marked_pending_circ_line
= (uint16_t) lineno
;
1465 entry_conn
->marked_pending_circ_file
= fname
;
1468 untried_pending_connections
= 1;
1469 smartlist_add(pending_entry_connections
, entry_conn
);
1471 mainloop_event_activate(attach_pending_entry_connections_ev
);
1474 /** Mark <b>entry_conn</b> as no longer waiting for a circuit. */
1476 connection_ap_mark_as_non_pending_circuit(entry_connection_t
*entry_conn
)
1478 if (PREDICT_UNLIKELY(NULL
== pending_entry_connections
))
1480 smartlist_remove(pending_entry_connections
, entry_conn
);
1483 /** Mark <b>entry_conn</b> as waiting for a rendezvous descriptor. This
1484 * function will remove the entry connection from the waiting for a circuit
1485 * list (pending_entry_connections).
1487 * This pattern is used across the code base because a connection in state
1488 * AP_CONN_STATE_RENDDESC_WAIT must not be in the pending list. */
1490 connection_ap_mark_as_waiting_for_renddesc(entry_connection_t
*entry_conn
)
1492 tor_assert(entry_conn
);
1494 connection_ap_mark_as_non_pending_circuit(entry_conn
);
1495 ENTRY_TO_CONN(entry_conn
)->state
= AP_CONN_STATE_RENDDESC_WAIT
;
1500 connection_ap_warn_and_unmark_if_pending_circ(entry_connection_t
*entry_conn
,
1503 if (pending_entry_connections
&&
1504 smartlist_contains(pending_entry_connections
, entry_conn
)) {
1505 log_warn(LD_BUG
, "What was %p doing in pending_entry_connections in %s?",
1507 connection_ap_mark_as_non_pending_circuit(entry_conn
);
1511 /** Tell any AP streams that are waiting for a one-hop tunnel to
1512 * <b>failed_digest</b> that they are going to fail. */
1513 /* XXXX We should get rid of this function, and instead attach
1514 * one-hop streams to circ->p_streams so they get marked in
1515 * circuit_mark_for_close like normal p_streams. */
1517 connection_ap_fail_onehop(const char *failed_digest
,
1518 cpath_build_state_t
*build_state
)
1520 entry_connection_t
*entry_conn
;
1521 char digest
[DIGEST_LEN
];
1522 smartlist_t
*conns
= get_connection_array();
1523 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
) {
1524 if (conn
->marked_for_close
||
1525 conn
->type
!= CONN_TYPE_AP
||
1526 conn
->state
!= AP_CONN_STATE_CIRCUIT_WAIT
)
1528 entry_conn
= TO_ENTRY_CONN(conn
);
1529 if (!entry_conn
->want_onehop
)
1531 if (hexdigest_to_digest(entry_conn
->chosen_exit_name
, digest
) < 0 ||
1532 tor_memneq(digest
, failed_digest
, DIGEST_LEN
))
1534 if (tor_digest_is_zero(digest
)) {
1535 /* we don't know the digest; have to compare addr:port */
1537 if (!build_state
|| !build_state
->chosen_exit
||
1538 !entry_conn
->socks_request
) {
1541 if (tor_addr_parse(&addr
, entry_conn
->socks_request
->address
)<0 ||
1542 !extend_info_has_orport(build_state
->chosen_exit
, &addr
,
1543 entry_conn
->socks_request
->port
))
1546 log_info(LD_APP
, "Closing one-hop stream to '%s/%s' because the OR conn "
1547 "just failed.", entry_conn
->chosen_exit_name
,
1548 entry_conn
->socks_request
->address
);
1549 connection_mark_unattached_ap(entry_conn
, END_STREAM_REASON_TIMEOUT
);
1550 } SMARTLIST_FOREACH_END(conn
);
1553 /** A circuit failed to finish on its last hop <b>info</b>. If there
1554 * are any streams waiting with this exit node in mind, but they
1555 * don't absolutely require it, make them give up on it.
1558 circuit_discard_optional_exit_enclaves(extend_info_t
*info
)
1560 entry_connection_t
*entry_conn
;
1561 const node_t
*r1
, *r2
;
1563 smartlist_t
*conns
= get_connection_array();
1564 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
) {
1565 if (conn
->marked_for_close
||
1566 conn
->type
!= CONN_TYPE_AP
||
1567 conn
->state
!= AP_CONN_STATE_CIRCUIT_WAIT
)
1569 entry_conn
= TO_ENTRY_CONN(conn
);
1570 if (!entry_conn
->chosen_exit_optional
&&
1571 !entry_conn
->chosen_exit_retries
)
1573 r1
= node_get_by_nickname(entry_conn
->chosen_exit_name
,
1574 NNF_NO_WARN_UNNAMED
);
1575 r2
= node_get_by_id(info
->identity_digest
);
1576 if (!r1
|| !r2
|| r1
!= r2
)
1578 tor_assert(entry_conn
->socks_request
);
1579 if (entry_conn
->chosen_exit_optional
) {
1580 log_info(LD_APP
, "Giving up on enclave exit '%s' for destination %s.",
1581 safe_str_client(entry_conn
->chosen_exit_name
),
1582 escaped_safe_str_client(entry_conn
->socks_request
->address
));
1583 entry_conn
->chosen_exit_optional
= 0;
1584 tor_free(entry_conn
->chosen_exit_name
); /* clears it */
1585 /* if this port is dangerous, warn or reject it now that we don't
1586 * think it'll be using an enclave. */
1587 consider_plaintext_ports(entry_conn
, entry_conn
->socks_request
->port
);
1589 if (entry_conn
->chosen_exit_retries
) {
1590 if (--entry_conn
->chosen_exit_retries
== 0) { /* give up! */
1591 clear_trackexithost_mappings(entry_conn
->chosen_exit_name
);
1592 tor_free(entry_conn
->chosen_exit_name
); /* clears it */
1593 /* if this port is dangerous, warn or reject it now that we don't
1594 * think it'll be using an enclave. */
1595 consider_plaintext_ports(entry_conn
, entry_conn
->socks_request
->port
);
1598 } SMARTLIST_FOREACH_END(conn
);
1601 /** Set the connection state to CONTROLLER_WAIT and send an control port event.
1604 connection_entry_set_controller_wait(entry_connection_t
*conn
)
1606 CONNECTION_AP_EXPECT_NONPENDING(conn
);
1607 ENTRY_TO_CONN(conn
)->state
= AP_CONN_STATE_CONTROLLER_WAIT
;
1608 control_event_stream_status(conn
, STREAM_EVENT_CONTROLLER_WAIT
, 0);
1611 /** The AP connection <b>conn</b> has just failed while attaching or
1612 * sending a BEGIN or resolving on <b>circ</b>, but another circuit
1613 * might work. Detach the circuit, and either reattach it, launch a
1614 * new circuit, tell the controller, or give up as appropriate.
1616 * Returns -1 on err, 1 on success, 0 on not-yet-sure.
1619 connection_ap_detach_retriable(entry_connection_t
*conn
,
1620 origin_circuit_t
*circ
,
1623 control_event_stream_status(conn
, STREAM_EVENT_FAILED_RETRIABLE
, reason
);
1624 ENTRY_TO_CONN(conn
)->timestamp_last_read_allowed
= time(NULL
);
1626 /* Roll back path bias use state so that we probe the circuit
1627 * if nothing else succeeds on it */
1628 pathbias_mark_use_rollback(circ
);
1630 if (conn
->pending_optimistic_data
) {
1631 buf_set_to_copy(&conn
->sending_optimistic_data
,
1632 conn
->pending_optimistic_data
);
1635 if (!get_options()->LeaveStreamsUnattached
|| conn
->use_begindir
) {
1636 /* If we're attaching streams ourself, or if this connection is
1637 * a tunneled directory connection, then just attach it. */
1638 ENTRY_TO_CONN(conn
)->state
= AP_CONN_STATE_CIRCUIT_WAIT
;
1639 circuit_detach_stream(TO_CIRCUIT(circ
),ENTRY_TO_EDGE_CONN(conn
));
1640 connection_ap_mark_as_pending_circuit(conn
);
1642 connection_entry_set_controller_wait(conn
);
1643 circuit_detach_stream(TO_CIRCUIT(circ
),ENTRY_TO_EDGE_CONN(conn
));
1648 /** Check if <b>conn</b> is using a dangerous port. Then warn and/or
1649 * reject depending on our config options. */
1651 consider_plaintext_ports(entry_connection_t
*conn
, uint16_t port
)
1653 const or_options_t
*options
= get_options();
1654 int reject
= smartlist_contains_int_as_string(
1655 options
->RejectPlaintextPorts
, port
);
1657 if (smartlist_contains_int_as_string(options
->WarnPlaintextPorts
, port
)) {
1658 log_warn(LD_APP
, "Application request to port %d: this port is "
1659 "commonly used for unencrypted protocols. Please make sure "
1660 "you don't send anything you would mind the rest of the "
1661 "Internet reading!%s", port
, reject
? " Closing." : "");
1662 control_event_client_status(LOG_WARN
, "DANGEROUS_PORT PORT=%d RESULT=%s",
1663 port
, reject
? "REJECT" : "WARN");
1667 log_info(LD_APP
, "Port %d listed in RejectPlaintextPorts. Closing.", port
);
1668 connection_mark_unattached_ap(conn
, END_STREAM_REASON_ENTRYPOLICY
);
1675 /** Parse the given hostname in address. Returns true if the parsing was
1676 * successful and type_out contains the type of the hostname. Else, false is
1677 * returned which means it was not recognized and type_out is set to
1680 * The possible recognized forms are (where true is returned):
1682 * If address is of the form "y.onion" with a well-formed handle y:
1683 * Put a NUL after y, lower-case it, and return ONION_V3_HOSTNAME
1684 * depending on the HS version.
1686 * If address is of the form "x.y.onion" with a well-formed handle x:
1687 * Drop "x.", put a NUL after y, lower-case it, and return
1688 * ONION_V3_HOSTNAME depending on the HS version.
1690 * If address is of the form "y.onion" with a badly-formed handle y:
1691 * Return BAD_HOSTNAME and log a message.
1693 * If address is of the form "y.exit":
1694 * Put a NUL after y and return EXIT_HOSTNAME.
1697 * Return NORMAL_HOSTNAME and change nothing.
1700 parse_extended_hostname(char *address
, hostname_type_t
*type_out
)
1704 char query
[HS_SERVICE_ADDR_LEN_BASE32
+1];
1706 s
= strrchr(address
,'.');
1708 *type_out
= NORMAL_HOSTNAME
; /* no dot, thus normal */
1711 if (!strcmp(s
+1,"exit")) {
1712 *s
= 0; /* NUL-terminate it */
1713 *type_out
= EXIT_HOSTNAME
; /* .exit */
1716 if (strcmp(s
+1,"onion")) {
1717 *type_out
= NORMAL_HOSTNAME
; /* neither .exit nor .onion, thus normal */
1721 /* so it is .onion */
1722 *s
= 0; /* NUL-terminate it */
1723 /* locate a 'sub-domain' component, in order to remove it */
1724 q
= strrchr(address
, '.');
1726 *type_out
= BAD_HOSTNAME
;
1727 goto failed
; /* reject sub-domain, as DNS does */
1729 q
= (NULL
== q
) ? address
: q
+ 1;
1730 if (strlcpy(query
, q
, HS_SERVICE_ADDR_LEN_BASE32
+1) >=
1731 HS_SERVICE_ADDR_LEN_BASE32
+1) {
1732 *type_out
= BAD_HOSTNAME
;
1736 memmove(address
, q
, strlen(q
) + 1 /* also get \0 */);
1739 /* v3 onion address check. */
1740 if (strlen(query
) == HS_SERVICE_ADDR_LEN_BASE32
) {
1741 *type_out
= ONION_V3_HOSTNAME
;
1742 if (hs_address_is_valid(query
)) {
1748 /* Reaching this point, nothing was recognized. */
1749 *type_out
= BAD_HOSTNAME
;
1755 /* otherwise, return to previous state and return 0 */
1757 const bool is_onion
= (*type_out
== ONION_V3_HOSTNAME
);
1758 log_warn(LD_APP
, "Invalid %shostname %s; rejecting",
1759 is_onion
? "onion " : "",
1760 safe_str_client(address
));
1761 if (*type_out
== ONION_V3_HOSTNAME
) {
1762 *type_out
= BAD_HOSTNAME
;
1767 /** How many times do we try connecting with an exit configured via
1768 * TrackHostExits before concluding that it won't work any more and trying a
1770 #define TRACKHOSTEXITS_RETRIES 5
1772 /** Call connection_ap_handshake_rewrite_and_attach() unless a controller
1773 * asked us to leave streams unattached. Return 0 in that case.
1775 * See connection_ap_handshake_rewrite_and_attach()'s
1776 * documentation for arguments and return value.
1779 connection_ap_rewrite_and_attach_if_allowed
,(entry_connection_t
*conn
,
1780 origin_circuit_t
*circ
,
1781 crypt_path_t
*cpath
))
1783 const or_options_t
*options
= get_options();
1785 if (options
->LeaveStreamsUnattached
) {
1786 connection_entry_set_controller_wait(conn
);
1789 return connection_ap_handshake_rewrite_and_attach(conn
, circ
, cpath
);
1792 /* Try to perform any map-based rewriting of the target address in
1793 * <b>conn</b>, filling in the fields of <b>out</b> as we go, and modifying
1794 * conn->socks_request.address as appropriate.
1797 connection_ap_handshake_rewrite(entry_connection_t
*conn
,
1798 rewrite_result_t
*out
)
1800 socks_request_t
*socks
= conn
->socks_request
;
1801 const or_options_t
*options
= get_options();
1802 tor_addr_t addr_tmp
;
1804 /* Initialize all the fields of 'out' to reasonable defaults */
1806 out
->exit_source
= ADDRMAPSRC_NONE
;
1807 out
->map_expires
= TIME_MAX
;
1808 out
->end_reason
= 0;
1809 out
->should_close
= 0;
1810 out
->orig_address
[0] = 0;
1812 /* We convert all incoming addresses to lowercase. */
1813 tor_strlower(socks
->address
);
1814 /* Remember the original address. */
1815 strlcpy(out
->orig_address
, socks
->address
, sizeof(out
->orig_address
));
1816 log_debug(LD_APP
,"Client asked for %s:%d",
1817 safe_str_client(socks
->address
),
1820 /* Check for whether this is a .exit address. By default, those are
1821 * disallowed when they're coming straight from the client, but you're
1822 * allowed to have them in MapAddress commands and so forth. */
1823 if (!strcmpend(socks
->address
, ".exit")) {
1824 static ratelim_t exit_warning_limit
= RATELIM_INIT(60*15);
1825 log_fn_ratelim(&exit_warning_limit
, LOG_WARN
, LD_APP
,
1826 "The \".exit\" notation is disabled in Tor due to "
1828 control_event_client_status(LOG_WARN
, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1829 escaped(socks
->address
));
1830 out
->end_reason
= END_STREAM_REASON_TORPROTOCOL
;
1831 out
->should_close
= 1;
1835 /* Remember the original address so we can tell the user about what
1836 * they actually said, not just what it turned into. */
1837 /* XXX yes, this is the same as out->orig_address above. One is
1838 * in the output, and one is in the connection. */
1839 if (! conn
->original_dest_address
) {
1840 /* Is the 'if' necessary here? XXXX */
1841 conn
->original_dest_address
= tor_strdup(conn
->socks_request
->address
);
1844 /* First, apply MapAddress and MAPADDRESS mappings. We need to do
1845 * these only for non-reverse lookups, since they don't exist for those.
1846 * We also need to do this before we consider automapping, since we might
1847 * e.g. resolve irc.oftc.net into irconionaddress.onion, at which point
1848 * we'd need to automap it. */
1849 if (socks
->command
!= SOCKS_COMMAND_RESOLVE_PTR
) {
1850 const unsigned rewrite_flags
= AMR_FLAG_USE_MAPADDRESS
;
1851 if (addressmap_rewrite(socks
->address
, sizeof(socks
->address
),
1852 rewrite_flags
, &out
->map_expires
, &out
->exit_source
)) {
1853 control_event_stream_status(conn
, STREAM_EVENT_REMAP
,
1854 REMAP_STREAM_SOURCE_CACHE
);
1858 /* Now see if we need to create or return an existing Hostname->IP
1859 * automapping. Automapping happens when we're asked to resolve a
1860 * hostname, and AutomapHostsOnResolve is set, and the hostname has a
1861 * suffix listed in AutomapHostsSuffixes. It's a handy feature
1862 * that lets you have Tor assign e.g. IPv6 addresses for .onion
1863 * names, and return them safely from DNSPort.
1865 if (socks
->command
== SOCKS_COMMAND_RESOLVE
&&
1866 tor_addr_parse(&addr_tmp
, socks
->address
)<0 &&
1867 options
->AutomapHostsOnResolve
) {
1868 /* Check the suffix... */
1869 out
->automap
= addressmap_address_should_automap(socks
->address
, options
);
1871 /* If we get here, then we should apply an automapping for this. */
1872 const char *new_addr
;
1873 /* We return an IPv4 address by default, or an IPv6 address if we
1874 * are allowed to do so. */
1875 int addr_type
= RESOLVED_TYPE_IPV4
;
1876 if (conn
->socks_request
->socks_version
!= 4) {
1877 if (!conn
->entry_cfg
.ipv4_traffic
||
1878 (conn
->entry_cfg
.ipv6_traffic
&& conn
->entry_cfg
.prefer_ipv6
) ||
1879 conn
->entry_cfg
.prefer_ipv6_virtaddr
)
1880 addr_type
= RESOLVED_TYPE_IPV6
;
1882 /* Okay, register the target address as automapped, and find the new
1883 * address we're supposed to give as a resolve answer. (Return a cached
1884 * value if we've looked up this address before.
1886 new_addr
= addressmap_register_virtual_address(
1887 addr_type
, tor_strdup(socks
->address
));
1889 log_warn(LD_APP
, "Unable to automap address %s",
1890 escaped_safe_str(socks
->address
));
1891 out
->end_reason
= END_STREAM_REASON_INTERNAL
;
1892 out
->should_close
= 1;
1895 log_info(LD_APP
, "Automapping %s to %s",
1896 escaped_safe_str_client(socks
->address
),
1897 safe_str_client(new_addr
));
1898 strlcpy(socks
->address
, new_addr
, sizeof(socks
->address
));
1902 /* Now handle reverse lookups, if they're in the cache. This doesn't
1903 * happen too often, since client-side DNS caching is off by default,
1904 * and very deprecated. */
1905 if (socks
->command
== SOCKS_COMMAND_RESOLVE_PTR
) {
1906 unsigned rewrite_flags
= 0;
1907 if (conn
->entry_cfg
.use_cached_ipv4_answers
)
1908 rewrite_flags
|= AMR_FLAG_USE_IPV4_DNS
;
1909 if (conn
->entry_cfg
.use_cached_ipv6_answers
)
1910 rewrite_flags
|= AMR_FLAG_USE_IPV6_DNS
;
1912 if (addressmap_rewrite_reverse(socks
->address
, sizeof(socks
->address
),
1913 rewrite_flags
, &out
->map_expires
)) {
1914 char *result
= tor_strdup(socks
->address
);
1915 /* remember _what_ is supposed to have been resolved. */
1916 tor_snprintf(socks
->address
, sizeof(socks
->address
), "REVERSE[%s]",
1918 connection_ap_handshake_socks_resolved(conn
, RESOLVED_TYPE_HOSTNAME
,
1919 strlen(result
), (uint8_t*)result
,
1923 out
->end_reason
= END_STREAM_REASON_DONE
|
1924 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
;
1925 out
->should_close
= 1;
1929 /* Hang on, did we find an answer saying that this is a reverse lookup for
1930 * an internal address? If so, we should reject it if we're configured to
1932 if (options
->ClientDNSRejectInternalAddresses
) {
1933 /* Don't let clients try to do a reverse lookup on 10.0.0.1. */
1936 ok
= tor_addr_parse_PTR_name(
1937 &addr
, socks
->address
, AF_UNSPEC
, 1);
1938 if (ok
== 1 && tor_addr_is_internal(&addr
, 0)) {
1939 connection_ap_handshake_socks_resolved(conn
, RESOLVED_TYPE_ERROR
,
1940 0, NULL
, -1, TIME_MAX
);
1941 out
->end_reason
= END_STREAM_REASON_SOCKSPROTOCOL
|
1942 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
;
1943 out
->should_close
= 1;
1949 /* If we didn't automap it before, then this is still the address that
1950 * came straight from the user, mapped according to any
1951 * MapAddress/MAPADDRESS commands. Now apply other mappings,
1952 * including previously registered Automap entries (IP back to
1953 * hostname), TrackHostExits entries, and client-side DNS cache
1954 * entries (if they're turned on).
1956 if (socks
->command
!= SOCKS_COMMAND_RESOLVE_PTR
&&
1958 unsigned rewrite_flags
= AMR_FLAG_USE_AUTOMAP
| AMR_FLAG_USE_TRACKEXIT
;
1959 addressmap_entry_source_t exit_source2
;
1960 if (conn
->entry_cfg
.use_cached_ipv4_answers
)
1961 rewrite_flags
|= AMR_FLAG_USE_IPV4_DNS
;
1962 if (conn
->entry_cfg
.use_cached_ipv6_answers
)
1963 rewrite_flags
|= AMR_FLAG_USE_IPV6_DNS
;
1964 if (addressmap_rewrite(socks
->address
, sizeof(socks
->address
),
1965 rewrite_flags
, &out
->map_expires
, &exit_source2
)) {
1966 control_event_stream_status(conn
, STREAM_EVENT_REMAP
,
1967 REMAP_STREAM_SOURCE_CACHE
);
1969 if (out
->exit_source
== ADDRMAPSRC_NONE
) {
1970 /* If it wasn't a .exit before, maybe it turned into a .exit. Remember
1971 * the original source of a .exit. */
1972 out
->exit_source
= exit_source2
;
1976 /* Check to see whether we're about to use an address in the virtual
1977 * range without actually having gotten it from an Automap. */
1978 if (!out
->automap
&& address_is_in_virtual_range(socks
->address
)) {
1979 /* This address was probably handed out by
1980 * client_dns_get_unmapped_address, but the mapping was discarded for some
1981 * reason. Or the user typed in a virtual address range manually. We
1982 * *don't* want to send the address through Tor; that's likely to fail,
1983 * and may leak information.
1985 log_warn(LD_APP
,"Missing mapping for virtual address '%s'. Refusing.",
1986 safe_str_client(socks
->address
));
1987 out
->end_reason
= END_STREAM_REASON_INTERNAL
;
1988 out
->should_close
= 1;
1993 /** We just received a SOCKS request in <b>conn</b> to a v3 onion. Start
1994 * connecting to the onion service. */
1996 connection_ap_handle_onion(entry_connection_t
*conn
,
1997 socks_request_t
*socks
,
1998 origin_circuit_t
*circ
)
2001 time_t now
= approx_time();
2002 connection_t
*base_conn
= ENTRY_TO_CONN(conn
);
2004 /* If .onion address requests are disabled, refuse the request */
2005 if (!conn
->entry_cfg
.onion_traffic
) {
2006 log_warn(LD_APP
, "Onion address %s requested from a port with .onion "
2007 "disabled", safe_str_client(socks
->address
));
2008 connection_mark_unattached_ap(conn
, END_STREAM_REASON_ENTRYPOLICY
);
2012 /* Check whether it's RESOLVE or RESOLVE_PTR. We don't handle those
2013 * for hidden service addresses. */
2014 if (SOCKS_COMMAND_IS_RESOLVE(socks
->command
)) {
2015 /* if it's a resolve request, fail it right now, rather than
2016 * building all the circuits and then realizing it won't work. */
2018 "Resolve requests to hidden services not allowed. Failing.");
2019 connection_ap_handshake_socks_resolved(conn
,RESOLVED_TYPE_ERROR
,
2020 0,NULL
,-1,TIME_MAX
);
2021 connection_mark_unattached_ap(conn
,
2022 END_STREAM_REASON_SOCKSPROTOCOL
|
2023 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
);
2027 /* If we were passed a circuit, then we need to fail. .onion addresses
2028 * only work when we launch our own circuits for now. */
2030 log_warn(LD_CONTROL
, "Attachstream to a circuit is not "
2031 "supported for .onion addresses currently. Failing.");
2032 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
2036 int descriptor_is_usable
= 0;
2038 /* Create HS conn identifier with HS pubkey */
2039 hs_ident_edge_conn_t
*hs_conn_ident
=
2040 tor_malloc_zero(sizeof(hs_ident_edge_conn_t
));
2042 retval
= hs_parse_address(socks
->address
, &hs_conn_ident
->identity_pk
,
2045 log_warn(LD_GENERAL
, "failed to parse hs address");
2046 tor_free(hs_conn_ident
);
2049 ENTRY_TO_EDGE_CONN(conn
)->hs_ident
= hs_conn_ident
;
2051 /* Check the v3 desc cache */
2052 const hs_descriptor_t
*cached_desc
= NULL
;
2053 unsigned int refetch_desc
= 0;
2054 cached_desc
= hs_cache_lookup_as_client(&hs_conn_ident
->identity_pk
);
2056 descriptor_is_usable
=
2057 hs_client_any_intro_points_usable(&hs_conn_ident
->identity_pk
,
2059 /* Check if PoW parameters have expired. If yes, the descriptor is
2061 if (cached_desc
->encrypted_data
.pow_params
) {
2062 if (cached_desc
->encrypted_data
.pow_params
->expiration_time
<
2064 log_info(LD_REND
, "Descriptor PoW parameters have expired.");
2065 descriptor_is_usable
= 0;
2067 /* Mark that the connection is to an HS with PoW defenses on. */
2068 conn
->hs_with_pow_conn
= 1;
2072 log_info(LD_GENERAL
, "Found %s descriptor in cache for %s. %s.",
2073 (descriptor_is_usable
) ? "usable" : "unusable",
2074 safe_str_client(socks
->address
),
2075 (descriptor_is_usable
) ? "Not fetching." : "Refetching.");
2077 /* We couldn't find this descriptor; we should look it up. */
2078 log_info(LD_REND
, "No descriptor found in our cache for %s. Fetching.",
2079 safe_str_client(socks
->address
));
2083 /* Help predict that we'll want to do hidden service circuits in the
2084 * future. We're not sure if it will need a stable circuit yet, but
2085 * we know we'll need *something*. */
2086 rep_hist_note_used_internal(now
, 0, 1);
2088 /* Now we have a descriptor but is it usable or not? If not, refetch.
2089 * Also, a fetch could have been requested if the onion address was not
2090 * found in the cache previously. */
2091 if (refetch_desc
|| !descriptor_is_usable
) {
2092 edge_connection_t
*edge_conn
= ENTRY_TO_EDGE_CONN(conn
);
2093 connection_ap_mark_as_non_pending_circuit(conn
);
2094 base_conn
->state
= AP_CONN_STATE_RENDDESC_WAIT
;
2095 tor_assert(edge_conn
->hs_ident
);
2096 /* Attempt to fetch the hsv3 descriptor. Check the retval to see how it
2097 * went and act accordingly. */
2098 int ret
= hs_client_refetch_hsdesc(&edge_conn
->hs_ident
->identity_pk
);
2100 case HS_CLIENT_FETCH_MISSING_INFO
:
2101 /* Keeping the connection in descriptor wait state is fine because
2102 * once we get enough dirinfo or a new live consensus, the HS client
2103 * subsystem is notified and every connection in that state will
2104 * trigger a fetch for the service key. */
2105 case HS_CLIENT_FETCH_LAUNCHED
:
2106 case HS_CLIENT_FETCH_PENDING
:
2107 case HS_CLIENT_FETCH_HAVE_DESC
:
2109 case HS_CLIENT_FETCH_ERROR
:
2110 case HS_CLIENT_FETCH_NO_HSDIRS
:
2111 case HS_CLIENT_FETCH_NOT_ALLOWED
:
2112 /* Can't proceed further and better close the SOCKS request. */
2117 /* We have the descriptor! So launch a connection to the HS. */
2118 log_info(LD_REND
, "Descriptor is here. Great.");
2120 base_conn
->state
= AP_CONN_STATE_CIRCUIT_WAIT
;
2121 /* We'll try to attach it at the next event loop, or whenever
2122 * we call connection_ap_attach_pending() */
2123 connection_ap_mark_as_pending_circuit(conn
);
2127 /** Connection <b>conn</b> just finished its socks handshake, or the
2128 * controller asked us to take care of it. If <b>circ</b> is defined,
2129 * then that's where we'll want to attach it. Otherwise we have to
2130 * figure it out ourselves.
2132 * First, parse whether it's a .exit address, remap it, and so on. Then
2133 * if it's for a general circuit, try to attach it to a circuit (or launch
2134 * one as needed), else if it's for a rendezvous circuit, fetch a
2135 * rendezvous descriptor first (or attach/launch a circuit if the
2136 * rendezvous descriptor is already here and fresh enough).
2138 * The stream will exit from the hop
2139 * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
2140 * <b>cpath</b> is NULL.
2143 connection_ap_handshake_rewrite_and_attach(entry_connection_t
*conn
,
2144 origin_circuit_t
*circ
,
2145 crypt_path_t
*cpath
)
2147 socks_request_t
*socks
= conn
->socks_request
;
2148 const or_options_t
*options
= get_options();
2149 connection_t
*base_conn
= ENTRY_TO_CONN(conn
);
2150 time_t now
= time(NULL
);
2151 rewrite_result_t rr
;
2153 /* First we'll do the rewrite part. Let's see if we get a reasonable
2156 memset(&rr
, 0, sizeof(rr
));
2157 connection_ap_handshake_rewrite(conn
,&rr
);
2159 if (rr
.should_close
) {
2160 /* connection_ap_handshake_rewrite told us to close the connection:
2161 * either because it sent back an answer, or because it sent back an
2163 connection_mark_unattached_ap(conn
, rr
.end_reason
);
2164 if (END_STREAM_REASON_DONE
== (rr
.end_reason
& END_STREAM_REASON_MASK
))
2170 const time_t map_expires
= rr
.map_expires
;
2171 const int automap
= rr
.automap
;
2172 const addressmap_entry_source_t exit_source
= rr
.exit_source
;
2174 /* Now see whether the hostname is bogus. This could happen because of an
2175 * onion hostname whose format we don't recognize. */
2176 hostname_type_t addresstype
;
2177 if (!parse_extended_hostname(socks
->address
, &addresstype
)) {
2178 control_event_client_status(LOG_WARN
, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
2179 escaped(socks
->address
));
2180 if (addresstype
== BAD_HOSTNAME
) {
2181 conn
->socks_request
->socks_extended_error_code
= SOCKS5_HS_BAD_ADDRESS
;
2183 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
2187 /* If this is a .exit hostname, strip off the .name.exit part, and
2188 * see whether we're willing to connect there, and otherwise handle the
2191 * We'll set chosen_exit_name and/or close the connection as appropriate.
2193 if (addresstype
== EXIT_HOSTNAME
) {
2194 /* If StrictNodes is not set, then .exit overrides ExcludeNodes but
2195 * not ExcludeExitNodes. */
2196 routerset_t
*excludeset
= options
->StrictNodes
?
2197 options
->ExcludeExitNodesUnion_
: options
->ExcludeExitNodes
;
2198 const node_t
*node
= NULL
;
2200 /* If this .exit was added by an AUTOMAP, then it came straight from
2201 * a user. That's not safe. */
2202 if (exit_source
== ADDRMAPSRC_AUTOMAP
) {
2203 /* Whoops; this one is stale. It must have gotten added earlier?
2204 * (Probably this is not possible, since AllowDotExit no longer
2206 log_warn(LD_APP
,"Stale automapped address for '%s.exit'. Refusing.",
2207 safe_str_client(socks
->address
));
2208 control_event_client_status(LOG_WARN
, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
2209 escaped(socks
->address
));
2210 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
2211 tor_assert_nonfatal_unreached();
2215 /* Double-check to make sure there are no .exits coming from
2216 * impossible/weird sources. */
2217 if (exit_source
== ADDRMAPSRC_DNS
|| exit_source
== ADDRMAPSRC_NONE
) {
2218 /* It shouldn't be possible to get a .exit address from any of these
2220 log_warn(LD_BUG
,"Address '%s.exit', with impossible source for the "
2221 ".exit part. Refusing.",
2222 safe_str_client(socks
->address
));
2223 control_event_client_status(LOG_WARN
, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
2224 escaped(socks
->address
));
2225 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
2229 tor_assert(!automap
);
2231 /* Now, find the character before the .(name) part.
2232 * (The ".exit" part got stripped off by "parse_extended_hostname").
2234 * We're going to put the exit name into conn->chosen_exit_name, and
2235 * look up a node correspondingly. */
2236 char *s
= strrchr(socks
->address
,'.');
2238 /* The address was of the form "(stuff).(name).exit */
2240 /* Looks like a real .exit one. */
2241 conn
->chosen_exit_name
= tor_strdup(s
+1);
2242 node
= node_get_by_nickname(conn
->chosen_exit_name
, 0);
2244 if (exit_source
== ADDRMAPSRC_TRACKEXIT
) {
2245 /* We 5 tries before it expires the addressmap */
2246 conn
->chosen_exit_retries
= TRACKHOSTEXITS_RETRIES
;
2250 /* Oops, the address was (stuff)..exit. That's not okay. */
2251 log_warn(LD_APP
,"Malformed exit address '%s.exit'. Refusing.",
2252 safe_str_client(socks
->address
));
2253 control_event_client_status(LOG_WARN
, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
2254 escaped(socks
->address
));
2255 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
2259 /* It looks like they just asked for "foo.exit". That's a special
2260 * form that means (foo's address).foo.exit. */
2262 conn
->chosen_exit_name
= tor_strdup(socks
->address
);
2263 node
= node_get_by_nickname(conn
->chosen_exit_name
, 0);
2265 *socks
->address
= 0;
2266 node_get_address_string(node
, socks
->address
, sizeof(socks
->address
));
2270 /* Now make sure that the chosen exit exists... */
2273 "Unrecognized relay in exit address '%s.exit'. Refusing.",
2274 safe_str_client(socks
->address
));
2275 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
2278 /* ...and make sure that it isn't excluded. */
2279 if (routerset_contains_node(excludeset
, node
)) {
2281 "Excluded relay in exit address '%s.exit'. Refusing.",
2282 safe_str_client(socks
->address
));
2283 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
2286 /* XXXX-1090 Should we also allow foo.bar.exit if ExitNodes is set and
2287 Bar is not listed in it? I say yes, but our revised manpage branch
2291 /* Now, we handle everything that isn't a .onion address. */
2292 if (addresstype
!= ONION_V3_HOSTNAME
) {
2293 /* Not a hidden-service request. It's either a hostname or an IP,
2294 * possibly with a .exit that we stripped off. We're going to check
2295 * if we're allowed to connect/resolve there, and then launch the
2296 * appropriate request. */
2298 /* Check for funny characters in the address. */
2299 if (address_is_invalid_destination(socks
->address
, 1)) {
2300 control_event_client_status(LOG_WARN
, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
2301 escaped(socks
->address
));
2303 "Destination '%s' seems to be an invalid hostname. Failing.",
2304 safe_str_client(socks
->address
));
2305 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
2309 /* socks->address is a non-onion hostname or IP address.
2310 * If we can't do any non-onion requests, refuse the connection.
2311 * If we have a hostname but can't do DNS, refuse the connection.
2312 * If we have an IP address, but we can't use that address family,
2313 * refuse the connection.
2315 * If we can do DNS requests, and we can use at least one address family,
2316 * then we have to resolve the address first. Then we'll know if it
2317 * resolves to a usable address family. */
2319 /* First, check if all non-onion traffic is disabled */
2320 if (!conn
->entry_cfg
.dns_request
&& !conn
->entry_cfg
.ipv4_traffic
2321 && !conn
->entry_cfg
.ipv6_traffic
) {
2322 log_warn(LD_APP
, "Refusing to connect to non-hidden-service hostname "
2323 "or IP address %s because Port has OnionTrafficOnly set (or "
2324 "NoDNSRequest, NoIPv4Traffic, and NoIPv6Traffic).",
2325 safe_str_client(socks
->address
));
2326 connection_mark_unattached_ap(conn
, END_STREAM_REASON_ENTRYPOLICY
);
2330 /* Then check if we have a hostname or IP address, and whether DNS or
2331 * the IP address family are permitted. Reject if not. */
2332 tor_addr_t dummy_addr
;
2333 int socks_family
= tor_addr_parse(&dummy_addr
, socks
->address
);
2334 /* family will be -1 for a non-onion hostname that's not an IP */
2335 if (socks_family
== -1) {
2336 if (!conn
->entry_cfg
.dns_request
) {
2337 log_warn(LD_APP
, "Refusing to connect to hostname %s "
2338 "because Port has NoDNSRequest set.",
2339 safe_str_client(socks
->address
));
2340 connection_mark_unattached_ap(conn
, END_STREAM_REASON_ENTRYPOLICY
);
2343 } else if (socks_family
== AF_INET
) {
2344 if (!conn
->entry_cfg
.ipv4_traffic
) {
2345 log_warn(LD_APP
, "Refusing to connect to IPv4 address %s because "
2346 "Port has NoIPv4Traffic set.",
2347 safe_str_client(socks
->address
));
2348 connection_mark_unattached_ap(conn
, END_STREAM_REASON_ENTRYPOLICY
);
2351 } else if (socks_family
== AF_INET6
) {
2352 if (!conn
->entry_cfg
.ipv6_traffic
) {
2353 log_warn(LD_APP
, "Refusing to connect to IPv6 address %s because "
2354 "Port has NoIPv6Traffic set.",
2355 safe_str_client(socks
->address
));
2356 connection_mark_unattached_ap(conn
, END_STREAM_REASON_ENTRYPOLICY
);
2360 tor_assert_nonfatal_unreached_once();
2363 /* See if this is a hostname lookup that we can answer immediately.
2364 * (For example, an attempt to look up the IP address for an IP address.)
2366 if (socks
->command
== SOCKS_COMMAND_RESOLVE
) {
2368 /* Reply to resolves immediately if we can. */
2369 if (tor_addr_parse(&answer
, socks
->address
) >= 0) {/* is it an IP? */
2370 /* remember _what_ is supposed to have been resolved. */
2371 strlcpy(socks
->address
, rr
.orig_address
, sizeof(socks
->address
));
2372 connection_ap_handshake_socks_resolved_addr(conn
, &answer
, -1,
2374 connection_mark_unattached_ap(conn
,
2375 END_STREAM_REASON_DONE
|
2376 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
);
2379 tor_assert(!automap
);
2380 rep_hist_note_used_resolve(now
); /* help predict this next time */
2381 } else if (socks
->command
== SOCKS_COMMAND_CONNECT
) {
2382 /* Now see if this is a connect request that we can reject immediately */
2384 tor_assert(!automap
);
2385 /* Don't allow connections to port 0. */
2386 if (socks
->port
== 0) {
2387 log_notice(LD_APP
,"Application asked to connect to port 0. Refusing.");
2388 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
2391 /* You can't make connections to internal addresses, by default.
2392 * Exceptions are begindir requests (where the address is meaningless),
2393 * or cases where you've hand-configured a particular exit, thereby
2394 * making the local address meaningful. */
2395 if (options
->ClientRejectInternalAddresses
&&
2396 !conn
->use_begindir
&& !conn
->chosen_exit_name
&& !circ
) {
2397 /* If we reach this point then we don't want to allow internal
2398 * addresses. Check if we got one. */
2400 if (tor_addr_hostname_is_local(socks
->address
) ||
2401 (tor_addr_parse(&addr
, socks
->address
) >= 0 &&
2402 tor_addr_is_internal(&addr
, 0))) {
2403 /* If this is an explicit private address with no chosen exit node,
2404 * then we really don't want to try to connect to it. That's
2405 * probably an error. */
2406 if (conn
->is_transparent_ap
) {
2407 #define WARN_INTRVL_LOOP 300
2408 static ratelim_t loop_warn_limit
= RATELIM_INIT(WARN_INTRVL_LOOP
);
2410 if ((m
= rate_limit_log(&loop_warn_limit
, approx_time()))) {
2412 "Rejecting request for anonymous connection to private "
2413 "address %s on a TransPort or NATDPort. Possible loop "
2414 "in your NAT rules?%s", safe_str_client(socks
->address
),
2419 #define WARN_INTRVL_PRIV 300
2420 static ratelim_t priv_warn_limit
= RATELIM_INIT(WARN_INTRVL_PRIV
);
2422 if ((m
= rate_limit_log(&priv_warn_limit
, approx_time()))) {
2424 "Rejecting SOCKS request for anonymous connection to "
2425 "private address %s.%s",
2426 safe_str_client(socks
->address
),m
);
2430 connection_mark_unattached_ap(conn
, END_STREAM_REASON_PRIVATE_ADDR
);
2433 } /* end "if we should check for internal addresses" */
2435 /* Okay. We're still doing a CONNECT, and it wasn't a private
2436 * address. Here we do special handling for literal IP addresses,
2437 * to see if we should reject this preemptively, and to set up
2438 * fields in conn->entry_cfg to tell the exit what AF we want. */
2441 /* XXX Duplicate call to tor_addr_parse. */
2442 if (tor_addr_parse(&addr
, socks
->address
) >= 0) {
2443 /* If we reach this point, it's an IPv4 or an IPv6 address. */
2444 sa_family_t family
= tor_addr_family(&addr
);
2446 if ((family
== AF_INET
&& ! conn
->entry_cfg
.ipv4_traffic
) ||
2447 (family
== AF_INET6
&& ! conn
->entry_cfg
.ipv6_traffic
)) {
2448 /* You can't do an IPv4 address on a v6-only socks listener,
2450 log_warn(LD_NET
, "Rejecting SOCKS request for an IP address "
2451 "family that this listener does not support.");
2452 connection_mark_unattached_ap(conn
, END_STREAM_REASON_ENTRYPOLICY
);
2454 } else if (family
== AF_INET6
&& socks
->socks_version
== 4) {
2455 /* You can't make a socks4 request to an IPv6 address. Socks4
2456 * doesn't support that. */
2457 log_warn(LD_NET
, "Rejecting SOCKS4 request for an IPv6 address.");
2458 connection_mark_unattached_ap(conn
, END_STREAM_REASON_ENTRYPOLICY
);
2460 } else if (socks
->socks_version
== 4 &&
2461 !conn
->entry_cfg
.ipv4_traffic
) {
2462 /* You can't do any kind of Socks4 request when IPv4 is forbidden.
2464 * XXX raise this check outside the enclosing block? */
2465 log_warn(LD_NET
, "Rejecting SOCKS4 request on a listener with "
2466 "no IPv4 traffic supported.");
2467 connection_mark_unattached_ap(conn
, END_STREAM_REASON_ENTRYPOLICY
);
2469 } else if (family
== AF_INET6
) {
2470 /* Tell the exit: we won't accept any ipv4 connection to an IPv6
2472 conn
->entry_cfg
.ipv4_traffic
= 0;
2473 } else if (family
== AF_INET
) {
2474 /* Tell the exit: we won't accept any ipv6 connection to an IPv4
2476 conn
->entry_cfg
.ipv6_traffic
= 0;
2479 /* Next, yet another check: we know it's a direct IP address. Is it
2480 * the IP address of a known relay and its ORPort, or of a directory
2481 * authority and its OR or Dir Port? If so, and if a consensus param
2482 * says to, then exit relays will refuse this request (see ticket
2483 * 2667 for details). Let's just refuse it locally right now, to
2484 * save time and network load but also to give the user a more
2485 * useful log message. */
2486 if (!network_reentry_is_allowed() &&
2487 nodelist_reentry_contains(&addr
, socks
->port
)) {
2488 log_warn(LD_APP
, "Not attempting connection to %s:%d because "
2489 "the network would reject it. Are you trying to send "
2490 "Tor traffic over Tor? This traffic can be harmful to "
2491 "the Tor network. If you really need it, try using "
2492 "a bridge as a workaround.",
2493 safe_str_client(socks
->address
), socks
->port
);
2494 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
2500 /* we never allow IPv6 answers on socks4. (TODO: Is this smart?) */
2501 if (socks
->socks_version
== 4)
2502 conn
->entry_cfg
.ipv6_traffic
= 0;
2504 /* Still handling CONNECT. Now, check for exit enclaves. (Which we
2505 * don't do on BEGIN_DIR, or when there is a chosen exit.)
2507 * TODO: Should we remove this? Exit enclaves are nutty and don't
2510 if (!conn
->use_begindir
&& !conn
->chosen_exit_name
&& !circ
) {
2511 /* see if we can find a suitable enclave exit */
2513 router_find_exact_exit_enclave(socks
->address
, socks
->port
);
2516 "Redirecting address %s to exit at enclave router %s",
2517 safe_str_client(socks
->address
), node_describe(r
));
2518 /* use the hex digest, not nickname, in case there are two
2519 routers with this nickname */
2520 conn
->chosen_exit_name
=
2521 tor_strdup(hex_str(r
->identity
, DIGEST_LEN
));
2522 conn
->chosen_exit_optional
= 1;
2526 /* Still handling CONNECT: warn or reject if it's using a dangerous
2528 if (!conn
->use_begindir
&& !conn
->chosen_exit_name
&& !circ
)
2529 if (consider_plaintext_ports(conn
, socks
->port
) < 0)
2532 /* Remember the port so that we will predict that more requests
2533 there will happen in the future. */
2534 if (!conn
->use_begindir
) {
2535 /* help predict this next time */
2536 rep_hist_note_used_port(now
, socks
->port
);
2538 } else if (socks
->command
== SOCKS_COMMAND_RESOLVE_PTR
) {
2539 rep_hist_note_used_resolve(now
); /* help predict this next time */
2540 /* no extra processing needed */
2542 /* We should only be doing CONNECT, RESOLVE, or RESOLVE_PTR! */
2543 tor_fragile_assert();
2546 /* Okay. At this point we've set chosen_exit_name if needed, rewritten the
2547 * address, and decided not to reject it for any number of reasons. Now
2548 * mark the connection as waiting for a circuit, and try to attach it!
2550 base_conn
->state
= AP_CONN_STATE_CIRCUIT_WAIT
;
2552 /* If we were given a circuit to attach to, try to attach. Otherwise,
2553 * try to find a good one and attach to that. */
2556 rv
= connection_ap_handshake_attach_chosen_circuit(conn
, circ
, cpath
);
2558 /* We'll try to attach it at the next event loop, or whenever
2559 * we call connection_ap_attach_pending() */
2560 connection_ap_mark_as_pending_circuit(conn
);
2564 /* If the above function returned 0 then we're waiting for a circuit.
2565 * if it returned 1, we're attached. Both are okay. But if it returned
2566 * -1, there was an error, so make sure the connection is marked, and
2569 if (!base_conn
->marked_for_close
)
2570 connection_mark_unattached_ap(conn
, END_STREAM_REASON_CANT_ATTACH
);
2576 /* If we get here, it's a request for a .onion address! */
2577 tor_assert(addresstype
== ONION_V3_HOSTNAME
);
2578 tor_assert(!automap
);
2579 return connection_ap_handle_onion(conn
, socks
, circ
);
2582 return 0; /* unreached but keeps the compiler happy */
2586 static int pf_socket
= -1;
2591 /* This should be opened before dropping privileges. */
2595 #if defined(OpenBSD)
2596 /* only works on OpenBSD */
2597 pf
= tor_open_cloexec("/dev/pf", O_RDONLY
, 0);
2599 /* works on NetBSD and FreeBSD */
2600 pf
= tor_open_cloexec("/dev/pf", O_RDWR
, 0);
2601 #endif /* defined(OpenBSD) */
2604 log_warn(LD_NET
, "open(\"/dev/pf\") failed: %s", strerror(errno
));
2611 #endif /* defined(TRANS_PF) */
2613 #if defined(TRANS_NETFILTER) || defined(TRANS_PF) || \
2614 defined(TRANS_TPROXY)
2615 /** Try fill in the address of <b>req</b> from the socket configured
2616 * with <b>conn</b>. */
2618 destination_from_socket(entry_connection_t
*conn
, socks_request_t
*req
)
2620 struct sockaddr_storage orig_dst
;
2621 socklen_t orig_dst_len
= sizeof(orig_dst
);
2625 if (get_options()->TransProxyType_parsed
== TPT_TPROXY
) {
2626 if (getsockname(ENTRY_TO_CONN(conn
)->s
, (struct sockaddr
*)&orig_dst
,
2627 &orig_dst_len
) < 0) {
2628 int e
= tor_socket_errno(ENTRY_TO_CONN(conn
)->s
);
2629 log_warn(LD_NET
, "getsockname() failed: %s", tor_socket_strerror(e
));
2634 #endif /* defined(TRANS_TPROXY) */
2636 #ifdef TRANS_NETFILTER
2638 switch (ENTRY_TO_CONN(conn
)->socket_family
) {
2639 #ifdef TRANS_NETFILTER_IPV4
2641 rv
= getsockopt(ENTRY_TO_CONN(conn
)->s
, SOL_IP
, SO_ORIGINAL_DST
,
2642 (struct sockaddr
*)&orig_dst
, &orig_dst_len
);
2644 #endif /* defined(TRANS_NETFILTER_IPV4) */
2645 #ifdef TRANS_NETFILTER_IPV6
2647 rv
= getsockopt(ENTRY_TO_CONN(conn
)->s
, SOL_IPV6
, IP6T_SO_ORIGINAL_DST
,
2648 (struct sockaddr
*)&orig_dst
, &orig_dst_len
);
2650 #endif /* defined(TRANS_NETFILTER_IPV6) */
2652 log_warn(LD_BUG
, "Received transparent data from an unsupported "
2654 ENTRY_TO_CONN(conn
)->socket_family
);
2658 int e
= tor_socket_errno(ENTRY_TO_CONN(conn
)->s
);
2659 log_warn(LD_NET
, "getsockopt() failed: %s", tor_socket_strerror(e
));
2663 #elif defined(TRANS_PF)
2664 if (getsockname(ENTRY_TO_CONN(conn
)->s
, (struct sockaddr
*)&orig_dst
,
2665 &orig_dst_len
) < 0) {
2666 int e
= tor_socket_errno(ENTRY_TO_CONN(conn
)->s
);
2667 log_warn(LD_NET
, "getsockname() failed: %s", tor_socket_strerror(e
));
2674 log_warn(LD_BUG
, "Unable to determine destination from socket.");
2676 #endif /* defined(TRANS_NETFILTER) || ... */
2679 tor_addr_from_sockaddr(&addr
, (struct sockaddr
*)&orig_dst
, &req
->port
);
2680 tor_addr_to_str(req
->address
, &addr
, sizeof(req
->address
), 1);
2684 #endif /* defined(TRANS_NETFILTER) || defined(TRANS_PF) || ... */
2688 destination_from_pf(entry_connection_t
*conn
, socks_request_t
*req
)
2690 struct sockaddr_storage proxy_addr
;
2691 socklen_t proxy_addr_len
= sizeof(proxy_addr
);
2692 struct sockaddr
*proxy_sa
= (struct sockaddr
*) &proxy_addr
;
2693 struct pfioc_natlook pnl
;
2697 if (getsockname(ENTRY_TO_CONN(conn
)->s
, (struct sockaddr
*)&proxy_addr
,
2698 &proxy_addr_len
) < 0) {
2699 int e
= tor_socket_errno(ENTRY_TO_CONN(conn
)->s
);
2700 log_warn(LD_NET
, "getsockname() to determine transocks destination "
2701 "failed: %s", tor_socket_strerror(e
));
2706 if (get_options()->TransProxyType_parsed
== TPT_IPFW
) {
2707 /* ipfw(8) is used and in this case getsockname returned the original
2709 if (tor_addr_from_sockaddr(&addr
, proxy_sa
, &req
->port
) < 0) {
2710 tor_fragile_assert();
2714 tor_addr_to_str(req
->address
, &addr
, sizeof(req
->address
), 0);
2718 #endif /* defined(__FreeBSD__) */
2720 memset(&pnl
, 0, sizeof(pnl
));
2721 pnl
.proto
= IPPROTO_TCP
;
2722 pnl
.direction
= PF_OUT
;
2723 if (proxy_sa
->sa_family
== AF_INET
) {
2724 struct sockaddr_in
*sin
= (struct sockaddr_in
*)proxy_sa
;
2726 pnl
.saddr
.v4
.s_addr
= tor_addr_to_ipv4n(&ENTRY_TO_CONN(conn
)->addr
);
2727 pnl
.sport
= htons(ENTRY_TO_CONN(conn
)->port
);
2728 pnl
.daddr
.v4
.s_addr
= sin
->sin_addr
.s_addr
;
2729 pnl
.dport
= sin
->sin_port
;
2730 } else if (proxy_sa
->sa_family
== AF_INET6
) {
2731 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*)proxy_sa
;
2733 const struct in6_addr
*dest_in6
=
2734 tor_addr_to_in6(&ENTRY_TO_CONN(conn
)->addr
);
2737 memcpy(&pnl
.saddr
.v6
, dest_in6
, sizeof(struct in6_addr
));
2738 pnl
.sport
= htons(ENTRY_TO_CONN(conn
)->port
);
2739 memcpy(&pnl
.daddr
.v6
, &sin6
->sin6_addr
, sizeof(struct in6_addr
));
2740 pnl
.dport
= sin6
->sin6_port
;
2742 log_warn(LD_NET
, "getsockname() gave an unexpected address family (%d)",
2743 (int)proxy_sa
->sa_family
);
2747 pf
= get_pf_socket();
2751 if (ioctl(pf
, DIOCNATLOOK
, &pnl
) < 0) {
2752 log_warn(LD_NET
, "ioctl(DIOCNATLOOK) failed: %s", strerror(errno
));
2756 if (pnl
.af
== AF_INET
) {
2757 tor_addr_from_ipv4n(&addr
, pnl
.rdaddr
.v4
.s_addr
);
2758 } else if (pnl
.af
== AF_INET6
) {
2759 tor_addr_from_in6(&addr
, &pnl
.rdaddr
.v6
);
2761 tor_fragile_assert();
2765 tor_addr_to_str(req
->address
, &addr
, sizeof(req
->address
), 1);
2766 req
->port
= ntohs(pnl
.rdport
);
2770 #endif /* defined(TRANS_PF) */
2772 /** Fetch the original destination address and port from a
2773 * system-specific interface and put them into a
2774 * socks_request_t as if they came from a socks request.
2776 * Return -1 if an error prevents fetching the destination,
2780 connection_ap_get_original_destination(entry_connection_t
*conn
,
2781 socks_request_t
*req
)
2783 #ifdef TRANS_NETFILTER
2784 return destination_from_socket(conn
, req
);
2785 #elif defined(TRANS_PF)
2786 const or_options_t
*options
= get_options();
2788 if (options
->TransProxyType_parsed
== TPT_PF_DIVERT
)
2789 return destination_from_socket(conn
, req
);
2791 if (options
->TransProxyType_parsed
== TPT_DEFAULT
||
2792 options
->TransProxyType_parsed
== TPT_IPFW
)
2793 return destination_from_pf(conn
, req
);
2797 log_warn(LD_BUG
, "Proxy destination determination mechanism %s unknown.",
2798 options
->TransProxyType
);
2803 log_warn(LD_BUG
, "Called connection_ap_get_original_destination, but no "
2804 "transparent proxy method was configured.");
2806 #endif /* defined(TRANS_NETFILTER) || ... */
2809 /** connection_edge_process_inbuf() found a conn in state
2810 * socks_wait. See if conn->inbuf has the right bytes to proceed with
2811 * the socks handshake.
2813 * If the handshake is complete, send it to
2814 * connection_ap_handshake_rewrite_and_attach().
2816 * Return -1 if an unexpected error with conn occurs (and mark it for close),
2820 connection_ap_handshake_process_socks(entry_connection_t
*conn
)
2822 socks_request_t
*socks
;
2824 const or_options_t
*options
= get_options();
2826 connection_t
*base_conn
= ENTRY_TO_CONN(conn
);
2829 tor_assert(base_conn
->type
== CONN_TYPE_AP
);
2830 tor_assert(base_conn
->state
== AP_CONN_STATE_SOCKS_WAIT
);
2831 tor_assert(conn
->socks_request
);
2832 socks
= conn
->socks_request
;
2834 log_debug(LD_APP
,"entered.");
2836 sockshere
= fetch_from_buf_socks(base_conn
->inbuf
, socks
,
2837 options
->TestSocks
, options
->SafeSocks
);
2839 if (socks
->replylen
) {
2841 connection_buf_add((const char*)socks
->reply
, socks
->replylen
,
2843 socks
->replylen
= 0;
2844 if (sockshere
== -1) {
2845 /* An invalid request just got a reply, no additional
2846 * one is necessary. */
2847 socks
->has_finished
= 1;
2851 if (sockshere
== 0) {
2852 log_debug(LD_APP
,"socks handshake not all here yet.");
2854 } else if (sockshere
== -1) {
2856 log_warn(LD_APP
,"Fetching socks handshake failed. Closing.");
2857 connection_ap_handshake_socks_reply(conn
, NULL
, 0,
2858 END_STREAM_REASON_SOCKSPROTOCOL
);
2860 connection_mark_unattached_ap(conn
,
2861 END_STREAM_REASON_SOCKSPROTOCOL
|
2862 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
);
2864 } /* else socks handshake is done, continue processing */
2866 if (SOCKS_COMMAND_IS_CONNECT(socks
->command
))
2867 control_event_stream_status(conn
, STREAM_EVENT_NEW
, 0);
2869 control_event_stream_status(conn
, STREAM_EVENT_NEW_RESOLVE
, 0);
2871 return connection_ap_rewrite_and_attach_if_allowed(conn
, NULL
, NULL
);
2874 /** connection_init_accepted_conn() found a new trans AP conn.
2875 * Get the original destination and send it to
2876 * connection_ap_handshake_rewrite_and_attach().
2878 * Return -1 if an unexpected error with conn (and it should be marked
2879 * for close), else return 0.
2882 connection_ap_process_transparent(entry_connection_t
*conn
)
2884 socks_request_t
*socks
;
2887 tor_assert(conn
->socks_request
);
2888 socks
= conn
->socks_request
;
2890 /* pretend that a socks handshake completed so we don't try to
2891 * send a socks reply down a transparent conn */
2892 socks
->command
= SOCKS_COMMAND_CONNECT
;
2893 socks
->has_finished
= 1;
2895 log_debug(LD_APP
,"entered.");
2897 if (connection_ap_get_original_destination(conn
, socks
) < 0) {
2898 log_warn(LD_APP
,"Fetching original destination failed. Closing.");
2899 connection_mark_unattached_ap(conn
,
2900 END_STREAM_REASON_CANT_FETCH_ORIG_DEST
);
2903 /* we have the original destination */
2905 control_event_stream_status(conn
, STREAM_EVENT_NEW
, 0);
2907 return connection_ap_rewrite_and_attach_if_allowed(conn
, NULL
, NULL
);
2910 /** connection_edge_process_inbuf() found a conn in state natd_wait. See if
2911 * conn-\>inbuf has the right bytes to proceed. See FreeBSD's libalias(3) and
2912 * ProxyEncodeTcpStream() in src/lib/libalias/alias_proxy.c for the encoding
2913 * form of the original destination.
2915 * If the original destination is complete, send it to
2916 * connection_ap_handshake_rewrite_and_attach().
2918 * Return -1 if an unexpected error with conn (and it should be marked
2919 * for close), else return 0.
2922 connection_ap_process_natd(entry_connection_t
*conn
)
2924 char tmp_buf
[36], *tbuf
, *daddr
;
2927 socks_request_t
*socks
;
2930 tor_assert(ENTRY_TO_CONN(conn
)->state
== AP_CONN_STATE_NATD_WAIT
);
2931 tor_assert(conn
->socks_request
);
2932 socks
= conn
->socks_request
;
2934 log_debug(LD_APP
,"entered.");
2936 /* look for LF-terminated "[DEST ip_addr port]"
2937 * where ip_addr is a dotted-quad and port is in string form */
2938 err
= connection_buf_get_line(ENTRY_TO_CONN(conn
), tmp_buf
, &tlen
);
2942 log_warn(LD_APP
,"NATD handshake failed (DEST too long). Closing");
2943 connection_mark_unattached_ap(conn
, END_STREAM_REASON_INVALID_NATD_DEST
);
2947 if (strcmpstart(tmp_buf
, "[DEST ")) {
2948 log_warn(LD_APP
,"NATD handshake was ill-formed; closing. The client "
2951 connection_mark_unattached_ap(conn
, END_STREAM_REASON_INVALID_NATD_DEST
);
2955 daddr
= tbuf
= &tmp_buf
[0] + 6; /* after end of "[DEST " */
2956 if (!(tbuf
= strchr(tbuf
, ' '))) {
2957 log_warn(LD_APP
,"NATD handshake was ill-formed; closing. The client "
2960 connection_mark_unattached_ap(conn
, END_STREAM_REASON_INVALID_NATD_DEST
);
2965 /* pretend that a socks handshake completed so we don't try to
2966 * send a socks reply down a natd conn */
2967 strlcpy(socks
->address
, daddr
, sizeof(socks
->address
));
2968 socks
->port
= (uint16_t)
2969 tor_parse_long(tbuf
, 10, 1, 65535, &port_ok
, &daddr
);
2971 log_warn(LD_APP
,"NATD handshake failed; port %s is ill-formed or out "
2972 "of range.", escaped(tbuf
));
2973 connection_mark_unattached_ap(conn
, END_STREAM_REASON_INVALID_NATD_DEST
);
2977 socks
->command
= SOCKS_COMMAND_CONNECT
;
2978 socks
->has_finished
= 1;
2980 control_event_stream_status(conn
, STREAM_EVENT_NEW
, 0);
2982 ENTRY_TO_CONN(conn
)->state
= AP_CONN_STATE_CIRCUIT_WAIT
;
2984 return connection_ap_rewrite_and_attach_if_allowed(conn
, NULL
, NULL
);
2987 static const char HTTP_CONNECT_IS_NOT_AN_HTTP_PROXY_MSG
[] =
2988 "HTTP/1.0 405 Method Not Allowed\r\n"
2989 "Content-Type: text/html; charset=iso-8859-1\r\n\r\n"
2992 "<title>This is an HTTP CONNECT tunnel, not a full HTTP Proxy</title>\n"
2995 "<h1>This is an HTTP CONNECT tunnel, not an HTTP proxy.</h1>\n"
2997 "It appears you have configured your web browser to use this Tor port as\n"
3000 "This is not correct: This port is configured as a CONNECT tunnel, not\n"
3001 "an HTTP proxy. Please configure your client accordingly. You can also\n"
3002 "use HTTPS; then the client should automatically use HTTP CONNECT."
3005 "See <a href=\"https://www.torproject.org/documentation.html\">"
3006 "https://www.torproject.org/documentation.html</a> for more "
3012 /** Called on an HTTP CONNECT entry connection when some bytes have arrived,
3013 * but we have not yet received a full HTTP CONNECT request. Try to parse an
3014 * HTTP CONNECT request from the connection's inbuf. On success, set up the
3015 * connection's socks_request field and try to attach the connection. On
3016 * failure, send an HTTP reply, and mark the connection.
3019 connection_ap_process_http_connect(entry_connection_t
*conn
)
3021 if (BUG(ENTRY_TO_CONN(conn
)->state
!= AP_CONN_STATE_HTTP_CONNECT_WAIT
))
3024 char *headers
= NULL
, *body
= NULL
;
3025 char *command
= NULL
, *addrport
= NULL
;
3029 const char *errmsg
= NULL
;
3032 const int http_status
=
3033 fetch_from_buf_http(ENTRY_TO_CONN(conn
)->inbuf
, &headers
, 8192,
3034 &body
, &bodylen
, 1024, 0);
3035 if (http_status
< 0) {
3036 /* Bad http status */
3037 errmsg
= "HTTP/1.0 400 Bad Request\r\n\r\n";
3039 } else if (http_status
== 0) {
3040 /* no HTTP request yet. */
3044 const int cmd_status
= parse_http_command(headers
, &command
, &addrport
);
3045 if (cmd_status
< 0) {
3046 errmsg
= "HTTP/1.0 400 Bad Request\r\n\r\n";
3049 tor_assert(command
);
3050 tor_assert(addrport
);
3051 if (strcasecmp(command
, "connect")) {
3052 errmsg
= HTTP_CONNECT_IS_NOT_AN_HTTP_PROXY_MSG
;
3056 tor_assert(conn
->socks_request
);
3057 socks_request_t
*socks
= conn
->socks_request
;
3059 if (tor_addr_port_split(LOG_WARN
, addrport
, &addr
, &port
) < 0) {
3060 errmsg
= "HTTP/1.0 400 Bad Request\r\n\r\n";
3063 if (strlen(addr
) >= MAX_SOCKS_ADDR_LEN
) {
3064 errmsg
= "HTTP/1.0 414 Request-URI Too Long\r\n\r\n";
3068 /* Abuse the 'username' and 'password' fields here. They are already an
3071 char *authorization
= http_get_header(headers
, "Proxy-Authorization: ");
3072 if (authorization
) {
3073 socks
->username
= authorization
; // steal reference
3074 socks
->usernamelen
= strlen(authorization
);
3076 char *isolation
= http_get_header(headers
, "X-Tor-Stream-Isolation: ");
3078 socks
->password
= isolation
; // steal reference
3079 socks
->passwordlen
= strlen(isolation
);
3083 socks
->command
= SOCKS_COMMAND_CONNECT
;
3084 socks
->listener_type
= CONN_TYPE_AP_HTTP_CONNECT_LISTENER
;
3085 strlcpy(socks
->address
, addr
, sizeof(socks
->address
));
3088 control_event_stream_status(conn
, STREAM_EVENT_NEW
, 0);
3090 rv
= connection_ap_rewrite_and_attach_if_allowed(conn
, NULL
, NULL
);
3092 // XXXX send a "100 Continue" message?
3097 if (BUG(errmsg
== NULL
))
3098 errmsg
= "HTTP/1.0 400 Bad Request\r\n\r\n";
3099 log_info(LD_EDGE
, "HTTP tunnel error: saying %s", escaped(errmsg
));
3100 connection_buf_add(errmsg
, strlen(errmsg
), ENTRY_TO_CONN(conn
));
3101 /* Mark it as "has_finished" so that we don't try to send an extra socks
3103 conn
->socks_request
->has_finished
= 1;
3104 connection_mark_unattached_ap(conn
,
3105 END_STREAM_REASON_HTTPPROTOCOL
|
3106 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
);
3117 /** Iterate over the two bytes of stream_id until we get one that is not
3118 * already in use; return it. Return 0 if can't get a unique stream_id.
3121 get_unique_stream_id_by_circ(origin_circuit_t
*circ
)
3123 edge_connection_t
*tmpconn
;
3124 streamid_t test_stream_id
;
3125 uint32_t attempts
=0;
3128 test_stream_id
= circ
->next_stream_id
++;
3129 if (++attempts
> 1<<16) {
3130 /* Make sure we don't loop forever if all stream_id's are used. */
3131 log_warn(LD_APP
,"No unused stream IDs. Failing.");
3134 if (test_stream_id
== 0)
3136 for (tmpconn
= circ
->p_streams
; tmpconn
; tmpconn
=tmpconn
->next_stream
)
3137 if (tmpconn
->stream_id
== test_stream_id
)
3140 if (connection_half_edge_find_stream_id(circ
->half_streams
,
3144 if (TO_CIRCUIT(circ
)->conflux
) {
3145 conflux_sync_circ_fields(TO_CIRCUIT(circ
)->conflux
, circ
);
3148 return test_stream_id
;
3151 /** Return true iff <b>conn</b> is linked to a circuit and configured to use
3152 * an exit that supports optimistic data. */
3154 connection_ap_supports_optimistic_data(const entry_connection_t
*conn
)
3156 const edge_connection_t
*edge_conn
= ENTRY_TO_EDGE_CONN(conn
);
3157 /* We can only send optimistic data if we're connected to an open
3159 // TODO-329-PURPOSE: Can conflux circuits use optimistic data?
3160 // Does anything use optimistic data?
3161 if (edge_conn
->on_circuit
== NULL
||
3162 edge_conn
->on_circuit
->state
!= CIRCUIT_STATE_OPEN
||
3163 (edge_conn
->on_circuit
->purpose
!= CIRCUIT_PURPOSE_C_GENERAL
&&
3164 edge_conn
->on_circuit
->purpose
!= CIRCUIT_PURPOSE_C_HSDIR_GET
&&
3165 edge_conn
->on_circuit
->purpose
!= CIRCUIT_PURPOSE_S_HSDIR_POST
&&
3166 edge_conn
->on_circuit
->purpose
!= CIRCUIT_PURPOSE_C_REND_JOINED
))
3169 return conn
->may_use_optimistic_data
;
3172 /** Return a bitmask of BEGIN_FLAG_* flags that we should transmit in the
3173 * RELAY_BEGIN cell for <b>ap_conn</b>. */
3175 connection_ap_get_begincell_flags(entry_connection_t
*ap_conn
)
3177 edge_connection_t
*edge_conn
= ENTRY_TO_EDGE_CONN(ap_conn
);
3178 const node_t
*exitnode
= NULL
;
3179 const crypt_path_t
*cpath_layer
= edge_conn
->cpath_layer
;
3182 /* No flags for begindir */
3183 if (ap_conn
->use_begindir
)
3186 /* No flags for hidden services. */
3187 if (edge_conn
->on_circuit
->purpose
!= CIRCUIT_PURPOSE_C_GENERAL
&&
3188 edge_conn
->on_circuit
->purpose
!= CIRCUIT_PURPOSE_CONFLUX_LINKED
)
3191 /* If only IPv4 is supported, no flags */
3192 if (ap_conn
->entry_cfg
.ipv4_traffic
&& !ap_conn
->entry_cfg
.ipv6_traffic
)
3195 if (! cpath_layer
||
3196 ! cpath_layer
->extend_info
)
3199 if (!ap_conn
->entry_cfg
.ipv4_traffic
)
3200 flags
|= BEGIN_FLAG_IPV4_NOT_OK
;
3202 exitnode
= node_get_by_id(cpath_layer
->extend_info
->identity_digest
);
3204 if (ap_conn
->entry_cfg
.ipv6_traffic
&& exitnode
) {
3206 tor_addr_make_null(&a
, AF_INET6
);
3207 if (compare_tor_addr_to_node_policy(&a
, ap_conn
->socks_request
->port
,
3209 != ADDR_POLICY_REJECTED
) {
3210 /* Only say "IPv6 OK" if the exit node supports IPv6. Otherwise there's
3212 flags
|= BEGIN_FLAG_IPV6_OK
;
3216 if (flags
== BEGIN_FLAG_IPV6_OK
) {
3217 /* When IPv4 and IPv6 are both allowed, consider whether to say we
3218 * prefer IPv6. Otherwise there's no point in declaring a preference */
3219 if (ap_conn
->entry_cfg
.prefer_ipv6
)
3220 flags
|= BEGIN_FLAG_IPV6_PREFERRED
;
3223 if (flags
== BEGIN_FLAG_IPV4_NOT_OK
) {
3224 log_warn(LD_EDGE
, "I'm about to ask a node for a connection that I "
3225 "am telling it to fulfil with neither IPv4 nor IPv6. That's "
3226 "not going to work. Did you perhaps ask for an IPv6 address "
3227 "on an IPv4Only port, or vice versa?");
3233 /** Write a relay begin cell, using destaddr and destport from ap_conn's
3234 * socks_request field, and send it down circ.
3236 * If ap_conn is broken, mark it for close and return -1. Else return 0.
3239 connection_ap_handshake_send_begin
,(entry_connection_t
*ap_conn
))
3241 char payload
[CELL_PAYLOAD_SIZE
];
3244 const or_options_t
*options
= get_options();
3245 origin_circuit_t
*circ
;
3246 edge_connection_t
*edge_conn
= ENTRY_TO_EDGE_CONN(ap_conn
);
3247 connection_t
*base_conn
= TO_CONN(edge_conn
);
3248 tor_assert(edge_conn
->on_circuit
);
3249 circ
= TO_ORIGIN_CIRCUIT(edge_conn
->on_circuit
);
3251 tor_assert(base_conn
->type
== CONN_TYPE_AP
);
3252 tor_assert(base_conn
->state
== AP_CONN_STATE_CIRCUIT_WAIT
);
3253 tor_assert(ap_conn
->socks_request
);
3254 tor_assert(SOCKS_COMMAND_IS_CONNECT(ap_conn
->socks_request
->command
));
3256 edge_conn
->stream_id
= get_unique_stream_id_by_circ(circ
);
3257 if (edge_conn
->stream_id
==0) {
3258 /* XXXX+ Instead of closing this stream, we should make it get
3259 * retried on another circuit. */
3260 connection_mark_unattached_ap(ap_conn
, END_STREAM_REASON_INTERNAL
);
3262 /* Mark this circuit "unusable for new streams". */
3263 mark_circuit_unusable_for_new_conns(circ
);
3267 /* Set up begin cell flags. */
3268 edge_conn
->begincell_flags
= connection_ap_get_begincell_flags(ap_conn
);
3270 tor_snprintf(payload
,RELAY_PAYLOAD_SIZE
, "%s:%d",
3271 (circ
->base_
.purpose
== CIRCUIT_PURPOSE_C_GENERAL
||
3272 circ
->base_
.purpose
== CIRCUIT_PURPOSE_CONFLUX_LINKED
||
3273 circ
->base_
.purpose
== CIRCUIT_PURPOSE_CONTROLLER
) ?
3274 ap_conn
->socks_request
->address
: "",
3275 ap_conn
->socks_request
->port
);
3276 payload_len
= (int)strlen(payload
)+1;
3277 if (payload_len
<= RELAY_PAYLOAD_SIZE
- 4 && edge_conn
->begincell_flags
) {
3278 set_uint32(payload
+ payload_len
, htonl(edge_conn
->begincell_flags
));
3283 "Sending relay cell %d on circ %u to begin stream %d.",
3284 (int)ap_conn
->use_begindir
,
3285 (unsigned)circ
->base_
.n_circ_id
,
3286 edge_conn
->stream_id
);
3288 begin_type
= ap_conn
->use_begindir
?
3289 RELAY_COMMAND_BEGIN_DIR
: RELAY_COMMAND_BEGIN
;
3291 /* Check that circuits are anonymised, based on their type. */
3292 if (begin_type
== RELAY_COMMAND_BEGIN
) {
3293 /* This connection is a standard OR connection.
3294 * Make sure its path length is anonymous, or that we're in a
3295 * non-anonymous mode. */
3296 assert_circ_anonymity_ok(circ
, options
);
3297 } else if (begin_type
== RELAY_COMMAND_BEGIN_DIR
) {
3298 /* This connection is a begindir directory connection.
3299 * Look at the linked directory connection to access the directory purpose.
3300 * If a BEGINDIR connection is ever not linked, that's a bug. */
3301 if (BUG(!base_conn
->linked
)) {
3304 connection_t
*linked_dir_conn_base
= base_conn
->linked_conn
;
3305 /* If the linked connection has been unlinked by other code, we can't send
3306 * a begin cell on it. */
3307 if (!linked_dir_conn_base
) {
3310 /* Sensitive directory connections must have an anonymous path length.
3311 * Otherwise, directory connections are typically one-hop.
3312 * This matches the earlier check for directory connection path anonymity
3313 * in directory_initiate_request(). */
3314 if (purpose_needs_anonymity(linked_dir_conn_base
->purpose
,
3315 TO_DIR_CONN(linked_dir_conn_base
)->router_purpose
,
3316 TO_DIR_CONN(linked_dir_conn_base
)->requested_resource
)) {
3317 assert_circ_anonymity_ok(circ
, options
);
3320 /* This code was written for the two connection types BEGIN and BEGIN_DIR
3322 tor_assert_unreached();
3325 if (connection_edge_send_command(edge_conn
, begin_type
,
3326 begin_type
== RELAY_COMMAND_BEGIN
? payload
: NULL
,
3327 begin_type
== RELAY_COMMAND_BEGIN
? payload_len
: 0) < 0)
3328 return -1; /* circuit is closed, don't continue */
3330 edge_conn
->package_window
= STREAMWINDOW_START
;
3331 edge_conn
->deliver_window
= STREAMWINDOW_START
;
3332 base_conn
->state
= AP_CONN_STATE_CONNECT_WAIT
;
3333 log_info(LD_APP
,"Address/port sent, ap socket "TOR_SOCKET_T_FORMAT
3335 base_conn
->s
, (unsigned)circ
->base_
.n_circ_id
);
3336 control_event_stream_status(ap_conn
, STREAM_EVENT_SENT_CONNECT
, 0);
3338 /* If there's queued-up data, send it now */
3339 if ((connection_get_inbuf_len(base_conn
) ||
3340 ap_conn
->sending_optimistic_data
) &&
3341 connection_ap_supports_optimistic_data(ap_conn
)) {
3342 log_info(LD_APP
, "Sending up to %ld + %ld bytes of queued-up data",
3343 (long)connection_get_inbuf_len(base_conn
),
3344 ap_conn
->sending_optimistic_data
?
3345 (long)buf_datalen(ap_conn
->sending_optimistic_data
) : 0);
3346 if (connection_edge_package_raw_inbuf(edge_conn
, 1, NULL
) < 0) {
3347 connection_mark_for_close(base_conn
);
3354 /** Write a relay resolve cell, using destaddr and destport from ap_conn's
3355 * socks_request field, and send it down circ.
3357 * If ap_conn is broken, mark it for close and return -1. Else return 0.
3360 connection_ap_handshake_send_resolve(entry_connection_t
*ap_conn
)
3362 int payload_len
, command
;
3363 const char *string_addr
;
3364 char inaddr_buf
[REVERSE_LOOKUP_NAME_BUF_LEN
];
3365 origin_circuit_t
*circ
;
3366 edge_connection_t
*edge_conn
= ENTRY_TO_EDGE_CONN(ap_conn
);
3367 connection_t
*base_conn
= TO_CONN(edge_conn
);
3368 tor_assert(edge_conn
->on_circuit
);
3369 circ
= TO_ORIGIN_CIRCUIT(edge_conn
->on_circuit
);
3371 tor_assert(base_conn
->type
== CONN_TYPE_AP
);
3372 tor_assert(base_conn
->state
== AP_CONN_STATE_CIRCUIT_WAIT
);
3373 tor_assert(ap_conn
->socks_request
);
3374 tor_assert(circ
->base_
.purpose
== CIRCUIT_PURPOSE_C_GENERAL
||
3375 circ
->base_
.purpose
== CIRCUIT_PURPOSE_CONFLUX_LINKED
);
3377 command
= ap_conn
->socks_request
->command
;
3378 tor_assert(SOCKS_COMMAND_IS_RESOLVE(command
));
3380 edge_conn
->stream_id
= get_unique_stream_id_by_circ(circ
);
3381 if (edge_conn
->stream_id
==0) {
3382 /* XXXX+ Instead of closing this stream, we should make it get
3383 * retried on another circuit. */
3384 connection_mark_unattached_ap(ap_conn
, END_STREAM_REASON_INTERNAL
);
3386 /* Mark this circuit "unusable for new streams". */
3387 mark_circuit_unusable_for_new_conns(circ
);
3391 if (command
== SOCKS_COMMAND_RESOLVE
) {
3392 string_addr
= ap_conn
->socks_request
->address
;
3393 payload_len
= (int)strlen(string_addr
)+1;
3395 /* command == SOCKS_COMMAND_RESOLVE_PTR */
3396 const char *a
= ap_conn
->socks_request
->address
;
3400 /* We're doing a reverse lookup. The input could be an IP address, or
3401 * could be an .in-addr.arpa or .ip6.arpa address */
3402 r
= tor_addr_parse_PTR_name(&addr
, a
, AF_UNSPEC
, 1);
3404 log_warn(LD_APP
, "Rejecting ill-formed reverse lookup of %s",
3405 safe_str_client(a
));
3406 connection_mark_unattached_ap(ap_conn
, END_STREAM_REASON_INTERNAL
);
3410 r
= tor_addr_to_PTR_name(inaddr_buf
, sizeof(inaddr_buf
), &addr
);
3412 log_warn(LD_BUG
, "Couldn't generate reverse lookup hostname of %s",
3413 safe_str_client(a
));
3414 connection_mark_unattached_ap(ap_conn
, END_STREAM_REASON_INTERNAL
);
3418 string_addr
= inaddr_buf
;
3419 payload_len
= (int)strlen(inaddr_buf
)+1;
3420 tor_assert(payload_len
<= (int)sizeof(inaddr_buf
));
3424 "Sending relay cell to begin stream %d.", edge_conn
->stream_id
);
3426 if (connection_edge_send_command(edge_conn
,
3427 RELAY_COMMAND_RESOLVE
,
3428 string_addr
, payload_len
) < 0)
3429 return -1; /* circuit is closed, don't continue */
3431 if (!base_conn
->address
) {
3432 /* This might be unnecessary. XXXX */
3433 base_conn
->address
= tor_addr_to_str_dup(&base_conn
->addr
);
3435 base_conn
->state
= AP_CONN_STATE_RESOLVE_WAIT
;
3436 log_info(LD_APP
,"Address sent for resolve, ap socket "TOR_SOCKET_T_FORMAT
3438 base_conn
->s
, (unsigned)circ
->base_
.n_circ_id
);
3439 control_event_stream_status(ap_conn
, STREAM_EVENT_SENT_RESOLVE
, 0);
3443 /** Make an AP connection_t linked to the connection_t <b>partner</b>. make a
3444 * new linked connection pair, and attach one side to the conn, connection_add
3445 * it, initialize it to circuit_wait, and call
3446 * connection_ap_handshake_attach_circuit(conn) on it.
3448 * Return the newly created end of the linked connection pair, or -1 if error.
3450 entry_connection_t
*
3451 connection_ap_make_link(connection_t
*partner
,
3452 char *address
, uint16_t port
,
3454 int session_group
, int isolation_flags
,
3455 int use_begindir
, int want_onehop
)
3457 entry_connection_t
*conn
;
3458 connection_t
*base_conn
;
3460 log_info(LD_APP
,"Making internal %s tunnel to %s:%d ...",
3461 want_onehop
? "direct" : "anonymized",
3462 safe_str_client(address
), port
);
3464 conn
= entry_connection_new(CONN_TYPE_AP
, tor_addr_family(&partner
->addr
));
3465 base_conn
= ENTRY_TO_CONN(conn
);
3466 base_conn
->linked
= 1; /* so that we can add it safely below. */
3468 /* populate conn->socks_request */
3470 /* leave version at zero, so the socks_reply is empty */
3471 conn
->socks_request
->socks_version
= 0;
3472 conn
->socks_request
->has_finished
= 0; /* waiting for 'connected' */
3473 strlcpy(conn
->socks_request
->address
, address
,
3474 sizeof(conn
->socks_request
->address
));
3475 conn
->socks_request
->port
= port
;
3476 conn
->socks_request
->command
= SOCKS_COMMAND_CONNECT
;
3477 conn
->want_onehop
= want_onehop
;
3478 conn
->use_begindir
= use_begindir
;
3480 conn
->chosen_exit_name
= tor_malloc(HEX_DIGEST_LEN
+2);
3481 conn
->chosen_exit_name
[0] = '$';
3483 base16_encode(conn
->chosen_exit_name
+1,HEX_DIGEST_LEN
+1,
3484 digest
, DIGEST_LEN
);
3487 /* Populate isolation fields. */
3488 conn
->socks_request
->listener_type
= CONN_TYPE_DIR_LISTENER
;
3489 conn
->original_dest_address
= tor_strdup(address
);
3490 conn
->entry_cfg
.session_group
= session_group
;
3491 conn
->entry_cfg
.isolation_flags
= isolation_flags
;
3493 base_conn
->address
= tor_strdup("(Tor_internal)");
3494 tor_addr_make_unspec(&base_conn
->addr
);
3495 base_conn
->port
= 0;
3497 connection_link_connections(partner
, base_conn
);
3499 if (connection_add(base_conn
) < 0) { /* no space, forget it */
3500 connection_free(base_conn
);
3504 base_conn
->state
= AP_CONN_STATE_CIRCUIT_WAIT
;
3506 control_event_stream_status(conn
, STREAM_EVENT_NEW
, 0);
3508 /* attaching to a dirty circuit is fine */
3509 connection_ap_mark_as_pending_circuit(conn
);
3510 log_info(LD_APP
,"... application connection created and linked.");
3514 /** Notify any interested controller connections about a new hostname resolve
3515 * or resolve error. Takes the same arguments as does
3516 * connection_ap_handshake_socks_resolved(). */
3518 tell_controller_about_resolved_result(entry_connection_t
*conn
,
3525 uint64_t stream_id
= 0;
3531 stream_id
= ENTRY_TO_CONN(conn
)->global_identifier
;
3533 expires
= time(NULL
) + ttl
;
3534 if (answer_type
== RESOLVED_TYPE_IPV4
&& answer_len
>= 4) {
3535 char *cp
= tor_dup_ip(ntohl(get_uint32(answer
)));
3537 control_event_address_mapped(conn
->socks_request
->address
,
3538 cp
, expires
, NULL
, 0, stream_id
);
3540 } else if (answer_type
== RESOLVED_TYPE_HOSTNAME
&& answer_len
< 256) {
3541 char *cp
= tor_strndup(answer
, answer_len
);
3542 control_event_address_mapped(conn
->socks_request
->address
,
3543 cp
, expires
, NULL
, 0, stream_id
);
3546 control_event_address_mapped(conn
->socks_request
->address
,
3547 "<error>", time(NULL
)+ttl
,
3548 "error=yes", 0, stream_id
);
3553 * As connection_ap_handshake_socks_resolved, but take a tor_addr_t to send
3557 connection_ap_handshake_socks_resolved_addr(entry_connection_t
*conn
,
3558 const tor_addr_t
*answer
,
3562 if (tor_addr_family(answer
) == AF_INET
) {
3563 uint32_t a
= tor_addr_to_ipv4n(answer
); /* network order */
3564 connection_ap_handshake_socks_resolved(conn
,RESOLVED_TYPE_IPV4
,4,
3567 } else if (tor_addr_family(answer
) == AF_INET6
) {
3568 const uint8_t *a
= tor_addr_to_in6_addr8(answer
);
3569 connection_ap_handshake_socks_resolved(conn
,RESOLVED_TYPE_IPV6
,16,
3573 log_warn(LD_BUG
, "Got called with address of unexpected family %d",
3574 tor_addr_family(answer
));
3575 connection_ap_handshake_socks_resolved(conn
,
3576 RESOLVED_TYPE_ERROR
,0,NULL
,-1,-1);
3580 /** Send an answer to an AP connection that has requested a DNS lookup via
3581 * SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6|HOSTNAME) or -1
3582 * for unreachable; the answer should be in the format specified in the socks
3583 * extensions document. <b>ttl</b> is the ttl for the answer, or -1 on
3584 * certain errors or for values that didn't come via DNS. <b>expires</b> is
3585 * a time when the answer expires, or -1 or TIME_MAX if there's a good TTL.
3587 /* XXXX the use of the ttl and expires fields is nutty. Let's make this
3588 * interface and those that use it less ugly. */
3590 connection_ap_handshake_socks_resolved
,(entry_connection_t
*conn
,
3593 const uint8_t *answer
,
3601 if (answer_type
== RESOLVED_TYPE_IPV4
&& answer_len
== 4) {
3603 tor_addr_from_ipv4n(&a
, get_uint32(answer
));
3604 if (! tor_addr_is_null(&a
)) {
3605 client_dns_set_addressmap(conn
,
3606 conn
->socks_request
->address
, &a
,
3607 conn
->chosen_exit_name
, ttl
);
3609 } else if (answer_type
== RESOLVED_TYPE_IPV6
&& answer_len
== 16) {
3611 tor_addr_from_ipv6_bytes(&a
, answer
);
3612 if (! tor_addr_is_null(&a
)) {
3613 client_dns_set_addressmap(conn
,
3614 conn
->socks_request
->address
, &a
,
3615 conn
->chosen_exit_name
, ttl
);
3617 } else if (answer_type
== RESOLVED_TYPE_HOSTNAME
&& answer_len
< 256) {
3618 char *cp
= tor_strndup((char*)answer
, answer_len
);
3619 client_dns_set_reverse_addressmap(conn
,
3620 conn
->socks_request
->address
,
3622 conn
->chosen_exit_name
, ttl
);
3627 if (ENTRY_TO_EDGE_CONN(conn
)->is_dns_request
) {
3628 if (conn
->dns_server_request
) {
3629 /* We had a request on our DNS port: answer it. */
3630 dnsserv_resolved(conn
, answer_type
, answer_len
, (char*)answer
, ttl
);
3631 conn
->socks_request
->has_finished
= 1;
3634 /* This must be a request from the controller. Since answers to those
3635 * requests are not cached, they do not generate an ADDRMAP event on
3637 tell_controller_about_resolved_result(conn
, answer_type
, answer_len
,
3638 (char*)answer
, ttl
, expires
);
3639 conn
->socks_request
->has_finished
= 1;
3642 /* We shouldn't need to free conn here; it gets marked by the caller. */
3645 if (conn
->socks_request
->socks_version
== 4) {
3646 buf
[0] = 0x00; /* version */
3647 if (answer_type
== RESOLVED_TYPE_IPV4
&& answer_len
== 4) {
3648 buf
[1] = SOCKS4_GRANTED
;
3649 set_uint16(buf
+2, 0);
3650 memcpy(buf
+4, answer
, 4); /* address */
3651 replylen
= SOCKS4_NETWORK_LEN
;
3652 } else { /* "error" */
3653 buf
[1] = SOCKS4_REJECT
;
3654 memset(buf
+2, 0, 6);
3655 replylen
= SOCKS4_NETWORK_LEN
;
3657 } else if (conn
->socks_request
->socks_version
== 5) {
3659 buf
[0] = 0x05; /* version */
3660 if (answer_type
== RESOLVED_TYPE_IPV4
&& answer_len
== 4) {
3661 buf
[1] = SOCKS5_SUCCEEDED
;
3662 buf
[2] = 0; /* reserved */
3663 buf
[3] = 0x01; /* IPv4 address type */
3664 memcpy(buf
+4, answer
, 4); /* address */
3665 set_uint16(buf
+8, 0); /* port == 0. */
3667 } else if (answer_type
== RESOLVED_TYPE_IPV6
&& answer_len
== 16) {
3668 buf
[1] = SOCKS5_SUCCEEDED
;
3669 buf
[2] = 0; /* reserved */
3670 buf
[3] = 0x04; /* IPv6 address type */
3671 memcpy(buf
+4, answer
, 16); /* address */
3672 set_uint16(buf
+20, 0); /* port == 0. */
3674 } else if (answer_type
== RESOLVED_TYPE_HOSTNAME
&& answer_len
< 256) {
3675 buf
[1] = SOCKS5_SUCCEEDED
;
3676 buf
[2] = 0; /* reserved */
3677 buf
[3] = 0x03; /* Domainname address type */
3678 buf
[4] = (char)answer_len
;
3679 memcpy(buf
+5, answer
, answer_len
); /* address */
3680 set_uint16(buf
+5+answer_len
, 0); /* port == 0. */
3681 replylen
= 5+answer_len
+2;
3683 buf
[1] = SOCKS5_HOST_UNREACHABLE
;
3684 memset(buf
+2, 0, 8);
3688 /* no socks version info; don't send anything back */
3691 connection_ap_handshake_socks_reply(conn
, buf
, replylen
,
3692 (answer_type
== RESOLVED_TYPE_IPV4
||
3693 answer_type
== RESOLVED_TYPE_IPV6
||
3694 answer_type
== RESOLVED_TYPE_HOSTNAME
) ?
3695 0 : END_STREAM_REASON_RESOLVEFAILED
);
3698 /** Send a socks reply to stream <b>conn</b>, using the appropriate
3699 * socks version, etc, and mark <b>conn</b> as completed with SOCKS
3702 * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it to conn
3703 * and return, else reply based on <b>endreason</b> (one of
3704 * END_STREAM_REASON_*). If <b>reply</b> is undefined, <b>endreason</b> can't
3705 * be 0 or REASON_DONE. Send endreason to the controller, if appropriate.
3708 connection_ap_handshake_socks_reply(entry_connection_t
*conn
, char *reply
,
3709 size_t replylen
, int endreason
)
3712 socks5_reply_status_t status
;
3714 tor_assert(conn
->socks_request
); /* make sure it's an AP stream */
3716 if (conn
->socks_request
->socks_use_extended_errors
&&
3717 conn
->socks_request
->socks_extended_error_code
!= 0) {
3718 status
= conn
->socks_request
->socks_extended_error_code
;
3720 status
= stream_end_reason_to_socks5_response(endreason
);
3723 if (!SOCKS_COMMAND_IS_RESOLVE(conn
->socks_request
->command
)) {
3724 control_event_stream_status(conn
, status
==SOCKS5_SUCCEEDED
?
3725 STREAM_EVENT_SUCCEEDED
: STREAM_EVENT_FAILED
,
3729 /* Flag this stream's circuit as having completed a stream successfully
3730 * (for path bias) */
3731 if (status
== SOCKS5_SUCCEEDED
||
3732 endreason
== END_STREAM_REASON_RESOLVEFAILED
||
3733 endreason
== END_STREAM_REASON_CONNECTREFUSED
||
3734 endreason
== END_STREAM_REASON_CONNRESET
||
3735 endreason
== END_STREAM_REASON_NOROUTE
||
3736 endreason
== END_STREAM_REASON_RESOURCELIMIT
) {
3737 if (!conn
->edge_
.on_circuit
||
3738 !CIRCUIT_IS_ORIGIN(conn
->edge_
.on_circuit
)) {
3739 if (endreason
!= END_STREAM_REASON_RESOLVEFAILED
) {
3741 "No origin circuit for successful SOCKS stream %"PRIu64
3743 (ENTRY_TO_CONN(conn
)->global_identifier
),
3747 * Else DNS remaps and failed hidden service lookups can send us
3748 * here with END_STREAM_REASON_RESOLVEFAILED; ignore it
3750 * Perhaps we could make the test more precise; we can tell hidden
3751 * services by conn->edge_.renddata != NULL; anything analogous for
3752 * the DNS remap case?
3755 // XXX: Hrmm. It looks like optimistic data can't go through this
3756 // codepath, but someone should probably test it and make sure.
3757 // We don't want to mark optimistically opened streams as successful.
3758 pathbias_mark_use_success(TO_ORIGIN_CIRCUIT(conn
->edge_
.on_circuit
));
3762 if (conn
->socks_request
->has_finished
) {
3763 log_warn(LD_BUG
, "(Harmless.) duplicate calls to "
3764 "connection_ap_handshake_socks_reply.");
3767 if (replylen
) { /* we already have a reply in mind */
3768 connection_buf_add(reply
, replylen
, ENTRY_TO_CONN(conn
));
3769 conn
->socks_request
->has_finished
= 1;
3772 if (conn
->socks_request
->listener_type
==
3773 CONN_TYPE_AP_HTTP_CONNECT_LISTENER
) {
3774 const char *response
= end_reason_to_http_connect_response_line(endreason
);
3776 response
= "HTTP/1.0 400 Bad Request\r\n\r\n";
3778 connection_buf_add(response
, strlen(response
), ENTRY_TO_CONN(conn
));
3779 } else if (conn
->socks_request
->socks_version
== 4) {
3780 memset(buf
,0,SOCKS4_NETWORK_LEN
);
3781 buf
[1] = (status
==SOCKS5_SUCCEEDED
? SOCKS4_GRANTED
: SOCKS4_REJECT
);
3782 /* leave version, destport, destip zero */
3783 connection_buf_add(buf
, SOCKS4_NETWORK_LEN
, ENTRY_TO_CONN(conn
));
3784 } else if (conn
->socks_request
->socks_version
== 5) {
3786 memset(buf
,0,sizeof(buf
));
3787 if (tor_addr_family(&conn
->edge_
.base_
.addr
) == AF_INET
) {
3788 buf
[0] = 5; /* version 5 */
3789 buf
[1] = (char)status
;
3791 buf
[3] = 1; /* ipv4 addr */
3792 /* 4 bytes for the header, 2 bytes for the port, 4 for the address. */
3794 } else { /* AF_INET6. */
3795 buf
[0] = 5; /* version 5 */
3796 buf
[1] = (char)status
;
3798 buf
[3] = 4; /* ipv6 addr */
3799 /* 4 bytes for the header, 2 bytes for the port, 16 for the address. */
3802 connection_buf_add(buf
,buf_len
,ENTRY_TO_CONN(conn
));
3804 /* If socks_version isn't 4 or 5, don't send anything.
3805 * This can happen in the case of AP bridges. */
3806 conn
->socks_request
->has_finished
= 1;
3810 /** Read a RELAY_BEGIN or RELAY_BEGIN_DIR cell from <b>cell</b>, decode it, and
3811 * place the result in <b>bcell</b>. On success return 0; on failure return
3812 * <0 and set *<b>end_reason_out</b> to the end reason we should send back to
3815 * Return -1 in the case where we want to send a RELAY_END cell, and < -1 when
3819 begin_cell_parse(const cell_t
*cell
, begin_cell_t
*bcell
,
3820 uint8_t *end_reason_out
)
3823 const uint8_t *body
, *nul
;
3825 memset(bcell
, 0, sizeof(*bcell
));
3826 *end_reason_out
= END_STREAM_REASON_MISC
;
3828 relay_header_unpack(&rh
, cell
->payload
);
3829 if (rh
.length
> RELAY_PAYLOAD_SIZE
) {
3830 return -2; /*XXXX why not TORPROTOCOL? */
3833 bcell
->stream_id
= rh
.stream_id
;
3835 if (rh
.command
== RELAY_COMMAND_BEGIN_DIR
) {
3836 bcell
->is_begindir
= 1;
3838 } else if (rh
.command
!= RELAY_COMMAND_BEGIN
) {
3839 log_warn(LD_BUG
, "Got an unexpected command %d", (int)rh
.command
);
3840 *end_reason_out
= END_STREAM_REASON_INTERNAL
;
3844 body
= cell
->payload
+ RELAY_HEADER_SIZE
;
3845 nul
= memchr(body
, 0, rh
.length
);
3847 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
3848 "Relay begin cell has no \\0. Closing.");
3849 *end_reason_out
= END_STREAM_REASON_TORPROTOCOL
;
3853 if (tor_addr_port_split(LOG_PROTOCOL_WARN
,
3855 &bcell
->address
,&bcell
->port
)<0) {
3856 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
3857 "Unable to parse addr:port in relay begin cell. Closing.");
3858 *end_reason_out
= END_STREAM_REASON_TORPROTOCOL
;
3861 if (bcell
->port
== 0) {
3862 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
3863 "Missing port in relay begin cell. Closing.");
3864 tor_free(bcell
->address
);
3865 *end_reason_out
= END_STREAM_REASON_TORPROTOCOL
;
3868 if (body
+ rh
.length
>= nul
+ 4)
3869 bcell
->flags
= ntohl(get_uint32(nul
+1));
3874 /** For the given <b>circ</b> and the edge connection <b>conn</b>, setup the
3875 * connection, attach it to the circ and connect it. Return 0 on success
3876 * or END_CIRC_AT_ORIGIN if we can't find the requested hidden service port
3877 * where the caller should close the circuit. */
3879 handle_hs_exit_conn(circuit_t
*circ
, edge_connection_t
*conn
)
3882 origin_circuit_t
*origin_circ
;
3884 assert_circuit_ok(circ
);
3885 tor_assert(circ
->purpose
== CIRCUIT_PURPOSE_S_REND_JOINED
);
3888 log_debug(LD_REND
, "Connecting the hidden service rendezvous circuit "
3889 "to the service destination.");
3891 origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
3892 conn
->base_
.address
= tor_strdup("(rendezvous)");
3893 conn
->base_
.state
= EXIT_CONN_STATE_CONNECTING
;
3895 if (origin_circ
->hs_ident
) {
3896 /* Setup the identifier to be the one for the circuit service. */
3898 hs_ident_edge_conn_new(&origin_circ
->hs_ident
->identity_pk
);
3899 tor_assert(connection_edge_is_rendezvous_stream(conn
));
3900 ret
= hs_service_set_conn_addr_port(origin_circ
, conn
);
3902 /* We should never get here if the circuit's purpose is rendezvous. */
3903 tor_assert_nonfatal_unreached();
3907 log_info(LD_REND
, "Didn't find rendezvous service at %s",
3908 connection_describe_peer(TO_CONN(conn
)));
3909 /* Send back reason DONE because we want to make hidden service port
3910 * scanning harder thus instead of returning that the exit policy
3911 * didn't match, which makes it obvious that the port is closed,
3912 * return DONE and kill the circuit. That way, a user (malicious or
3913 * not) needs one circuit per bad port unless it matches the policy of
3914 * the hidden service. */
3915 relay_send_end_cell_from_edge(conn
->stream_id
, circ
,
3916 END_STREAM_REASON_DONE
,
3917 origin_circ
->cpath
->prev
);
3918 connection_free_(TO_CONN(conn
));
3920 /* Drop the circuit here since it might be someone deliberately
3921 * scanning the hidden service ports. Note that this mitigates port
3922 * scanning by adding more work on the attacker side to successfully
3923 * scan but does not fully solve it. */
3925 return END_CIRC_AT_ORIGIN
;
3931 /* Link the circuit and the connection crypt path. */
3932 conn
->cpath_layer
= origin_circ
->cpath
->prev
;
3934 /* If this is the first stream on this circuit, tell circpad */
3935 if (!origin_circ
->p_streams
)
3936 circpad_machine_event_circ_has_streams(origin_circ
);
3938 /* Add it into the linked list of p_streams on this circuit */
3939 conn
->next_stream
= origin_circ
->p_streams
;
3940 origin_circ
->p_streams
= conn
;
3941 conn
->on_circuit
= circ
;
3942 assert_circuit_ok(circ
);
3944 hs_inc_rdv_stream_counter(origin_circ
);
3946 /* If it's an onion service connection, we might want to include the proxy
3947 * protocol header: */
3948 if (conn
->hs_ident
) {
3949 hs_circuit_id_protocol_t circuit_id_protocol
=
3950 hs_service_exports_circuit_id(&conn
->hs_ident
->identity_pk
);
3951 export_hs_client_circuit_id(conn
, circuit_id_protocol
);
3954 /* Connect tor to the hidden service destination. */
3955 connection_exit_connect(conn
);
3957 /* For path bias: This circuit was used successfully */
3958 pathbias_mark_use_success(origin_circ
);
3962 /** A relay 'begin' or 'begin_dir' cell has arrived, and either we are
3963 * an exit hop for the circuit, or we are the origin and it is a
3966 * Launch a new exit connection and initialize things appropriately.
3968 * If it's a rendezvous stream, call connection_exit_connect() on
3971 * For general streams, call dns_resolve() on it first, and only call
3972 * connection_exit_connect() if the dns answer is already known.
3974 * Note that we don't call connection_add() on the new stream! We wait
3975 * for connection_exit_connect() to do that.
3977 * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
3981 connection_exit_begin_conn(cell_t
*cell
, circuit_t
*circ
)
3983 edge_connection_t
*n_stream
;
3985 char *address
= NULL
;
3987 or_circuit_t
*or_circ
= NULL
;
3988 origin_circuit_t
*origin_circ
= NULL
;
3989 crypt_path_t
*layer_hint
= NULL
;
3990 const or_options_t
*options
= get_options();
3993 uint8_t end_reason
=0;
3994 dos_stream_defense_type_t dos_defense_type
;
3996 assert_circuit_ok(circ
);
3997 if (!CIRCUIT_IS_ORIGIN(circ
)) {
3998 or_circ
= TO_OR_CIRCUIT(circ
);
4000 tor_assert(circ
->purpose
== CIRCUIT_PURPOSE_S_REND_JOINED
);
4001 origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
4002 layer_hint
= origin_circ
->cpath
->prev
;
4005 relay_header_unpack(&rh
, cell
->payload
);
4006 if (rh
.length
> RELAY_PAYLOAD_SIZE
)
4007 return -END_CIRC_REASON_TORPROTOCOL
;
4009 if (!server_mode(options
) &&
4010 circ
->purpose
!= CIRCUIT_PURPOSE_S_REND_JOINED
) {
4011 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
4012 "Relay begin cell at non-server. Closing.");
4013 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
4014 END_STREAM_REASON_EXITPOLICY
, NULL
);
4018 rv
= begin_cell_parse(cell
, &bcell
, &end_reason
);
4020 return -END_CIRC_REASON_TORPROTOCOL
;
4021 } else if (rv
== -1) {
4022 tor_free(bcell
.address
);
4023 relay_send_end_cell_from_edge(rh
.stream_id
, circ
, end_reason
, layer_hint
);
4027 if (! bcell
.is_begindir
) {
4028 /* Steal reference */
4029 tor_assert(bcell
.address
);
4030 address
= bcell
.address
;
4033 if (or_circ
&& or_circ
->p_chan
) {
4034 const int client_chan
= channel_is_client(or_circ
->p_chan
);
4036 (!connection_or_digest_is_known_relay(
4037 or_circ
->p_chan
->identity_digest
) &&
4038 should_refuse_unknown_exits(options
)))) {
4039 /* Don't let clients use us as a single-hop proxy. It attracts
4040 * attackers and users who'd be better off with, well, single-hop
4042 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
4043 "Attempt by %s to open a stream %s. Closing.",
4044 safe_str(channel_describe_peer(or_circ
->p_chan
)),
4045 client_chan
? "on first hop of circuit" :
4046 "from unknown relay");
4047 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
4049 END_STREAM_REASON_TORPROTOCOL
:
4050 END_STREAM_REASON_MISC
,
4056 } else if (rh
.command
== RELAY_COMMAND_BEGIN_DIR
) {
4057 if (!directory_permits_begindir_requests(options
) ||
4058 circ
->purpose
!= CIRCUIT_PURPOSE_OR
) {
4059 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
4060 END_STREAM_REASON_NOTDIRECTORY
, layer_hint
);
4063 /* Make sure to get the 'real' address of the previous hop: the
4064 * caller might want to know whether the remote IP address has changed,
4065 * and we might already have corrected base_.addr[ess] for the relay's
4066 * canonical IP address. */
4067 tor_addr_t chan_addr
;
4068 if (or_circ
&& or_circ
->p_chan
&&
4069 channel_get_addr_if_possible(or_circ
->p_chan
, &chan_addr
)) {
4070 address
= tor_addr_to_str_dup(&chan_addr
);
4072 address
= tor_strdup("127.0.0.1");
4074 port
= 1; /* XXXX This value is never actually used anywhere, and there
4075 * isn't "really" a connection here. But we
4076 * need to set it to something nonzero. */
4078 log_warn(LD_BUG
, "Got an unexpected command %d", (int)rh
.command
);
4079 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
4080 END_STREAM_REASON_INTERNAL
, layer_hint
);
4084 if (! options
->IPv6Exit
) {
4085 /* I don't care if you prefer IPv6; I can't give you any. */
4086 bcell
.flags
&= ~BEGIN_FLAG_IPV6_PREFERRED
;
4087 /* If you don't want IPv4, I can't help. */
4088 if (bcell
.flags
& BEGIN_FLAG_IPV4_NOT_OK
) {
4090 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
4091 END_STREAM_REASON_EXITPOLICY
, layer_hint
);
4096 log_debug(LD_EXIT
,"Creating new exit connection.");
4097 /* The 'AF_INET' here is temporary; we might need to change it later in
4098 * connection_exit_connect(). */
4099 n_stream
= edge_connection_new(CONN_TYPE_EXIT
, AF_INET
);
4101 /* Remember the tunneled request ID in the new edge connection, so that
4102 * we can measure download times. */
4103 n_stream
->dirreq_id
= circ
->dirreq_id
;
4105 n_stream
->base_
.purpose
= EXIT_PURPOSE_CONNECT
;
4106 n_stream
->begincell_flags
= bcell
.flags
;
4107 n_stream
->stream_id
= rh
.stream_id
;
4108 n_stream
->base_
.port
= port
;
4109 /* leave n_stream->s at -1, because it's not yet valid */
4110 n_stream
->package_window
= STREAMWINDOW_START
;
4111 n_stream
->deliver_window
= STREAMWINDOW_START
;
4113 if (circ
->purpose
== CIRCUIT_PURPOSE_S_REND_JOINED
) {
4116 /* We handle this circuit and stream in this function for all supported
4117 * hidden service version. */
4118 ret
= handle_hs_exit_conn(circ
, n_stream
);
4121 /* This was a valid cell. Count it as delivered + overhead. */
4122 circuit_read_valid_data(origin_circ
, rh
.length
);
4126 tor_strlower(address
);
4127 n_stream
->base_
.address
= address
;
4128 n_stream
->base_
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
4129 /* default to failed, change in dns_resolve if it turns out not to fail */
4131 /* If we're hibernating or shutting down, we refuse to open new streams. */
4132 if (we_are_hibernating()) {
4133 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
4134 END_STREAM_REASON_HIBERNATING
, NULL
);
4135 connection_free_(TO_CONN(n_stream
));
4139 n_stream
->on_circuit
= circ
;
4141 if (rh
.command
== RELAY_COMMAND_BEGIN_DIR
) {
4142 tor_addr_t tmp_addr
;
4143 tor_assert(or_circ
);
4144 if (or_circ
->p_chan
&&
4145 channel_get_addr_if_possible(or_circ
->p_chan
, &tmp_addr
)) {
4146 tor_addr_copy(&n_stream
->base_
.addr
, &tmp_addr
);
4148 return connection_exit_connect_dir(n_stream
);
4151 log_debug(LD_EXIT
,"about to start the dns_resolve().");
4153 // in the future we may want to have a similar defense for BEGIN_DIR and
4154 // BEGIN sent to OS.
4155 dos_defense_type
= dos_stream_new_begin_or_resolve_cell(or_circ
);
4156 switch (dos_defense_type
) {
4157 case DOS_STREAM_DEFENSE_NONE
:
4159 case DOS_STREAM_DEFENSE_REFUSE_STREAM
:
4160 // we don't use END_STREAM_REASON_RESOURCELIMIT because it would make a
4161 // client mark us as non-functional until they get a new consensus.
4162 relay_send_end_cell_from_edge(rh
.stream_id
, circ
, END_STREAM_REASON_MISC
,
4164 connection_free_(TO_CONN(n_stream
));
4166 case DOS_STREAM_DEFENSE_CLOSE_CIRCUIT
:
4167 connection_free_(TO_CONN(n_stream
));
4168 return -END_CIRC_REASON_RESOURCELIMIT
;
4171 /* send it off to the gethostbyname farm */
4172 switch (dns_resolve(n_stream
)) {
4173 case 1: /* resolve worked; now n_stream is attached to circ. */
4174 assert_circuit_ok(circ
);
4175 log_debug(LD_EXIT
,"about to call connection_exit_connect().");
4176 connection_exit_connect(n_stream
);
4178 case -1: /* resolve failed */
4179 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
4180 END_STREAM_REASON_RESOLVEFAILED
, NULL
);
4181 /* n_stream got freed. don't touch it. */
4183 case 0: /* resolve added to pending list */
4184 assert_circuit_ok(circ
);
4191 * Called when we receive a RELAY_COMMAND_RESOLVE cell 'cell' along the
4192 * circuit <b>circ</b>;
4193 * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
4195 * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
4199 connection_exit_begin_resolve(cell_t
*cell
, or_circuit_t
*circ
)
4201 edge_connection_t
*dummy_conn
;
4203 dos_stream_defense_type_t dos_defense_type
;
4205 assert_circuit_ok(TO_CIRCUIT(circ
));
4206 relay_header_unpack(&rh
, cell
->payload
);
4207 if (rh
.length
> RELAY_PAYLOAD_SIZE
)
4210 /* Note the RESOLVE stream as seen. */
4211 rep_hist_note_exit_stream(RELAY_COMMAND_RESOLVE
);
4213 /* This 'dummy_conn' only exists to remember the stream ID
4214 * associated with the resolve request; and to make the
4215 * implementation of dns.c more uniform. (We really only need to
4216 * remember the circuit, the stream ID, and the hostname to be
4217 * resolved; but if we didn't store them in a connection like this,
4218 * the housekeeping in dns.c would get way more complicated.)
4220 dummy_conn
= edge_connection_new(CONN_TYPE_EXIT
, AF_INET
);
4221 dummy_conn
->stream_id
= rh
.stream_id
;
4222 dummy_conn
->base_
.address
= tor_strndup(
4223 (char*)cell
->payload
+RELAY_HEADER_SIZE
,
4225 dummy_conn
->base_
.port
= 0;
4226 dummy_conn
->base_
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
4227 dummy_conn
->base_
.purpose
= EXIT_PURPOSE_RESOLVE
;
4229 dummy_conn
->on_circuit
= TO_CIRCUIT(circ
);
4231 dos_defense_type
= dos_stream_new_begin_or_resolve_cell(circ
);
4232 switch (dos_defense_type
) {
4233 case DOS_STREAM_DEFENSE_NONE
:
4235 case DOS_STREAM_DEFENSE_REFUSE_STREAM
:
4236 dns_send_resolved_error_cell(dummy_conn
, RESOLVED_TYPE_ERROR_TRANSIENT
);
4237 connection_free_(TO_CONN(dummy_conn
));
4239 case DOS_STREAM_DEFENSE_CLOSE_CIRCUIT
:
4240 connection_free_(TO_CONN(dummy_conn
));
4241 return -END_CIRC_REASON_RESOURCELIMIT
;
4244 /* send it off to the gethostbyname farm */
4245 switch (dns_resolve(dummy_conn
)) {
4246 case -1: /* Impossible to resolve; a resolved cell was sent. */
4247 /* Connection freed; don't touch it. */
4249 case 1: /* The result was cached; a resolved cell was sent. */
4250 if (!dummy_conn
->base_
.marked_for_close
)
4251 connection_free_(TO_CONN(dummy_conn
));
4253 case 0: /* resolve added to pending list */
4254 assert_circuit_ok(TO_CIRCUIT(circ
));
4260 /** Helper: Return true and set *<b>why_rejected</b> to an optional clarifying
4261 * message message iff we do not allow connections to <b>addr</b>:<b>port</b>.
4264 my_exit_policy_rejects(const tor_addr_t
*addr
,
4266 const char **why_rejected
)
4268 if (router_compare_to_my_exit_policy(addr
, port
)) {
4271 } else if (tor_addr_family(addr
) == AF_INET6
&& !get_options()->IPv6Exit
) {
4272 *why_rejected
= " (IPv6 address without IPv6Exit configured)";
4278 /* Reapply exit policy to existing connections, possibly terminating
4280 * no longer allowed by the policy.
4283 connection_reapply_exit_policy(config_line_t
*changes
)
4285 int marked_for_close
= 0;
4286 smartlist_t
*conn_list
= NULL
;
4287 smartlist_t
*policy
= NULL
;
4288 int config_change_relevant
= 0;
4290 if (get_options()->ReevaluateExitPolicy
== 0) {
4294 for (const config_line_t
*line
= changes
;
4295 line
&& !config_change_relevant
;
4296 line
= line
->next
) {
4297 const char* exit_policy_options
[] = {
4300 "ReducedExitPolicy",
4301 "ReevaluateExitPolicy",
4305 for (unsigned int i
= 0; exit_policy_options
[i
] != NULL
; ++i
) {
4306 if (strcmp(line
->key
, exit_policy_options
[i
]) == 0) {
4307 config_change_relevant
= 1;
4313 if (!config_change_relevant
) {
4314 /* Policy did not change: no need to iterate over connections */
4318 // we can't use router_compare_to_my_exit_policy as it depend on the
4319 // descriptor, which is regenerated asynchronously, so we have to parse the
4320 // policy ourselves.
4321 // We don't verify for our own IP, it's not part of the configuration.
4322 if (BUG(policies_parse_exit_policy_from_options(get_options(), NULL
, NULL
,
4327 conn_list
= connection_list_by_type_purpose(CONN_TYPE_EXIT
,
4328 EXIT_PURPOSE_CONNECT
);
4330 SMARTLIST_FOREACH_BEGIN(conn_list
, connection_t
*, conn
) {
4331 addr_policy_result_t verdict
= compare_tor_addr_to_addr_policy(&conn
->addr
,
4334 if (verdict
!= ADDR_POLICY_ACCEPTED
) {
4335 connection_edge_end(TO_EDGE_CONN(conn
), END_STREAM_REASON_EXITPOLICY
);
4336 connection_mark_for_close(conn
);
4339 } SMARTLIST_FOREACH_END(conn
);
4341 smartlist_free(conn_list
);
4342 smartlist_free(policy
);
4344 log_info(LD_GENERAL
, "Marked %d connections to be closed as no longer "
4345 "allowed per ExitPolicy", marked_for_close
);
4348 /** Return true iff the consensus allows network reentry. The default value is
4349 * false if the parameter is not found. */
4351 network_reentry_is_allowed(void)
4353 /* Default is false, re-entry is not allowed. */
4354 return !!networkstatus_get_param(NULL
, "allow-network-reentry", 0, 0, 1);
4357 /** Connect to conn's specified addr and port. If it worked, conn
4358 * has now been added to the connection_array.
4360 * Send back a connected cell. Include the resolved IP of the destination
4361 * address, but <em>only</em> if it's a general exit stream. (Rendezvous
4362 * streams must not reveal what IP they connected to.)
4365 connection_exit_connect(edge_connection_t
*edge_conn
)
4367 const tor_addr_t
*addr
;
4369 connection_t
*conn
= TO_CONN(edge_conn
);
4370 int socket_error
= 0, result
;
4371 const char *why_failed_exit_policy
= NULL
;
4373 /* Apply exit policy to non-rendezvous connections. */
4374 if (! connection_edge_is_rendezvous_stream(edge_conn
) &&
4375 my_exit_policy_rejects(&edge_conn
->base_
.addr
,
4376 edge_conn
->base_
.port
,
4377 &why_failed_exit_policy
)) {
4378 if (BUG(!why_failed_exit_policy
))
4379 why_failed_exit_policy
= "";
4380 log_info(LD_EXIT
,"%s failed exit policy%s. Closing.",
4381 connection_describe(conn
),
4382 why_failed_exit_policy
);
4383 rep_hist_note_conn_rejected(conn
->type
, conn
->socket_family
);
4384 connection_edge_end(edge_conn
, END_STREAM_REASON_EXITPOLICY
);
4385 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn
), edge_conn
);
4386 connection_free(conn
);
4390 /* Next, check for attempts to connect back into the Tor network. We don't
4391 * want to allow these for the same reason we don't want to allow
4392 * infinite-length circuits (see "A Practical Congestion Attack on Tor Using
4393 * Long Paths", Usenix Security 2009). See also ticket 2667.
4395 * Skip this if the network reentry is allowed (known from the consensus).
4397 * The TORPROTOCOL reason is used instead of EXITPOLICY so client do NOT
4398 * attempt to retry connecting onto another circuit that will also fail
4399 * bringing considerable more load on the network if so.
4401 * Since the address+port set here is a bloomfilter, in very rare cases, the
4402 * check will create a false positive meaning that the destination could
4403 * actually be legit and thus being denied exit. However, sending back a
4404 * reason that makes the client retry results in much worst consequences in
4405 * case of an attack so this is a small price to pay. */
4406 if (!connection_edge_is_rendezvous_stream(edge_conn
) &&
4407 !network_reentry_is_allowed() &&
4408 nodelist_reentry_contains(&conn
->addr
, conn
->port
)) {
4409 log_info(LD_EXIT
, "%s tried to connect back to a known relay address. "
4410 "Closing.", connection_describe(conn
));
4411 rep_hist_note_conn_rejected(conn
->type
, conn
->socket_family
);
4412 connection_edge_end(edge_conn
, END_STREAM_REASON_CONNECTREFUSED
);
4413 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn
), edge_conn
);
4414 connection_free(conn
);
4418 /* Note the BEGIN stream as seen. We do this after the Exit policy check in
4419 * order to only account for valid streams. */
4420 rep_hist_note_exit_stream(RELAY_COMMAND_BEGIN
);
4422 #ifdef HAVE_SYS_UN_H
4423 if (conn
->socket_family
!= AF_UNIX
) {
4426 #endif /* defined(HAVE_SYS_UN_H) */
4430 if (tor_addr_family(addr
) == AF_INET6
)
4431 conn
->socket_family
= AF_INET6
;
4433 log_debug(LD_EXIT
, "about to try connecting");
4434 result
= connection_connect(conn
, conn
->address
,
4435 addr
, port
, &socket_error
);
4436 #ifdef HAVE_SYS_UN_H
4439 * In the AF_UNIX case, we expect to have already had conn->port = 1,
4440 * tor_addr_make_unspec(conn->addr) (cf. the way we mark in the incoming
4441 * case in connection_handle_listener_read()), and conn->address should
4442 * have the socket path to connect to.
4444 tor_assert(conn
->address
&& strlen(conn
->address
) > 0);
4446 log_debug(LD_EXIT
, "about to try connecting");
4447 result
= connection_connect_unix(conn
, conn
->address
, &socket_error
);
4448 #endif /* defined(HAVE_SYS_UN_H) */
4453 int reason
= errno_to_stream_end_reason(socket_error
);
4454 connection_edge_end(edge_conn
, reason
);
4455 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn
), edge_conn
);
4456 connection_free(conn
);
4460 conn
->state
= EXIT_CONN_STATE_CONNECTING
;
4462 connection_watch_events(conn
, READ_EVENT
| WRITE_EVENT
);
4463 /* writable indicates finish;
4464 * readable/error indicates broken link in windows-land. */
4466 /* case 1: fall through */
4469 conn
->state
= EXIT_CONN_STATE_OPEN
;
4470 if (connection_get_outbuf_len(conn
)) {
4471 /* in case there are any queued data cells, from e.g. optimistic data */
4472 connection_watch_events(conn
, READ_EVENT
|WRITE_EVENT
);
4474 connection_watch_events(conn
, READ_EVENT
);
4477 /* also, deliver a 'connected' cell back through the circuit. */
4478 if (connection_edge_is_rendezvous_stream(edge_conn
)) {
4479 /* don't send an address back! */
4480 connection_edge_send_command(edge_conn
,
4481 RELAY_COMMAND_CONNECTED
,
4483 } else { /* normal stream */
4484 uint8_t connected_payload
[MAX_CONNECTED_CELL_PAYLOAD_LEN
];
4485 int connected_payload_len
=
4486 connected_cell_format_payload(connected_payload
, &conn
->addr
,
4487 edge_conn
->address_ttl
);
4488 if (connected_payload_len
< 0) {
4489 connection_edge_end(edge_conn
, END_STREAM_REASON_INTERNAL
);
4490 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn
), edge_conn
);
4491 connection_free(conn
);
4495 connection_edge_send_command(edge_conn
,
4496 RELAY_COMMAND_CONNECTED
,
4497 (char*)connected_payload
,
4498 connected_payload_len
);
4502 /** Given an exit conn that should attach to us as a directory server, open a
4503 * bridge connection with a linked connection pair, create a new directory
4504 * conn, and join them together. Return 0 on success (or if there was an
4505 * error we could send back an end cell for). Return -(some circuit end
4506 * reason) if the circuit needs to be torn down. Either connects
4507 * <b>exitconn</b>, frees it, or marks it, as appropriate.
4510 connection_exit_connect_dir(edge_connection_t
*exitconn
)
4512 dir_connection_t
*dirconn
= NULL
;
4513 or_circuit_t
*circ
= TO_OR_CIRCUIT(exitconn
->on_circuit
);
4515 log_info(LD_EXIT
, "Opening local connection for anonymized directory exit");
4517 /* Note the BEGIN_DIR stream as seen. */
4518 rep_hist_note_exit_stream(RELAY_COMMAND_BEGIN_DIR
);
4520 exitconn
->base_
.state
= EXIT_CONN_STATE_OPEN
;
4522 dirconn
= dir_connection_new(tor_addr_family(&exitconn
->base_
.addr
));
4524 tor_addr_copy(&dirconn
->base_
.addr
, &exitconn
->base_
.addr
);
4525 dirconn
->base_
.port
= 0;
4526 dirconn
->base_
.address
= tor_strdup(exitconn
->base_
.address
);
4527 dirconn
->base_
.type
= CONN_TYPE_DIR
;
4528 dirconn
->base_
.purpose
= DIR_PURPOSE_SERVER
;
4529 dirconn
->base_
.state
= DIR_CONN_STATE_SERVER_COMMAND_WAIT
;
4531 /* Note that the new dir conn belongs to the same tunneled request as
4532 * the edge conn, so that we can measure download times. */
4533 dirconn
->dirreq_id
= exitconn
->dirreq_id
;
4535 connection_link_connections(TO_CONN(dirconn
), TO_CONN(exitconn
));
4537 if (connection_add(TO_CONN(exitconn
))<0) {
4538 connection_edge_end(exitconn
, END_STREAM_REASON_RESOURCELIMIT
);
4539 connection_free_(TO_CONN(exitconn
));
4540 connection_free_(TO_CONN(dirconn
));
4544 /* link exitconn to circ, now that we know we can use it. */
4545 exitconn
->next_stream
= circ
->n_streams
;
4546 circ
->n_streams
= exitconn
;
4548 if (connection_add(TO_CONN(dirconn
))<0) {
4549 connection_edge_end(exitconn
, END_STREAM_REASON_RESOURCELIMIT
);
4550 connection_close_immediate(TO_CONN(exitconn
));
4551 connection_mark_for_close(TO_CONN(exitconn
));
4552 connection_free_(TO_CONN(dirconn
));
4556 connection_start_reading(TO_CONN(dirconn
));
4557 connection_start_reading(TO_CONN(exitconn
));
4559 if (connection_edge_send_command(exitconn
,
4560 RELAY_COMMAND_CONNECTED
, NULL
, 0) < 0) {
4561 connection_mark_for_close(TO_CONN(exitconn
));
4562 connection_mark_for_close(TO_CONN(dirconn
));
4569 /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
4570 * it is a general stream.
4573 connection_edge_is_rendezvous_stream(const edge_connection_t
*conn
)
4577 if (conn
->hs_ident
) {
4583 /** Return 1 if router <b>exit_node</b> is likely to allow stream <b>conn</b>
4584 * to exit from it, or 0 if it probably will not allow it.
4585 * (We might be uncertain if conn's destination address has not yet been
4589 connection_ap_can_use_exit(const entry_connection_t
*conn
,
4590 const node_t
*exit_node
)
4592 const or_options_t
*options
= get_options();
4595 tor_assert(conn
->socks_request
);
4596 tor_assert(exit_node
);
4598 /* If a particular exit node has been requested for the new connection,
4599 * make sure the exit node of the existing circuit matches exactly.
4601 if (conn
->chosen_exit_name
) {
4602 const node_t
*chosen_exit
=
4603 node_get_by_nickname(conn
->chosen_exit_name
, 0);
4604 if (!chosen_exit
|| tor_memneq(chosen_exit
->identity
,
4605 exit_node
->identity
, DIGEST_LEN
)) {
4607 // log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
4608 // conn->chosen_exit_name, exit->nickname);
4613 if (conn
->use_begindir
) {
4614 /* Internal directory fetches do not count as exiting. */
4618 if (conn
->socks_request
->command
== SOCKS_COMMAND_CONNECT
) {
4619 tor_addr_t addr
, *addrp
= NULL
;
4620 addr_policy_result_t r
;
4621 if (0 == tor_addr_parse(&addr
, conn
->socks_request
->address
)) {
4623 } else if (!conn
->entry_cfg
.ipv4_traffic
&& conn
->entry_cfg
.ipv6_traffic
) {
4624 tor_addr_make_null(&addr
, AF_INET6
);
4626 } else if (conn
->entry_cfg
.ipv4_traffic
&& !conn
->entry_cfg
.ipv6_traffic
) {
4627 tor_addr_make_null(&addr
, AF_INET
);
4630 r
= compare_tor_addr_to_node_policy(addrp
, conn
->socks_request
->port
,
4632 if (r
== ADDR_POLICY_REJECTED
)
4633 return 0; /* We know the address, and the exit policy rejects it. */
4634 if (r
== ADDR_POLICY_PROBABLY_REJECTED
&& !conn
->chosen_exit_name
)
4635 return 0; /* We don't know the addr, but the exit policy rejects most
4636 * addresses with this port. Since the user didn't ask for
4637 * this node, err on the side of caution. */
4638 } else if (SOCKS_COMMAND_IS_RESOLVE(conn
->socks_request
->command
)) {
4639 /* Don't send DNS requests to non-exit servers by default. */
4640 if (!conn
->chosen_exit_name
&& node_exit_policy_rejects_all(exit_node
))
4643 if (routerset_contains_node(options
->ExcludeExitNodesUnion_
, exit_node
)) {
4644 /* Not a suitable exit. Refuse it. */
4651 /** Return true iff the (possibly NULL) <b>alen</b>-byte chunk of memory at
4652 * <b>a</b> is equal to the (possibly NULL) <b>blen</b>-byte chunk of memory
4655 memeq_opt(const char *a
, size_t alen
, const char *b
, size_t blen
)
4659 } else if (b
== NULL
) {
4661 } else if (alen
!= blen
) {
4664 return tor_memeq(a
, b
, alen
);
4669 * Return true iff none of the isolation flags and fields in <b>conn</b>
4670 * should prevent it from being attached to <b>circ</b>.
4673 connection_edge_compatible_with_circuit(const entry_connection_t
*conn
,
4674 const origin_circuit_t
*circ
)
4676 const uint8_t iso
= conn
->entry_cfg
.isolation_flags
;
4677 const socks_request_t
*sr
= conn
->socks_request
;
4679 /* If circ has never been used for an isolated connection, we can
4680 * totally use it for this one. */
4681 if (!circ
->isolation_values_set
)
4684 /* If circ has been used for connections having more than one value
4685 * for some field f, it will have the corresponding bit set in
4686 * isolation_flags_mixed. If isolation_flags_mixed has any bits
4687 * in common with iso, then conn must be isolated from at least
4688 * one stream that has been attached to circ. */
4689 if ((iso
& circ
->isolation_flags_mixed
) != 0) {
4690 /* For at least one field where conn is isolated, the circuit
4691 * already has mixed streams. */
4695 if (! conn
->original_dest_address
) {
4696 log_warn(LD_BUG
, "Reached connection_edge_compatible_with_circuit without "
4697 "having set conn->original_dest_address");
4698 ((entry_connection_t
*)conn
)->original_dest_address
=
4699 tor_strdup(conn
->socks_request
->address
);
4702 if ((iso
& ISO_STREAM
) &&
4703 (circ
->associated_isolated_stream_global_id
!=
4704 ENTRY_TO_CONN(conn
)->global_identifier
))
4707 if ((iso
& ISO_DESTPORT
) && conn
->socks_request
->port
!= circ
->dest_port
)
4709 if ((iso
& ISO_DESTADDR
) &&
4710 strcasecmp(conn
->original_dest_address
, circ
->dest_address
))
4712 if ((iso
& ISO_SOCKSAUTH
) &&
4713 (! memeq_opt(sr
->username
, sr
->usernamelen
,
4714 circ
->socks_username
, circ
->socks_username_len
) ||
4715 ! memeq_opt(sr
->password
, sr
->passwordlen
,
4716 circ
->socks_password
, circ
->socks_password_len
)))
4718 if ((iso
& ISO_CLIENTPROTO
) &&
4719 (conn
->socks_request
->listener_type
!= circ
->client_proto_type
||
4720 conn
->socks_request
->socks_version
!= circ
->client_proto_socksver
))
4722 if ((iso
& ISO_CLIENTADDR
) &&
4723 !tor_addr_eq(&ENTRY_TO_CONN(conn
)->addr
, &circ
->client_addr
))
4725 if ((iso
& ISO_SESSIONGRP
) &&
4726 conn
->entry_cfg
.session_group
!= circ
->session_group
)
4728 if ((iso
& ISO_NYM_EPOCH
) && conn
->nym_epoch
!= circ
->nym_epoch
)
4735 * If <b>dry_run</b> is false, update <b>circ</b>'s isolation flags and fields
4736 * to reflect having had <b>conn</b> attached to it, and return 0. Otherwise,
4737 * if <b>dry_run</b> is true, then make no changes to <b>circ</b>, and return
4738 * a bitfield of isolation flags that we would have to set in
4739 * isolation_flags_mixed to add <b>conn</b> to <b>circ</b>, or -1 if
4740 * <b>circ</b> has had no streams attached to it.
4743 connection_edge_update_circuit_isolation(const entry_connection_t
*conn
,
4744 origin_circuit_t
*circ
,
4747 const socks_request_t
*sr
= conn
->socks_request
;
4748 if (! conn
->original_dest_address
) {
4749 log_warn(LD_BUG
, "Reached connection_update_circuit_isolation without "
4750 "having set conn->original_dest_address");
4751 ((entry_connection_t
*)conn
)->original_dest_address
=
4752 tor_strdup(conn
->socks_request
->address
);
4755 if (!circ
->isolation_values_set
) {
4758 circ
->associated_isolated_stream_global_id
=
4759 ENTRY_TO_CONN(conn
)->global_identifier
;
4760 circ
->dest_port
= conn
->socks_request
->port
;
4761 circ
->dest_address
= tor_strdup(conn
->original_dest_address
);
4762 circ
->client_proto_type
= conn
->socks_request
->listener_type
;
4763 circ
->client_proto_socksver
= conn
->socks_request
->socks_version
;
4764 tor_addr_copy(&circ
->client_addr
, &ENTRY_TO_CONN(conn
)->addr
);
4765 circ
->session_group
= conn
->entry_cfg
.session_group
;
4766 circ
->nym_epoch
= conn
->nym_epoch
;
4767 circ
->socks_username
= sr
->username
?
4768 tor_memdup(sr
->username
, sr
->usernamelen
) : NULL
;
4769 circ
->socks_password
= sr
->password
?
4770 tor_memdup(sr
->password
, sr
->passwordlen
) : NULL
;
4771 circ
->socks_username_len
= sr
->usernamelen
;
4772 circ
->socks_password_len
= sr
->passwordlen
;
4774 circ
->isolation_values_set
= 1;
4778 if (conn
->socks_request
->port
!= circ
->dest_port
)
4779 mixed
|= ISO_DESTPORT
;
4780 if (strcasecmp(conn
->original_dest_address
, circ
->dest_address
))
4781 mixed
|= ISO_DESTADDR
;
4782 if (!memeq_opt(sr
->username
, sr
->usernamelen
,
4783 circ
->socks_username
, circ
->socks_username_len
) ||
4784 !memeq_opt(sr
->password
, sr
->passwordlen
,
4785 circ
->socks_password
, circ
->socks_password_len
))
4786 mixed
|= ISO_SOCKSAUTH
;
4787 if ((conn
->socks_request
->listener_type
!= circ
->client_proto_type
||
4788 conn
->socks_request
->socks_version
!= circ
->client_proto_socksver
))
4789 mixed
|= ISO_CLIENTPROTO
;
4790 if (!tor_addr_eq(&ENTRY_TO_CONN(conn
)->addr
, &circ
->client_addr
))
4791 mixed
|= ISO_CLIENTADDR
;
4792 if (conn
->entry_cfg
.session_group
!= circ
->session_group
)
4793 mixed
|= ISO_SESSIONGRP
;
4794 if (conn
->nym_epoch
!= circ
->nym_epoch
)
4795 mixed
|= ISO_NYM_EPOCH
;
4800 if ((mixed
& conn
->entry_cfg
.isolation_flags
) != 0) {
4801 log_warn(LD_BUG
, "Updating a circuit with seemingly incompatible "
4802 "isolation flags.");
4804 circ
->isolation_flags_mixed
|= mixed
;
4810 * Clear the isolation settings on <b>circ</b>.
4812 * This only works on an open circuit that has never had a stream attached to
4813 * it, and whose isolation settings are hypothetical. (We set hypothetical
4814 * isolation settings on circuits as we're launching them, so that we
4815 * know whether they can handle more streams or whether we need to launch
4816 * even more circuits. Once the circuit is open, if it turns out that
4817 * we no longer have any streams to attach to it, we clear the isolation flags
4818 * and data so that other streams can have a chance.)
4821 circuit_clear_isolation(origin_circuit_t
*circ
)
4823 if (circ
->isolation_any_streams_attached
) {
4824 log_warn(LD_BUG
, "Tried to clear the isolation status of a dirty circuit");
4827 if (TO_CIRCUIT(circ
)->state
!= CIRCUIT_STATE_OPEN
) {
4828 log_warn(LD_BUG
, "Tried to clear the isolation status of a non-open "
4833 circ
->isolation_values_set
= 0;
4834 circ
->isolation_flags_mixed
= 0;
4835 circ
->associated_isolated_stream_global_id
= 0;
4836 circ
->client_proto_type
= 0;
4837 circ
->client_proto_socksver
= 0;
4838 circ
->dest_port
= 0;
4839 tor_addr_make_unspec(&circ
->client_addr
);
4840 tor_free(circ
->dest_address
);
4841 circ
->session_group
= -1;
4842 circ
->nym_epoch
= 0;
4843 if (circ
->socks_username
) {
4844 memwipe(circ
->socks_username
, 0x11, circ
->socks_username_len
);
4845 tor_free(circ
->socks_username
);
4847 if (circ
->socks_password
) {
4848 memwipe(circ
->socks_password
, 0x05, circ
->socks_password_len
);
4849 tor_free(circ
->socks_password
);
4851 circ
->socks_username_len
= circ
->socks_password_len
= 0;
4854 /** Send an END and mark for close the given edge connection conn using the
4855 * given reason that has to be a stream reason.
4857 * Note: We don't unattached the AP connection (if applicable) because we
4858 * don't want to flush the remaining data. This function aims at ending
4859 * everything quickly regardless of the connection state.
4861 * This function can't fail and does nothing if conn is NULL. */
4863 connection_edge_end_close(edge_connection_t
*conn
, uint8_t reason
)
4869 connection_edge_end(conn
, reason
);
4870 connection_mark_for_close(TO_CONN(conn
));
4873 /** Free all storage held in module-scoped variables for connection_edge.c */
4875 connection_edge_free_all(void)
4877 untried_pending_connections
= 0;
4878 smartlist_free(pending_entry_connections
);
4879 pending_entry_connections
= NULL
;
4880 mainloop_event_free(attach_pending_entry_connections_ev
);