1 /* Copyright (c) 2001 Matej Pfajfar.
2 * Copyright (c) 2001-2004, Roger Dingledine.
3 * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
4 * Copyright (c) 2007-2017, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
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 connction,
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
60 #include "backtrace.h"
62 #include "addressmap.h"
65 #include "circpathbias.h"
66 #include "circuitlist.h"
67 #include "circuituse.h"
69 #include "connection.h"
70 #include "connection_edge.h"
71 #include "connection_or.h"
75 #include "directory.h"
77 #include "hibernate.h"
78 #include "hs_common.h"
80 #include "hs_client.h"
81 #include "hs_circuit.h"
83 #include "networkstatus.h"
86 #include "proto_http.h"
87 #include "proto_socks.h"
90 #include "rendclient.h"
91 #include "rendcommon.h"
92 #include "rendservice.h"
95 #include "routerlist.h"
96 #include "routerset.h"
97 #include "circuitbuild.h"
99 #ifdef HAVE_LINUX_TYPES_H
100 #include <linux/types.h>
102 #ifdef HAVE_LINUX_NETFILTER_IPV4_H
103 #include <linux/netfilter_ipv4.h>
104 #define TRANS_NETFILTER
105 #define TRANS_NETFILTER_IPV4
108 #ifdef HAVE_LINUX_IF_H
109 #include <linux/if.h>
112 #ifdef HAVE_LINUX_NETFILTER_IPV6_IP6_TABLES_H
113 #include <linux/netfilter_ipv6/ip6_tables.h>
114 #if defined(IP6T_SO_ORIGINAL_DST)
115 #define TRANS_NETFILTER
116 #define TRANS_NETFILTER_IPV6
118 #endif /* defined(HAVE_LINUX_NETFILTER_IPV6_IP6_TABLES_H) */
120 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
122 #include <net/pfvar.h>
126 #ifdef IP_TRANSPARENT
130 #define SOCKS4_GRANTED 90
131 #define SOCKS4_REJECT 91
133 static int connection_ap_handshake_process_socks(entry_connection_t
*conn
);
134 static int connection_ap_process_natd(entry_connection_t
*conn
);
135 static int connection_exit_connect_dir(edge_connection_t
*exitconn
);
136 static int consider_plaintext_ports(entry_connection_t
*conn
, uint16_t port
);
137 static int connection_ap_supports_optimistic_data(const entry_connection_t
*);
139 /** An AP stream has failed/finished. If it hasn't already sent back
140 * a socks reply, send one now (based on endreason). Also set
141 * has_sent_end to 1, and mark the conn.
144 connection_mark_unattached_ap_
,(entry_connection_t
*conn
, int endreason
,
145 int line
, const char *file
))
147 connection_t
*base_conn
= ENTRY_TO_CONN(conn
);
148 edge_connection_t
*edge_conn
= ENTRY_TO_EDGE_CONN(conn
);
149 tor_assert(base_conn
->type
== CONN_TYPE_AP
);
150 ENTRY_TO_EDGE_CONN(conn
)->edge_has_sent_end
= 1; /* no circ yet */
152 /* If this is a rendezvous stream and it is failing without ever
153 * being attached to a circuit, assume that an attempt to connect to
154 * the destination hidden service has just ended.
156 * XXXX This condition doesn't limit to only streams failing
157 * without ever being attached. That sloppiness should be harmless,
158 * but we should fix it someday anyway. */
159 if ((edge_conn
->on_circuit
!= NULL
|| edge_conn
->edge_has_sent_end
) &&
160 connection_edge_is_rendezvous_stream(edge_conn
)) {
161 if (edge_conn
->rend_data
) {
162 rend_client_note_connection_attempt_ended(edge_conn
->rend_data
);
166 if (base_conn
->marked_for_close
) {
167 /* This call will warn as appropriate. */
168 connection_mark_for_close_(base_conn
, line
, file
);
172 if (!conn
->socks_request
->has_finished
) {
173 if (endreason
& END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
)
175 "stream (marked at %s:%d) sending two socks replies?",
178 if (SOCKS_COMMAND_IS_CONNECT(conn
->socks_request
->command
))
179 connection_ap_handshake_socks_reply(conn
, NULL
, 0, endreason
);
180 else if (SOCKS_COMMAND_IS_RESOLVE(conn
->socks_request
->command
))
181 connection_ap_handshake_socks_resolved(conn
,
182 RESOLVED_TYPE_ERROR_TRANSIENT
,
184 else /* unknown or no handshake at all. send no response. */
185 conn
->socks_request
->has_finished
= 1;
188 connection_mark_and_flush_(base_conn
, line
, file
);
190 ENTRY_TO_EDGE_CONN(conn
)->end_reason
= endreason
;
193 /** There was an EOF. Send an end and mark the connection for close.
196 connection_edge_reached_eof(edge_connection_t
*conn
)
198 if (connection_get_inbuf_len(TO_CONN(conn
)) &&
199 connection_state_is_open(TO_CONN(conn
))) {
200 /* it still has stuff to process. don't let it die yet. */
203 log_info(LD_EDGE
,"conn (fd "TOR_SOCKET_T_FORMAT
") reached eof. Closing.",
205 if (!conn
->base_
.marked_for_close
) {
206 /* only mark it if not already marked. it's possible to
207 * get the 'end' right around when the client hangs up on us. */
208 connection_edge_end(conn
, END_STREAM_REASON_DONE
);
209 if (conn
->base_
.type
== CONN_TYPE_AP
) {
210 /* eof, so don't send a socks reply back */
211 if (EDGE_TO_ENTRY_CONN(conn
)->socks_request
)
212 EDGE_TO_ENTRY_CONN(conn
)->socks_request
->has_finished
= 1;
214 connection_mark_for_close(TO_CONN(conn
));
219 /** Handle new bytes on conn->inbuf based on state:
220 * - If it's waiting for socks info, try to read another step of the
221 * socks handshake out of conn->inbuf.
222 * - If it's waiting for the original destination, fetch it.
223 * - If it's open, then package more relay cells from the stream.
224 * - Else, leave the bytes on inbuf alone for now.
226 * Mark and return -1 if there was an unexpected error with the conn,
230 connection_edge_process_inbuf(edge_connection_t
*conn
, int package_partial
)
234 switch (conn
->base_
.state
) {
235 case AP_CONN_STATE_SOCKS_WAIT
:
236 if (connection_ap_handshake_process_socks(EDGE_TO_ENTRY_CONN(conn
)) <0) {
241 case AP_CONN_STATE_NATD_WAIT
:
242 if (connection_ap_process_natd(EDGE_TO_ENTRY_CONN(conn
)) < 0) {
247 case AP_CONN_STATE_HTTP_CONNECT_WAIT
:
248 if (connection_ap_process_http_connect(EDGE_TO_ENTRY_CONN(conn
)) < 0) {
252 case AP_CONN_STATE_OPEN
:
253 case EXIT_CONN_STATE_OPEN
:
254 if (connection_edge_package_raw_inbuf(conn
, package_partial
, NULL
) < 0) {
255 /* (We already sent an end cell if possible) */
256 connection_mark_for_close(TO_CONN(conn
));
260 case AP_CONN_STATE_CONNECT_WAIT
:
261 if (connection_ap_supports_optimistic_data(EDGE_TO_ENTRY_CONN(conn
))) {
263 "data from edge while in '%s' state. Sending it anyway. "
264 "package_partial=%d, buflen=%ld",
265 conn_state_to_string(conn
->base_
.type
, conn
->base_
.state
),
267 (long)connection_get_inbuf_len(TO_CONN(conn
)));
268 if (connection_edge_package_raw_inbuf(conn
, package_partial
, NULL
)<0) {
269 /* (We already sent an end cell if possible) */
270 connection_mark_for_close(TO_CONN(conn
));
275 /* Fall through if the connection is on a circuit without optimistic
278 case EXIT_CONN_STATE_CONNECTING
:
279 case AP_CONN_STATE_RENDDESC_WAIT
:
280 case AP_CONN_STATE_CIRCUIT_WAIT
:
281 case AP_CONN_STATE_RESOLVE_WAIT
:
282 case AP_CONN_STATE_CONTROLLER_WAIT
:
284 "data from edge while in '%s' state. Leaving it on buffer.",
285 conn_state_to_string(conn
->base_
.type
, conn
->base_
.state
));
288 log_warn(LD_BUG
,"Got unexpected state %d. Closing.",conn
->base_
.state
);
289 tor_fragile_assert();
290 connection_edge_end(conn
, END_STREAM_REASON_INTERNAL
);
291 connection_mark_for_close(TO_CONN(conn
));
295 /** This edge needs to be closed, because its circuit has closed.
296 * Mark it for close and return 0.
299 connection_edge_destroy(circid_t circ_id
, edge_connection_t
*conn
)
301 if (!conn
->base_
.marked_for_close
) {
302 log_info(LD_EDGE
, "CircID %u: At an edge. Marking connection for close.",
304 if (conn
->base_
.type
== CONN_TYPE_AP
) {
305 entry_connection_t
*entry_conn
= EDGE_TO_ENTRY_CONN(conn
);
306 connection_mark_unattached_ap(entry_conn
, END_STREAM_REASON_DESTROY
);
307 control_event_stream_bandwidth(conn
);
308 control_event_stream_status(entry_conn
, STREAM_EVENT_CLOSED
,
309 END_STREAM_REASON_DESTROY
);
310 conn
->end_reason
|= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED
;
312 /* closing the circuit, nothing to send an END to */
313 conn
->edge_has_sent_end
= 1;
314 conn
->end_reason
= END_STREAM_REASON_DESTROY
;
315 conn
->end_reason
|= END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED
;
316 connection_mark_and_flush(TO_CONN(conn
));
319 conn
->cpath_layer
= NULL
;
320 conn
->on_circuit
= NULL
;
324 /** Send a raw end cell to the stream with ID <b>stream_id</b> out over the
325 * <b>circ</b> towards the hop identified with <b>cpath_layer</b>. If this
326 * is not a client connection, set the relay end cell's reason for closing
327 * as <b>reason</b> */
329 relay_send_end_cell_from_edge(streamid_t stream_id
, circuit_t
*circ
,
330 uint8_t reason
, crypt_path_t
*cpath_layer
)
334 if (CIRCUIT_PURPOSE_IS_CLIENT(circ
->purpose
)) {
335 /* Never send the server an informative reason code; it doesn't need to
336 * know why the client stream is failing. */
337 reason
= END_STREAM_REASON_MISC
;
340 payload
[0] = (char) reason
;
342 /* Note: we have to use relay_send_command_from_edge here, not
343 * connection_edge_end or connection_edge_send_command, since those require
344 * that we have a stream connected to a circuit, and we don't connect to a
345 * circuit until we have a pending/successful resolve. */
346 return relay_send_command_from_edge(stream_id
, circ
, RELAY_COMMAND_END
,
347 payload
, 1, cpath_layer
);
350 /* If the connection <b>conn</b> is attempting to connect to an external
351 * destination that is an hidden service and the reason is a connection
352 * refused or timeout, log it so the operator can take appropriate actions.
353 * The log statement is a rate limited warning. */
355 warn_if_hs_unreachable(const edge_connection_t
*conn
, uint8_t reason
)
359 if (conn
->base_
.type
== CONN_TYPE_EXIT
&&
360 connection_edge_is_rendezvous_stream(conn
) &&
361 (reason
== END_STREAM_REASON_CONNECTREFUSED
||
362 reason
== END_STREAM_REASON_TIMEOUT
)) {
363 #define WARN_FAILED_HS_CONNECTION 300
364 static ratelim_t warn_limit
= RATELIM_INIT(WARN_FAILED_HS_CONNECTION
);
366 if ((m
= rate_limit_log(&warn_limit
, approx_time()))) {
367 log_warn(LD_EDGE
, "Onion service connection to %s failed (%s)",
368 (conn
->base_
.socket_family
== AF_UNIX
) ?
369 safe_str(conn
->base_
.address
) :
370 safe_str(fmt_addrport(&conn
->base_
.addr
, conn
->base_
.port
)),
371 stream_end_reason_to_string(reason
));
377 /** Send a relay end cell from stream <b>conn</b> down conn's circuit, and
378 * remember that we've done so. If this is not a client connection, set the
379 * relay end cell's reason for closing as <b>reason</b>.
381 * Return -1 if this function has already been called on this conn,
385 connection_edge_end(edge_connection_t
*conn
, uint8_t reason
)
387 char payload
[RELAY_PAYLOAD_SIZE
];
388 size_t payload_len
=1;
390 uint8_t control_reason
= reason
;
392 if (conn
->edge_has_sent_end
) {
393 log_warn(LD_BUG
,"(Harmless.) Calling connection_edge_end (reason %d) "
394 "on an already ended stream?", reason
);
395 tor_fragile_assert();
399 if (conn
->base_
.marked_for_close
) {
401 "called on conn that's already marked for close at %s:%d.",
402 conn
->base_
.marked_for_close_file
, conn
->base_
.marked_for_close
);
406 circ
= circuit_get_by_edge_conn(conn
);
407 if (circ
&& CIRCUIT_PURPOSE_IS_CLIENT(circ
->purpose
)) {
408 /* If this is a client circuit, don't send the server an informative
409 * reason code; it doesn't need to know why the client stream is
411 reason
= END_STREAM_REASON_MISC
;
414 payload
[0] = (char)reason
;
415 if (reason
== END_STREAM_REASON_EXITPOLICY
&&
416 !connection_edge_is_rendezvous_stream(conn
)) {
418 if (tor_addr_family(&conn
->base_
.addr
) == AF_INET
) {
419 set_uint32(payload
+1, tor_addr_to_ipv4n(&conn
->base_
.addr
));
422 memcpy(payload
+1, tor_addr_to_in6_addr8(&conn
->base_
.addr
), 16);
425 set_uint32(payload
+1+addrlen
, htonl(dns_clip_ttl(conn
->address_ttl
)));
426 payload_len
+= 4+addrlen
;
429 if (circ
&& !circ
->marked_for_close
) {
430 log_debug(LD_EDGE
,"Sending end on conn (fd "TOR_SOCKET_T_FORMAT
").",
432 connection_edge_send_command(conn
, RELAY_COMMAND_END
,
433 payload
, payload_len
);
434 /* We'll log warn if the connection was an hidden service and couldn't be
435 * made because the service wasn't available. */
436 warn_if_hs_unreachable(conn
, control_reason
);
438 log_debug(LD_EDGE
,"No circ to send end on conn "
439 "(fd "TOR_SOCKET_T_FORMAT
").",
443 conn
->edge_has_sent_end
= 1;
444 conn
->end_reason
= control_reason
;
448 /** An error has just occurred on an operation on an edge connection
449 * <b>conn</b>. Extract the errno; convert it to an end reason, and send an
450 * appropriate relay end cell to the other end of the connection's circuit.
453 connection_edge_end_errno(edge_connection_t
*conn
)
457 reason
= errno_to_stream_end_reason(tor_socket_errno(conn
->base_
.s
));
458 return connection_edge_end(conn
, reason
);
461 /** We just wrote some data to <b>conn</b>; act appropriately.
463 * (That is, if it's open, consider sending a stream-level sendme cell if we
464 * have just flushed enough.)
467 connection_edge_flushed_some(edge_connection_t
*conn
)
469 switch (conn
->base_
.state
) {
470 case AP_CONN_STATE_OPEN
:
471 case EXIT_CONN_STATE_OPEN
:
472 connection_edge_consider_sending_sendme(conn
);
478 /** Connection <b>conn</b> has finished writing and has no bytes left on
481 * If it's in state 'open', stop writing, consider responding with a
482 * sendme, and return.
483 * Otherwise, stop writing and return.
485 * If <b>conn</b> is broken, mark it for close and return -1, else
489 connection_edge_finished_flushing(edge_connection_t
*conn
)
493 switch (conn
->base_
.state
) {
494 case AP_CONN_STATE_OPEN
:
495 case EXIT_CONN_STATE_OPEN
:
496 connection_edge_consider_sending_sendme(conn
);
498 case AP_CONN_STATE_SOCKS_WAIT
:
499 case AP_CONN_STATE_NATD_WAIT
:
500 case AP_CONN_STATE_RENDDESC_WAIT
:
501 case AP_CONN_STATE_CIRCUIT_WAIT
:
502 case AP_CONN_STATE_CONNECT_WAIT
:
503 case AP_CONN_STATE_CONTROLLER_WAIT
:
504 case AP_CONN_STATE_RESOLVE_WAIT
:
505 case AP_CONN_STATE_HTTP_CONNECT_WAIT
:
508 log_warn(LD_BUG
, "Called in unexpected state %d.",conn
->base_
.state
);
509 tor_fragile_assert();
515 /** Longest size for the relay payload of a RELAY_CONNECTED cell that we're
516 * able to generate. */
517 /* 4 zero bytes; 1 type byte; 16 byte IPv6 address; 4 byte TTL. */
518 #define MAX_CONNECTED_CELL_PAYLOAD_LEN 25
520 /** Set the buffer at <b>payload_out</b> -- which must have at least
521 * MAX_CONNECTED_CELL_PAYLOAD_LEN bytes available -- to the body of a
522 * RELAY_CONNECTED cell indicating that we have connected to <b>addr</b>, and
523 * that the name resolution that led us to <b>addr</b> will be valid for
524 * <b>ttl</b> seconds. Return -1 on error, or the number of bytes used on
527 connected_cell_format_payload(uint8_t *payload_out
,
528 const tor_addr_t
*addr
,
531 const sa_family_t family
= tor_addr_family(addr
);
532 int connected_payload_len
;
534 /* should be needless */
535 memset(payload_out
, 0, MAX_CONNECTED_CELL_PAYLOAD_LEN
);
537 if (family
== AF_INET
) {
538 set_uint32(payload_out
, tor_addr_to_ipv4n(addr
));
539 connected_payload_len
= 4;
540 } else if (family
== AF_INET6
) {
541 set_uint32(payload_out
, 0);
542 set_uint8(payload_out
+ 4, 6);
543 memcpy(payload_out
+ 5, tor_addr_to_in6_addr8(addr
), 16);
544 connected_payload_len
= 21;
549 set_uint32(payload_out
+ connected_payload_len
, htonl(dns_clip_ttl(ttl
)));
550 connected_payload_len
+= 4;
552 tor_assert(connected_payload_len
<= MAX_CONNECTED_CELL_PAYLOAD_LEN
);
554 return connected_payload_len
;
557 /** Connected handler for exit connections: start writing pending
558 * data, deliver 'CONNECTED' relay cells as appropriate, and check
559 * any pending data that may have been received. */
561 connection_edge_finished_connecting(edge_connection_t
*edge_conn
)
565 tor_assert(edge_conn
);
566 tor_assert(edge_conn
->base_
.type
== CONN_TYPE_EXIT
);
567 conn
= TO_CONN(edge_conn
);
568 tor_assert(conn
->state
== EXIT_CONN_STATE_CONNECTING
);
570 log_info(LD_EXIT
,"Exit connection to %s:%u (%s) established.",
571 escaped_safe_str(conn
->address
), conn
->port
,
572 safe_str(fmt_and_decorate_addr(&conn
->addr
)));
574 rep_hist_note_exit_stream_opened(conn
->port
);
576 conn
->state
= EXIT_CONN_STATE_OPEN
;
577 connection_watch_events(conn
, READ_EVENT
); /* stop writing, keep reading */
578 if (connection_get_outbuf_len(conn
)) /* in case there are any queued relay
580 connection_start_writing(conn
);
581 /* deliver a 'connected' relay cell back through the circuit. */
582 if (connection_edge_is_rendezvous_stream(edge_conn
)) {
583 if (connection_edge_send_command(edge_conn
,
584 RELAY_COMMAND_CONNECTED
, NULL
, 0) < 0)
585 return 0; /* circuit is closed, don't continue */
587 uint8_t connected_payload
[MAX_CONNECTED_CELL_PAYLOAD_LEN
];
588 int connected_payload_len
=
589 connected_cell_format_payload(connected_payload
, &conn
->addr
,
590 edge_conn
->address_ttl
);
591 if (connected_payload_len
< 0)
594 if (connection_edge_send_command(edge_conn
,
595 RELAY_COMMAND_CONNECTED
,
596 (char*)connected_payload
, connected_payload_len
) < 0)
597 return 0; /* circuit is closed, don't continue */
599 tor_assert(edge_conn
->package_window
> 0);
600 /* in case the server has written anything */
601 return connection_edge_process_inbuf(edge_conn
, 1);
604 /** A list of all the entry_connection_t * objects that are not marked
605 * for close, and are in AP_CONN_STATE_CIRCUIT_WAIT.
607 * (Right now, we check in several places to make sure that this list is
608 * correct. When it's incorrect, we'll fix it, and log a BUG message.)
610 static smartlist_t
*pending_entry_connections
= NULL
;
612 static int untried_pending_connections
= 0;
614 /** Common code to connection_(ap|exit)_about_to_close. */
616 connection_edge_about_to_close(edge_connection_t
*edge_conn
)
618 if (!edge_conn
->edge_has_sent_end
) {
619 connection_t
*conn
= TO_CONN(edge_conn
);
620 log_warn(LD_BUG
, "(Harmless.) Edge connection (marked at %s:%d) "
621 "hasn't sent end yet?",
622 conn
->marked_for_close_file
, conn
->marked_for_close
);
623 tor_fragile_assert();
627 /** Called when we're about to finally unlink and free an AP (client)
628 * connection: perform necessary accounting and cleanup */
630 connection_ap_about_to_close(entry_connection_t
*entry_conn
)
633 edge_connection_t
*edge_conn
= ENTRY_TO_EDGE_CONN(entry_conn
);
634 connection_t
*conn
= ENTRY_TO_CONN(entry_conn
);
636 connection_edge_about_to_close(edge_conn
);
638 if (entry_conn
->socks_request
->has_finished
== 0) {
639 /* since conn gets removed right after this function finishes,
640 * there's no point trying to send back a reply at this point. */
641 log_warn(LD_BUG
,"Closing stream (marked at %s:%d) without sending"
642 " back a socks reply.",
643 conn
->marked_for_close_file
, conn
->marked_for_close
);
645 if (!edge_conn
->end_reason
) {
646 log_warn(LD_BUG
,"Closing stream (marked at %s:%d) without having"
648 conn
->marked_for_close_file
, conn
->marked_for_close
);
650 if (entry_conn
->dns_server_request
) {
651 log_warn(LD_BUG
,"Closing stream (marked at %s:%d) without having"
652 " replied to DNS request.",
653 conn
->marked_for_close_file
, conn
->marked_for_close
);
654 dnsserv_reject_request(entry_conn
);
657 if (TO_CONN(edge_conn
)->state
== AP_CONN_STATE_CIRCUIT_WAIT
) {
658 smartlist_remove(pending_entry_connections
, entry_conn
);
662 /* Check to make sure that this isn't in pending_entry_connections if it
663 * didn't actually belong there. */
664 if (TO_CONN(edge_conn
)->type
== CONN_TYPE_AP
) {
665 connection_ap_warn_and_unmark_if_pending_circ(entry_conn
,
670 control_event_stream_bandwidth(edge_conn
);
671 control_event_stream_status(entry_conn
, STREAM_EVENT_CLOSED
,
672 edge_conn
->end_reason
);
673 circ
= circuit_get_by_edge_conn(edge_conn
);
675 circuit_detach_stream(circ
, edge_conn
);
678 /** Called when we're about to finally unlink and free an exit
679 * connection: perform necessary accounting and cleanup */
681 connection_exit_about_to_close(edge_connection_t
*edge_conn
)
684 connection_t
*conn
= TO_CONN(edge_conn
);
686 connection_edge_about_to_close(edge_conn
);
688 circ
= circuit_get_by_edge_conn(edge_conn
);
690 circuit_detach_stream(circ
, edge_conn
);
691 if (conn
->state
== EXIT_CONN_STATE_RESOLVING
) {
692 connection_dns_remove(edge_conn
);
696 /** Define a schedule for how long to wait between retrying
697 * application connections. Rather than waiting a fixed amount of
698 * time between each retry, we wait 10 seconds each for the first
699 * two tries, and 15 seconds for each retry after
700 * that. Hopefully this will improve the expected user experience. */
702 compute_retry_timeout(entry_connection_t
*conn
)
704 int timeout
= get_options()->CircuitStreamTimeout
;
705 if (timeout
) /* if our config options override the default, use them */
707 if (conn
->num_socks_retries
< 2) /* try 0 and try 1 */
712 /** Find all general-purpose AP streams waiting for a response that sent their
713 * begin/resolve cell too long ago. Detach from their current circuit, and
714 * mark their current circuit as unsuitable for new streams. Then call
715 * connection_ap_handshake_attach_circuit() to attach to a new circuit (if
716 * available) or launch a new one.
718 * For rendezvous streams, simply give up after SocksTimeout seconds (with no
722 connection_ap_expire_beginning(void)
724 edge_connection_t
*conn
;
725 entry_connection_t
*entry_conn
;
727 time_t now
= time(NULL
);
728 const or_options_t
*options
= get_options();
731 int seconds_idle
, seconds_since_born
;
732 smartlist_t
*conns
= get_connection_array();
734 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, base_conn
) {
735 if (base_conn
->type
!= CONN_TYPE_AP
|| base_conn
->marked_for_close
)
737 entry_conn
= TO_ENTRY_CONN(base_conn
);
738 conn
= ENTRY_TO_EDGE_CONN(entry_conn
);
739 /* if it's an internal linked connection, don't yell its status. */
740 severity
= (tor_addr_is_null(&base_conn
->addr
) && !base_conn
->port
)
741 ? LOG_INFO
: LOG_NOTICE
;
742 seconds_idle
= (int)( now
- base_conn
->timestamp_lastread
);
743 seconds_since_born
= (int)( now
- base_conn
->timestamp_created
);
745 if (base_conn
->state
== AP_CONN_STATE_OPEN
)
748 /* We already consider SocksTimeout in
749 * connection_ap_handshake_attach_circuit(), but we need to consider
750 * it here too because controllers that put streams in controller_wait
751 * state never ask Tor to attach the circuit. */
752 if (AP_CONN_STATE_IS_UNATTACHED(base_conn
->state
)) {
753 if (seconds_since_born
>= options
->SocksTimeout
) {
754 log_fn(severity
, LD_APP
,
755 "Tried for %d seconds to get a connection to %s:%d. "
758 safe_str_client(entry_conn
->socks_request
->address
),
759 entry_conn
->socks_request
->port
,
760 conn_state_to_string(CONN_TYPE_AP
, base_conn
->state
));
761 connection_mark_unattached_ap(entry_conn
, END_STREAM_REASON_TIMEOUT
);
766 /* We're in state connect_wait or resolve_wait now -- waiting for a
767 * reply to our relay cell. See if we want to retry/give up. */
769 cutoff
= compute_retry_timeout(entry_conn
);
770 if (seconds_idle
< cutoff
)
772 circ
= circuit_get_by_edge_conn(conn
);
773 if (!circ
) { /* it's vanished? */
774 log_info(LD_APP
,"Conn is waiting (address %s), but lost its circ.",
775 safe_str_client(entry_conn
->socks_request
->address
));
776 connection_mark_unattached_ap(entry_conn
, END_STREAM_REASON_TIMEOUT
);
779 if (circ
->purpose
== CIRCUIT_PURPOSE_C_REND_JOINED
) {
780 if (seconds_idle
>= options
->SocksTimeout
) {
781 log_fn(severity
, LD_REND
,
782 "Rend stream is %d seconds late. Giving up on address"
785 safe_str_client(entry_conn
->socks_request
->address
));
786 /* Roll back path bias use state so that we probe the circuit
787 * if nothing else succeeds on it */
788 pathbias_mark_use_rollback(TO_ORIGIN_CIRCUIT(circ
));
790 connection_edge_end(conn
, END_STREAM_REASON_TIMEOUT
);
791 connection_mark_unattached_ap(entry_conn
, END_STREAM_REASON_TIMEOUT
);
796 if (circ
->purpose
!= CIRCUIT_PURPOSE_C_GENERAL
&&
797 circ
->purpose
!= CIRCUIT_PURPOSE_C_HSDIR_GET
&&
798 circ
->purpose
!= CIRCUIT_PURPOSE_S_HSDIR_POST
&&
799 circ
->purpose
!= CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT
&&
800 circ
->purpose
!= CIRCUIT_PURPOSE_PATH_BIAS_TESTING
) {
801 log_warn(LD_BUG
, "circuit->purpose == CIRCUIT_PURPOSE_C_GENERAL failed. "
802 "The purpose on the circuit was %s; it was in state %s, "
804 circuit_purpose_to_string(circ
->purpose
),
805 circuit_state_to_string(circ
->state
),
806 CIRCUIT_IS_ORIGIN(circ
) ?
807 pathbias_state_to_string(TO_ORIGIN_CIRCUIT(circ
)->path_state
) :
810 log_fn(cutoff
< 15 ? LOG_INFO
: severity
, LD_APP
,
811 "We tried for %d seconds to connect to '%s' using exit %s."
812 " Retrying on a new circuit.",
814 safe_str_client(entry_conn
->socks_request
->address
),
816 extend_info_describe(conn
->cpath_layer
->extend_info
):
818 /* send an end down the circuit */
819 connection_edge_end(conn
, END_STREAM_REASON_TIMEOUT
);
820 /* un-mark it as ending, since we're going to reuse it */
821 conn
->edge_has_sent_end
= 0;
822 conn
->end_reason
= 0;
823 /* make us not try this circuit again, but allow
824 * current streams on it to survive if they can */
825 mark_circuit_unusable_for_new_conns(TO_ORIGIN_CIRCUIT(circ
));
827 /* give our stream another 'cutoff' seconds to try */
828 conn
->base_
.timestamp_lastread
+= cutoff
;
829 if (entry_conn
->num_socks_retries
< 250) /* avoid overflow */
830 entry_conn
->num_socks_retries
++;
831 /* move it back into 'pending' state, and try to attach. */
832 if (connection_ap_detach_retriable(entry_conn
, TO_ORIGIN_CIRCUIT(circ
),
833 END_STREAM_REASON_TIMEOUT
)<0) {
834 if (!base_conn
->marked_for_close
)
835 connection_mark_unattached_ap(entry_conn
,
836 END_STREAM_REASON_CANT_ATTACH
);
838 } SMARTLIST_FOREACH_END(base_conn
);
842 * As connection_ap_attach_pending, but first scans the entire connection
843 * array to see if any elements are missing.
846 connection_ap_rescan_and_attach_pending(void)
848 entry_connection_t
*entry_conn
;
849 smartlist_t
*conns
= get_connection_array();
851 if (PREDICT_UNLIKELY(NULL
== pending_entry_connections
))
852 pending_entry_connections
= smartlist_new();
854 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
) {
855 if (conn
->marked_for_close
||
856 conn
->type
!= CONN_TYPE_AP
||
857 conn
->state
!= AP_CONN_STATE_CIRCUIT_WAIT
)
860 entry_conn
= TO_ENTRY_CONN(conn
);
861 tor_assert(entry_conn
);
862 if (! smartlist_contains(pending_entry_connections
, entry_conn
)) {
863 log_warn(LD_BUG
, "Found a connection %p that was supposed to be "
864 "in pending_entry_connections, but wasn't. No worries; "
866 pending_entry_connections
);
867 untried_pending_connections
= 1;
868 connection_ap_mark_as_pending_circuit(entry_conn
);
871 } SMARTLIST_FOREACH_END(conn
);
873 connection_ap_attach_pending(1);
876 #ifdef DEBUGGING_17659
877 #define UNMARK() do { \
878 entry_conn->marked_pending_circ_line = 0; \
879 entry_conn->marked_pending_circ_file = 0; \
881 #else /* !(defined(DEBUGGING_17659)) */
882 #define UNMARK() do { } while (0)
883 #endif /* defined(DEBUGGING_17659) */
885 /** Tell any AP streams that are listed as waiting for a new circuit to try
886 * again. If there is an available circuit for a stream, attach it. Otherwise,
887 * launch a new circuit.
889 * If <b>retry</b> is false, only check the list if it contains at least one
890 * streams that we have not yet tried to attach to a circuit.
893 connection_ap_attach_pending(int retry
)
895 if (PREDICT_UNLIKELY(!pending_entry_connections
)) {
899 if (untried_pending_connections
== 0 && !retry
)
902 /* Don't allow any modifications to list while we are iterating over
903 * it. We'll put streams back on this list if we can't attach them
905 smartlist_t
*pending
= pending_entry_connections
;
906 pending_entry_connections
= smartlist_new();
908 SMARTLIST_FOREACH_BEGIN(pending
,
909 entry_connection_t
*, entry_conn
) {
910 connection_t
*conn
= ENTRY_TO_CONN(entry_conn
);
911 tor_assert(conn
&& entry_conn
);
912 if (conn
->marked_for_close
) {
916 if (conn
->magic
!= ENTRY_CONNECTION_MAGIC
) {
917 log_warn(LD_BUG
, "%p has impossible magic value %u.",
918 entry_conn
, (unsigned)conn
->magic
);
922 if (conn
->state
!= AP_CONN_STATE_CIRCUIT_WAIT
) {
923 log_warn(LD_BUG
, "%p is no longer in circuit_wait. Its current state "
924 "is %s. Why is it on pending_entry_connections?",
926 conn_state_to_string(conn
->type
, conn
->state
));
931 /* Okay, we're through the sanity checks. Try to handle this stream. */
932 if (connection_ap_handshake_attach_circuit(entry_conn
) < 0) {
933 if (!conn
->marked_for_close
)
934 connection_mark_unattached_ap(entry_conn
,
935 END_STREAM_REASON_CANT_ATTACH
);
938 if (! conn
->marked_for_close
&&
939 conn
->type
== CONN_TYPE_AP
&&
940 conn
->state
== AP_CONN_STATE_CIRCUIT_WAIT
) {
941 /* Is it still waiting for a circuit? If so, we didn't attach it,
942 * so it's still pending. Put it back on the list.
944 if (!smartlist_contains(pending_entry_connections
, entry_conn
)) {
945 smartlist_add(pending_entry_connections
, entry_conn
);
950 /* If we got here, then we either closed the connection, or
953 } SMARTLIST_FOREACH_END(entry_conn
);
955 smartlist_free(pending
);
956 untried_pending_connections
= 0;
959 /** Mark <b>entry_conn</b> as needing to get attached to a circuit.
961 * And <b>entry_conn</b> must be in AP_CONN_STATE_CIRCUIT_WAIT,
962 * should not already be pending a circuit. The circuit will get
963 * launched or the connection will get attached the next time we
964 * call connection_ap_attach_pending().
967 connection_ap_mark_as_pending_circuit_(entry_connection_t
*entry_conn
,
968 const char *fname
, int lineno
)
970 connection_t
*conn
= ENTRY_TO_CONN(entry_conn
);
971 tor_assert(conn
->state
== AP_CONN_STATE_CIRCUIT_WAIT
);
972 tor_assert(conn
->magic
== ENTRY_CONNECTION_MAGIC
);
973 if (conn
->marked_for_close
)
976 if (PREDICT_UNLIKELY(NULL
== pending_entry_connections
))
977 pending_entry_connections
= smartlist_new();
979 if (PREDICT_UNLIKELY(smartlist_contains(pending_entry_connections
,
981 log_warn(LD_BUG
, "What?? pending_entry_connections already contains %p! "
982 "(Called from %s:%d.)",
983 entry_conn
, fname
, lineno
);
984 #ifdef DEBUGGING_17659
985 const char *f2
= entry_conn
->marked_pending_circ_file
;
986 log_warn(LD_BUG
, "(Previously called from %s:%d.)\n",
988 entry_conn
->marked_pending_circ_line
);
989 #endif /* defined(DEBUGGING_17659) */
990 log_backtrace(LOG_WARN
, LD_BUG
, "To debug, this may help");
994 #ifdef DEBUGGING_17659
995 entry_conn
->marked_pending_circ_line
= (uint16_t) lineno
;
996 entry_conn
->marked_pending_circ_file
= fname
;
999 untried_pending_connections
= 1;
1000 smartlist_add(pending_entry_connections
, entry_conn
);
1002 /* Work-around for bug 19969: we handle pending_entry_connections at
1003 * the end of run_main_loop_once(), but in many cases that function will
1004 * take a very long time, if ever, to finish its call to event_base_loop().
1006 * So the fix is to tell it right now that it ought to finish its loop at
1007 * its next available opportunity.
1009 tell_event_loop_to_run_external_code();
1012 /** Mark <b>entry_conn</b> as no longer waiting for a circuit. */
1014 connection_ap_mark_as_non_pending_circuit(entry_connection_t
*entry_conn
)
1016 if (PREDICT_UNLIKELY(NULL
== pending_entry_connections
))
1019 smartlist_remove(pending_entry_connections
, entry_conn
);
1024 connection_ap_warn_and_unmark_if_pending_circ(entry_connection_t
*entry_conn
,
1027 if (pending_entry_connections
&&
1028 smartlist_contains(pending_entry_connections
, entry_conn
)) {
1029 log_warn(LD_BUG
, "What was %p doing in pending_entry_connections in %s?",
1031 connection_ap_mark_as_non_pending_circuit(entry_conn
);
1035 /** Tell any AP streams that are waiting for a one-hop tunnel to
1036 * <b>failed_digest</b> that they are going to fail. */
1037 /* XXXX We should get rid of this function, and instead attach
1038 * one-hop streams to circ->p_streams so they get marked in
1039 * circuit_mark_for_close like normal p_streams. */
1041 connection_ap_fail_onehop(const char *failed_digest
,
1042 cpath_build_state_t
*build_state
)
1044 entry_connection_t
*entry_conn
;
1045 char digest
[DIGEST_LEN
];
1046 smartlist_t
*conns
= get_connection_array();
1047 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
) {
1048 if (conn
->marked_for_close
||
1049 conn
->type
!= CONN_TYPE_AP
||
1050 conn
->state
!= AP_CONN_STATE_CIRCUIT_WAIT
)
1052 entry_conn
= TO_ENTRY_CONN(conn
);
1053 if (!entry_conn
->want_onehop
)
1055 if (hexdigest_to_digest(entry_conn
->chosen_exit_name
, digest
) < 0 ||
1056 tor_memneq(digest
, failed_digest
, DIGEST_LEN
))
1058 if (tor_digest_is_zero(digest
)) {
1059 /* we don't know the digest; have to compare addr:port */
1061 if (!build_state
|| !build_state
->chosen_exit
||
1062 !entry_conn
->socks_request
) {
1065 if (tor_addr_parse(&addr
, entry_conn
->socks_request
->address
)<0 ||
1066 !tor_addr_eq(&build_state
->chosen_exit
->addr
, &addr
) ||
1067 build_state
->chosen_exit
->port
!= entry_conn
->socks_request
->port
)
1070 log_info(LD_APP
, "Closing one-hop stream to '%s/%s' because the OR conn "
1071 "just failed.", entry_conn
->chosen_exit_name
,
1072 entry_conn
->socks_request
->address
);
1073 connection_mark_unattached_ap(entry_conn
, END_STREAM_REASON_TIMEOUT
);
1074 } SMARTLIST_FOREACH_END(conn
);
1077 /** A circuit failed to finish on its last hop <b>info</b>. If there
1078 * are any streams waiting with this exit node in mind, but they
1079 * don't absolutely require it, make them give up on it.
1082 circuit_discard_optional_exit_enclaves(extend_info_t
*info
)
1084 entry_connection_t
*entry_conn
;
1085 const node_t
*r1
, *r2
;
1087 smartlist_t
*conns
= get_connection_array();
1088 SMARTLIST_FOREACH_BEGIN(conns
, connection_t
*, conn
) {
1089 if (conn
->marked_for_close
||
1090 conn
->type
!= CONN_TYPE_AP
||
1091 conn
->state
!= AP_CONN_STATE_CIRCUIT_WAIT
)
1093 entry_conn
= TO_ENTRY_CONN(conn
);
1094 if (!entry_conn
->chosen_exit_optional
&&
1095 !entry_conn
->chosen_exit_retries
)
1097 r1
= node_get_by_nickname(entry_conn
->chosen_exit_name
,
1098 NNF_NO_WARN_UNNAMED
);
1099 r2
= node_get_by_id(info
->identity_digest
);
1100 if (!r1
|| !r2
|| r1
!= r2
)
1102 tor_assert(entry_conn
->socks_request
);
1103 if (entry_conn
->chosen_exit_optional
) {
1104 log_info(LD_APP
, "Giving up on enclave exit '%s' for destination %s.",
1105 safe_str_client(entry_conn
->chosen_exit_name
),
1106 escaped_safe_str_client(entry_conn
->socks_request
->address
));
1107 entry_conn
->chosen_exit_optional
= 0;
1108 tor_free(entry_conn
->chosen_exit_name
); /* clears it */
1109 /* if this port is dangerous, warn or reject it now that we don't
1110 * think it'll be using an enclave. */
1111 consider_plaintext_ports(entry_conn
, entry_conn
->socks_request
->port
);
1113 if (entry_conn
->chosen_exit_retries
) {
1114 if (--entry_conn
->chosen_exit_retries
== 0) { /* give up! */
1115 clear_trackexithost_mappings(entry_conn
->chosen_exit_name
);
1116 tor_free(entry_conn
->chosen_exit_name
); /* clears it */
1117 /* if this port is dangerous, warn or reject it now that we don't
1118 * think it'll be using an enclave. */
1119 consider_plaintext_ports(entry_conn
, entry_conn
->socks_request
->port
);
1122 } SMARTLIST_FOREACH_END(conn
);
1125 /** The AP connection <b>conn</b> has just failed while attaching or
1126 * sending a BEGIN or resolving on <b>circ</b>, but another circuit
1127 * might work. Detach the circuit, and either reattach it, launch a
1128 * new circuit, tell the controller, or give up as appropriate.
1130 * Returns -1 on err, 1 on success, 0 on not-yet-sure.
1133 connection_ap_detach_retriable(entry_connection_t
*conn
,
1134 origin_circuit_t
*circ
,
1137 control_event_stream_status(conn
, STREAM_EVENT_FAILED_RETRIABLE
, reason
);
1138 ENTRY_TO_CONN(conn
)->timestamp_lastread
= time(NULL
);
1140 /* Roll back path bias use state so that we probe the circuit
1141 * if nothing else succeeds on it */
1142 pathbias_mark_use_rollback(circ
);
1144 if (conn
->pending_optimistic_data
) {
1145 buf_set_to_copy(&conn
->sending_optimistic_data
,
1146 conn
->pending_optimistic_data
);
1149 if (!get_options()->LeaveStreamsUnattached
|| conn
->use_begindir
) {
1150 /* If we're attaching streams ourself, or if this connection is
1151 * a tunneled directory connection, then just attach it. */
1152 ENTRY_TO_CONN(conn
)->state
= AP_CONN_STATE_CIRCUIT_WAIT
;
1153 circuit_detach_stream(TO_CIRCUIT(circ
),ENTRY_TO_EDGE_CONN(conn
));
1154 connection_ap_mark_as_pending_circuit(conn
);
1156 CONNECTION_AP_EXPECT_NONPENDING(conn
);
1157 ENTRY_TO_CONN(conn
)->state
= AP_CONN_STATE_CONTROLLER_WAIT
;
1158 circuit_detach_stream(TO_CIRCUIT(circ
),ENTRY_TO_EDGE_CONN(conn
));
1163 /** Check if <b>conn</b> is using a dangerous port. Then warn and/or
1164 * reject depending on our config options. */
1166 consider_plaintext_ports(entry_connection_t
*conn
, uint16_t port
)
1168 const or_options_t
*options
= get_options();
1169 int reject
= smartlist_contains_int_as_string(
1170 options
->RejectPlaintextPorts
, port
);
1172 if (smartlist_contains_int_as_string(options
->WarnPlaintextPorts
, port
)) {
1173 log_warn(LD_APP
, "Application request to port %d: this port is "
1174 "commonly used for unencrypted protocols. Please make sure "
1175 "you don't send anything you would mind the rest of the "
1176 "Internet reading!%s", port
, reject
? " Closing." : "");
1177 control_event_client_status(LOG_WARN
, "DANGEROUS_PORT PORT=%d RESULT=%s",
1178 port
, reject
? "REJECT" : "WARN");
1182 log_info(LD_APP
, "Port %d listed in RejectPlaintextPorts. Closing.", port
);
1183 connection_mark_unattached_ap(conn
, END_STREAM_REASON_ENTRYPOLICY
);
1190 /** How many times do we try connecting with an exit configured via
1191 * TrackHostExits before concluding that it won't work any more and trying a
1193 #define TRACKHOSTEXITS_RETRIES 5
1195 /** Call connection_ap_handshake_rewrite_and_attach() unless a controller
1196 * asked us to leave streams unattached. Return 0 in that case.
1198 * See connection_ap_handshake_rewrite_and_attach()'s
1199 * documentation for arguments and return value.
1202 connection_ap_rewrite_and_attach_if_allowed
,(entry_connection_t
*conn
,
1203 origin_circuit_t
*circ
,
1204 crypt_path_t
*cpath
))
1206 const or_options_t
*options
= get_options();
1208 if (options
->LeaveStreamsUnattached
) {
1209 CONNECTION_AP_EXPECT_NONPENDING(conn
);
1210 ENTRY_TO_CONN(conn
)->state
= AP_CONN_STATE_CONTROLLER_WAIT
;
1213 return connection_ap_handshake_rewrite_and_attach(conn
, circ
, cpath
);
1216 /* Try to perform any map-based rewriting of the target address in
1217 * <b>conn</b>, filling in the fields of <b>out</b> as we go, and modifying
1218 * conn->socks_request.address as appropriate.
1221 connection_ap_handshake_rewrite(entry_connection_t
*conn
,
1222 rewrite_result_t
*out
)
1224 socks_request_t
*socks
= conn
->socks_request
;
1225 const or_options_t
*options
= get_options();
1226 tor_addr_t addr_tmp
;
1228 /* Initialize all the fields of 'out' to reasonable defaults */
1230 out
->exit_source
= ADDRMAPSRC_NONE
;
1231 out
->map_expires
= TIME_MAX
;
1232 out
->end_reason
= 0;
1233 out
->should_close
= 0;
1234 out
->orig_address
[0] = 0;
1236 /* We convert all incoming addresses to lowercase. */
1237 tor_strlower(socks
->address
);
1238 /* Remember the original address. */
1239 strlcpy(out
->orig_address
, socks
->address
, sizeof(out
->orig_address
));
1240 log_debug(LD_APP
,"Client asked for %s:%d",
1241 safe_str_client(socks
->address
),
1244 /* Check for whether this is a .exit address. By default, those are
1245 * disallowed when they're coming straight from the client, but you're
1246 * allowed to have them in MapAddress commands and so forth. */
1247 if (!strcmpend(socks
->address
, ".exit")) {
1248 log_warn(LD_APP
, "The \".exit\" notation is disabled in Tor due to "
1250 control_event_client_status(LOG_WARN
, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1251 escaped(socks
->address
));
1252 out
->end_reason
= END_STREAM_REASON_TORPROTOCOL
;
1253 out
->should_close
= 1;
1257 /* Remember the original address so we can tell the user about what
1258 * they actually said, not just what it turned into. */
1259 /* XXX yes, this is the same as out->orig_address above. One is
1260 * in the output, and one is in the connection. */
1261 if (! conn
->original_dest_address
) {
1262 /* Is the 'if' necessary here? XXXX */
1263 conn
->original_dest_address
= tor_strdup(conn
->socks_request
->address
);
1266 /* First, apply MapAddress and MAPADDRESS mappings. We need to do
1267 * these only for non-reverse lookups, since they don't exist for those.
1268 * We also need to do this before we consider automapping, since we might
1269 * e.g. resolve irc.oftc.net into irconionaddress.onion, at which point
1270 * we'd need to automap it. */
1271 if (socks
->command
!= SOCKS_COMMAND_RESOLVE_PTR
) {
1272 const unsigned rewrite_flags
= AMR_FLAG_USE_MAPADDRESS
;
1273 if (addressmap_rewrite(socks
->address
, sizeof(socks
->address
),
1274 rewrite_flags
, &out
->map_expires
, &out
->exit_source
)) {
1275 control_event_stream_status(conn
, STREAM_EVENT_REMAP
,
1276 REMAP_STREAM_SOURCE_CACHE
);
1280 /* Now see if we need to create or return an existing Hostname->IP
1281 * automapping. Automapping happens when we're asked to resolve a
1282 * hostname, and AutomapHostsOnResolve is set, and the hostname has a
1283 * suffix listed in AutomapHostsSuffixes. It's a handy feature
1284 * that lets you have Tor assign e.g. IPv6 addresses for .onion
1285 * names, and return them safely from DNSPort.
1287 if (socks
->command
== SOCKS_COMMAND_RESOLVE
&&
1288 tor_addr_parse(&addr_tmp
, socks
->address
)<0 &&
1289 options
->AutomapHostsOnResolve
) {
1290 /* Check the suffix... */
1291 out
->automap
= addressmap_address_should_automap(socks
->address
, options
);
1293 /* If we get here, then we should apply an automapping for this. */
1294 const char *new_addr
;
1295 /* We return an IPv4 address by default, or an IPv6 address if we
1296 * are allowed to do so. */
1297 int addr_type
= RESOLVED_TYPE_IPV4
;
1298 if (conn
->socks_request
->socks_version
!= 4) {
1299 if (!conn
->entry_cfg
.ipv4_traffic
||
1300 (conn
->entry_cfg
.ipv6_traffic
&& conn
->entry_cfg
.prefer_ipv6
) ||
1301 conn
->entry_cfg
.prefer_ipv6_virtaddr
)
1302 addr_type
= RESOLVED_TYPE_IPV6
;
1304 /* Okay, register the target address as automapped, and find the new
1305 * address we're supposed to give as a resolve answer. (Return a cached
1306 * value if we've looked up this address before.
1308 new_addr
= addressmap_register_virtual_address(
1309 addr_type
, tor_strdup(socks
->address
));
1311 log_warn(LD_APP
, "Unable to automap address %s",
1312 escaped_safe_str(socks
->address
));
1313 out
->end_reason
= END_STREAM_REASON_INTERNAL
;
1314 out
->should_close
= 1;
1317 log_info(LD_APP
, "Automapping %s to %s",
1318 escaped_safe_str_client(socks
->address
),
1319 safe_str_client(new_addr
));
1320 strlcpy(socks
->address
, new_addr
, sizeof(socks
->address
));
1324 /* Now handle reverse lookups, if they're in the cache. This doesn't
1325 * happen too often, since client-side DNS caching is off by default,
1326 * and very deprecated. */
1327 if (socks
->command
== SOCKS_COMMAND_RESOLVE_PTR
) {
1328 unsigned rewrite_flags
= 0;
1329 if (conn
->entry_cfg
.use_cached_ipv4_answers
)
1330 rewrite_flags
|= AMR_FLAG_USE_IPV4_DNS
;
1331 if (conn
->entry_cfg
.use_cached_ipv6_answers
)
1332 rewrite_flags
|= AMR_FLAG_USE_IPV6_DNS
;
1334 if (addressmap_rewrite_reverse(socks
->address
, sizeof(socks
->address
),
1335 rewrite_flags
, &out
->map_expires
)) {
1336 char *result
= tor_strdup(socks
->address
);
1337 /* remember _what_ is supposed to have been resolved. */
1338 tor_snprintf(socks
->address
, sizeof(socks
->address
), "REVERSE[%s]",
1340 connection_ap_handshake_socks_resolved(conn
, RESOLVED_TYPE_HOSTNAME
,
1341 strlen(result
), (uint8_t*)result
,
1345 out
->end_reason
= END_STREAM_REASON_DONE
|
1346 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
;
1347 out
->should_close
= 1;
1351 /* Hang on, did we find an answer saying that this is a reverse lookup for
1352 * an internal address? If so, we should reject it if we're configured to
1354 if (options
->ClientDNSRejectInternalAddresses
) {
1355 /* Don't let clients try to do a reverse lookup on 10.0.0.1. */
1358 ok
= tor_addr_parse_PTR_name(
1359 &addr
, socks
->address
, AF_UNSPEC
, 1);
1360 if (ok
== 1 && tor_addr_is_internal(&addr
, 0)) {
1361 connection_ap_handshake_socks_resolved(conn
, RESOLVED_TYPE_ERROR
,
1362 0, NULL
, -1, TIME_MAX
);
1363 out
->end_reason
= END_STREAM_REASON_SOCKSPROTOCOL
|
1364 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
;
1365 out
->should_close
= 1;
1371 /* If we didn't automap it before, then this is still the address that
1372 * came straight from the user, mapped according to any
1373 * MapAddress/MAPADDRESS commands. Now apply other mappings,
1374 * including previously registered Automap entries (IP back to
1375 * hostname), TrackHostExits entries, and client-side DNS cache
1376 * entries (if they're turned on).
1378 if (socks
->command
!= SOCKS_COMMAND_RESOLVE_PTR
&&
1380 unsigned rewrite_flags
= AMR_FLAG_USE_AUTOMAP
| AMR_FLAG_USE_TRACKEXIT
;
1381 addressmap_entry_source_t exit_source2
;
1382 if (conn
->entry_cfg
.use_cached_ipv4_answers
)
1383 rewrite_flags
|= AMR_FLAG_USE_IPV4_DNS
;
1384 if (conn
->entry_cfg
.use_cached_ipv6_answers
)
1385 rewrite_flags
|= AMR_FLAG_USE_IPV6_DNS
;
1386 if (addressmap_rewrite(socks
->address
, sizeof(socks
->address
),
1387 rewrite_flags
, &out
->map_expires
, &exit_source2
)) {
1388 control_event_stream_status(conn
, STREAM_EVENT_REMAP
,
1389 REMAP_STREAM_SOURCE_CACHE
);
1391 if (out
->exit_source
== ADDRMAPSRC_NONE
) {
1392 /* If it wasn't a .exit before, maybe it turned into a .exit. Remember
1393 * the original source of a .exit. */
1394 out
->exit_source
= exit_source2
;
1398 /* Check to see whether we're about to use an address in the virtual
1399 * range without actually having gotten it from an Automap. */
1400 if (!out
->automap
&& address_is_in_virtual_range(socks
->address
)) {
1401 /* This address was probably handed out by
1402 * client_dns_get_unmapped_address, but the mapping was discarded for some
1403 * reason. Or the user typed in a virtual address range manually. We
1404 * *don't* want to send the address through Tor; that's likely to fail,
1405 * and may leak information.
1407 log_warn(LD_APP
,"Missing mapping for virtual address '%s'. Refusing.",
1408 safe_str_client(socks
->address
));
1409 out
->end_reason
= END_STREAM_REASON_INTERNAL
;
1410 out
->should_close
= 1;
1415 /** We just received a SOCKS request in <b>conn</b> to an onion address of type
1416 * <b>addresstype</b>. Start connecting to the onion service. */
1418 connection_ap_handle_onion(entry_connection_t
*conn
,
1419 socks_request_t
*socks
,
1420 origin_circuit_t
*circ
,
1421 hostname_type_t addresstype
)
1423 time_t now
= approx_time();
1424 connection_t
*base_conn
= ENTRY_TO_CONN(conn
);
1426 /* If .onion address requests are disabled, refuse the request */
1427 if (!conn
->entry_cfg
.onion_traffic
) {
1428 log_warn(LD_APP
, "Onion address %s requested from a port with .onion "
1429 "disabled", safe_str_client(socks
->address
));
1430 connection_mark_unattached_ap(conn
, END_STREAM_REASON_ENTRYPOLICY
);
1434 /* Check whether it's RESOLVE or RESOLVE_PTR. We don't handle those
1435 * for hidden service addresses. */
1436 if (SOCKS_COMMAND_IS_RESOLVE(socks
->command
)) {
1437 /* if it's a resolve request, fail it right now, rather than
1438 * building all the circuits and then realizing it won't work. */
1440 "Resolve requests to hidden services not allowed. Failing.");
1441 connection_ap_handshake_socks_resolved(conn
,RESOLVED_TYPE_ERROR
,
1442 0,NULL
,-1,TIME_MAX
);
1443 connection_mark_unattached_ap(conn
,
1444 END_STREAM_REASON_SOCKSPROTOCOL
|
1445 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
);
1449 /* If we were passed a circuit, then we need to fail. .onion addresses
1450 * only work when we launch our own circuits for now. */
1452 log_warn(LD_CONTROL
, "Attachstream to a circuit is not "
1453 "supported for .onion addresses currently. Failing.");
1454 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1458 /* Interface: Regardless of HS version after the block below we should have
1459 set onion_address, rend_cache_lookup_result, and descriptor_is_usable. */
1460 const char *onion_address
= NULL
;
1461 int rend_cache_lookup_result
= -ENOENT
;
1462 int descriptor_is_usable
= 0;
1464 if (addresstype
== ONION_V2_HOSTNAME
) { /* it's a v2 hidden service */
1465 rend_cache_entry_t
*entry
= NULL
;
1466 /* Look up if we have client authorization configured for this hidden
1467 * service. If we do, associate it with the rend_data. */
1468 rend_service_authorization_t
*client_auth
=
1469 rend_client_lookup_service_authorization(socks
->address
);
1471 const uint8_t *cookie
= NULL
;
1472 rend_auth_type_t auth_type
= REND_NO_AUTH
;
1474 log_info(LD_REND
, "Using previously configured client authorization "
1475 "for hidden service request.");
1476 auth_type
= client_auth
->auth_type
;
1477 cookie
= client_auth
->descriptor_cookie
;
1480 /* Fill in the rend_data field so we can start doing a connection to
1481 * a hidden service. */
1482 rend_data_t
*rend_data
= ENTRY_TO_EDGE_CONN(conn
)->rend_data
=
1483 rend_data_client_create(socks
->address
, NULL
, (char *) cookie
,
1485 if (rend_data
== NULL
) {
1488 onion_address
= rend_data_get_address(rend_data
);
1489 log_info(LD_REND
,"Got a hidden service request for ID '%s'",
1490 safe_str_client(onion_address
));
1492 rend_cache_lookup_result
= rend_cache_lookup_entry(onion_address
,-1,
1494 if (!rend_cache_lookup_result
&& entry
) {
1495 descriptor_is_usable
= rend_client_any_intro_points_usable(entry
);
1497 } else { /* it's a v3 hidden service */
1498 tor_assert(addresstype
== ONION_V3_HOSTNAME
);
1499 const hs_descriptor_t
*cached_desc
= NULL
;
1501 /* Create HS conn identifier with HS pubkey */
1502 hs_ident_edge_conn_t
*hs_conn_ident
=
1503 tor_malloc_zero(sizeof(hs_ident_edge_conn_t
));
1505 retval
= hs_parse_address(socks
->address
, &hs_conn_ident
->identity_pk
,
1508 log_warn(LD_GENERAL
, "failed to parse hs address");
1509 tor_free(hs_conn_ident
);
1512 ENTRY_TO_EDGE_CONN(conn
)->hs_ident
= hs_conn_ident
;
1514 onion_address
= socks
->address
;
1516 /* Check the v3 desc cache */
1517 cached_desc
= hs_cache_lookup_as_client(&hs_conn_ident
->identity_pk
);
1519 rend_cache_lookup_result
= 0;
1520 descriptor_is_usable
=
1521 hs_client_any_intro_points_usable(&hs_conn_ident
->identity_pk
,
1523 log_info(LD_GENERAL
, "Found %s descriptor in cache for %s. %s.",
1524 (descriptor_is_usable
) ? "usable" : "unusable",
1525 safe_str_client(onion_address
),
1526 (descriptor_is_usable
) ? "Not fetching." : "Refecting.");
1528 rend_cache_lookup_result
= -ENOENT
;
1532 /* Lookup the given onion address. If invalid, stop right now.
1533 * Otherwise, we might have it in the cache or not. */
1534 unsigned int refetch_desc
= 0;
1535 if (rend_cache_lookup_result
< 0) {
1536 switch (-rend_cache_lookup_result
) {
1538 /* We should already have rejected this address! */
1539 log_warn(LD_BUG
,"Invalid service name '%s'",
1540 safe_str_client(onion_address
));
1541 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1544 /* We didn't have this; we should look it up. */
1545 log_info(LD_REND
, "No descriptor found in our cache for %s. Fetching.",
1546 safe_str_client(onion_address
));
1550 log_warn(LD_BUG
, "Unknown cache lookup error %d",
1551 rend_cache_lookup_result
);
1556 /* Help predict that we'll want to do hidden service circuits in the
1557 * future. We're not sure if it will need a stable circuit yet, but
1558 * we know we'll need *something*. */
1559 rep_hist_note_used_internal(now
, 0, 1);
1561 /* Now we have a descriptor but is it usable or not? If not, refetch.
1562 * Also, a fetch could have been requested if the onion address was not
1563 * found in the cache previously. */
1564 if (refetch_desc
|| !descriptor_is_usable
) {
1565 edge_connection_t
*edge_conn
= ENTRY_TO_EDGE_CONN(conn
);
1566 connection_ap_mark_as_non_pending_circuit(conn
);
1567 base_conn
->state
= AP_CONN_STATE_RENDDESC_WAIT
;
1568 if (addresstype
== ONION_V2_HOSTNAME
) {
1569 tor_assert(edge_conn
->rend_data
);
1570 rend_client_refetch_v2_renddesc(edge_conn
->rend_data
);
1571 /* Whatever the result of the refetch, we don't go further. */
1574 tor_assert(addresstype
== ONION_V3_HOSTNAME
);
1575 tor_assert(edge_conn
->hs_ident
);
1576 /* Attempt to fetch the hsv3 descriptor. Check the retval to see how it
1577 * went and act accordingly. */
1578 int ret
= hs_client_refetch_hsdesc(&edge_conn
->hs_ident
->identity_pk
);
1580 case HS_CLIENT_FETCH_MISSING_INFO
:
1581 /* Keeping the connection in descriptor wait state is fine because
1582 * once we get enough dirinfo or a new live consensus, the HS client
1583 * subsystem is notified and every connection in that state will
1584 * trigger a fetch for the service key. */
1585 case HS_CLIENT_FETCH_LAUNCHED
:
1586 case HS_CLIENT_FETCH_PENDING
:
1587 case HS_CLIENT_FETCH_HAVE_DESC
:
1589 case HS_CLIENT_FETCH_ERROR
:
1590 case HS_CLIENT_FETCH_NO_HSDIRS
:
1591 case HS_CLIENT_FETCH_NOT_ALLOWED
:
1592 /* Can't proceed further and better close the SOCKS request. */
1598 /* We have the descriptor! So launch a connection to the HS. */
1599 log_info(LD_REND
, "Descriptor is here. Great.");
1601 base_conn
->state
= AP_CONN_STATE_CIRCUIT_WAIT
;
1602 /* We'll try to attach it at the next event loop, or whenever
1603 * we call connection_ap_attach_pending() */
1604 connection_ap_mark_as_pending_circuit(conn
);
1608 /** Connection <b>conn</b> just finished its socks handshake, or the
1609 * controller asked us to take care of it. If <b>circ</b> is defined,
1610 * then that's where we'll want to attach it. Otherwise we have to
1611 * figure it out ourselves.
1613 * First, parse whether it's a .exit address, remap it, and so on. Then
1614 * if it's for a general circuit, try to attach it to a circuit (or launch
1615 * one as needed), else if it's for a rendezvous circuit, fetch a
1616 * rendezvous descriptor first (or attach/launch a circuit if the
1617 * rendezvous descriptor is already here and fresh enough).
1619 * The stream will exit from the hop
1620 * indicated by <b>cpath</b>, or from the last hop in circ's cpath if
1621 * <b>cpath</b> is NULL.
1624 connection_ap_handshake_rewrite_and_attach(entry_connection_t
*conn
,
1625 origin_circuit_t
*circ
,
1626 crypt_path_t
*cpath
)
1628 socks_request_t
*socks
= conn
->socks_request
;
1629 const or_options_t
*options
= get_options();
1630 connection_t
*base_conn
= ENTRY_TO_CONN(conn
);
1631 time_t now
= time(NULL
);
1632 rewrite_result_t rr
;
1634 /* First we'll do the rewrite part. Let's see if we get a reasonable
1637 memset(&rr
, 0, sizeof(rr
));
1638 connection_ap_handshake_rewrite(conn
,&rr
);
1640 if (rr
.should_close
) {
1641 /* connection_ap_handshake_rewrite told us to close the connection:
1642 * either because it sent back an answer, or because it sent back an
1644 connection_mark_unattached_ap(conn
, rr
.end_reason
);
1645 if (END_STREAM_REASON_DONE
== (rr
.end_reason
& END_STREAM_REASON_MASK
))
1651 const time_t map_expires
= rr
.map_expires
;
1652 const int automap
= rr
.automap
;
1653 const addressmap_entry_source_t exit_source
= rr
.exit_source
;
1655 /* Now, we parse the address to see if it's an .onion or .exit or
1656 * other special address.
1658 const hostname_type_t addresstype
= parse_extended_hostname(socks
->address
);
1660 /* Now see whether the hostname is bogus. This could happen because of an
1661 * onion hostname whose format we don't recognize. */
1662 if (addresstype
== BAD_HOSTNAME
) {
1663 control_event_client_status(LOG_WARN
, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1664 escaped(socks
->address
));
1665 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1669 /* If this is a .exit hostname, strip off the .name.exit part, and
1670 * see whether we're willing to connect there, and and otherwise handle the
1673 * We'll set chosen_exit_name and/or close the connection as appropriate.
1675 if (addresstype
== EXIT_HOSTNAME
) {
1676 /* If StrictNodes is not set, then .exit overrides ExcludeNodes but
1677 * not ExcludeExitNodes. */
1678 routerset_t
*excludeset
= options
->StrictNodes
?
1679 options
->ExcludeExitNodesUnion_
: options
->ExcludeExitNodes
;
1680 const node_t
*node
= NULL
;
1682 /* If this .exit was added by an AUTOMAP, then it came straight from
1683 * a user. That's not safe. */
1684 if (exit_source
== ADDRMAPSRC_AUTOMAP
) {
1685 /* Whoops; this one is stale. It must have gotten added earlier?
1686 * (Probably this is not possible, since AllowDotExit no longer
1688 log_warn(LD_APP
,"Stale automapped address for '%s.exit'. Refusing.",
1689 safe_str_client(socks
->address
));
1690 control_event_client_status(LOG_WARN
, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1691 escaped(socks
->address
));
1692 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1693 tor_assert_nonfatal_unreached();
1697 /* Double-check to make sure there are no .exits coming from
1698 * impossible/weird sources. */
1699 if (exit_source
== ADDRMAPSRC_DNS
|| exit_source
== ADDRMAPSRC_NONE
) {
1700 /* It shouldn't be possible to get a .exit address from any of these
1702 log_warn(LD_BUG
,"Address '%s.exit', with impossible source for the "
1703 ".exit part. Refusing.",
1704 safe_str_client(socks
->address
));
1705 control_event_client_status(LOG_WARN
, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1706 escaped(socks
->address
));
1707 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1711 tor_assert(!automap
);
1713 /* Now, find the character before the .(name) part.
1714 * (The ".exit" part got stripped off by "parse_extended_hostname").
1716 * We're going to put the exit name into conn->chosen_exit_name, and
1717 * look up a node correspondingly. */
1718 char *s
= strrchr(socks
->address
,'.');
1720 /* The address was of the form "(stuff).(name).exit */
1722 /* Looks like a real .exit one. */
1723 conn
->chosen_exit_name
= tor_strdup(s
+1);
1724 node
= node_get_by_nickname(conn
->chosen_exit_name
, 0);
1726 if (exit_source
== ADDRMAPSRC_TRACKEXIT
) {
1727 /* We 5 tries before it expires the addressmap */
1728 conn
->chosen_exit_retries
= TRACKHOSTEXITS_RETRIES
;
1732 /* Oops, the address was (stuff)..exit. That's not okay. */
1733 log_warn(LD_APP
,"Malformed exit address '%s.exit'. Refusing.",
1734 safe_str_client(socks
->address
));
1735 control_event_client_status(LOG_WARN
, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1736 escaped(socks
->address
));
1737 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1741 /* It looks like they just asked for "foo.exit". That's a special
1742 * form that means (foo's address).foo.exit. */
1744 conn
->chosen_exit_name
= tor_strdup(socks
->address
);
1745 node
= node_get_by_nickname(conn
->chosen_exit_name
, 0);
1747 *socks
->address
= 0;
1748 node_get_address_string(node
, socks
->address
, sizeof(socks
->address
));
1752 /* Now make sure that the chosen exit exists... */
1755 "Unrecognized relay in exit address '%s.exit'. Refusing.",
1756 safe_str_client(socks
->address
));
1757 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1760 /* ...and make sure that it isn't excluded. */
1761 if (routerset_contains_node(excludeset
, node
)) {
1763 "Excluded relay in exit address '%s.exit'. Refusing.",
1764 safe_str_client(socks
->address
));
1765 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1768 /* XXXX-1090 Should we also allow foo.bar.exit if ExitNodes is set and
1769 Bar is not listed in it? I say yes, but our revised manpage branch
1773 /* Now, we handle everything that isn't a .onion address. */
1774 if (addresstype
!= ONION_V2_HOSTNAME
&& addresstype
!= ONION_V3_HOSTNAME
) {
1775 /* Not a hidden-service request. It's either a hostname or an IP,
1776 * possibly with a .exit that we stripped off. We're going to check
1777 * if we're allowed to connect/resolve there, and then launch the
1778 * appropriate request. */
1780 /* Check for funny characters in the address. */
1781 if (address_is_invalid_destination(socks
->address
, 1)) {
1782 control_event_client_status(LOG_WARN
, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1783 escaped(socks
->address
));
1785 "Destination '%s' seems to be an invalid hostname. Failing.",
1786 safe_str_client(socks
->address
));
1787 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1791 #ifdef ENABLE_TOR2WEB_MODE
1792 /* If we're running in Tor2webMode, we don't allow anything BUT .onion
1794 if (options
->Tor2webMode
) {
1795 log_warn(LD_APP
, "Refusing to connect to non-hidden-service hostname "
1796 "or IP address %s because tor2web mode is enabled.",
1797 safe_str_client(socks
->address
));
1798 connection_mark_unattached_ap(conn
, END_STREAM_REASON_ENTRYPOLICY
);
1801 #endif /* defined(ENABLE_TOR2WEB_MODE) */
1803 /* socks->address is a non-onion hostname or IP address.
1804 * If we can't do any non-onion requests, refuse the connection.
1805 * If we have a hostname but can't do DNS, refuse the connection.
1806 * If we have an IP address, but we can't use that address family,
1807 * refuse the connection.
1809 * If we can do DNS requests, and we can use at least one address family,
1810 * then we have to resolve the address first. Then we'll know if it
1811 * resolves to a usable address family. */
1813 /* First, check if all non-onion traffic is disabled */
1814 if (!conn
->entry_cfg
.dns_request
&& !conn
->entry_cfg
.ipv4_traffic
1815 && !conn
->entry_cfg
.ipv6_traffic
) {
1816 log_warn(LD_APP
, "Refusing to connect to non-hidden-service hostname "
1817 "or IP address %s because Port has OnionTrafficOnly set (or "
1818 "NoDNSRequest, NoIPv4Traffic, and NoIPv6Traffic).",
1819 safe_str_client(socks
->address
));
1820 connection_mark_unattached_ap(conn
, END_STREAM_REASON_ENTRYPOLICY
);
1824 /* Then check if we have a hostname or IP address, and whether DNS or
1825 * the IP address family are permitted. Reject if not. */
1826 tor_addr_t dummy_addr
;
1827 int socks_family
= tor_addr_parse(&dummy_addr
, socks
->address
);
1828 /* family will be -1 for a non-onion hostname that's not an IP */
1829 if (socks_family
== -1) {
1830 if (!conn
->entry_cfg
.dns_request
) {
1831 log_warn(LD_APP
, "Refusing to connect to hostname %s "
1832 "because Port has NoDNSRequest set.",
1833 safe_str_client(socks
->address
));
1834 connection_mark_unattached_ap(conn
, END_STREAM_REASON_ENTRYPOLICY
);
1837 } else if (socks_family
== AF_INET
) {
1838 if (!conn
->entry_cfg
.ipv4_traffic
) {
1839 log_warn(LD_APP
, "Refusing to connect to IPv4 address %s because "
1840 "Port has NoIPv4Traffic set.",
1841 safe_str_client(socks
->address
));
1842 connection_mark_unattached_ap(conn
, END_STREAM_REASON_ENTRYPOLICY
);
1845 } else if (socks_family
== AF_INET6
) {
1846 if (!conn
->entry_cfg
.ipv6_traffic
) {
1847 log_warn(LD_APP
, "Refusing to connect to IPv6 address %s because "
1848 "Port has NoIPv6Traffic set.",
1849 safe_str_client(socks
->address
));
1850 connection_mark_unattached_ap(conn
, END_STREAM_REASON_ENTRYPOLICY
);
1854 tor_assert_nonfatal_unreached_once();
1857 /* See if this is a hostname lookup that we can answer immediately.
1858 * (For example, an attempt to look up the IP address for an IP address.)
1860 if (socks
->command
== SOCKS_COMMAND_RESOLVE
) {
1862 /* Reply to resolves immediately if we can. */
1863 if (tor_addr_parse(&answer
, socks
->address
) >= 0) {/* is it an IP? */
1864 /* remember _what_ is supposed to have been resolved. */
1865 strlcpy(socks
->address
, rr
.orig_address
, sizeof(socks
->address
));
1866 connection_ap_handshake_socks_resolved_addr(conn
, &answer
, -1,
1868 connection_mark_unattached_ap(conn
,
1869 END_STREAM_REASON_DONE
|
1870 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
);
1873 tor_assert(!automap
);
1874 rep_hist_note_used_resolve(now
); /* help predict this next time */
1875 } else if (socks
->command
== SOCKS_COMMAND_CONNECT
) {
1876 /* Now see if this is a connect request that we can reject immediately */
1878 tor_assert(!automap
);
1879 /* Don't allow connections to port 0. */
1880 if (socks
->port
== 0) {
1881 log_notice(LD_APP
,"Application asked to connect to port 0. Refusing.");
1882 connection_mark_unattached_ap(conn
, END_STREAM_REASON_TORPROTOCOL
);
1885 /* You can't make connections to internal addresses, by default.
1886 * Exceptions are begindir requests (where the address is meaningless),
1887 * or cases where you've hand-configured a particular exit, thereby
1888 * making the local address meaningful. */
1889 if (options
->ClientRejectInternalAddresses
&&
1890 !conn
->use_begindir
&& !conn
->chosen_exit_name
&& !circ
) {
1891 /* If we reach this point then we don't want to allow internal
1892 * addresses. Check if we got one. */
1894 if (tor_addr_hostname_is_local(socks
->address
) ||
1895 (tor_addr_parse(&addr
, socks
->address
) >= 0 &&
1896 tor_addr_is_internal(&addr
, 0))) {
1897 /* If this is an explicit private address with no chosen exit node,
1898 * then we really don't want to try to connect to it. That's
1899 * probably an error. */
1900 if (conn
->is_transparent_ap
) {
1901 #define WARN_INTRVL_LOOP 300
1902 static ratelim_t loop_warn_limit
= RATELIM_INIT(WARN_INTRVL_LOOP
);
1904 if ((m
= rate_limit_log(&loop_warn_limit
, approx_time()))) {
1906 "Rejecting request for anonymous connection to private "
1907 "address %s on a TransPort or NATDPort. Possible loop "
1908 "in your NAT rules?%s", safe_str_client(socks
->address
),
1913 #define WARN_INTRVL_PRIV 300
1914 static ratelim_t priv_warn_limit
= RATELIM_INIT(WARN_INTRVL_PRIV
);
1916 if ((m
= rate_limit_log(&priv_warn_limit
, approx_time()))) {
1918 "Rejecting SOCKS request for anonymous connection to "
1919 "private address %s.%s",
1920 safe_str_client(socks
->address
),m
);
1924 connection_mark_unattached_ap(conn
, END_STREAM_REASON_PRIVATE_ADDR
);
1927 } /* end "if we should check for internal addresses" */
1929 /* Okay. We're still doing a CONNECT, and it wasn't a private
1930 * address. Here we do special handling for literal IP addresses,
1931 * to see if we should reject this preemptively, and to set up
1932 * fields in conn->entry_cfg to tell the exit what AF we want. */
1935 /* XXX Duplicate call to tor_addr_parse. */
1936 if (tor_addr_parse(&addr
, socks
->address
) >= 0) {
1937 /* If we reach this point, it's an IPv4 or an IPv6 address. */
1938 sa_family_t family
= tor_addr_family(&addr
);
1940 if ((family
== AF_INET
&& ! conn
->entry_cfg
.ipv4_traffic
) ||
1941 (family
== AF_INET6
&& ! conn
->entry_cfg
.ipv6_traffic
)) {
1942 /* You can't do an IPv4 address on a v6-only socks listener,
1944 log_warn(LD_NET
, "Rejecting SOCKS request for an IP address "
1945 "family that this listener does not support.");
1946 connection_mark_unattached_ap(conn
, END_STREAM_REASON_ENTRYPOLICY
);
1948 } else if (family
== AF_INET6
&& socks
->socks_version
== 4) {
1949 /* You can't make a socks4 request to an IPv6 address. Socks4
1950 * doesn't support that. */
1951 log_warn(LD_NET
, "Rejecting SOCKS4 request for an IPv6 address.");
1952 connection_mark_unattached_ap(conn
, END_STREAM_REASON_ENTRYPOLICY
);
1954 } else if (socks
->socks_version
== 4 &&
1955 !conn
->entry_cfg
.ipv4_traffic
) {
1956 /* You can't do any kind of Socks4 request when IPv4 is forbidden.
1958 * XXX raise this check outside the enclosing block? */
1959 log_warn(LD_NET
, "Rejecting SOCKS4 request on a listener with "
1960 "no IPv4 traffic supported.");
1961 connection_mark_unattached_ap(conn
, END_STREAM_REASON_ENTRYPOLICY
);
1963 } else if (family
== AF_INET6
) {
1964 /* Tell the exit: we won't accept any ipv4 connection to an IPv6
1966 conn
->entry_cfg
.ipv4_traffic
= 0;
1967 } else if (family
== AF_INET
) {
1968 /* Tell the exit: we won't accept any ipv6 connection to an IPv4
1970 conn
->entry_cfg
.ipv6_traffic
= 0;
1975 /* we never allow IPv6 answers on socks4. (TODO: Is this smart?) */
1976 if (socks
->socks_version
== 4)
1977 conn
->entry_cfg
.ipv6_traffic
= 0;
1979 /* Still handling CONNECT. Now, check for exit enclaves. (Which we
1980 * don't do on BEGIN_DIR, or when there is a chosen exit.)
1982 * TODO: Should we remove this? Exit enclaves are nutty and don't
1985 if (!conn
->use_begindir
&& !conn
->chosen_exit_name
&& !circ
) {
1986 /* see if we can find a suitable enclave exit */
1988 router_find_exact_exit_enclave(socks
->address
, socks
->port
);
1991 "Redirecting address %s to exit at enclave router %s",
1992 safe_str_client(socks
->address
), node_describe(r
));
1993 /* use the hex digest, not nickname, in case there are two
1994 routers with this nickname */
1995 conn
->chosen_exit_name
=
1996 tor_strdup(hex_str(r
->identity
, DIGEST_LEN
));
1997 conn
->chosen_exit_optional
= 1;
2001 /* Still handling CONNECT: warn or reject if it's using a dangerous
2003 if (!conn
->use_begindir
&& !conn
->chosen_exit_name
&& !circ
)
2004 if (consider_plaintext_ports(conn
, socks
->port
) < 0)
2007 /* Remember the port so that we will predict that more requests
2008 there will happen in the future. */
2009 if (!conn
->use_begindir
) {
2010 /* help predict this next time */
2011 rep_hist_note_used_port(now
, socks
->port
);
2013 } else if (socks
->command
== SOCKS_COMMAND_RESOLVE_PTR
) {
2014 rep_hist_note_used_resolve(now
); /* help predict this next time */
2015 /* no extra processing needed */
2017 /* We should only be doing CONNECT, RESOLVE, or RESOLVE_PTR! */
2018 tor_fragile_assert();
2021 /* Okay. At this point we've set chosen_exit_name if needed, rewritten the
2022 * address, and decided not to reject it for any number of reasons. Now
2023 * mark the connection as waiting for a circuit, and try to attach it!
2025 base_conn
->state
= AP_CONN_STATE_CIRCUIT_WAIT
;
2027 /* If we were given a circuit to attach to, try to attach. Otherwise,
2028 * try to find a good one and attach to that. */
2031 rv
= connection_ap_handshake_attach_chosen_circuit(conn
, circ
, cpath
);
2033 /* We'll try to attach it at the next event loop, or whenever
2034 * we call connection_ap_attach_pending() */
2035 connection_ap_mark_as_pending_circuit(conn
);
2039 /* If the above function returned 0 then we're waiting for a circuit.
2040 * if it returned 1, we're attached. Both are okay. But if it returned
2041 * -1, there was an error, so make sure the connection is marked, and
2044 if (!base_conn
->marked_for_close
)
2045 connection_mark_unattached_ap(conn
, END_STREAM_REASON_CANT_ATTACH
);
2051 /* If we get here, it's a request for a .onion address! */
2052 tor_assert(addresstype
== ONION_V2_HOSTNAME
||
2053 addresstype
== ONION_V3_HOSTNAME
);
2054 tor_assert(!automap
);
2055 return connection_ap_handle_onion(conn
, socks
, circ
, addresstype
);
2058 return 0; /* unreached but keeps the compiler happy */
2062 static int pf_socket
= -1;
2067 /* This should be opened before dropping privileges. */
2071 #if defined(OpenBSD)
2072 /* only works on OpenBSD */
2073 pf
= tor_open_cloexec("/dev/pf", O_RDONLY
, 0);
2075 /* works on NetBSD and FreeBSD */
2076 pf
= tor_open_cloexec("/dev/pf", O_RDWR
, 0);
2077 #endif /* defined(OpenBSD) */
2080 log_warn(LD_NET
, "open(\"/dev/pf\") failed: %s", strerror(errno
));
2087 #endif /* defined(TRANS_PF) */
2089 #if defined(TRANS_NETFILTER) || defined(TRANS_PF) || \
2090 defined(TRANS_TPROXY)
2091 /** Try fill in the address of <b>req</b> from the socket configured
2092 * with <b>conn</b>. */
2094 destination_from_socket(entry_connection_t
*conn
, socks_request_t
*req
)
2096 struct sockaddr_storage orig_dst
;
2097 socklen_t orig_dst_len
= sizeof(orig_dst
);
2101 if (get_options()->TransProxyType_parsed
== TPT_TPROXY
) {
2102 if (getsockname(ENTRY_TO_CONN(conn
)->s
, (struct sockaddr
*)&orig_dst
,
2103 &orig_dst_len
) < 0) {
2104 int e
= tor_socket_errno(ENTRY_TO_CONN(conn
)->s
);
2105 log_warn(LD_NET
, "getsockname() failed: %s", tor_socket_strerror(e
));
2110 #endif /* defined(TRANS_TPROXY) */
2112 #ifdef TRANS_NETFILTER
2114 switch (ENTRY_TO_CONN(conn
)->socket_family
) {
2115 #ifdef TRANS_NETFILTER_IPV4
2117 rv
= getsockopt(ENTRY_TO_CONN(conn
)->s
, SOL_IP
, SO_ORIGINAL_DST
,
2118 (struct sockaddr
*)&orig_dst
, &orig_dst_len
);
2120 #endif /* defined(TRANS_NETFILTER_IPV4) */
2121 #ifdef TRANS_NETFILTER_IPV6
2123 rv
= getsockopt(ENTRY_TO_CONN(conn
)->s
, SOL_IPV6
, IP6T_SO_ORIGINAL_DST
,
2124 (struct sockaddr
*)&orig_dst
, &orig_dst_len
);
2126 #endif /* defined(TRANS_NETFILTER_IPV6) */
2129 "Received transparent data from an unsuported socket family %d",
2130 ENTRY_TO_CONN(conn
)->socket_family
);
2134 int e
= tor_socket_errno(ENTRY_TO_CONN(conn
)->s
);
2135 log_warn(LD_NET
, "getsockopt() failed: %s", tor_socket_strerror(e
));
2139 #elif defined(TRANS_PF)
2140 if (getsockname(ENTRY_TO_CONN(conn
)->s
, (struct sockaddr
*)&orig_dst
,
2141 &orig_dst_len
) < 0) {
2142 int e
= tor_socket_errno(ENTRY_TO_CONN(conn
)->s
);
2143 log_warn(LD_NET
, "getsockname() failed: %s", tor_socket_strerror(e
));
2150 log_warn(LD_BUG
, "Unable to determine destination from socket.");
2152 #endif /* defined(TRANS_NETFILTER) || ... */
2155 tor_addr_from_sockaddr(&addr
, (struct sockaddr
*)&orig_dst
, &req
->port
);
2156 tor_addr_to_str(req
->address
, &addr
, sizeof(req
->address
), 1);
2160 #endif /* defined(TRANS_NETFILTER) || defined(TRANS_PF) || ... */
2164 destination_from_pf(entry_connection_t
*conn
, socks_request_t
*req
)
2166 struct sockaddr_storage proxy_addr
;
2167 socklen_t proxy_addr_len
= sizeof(proxy_addr
);
2168 struct sockaddr
*proxy_sa
= (struct sockaddr
*) &proxy_addr
;
2169 struct pfioc_natlook pnl
;
2173 if (getsockname(ENTRY_TO_CONN(conn
)->s
, (struct sockaddr
*)&proxy_addr
,
2174 &proxy_addr_len
) < 0) {
2175 int e
= tor_socket_errno(ENTRY_TO_CONN(conn
)->s
);
2176 log_warn(LD_NET
, "getsockname() to determine transocks destination "
2177 "failed: %s", tor_socket_strerror(e
));
2182 if (get_options()->TransProxyType_parsed
== TPT_IPFW
) {
2183 /* ipfw(8) is used and in this case getsockname returned the original
2185 if (tor_addr_from_sockaddr(&addr
, proxy_sa
, &req
->port
) < 0) {
2186 tor_fragile_assert();
2190 tor_addr_to_str(req
->address
, &addr
, sizeof(req
->address
), 0);
2194 #endif /* defined(__FreeBSD__) */
2196 memset(&pnl
, 0, sizeof(pnl
));
2197 pnl
.proto
= IPPROTO_TCP
;
2198 pnl
.direction
= PF_OUT
;
2199 if (proxy_sa
->sa_family
== AF_INET
) {
2200 struct sockaddr_in
*sin
= (struct sockaddr_in
*)proxy_sa
;
2202 pnl
.saddr
.v4
.s_addr
= tor_addr_to_ipv4n(&ENTRY_TO_CONN(conn
)->addr
);
2203 pnl
.sport
= htons(ENTRY_TO_CONN(conn
)->port
);
2204 pnl
.daddr
.v4
.s_addr
= sin
->sin_addr
.s_addr
;
2205 pnl
.dport
= sin
->sin_port
;
2206 } else if (proxy_sa
->sa_family
== AF_INET6
) {
2207 struct sockaddr_in6
*sin6
= (struct sockaddr_in6
*)proxy_sa
;
2209 memcpy(&pnl
.saddr
.v6
, tor_addr_to_in6(&ENTRY_TO_CONN(conn
)->addr
),
2210 sizeof(struct in6_addr
));
2211 pnl
.sport
= htons(ENTRY_TO_CONN(conn
)->port
);
2212 memcpy(&pnl
.daddr
.v6
, &sin6
->sin6_addr
, sizeof(struct in6_addr
));
2213 pnl
.dport
= sin6
->sin6_port
;
2215 log_warn(LD_NET
, "getsockname() gave an unexpected address family (%d)",
2216 (int)proxy_sa
->sa_family
);
2220 pf
= get_pf_socket();
2224 if (ioctl(pf
, DIOCNATLOOK
, &pnl
) < 0) {
2225 log_warn(LD_NET
, "ioctl(DIOCNATLOOK) failed: %s", strerror(errno
));
2229 if (pnl
.af
== AF_INET
) {
2230 tor_addr_from_ipv4n(&addr
, pnl
.rdaddr
.v4
.s_addr
);
2231 } else if (pnl
.af
== AF_INET6
) {
2232 tor_addr_from_in6(&addr
, &pnl
.rdaddr
.v6
);
2234 tor_fragile_assert();
2238 tor_addr_to_str(req
->address
, &addr
, sizeof(req
->address
), 1);
2239 req
->port
= ntohs(pnl
.rdport
);
2243 #endif /* defined(TRANS_PF) */
2245 /** Fetch the original destination address and port from a
2246 * system-specific interface and put them into a
2247 * socks_request_t as if they came from a socks request.
2249 * Return -1 if an error prevents fetching the destination,
2253 connection_ap_get_original_destination(entry_connection_t
*conn
,
2254 socks_request_t
*req
)
2256 #ifdef TRANS_NETFILTER
2257 return destination_from_socket(conn
, req
);
2258 #elif defined(TRANS_PF)
2259 const or_options_t
*options
= get_options();
2261 if (options
->TransProxyType_parsed
== TPT_PF_DIVERT
)
2262 return destination_from_socket(conn
, req
);
2264 if (options
->TransProxyType_parsed
== TPT_DEFAULT
||
2265 options
->TransProxyType_parsed
== TPT_IPFW
)
2266 return destination_from_pf(conn
, req
);
2270 log_warn(LD_BUG
, "Proxy destination determination mechanism %s unknown.",
2271 options
->TransProxyType
);
2276 log_warn(LD_BUG
, "Called connection_ap_get_original_destination, but no "
2277 "transparent proxy method was configured.");
2279 #endif /* defined(TRANS_NETFILTER) || ... */
2282 /** connection_edge_process_inbuf() found a conn in state
2283 * socks_wait. See if conn->inbuf has the right bytes to proceed with
2284 * the socks handshake.
2286 * If the handshake is complete, send it to
2287 * connection_ap_handshake_rewrite_and_attach().
2289 * Return -1 if an unexpected error with conn occurs (and mark it for close),
2293 connection_ap_handshake_process_socks(entry_connection_t
*conn
)
2295 socks_request_t
*socks
;
2297 const or_options_t
*options
= get_options();
2299 connection_t
*base_conn
= ENTRY_TO_CONN(conn
);
2302 tor_assert(base_conn
->type
== CONN_TYPE_AP
);
2303 tor_assert(base_conn
->state
== AP_CONN_STATE_SOCKS_WAIT
);
2304 tor_assert(conn
->socks_request
);
2305 socks
= conn
->socks_request
;
2307 log_debug(LD_APP
,"entered.");
2309 sockshere
= fetch_from_buf_socks(base_conn
->inbuf
, socks
,
2310 options
->TestSocks
, options
->SafeSocks
);
2312 if (socks
->replylen
) {
2314 connection_buf_add((const char*)socks
->reply
, socks
->replylen
,
2316 socks
->replylen
= 0;
2317 if (sockshere
== -1) {
2318 /* An invalid request just got a reply, no additional
2319 * one is necessary. */
2320 socks
->has_finished
= 1;
2324 if (sockshere
== 0) {
2325 log_debug(LD_APP
,"socks handshake not all here yet.");
2327 } else if (sockshere
== -1) {
2329 log_warn(LD_APP
,"Fetching socks handshake failed. Closing.");
2330 connection_ap_handshake_socks_reply(conn
, NULL
, 0,
2331 END_STREAM_REASON_SOCKSPROTOCOL
);
2333 connection_mark_unattached_ap(conn
,
2334 END_STREAM_REASON_SOCKSPROTOCOL
|
2335 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
);
2337 } /* else socks handshake is done, continue processing */
2339 if (SOCKS_COMMAND_IS_CONNECT(socks
->command
))
2340 control_event_stream_status(conn
, STREAM_EVENT_NEW
, 0);
2342 control_event_stream_status(conn
, STREAM_EVENT_NEW_RESOLVE
, 0);
2344 return connection_ap_rewrite_and_attach_if_allowed(conn
, NULL
, NULL
);
2347 /** connection_init_accepted_conn() found a new trans AP conn.
2348 * Get the original destination and send it to
2349 * connection_ap_handshake_rewrite_and_attach().
2351 * Return -1 if an unexpected error with conn (and it should be marked
2352 * for close), else return 0.
2355 connection_ap_process_transparent(entry_connection_t
*conn
)
2357 socks_request_t
*socks
;
2360 tor_assert(conn
->socks_request
);
2361 socks
= conn
->socks_request
;
2363 /* pretend that a socks handshake completed so we don't try to
2364 * send a socks reply down a transparent conn */
2365 socks
->command
= SOCKS_COMMAND_CONNECT
;
2366 socks
->has_finished
= 1;
2368 log_debug(LD_APP
,"entered.");
2370 if (connection_ap_get_original_destination(conn
, socks
) < 0) {
2371 log_warn(LD_APP
,"Fetching original destination failed. Closing.");
2372 connection_mark_unattached_ap(conn
,
2373 END_STREAM_REASON_CANT_FETCH_ORIG_DEST
);
2376 /* we have the original destination */
2378 control_event_stream_status(conn
, STREAM_EVENT_NEW
, 0);
2380 return connection_ap_rewrite_and_attach_if_allowed(conn
, NULL
, NULL
);
2383 /** connection_edge_process_inbuf() found a conn in state natd_wait. See if
2384 * conn-\>inbuf has the right bytes to proceed. See FreeBSD's libalias(3) and
2385 * ProxyEncodeTcpStream() in src/lib/libalias/alias_proxy.c for the encoding
2386 * form of the original destination.
2388 * If the original destination is complete, send it to
2389 * connection_ap_handshake_rewrite_and_attach().
2391 * Return -1 if an unexpected error with conn (and it should be marked
2392 * for close), else return 0.
2395 connection_ap_process_natd(entry_connection_t
*conn
)
2397 char tmp_buf
[36], *tbuf
, *daddr
;
2400 socks_request_t
*socks
;
2403 tor_assert(ENTRY_TO_CONN(conn
)->state
== AP_CONN_STATE_NATD_WAIT
);
2404 tor_assert(conn
->socks_request
);
2405 socks
= conn
->socks_request
;
2407 log_debug(LD_APP
,"entered.");
2409 /* look for LF-terminated "[DEST ip_addr port]"
2410 * where ip_addr is a dotted-quad and port is in string form */
2411 err
= connection_buf_get_line(ENTRY_TO_CONN(conn
), tmp_buf
, &tlen
);
2415 log_warn(LD_APP
,"NATD handshake failed (DEST too long). Closing");
2416 connection_mark_unattached_ap(conn
, END_STREAM_REASON_INVALID_NATD_DEST
);
2420 if (strcmpstart(tmp_buf
, "[DEST ")) {
2421 log_warn(LD_APP
,"NATD handshake was ill-formed; closing. The client "
2424 connection_mark_unattached_ap(conn
, END_STREAM_REASON_INVALID_NATD_DEST
);
2428 daddr
= tbuf
= &tmp_buf
[0] + 6; /* after end of "[DEST " */
2429 if (!(tbuf
= strchr(tbuf
, ' '))) {
2430 log_warn(LD_APP
,"NATD handshake was ill-formed; closing. The client "
2433 connection_mark_unattached_ap(conn
, END_STREAM_REASON_INVALID_NATD_DEST
);
2438 /* pretend that a socks handshake completed so we don't try to
2439 * send a socks reply down a natd conn */
2440 strlcpy(socks
->address
, daddr
, sizeof(socks
->address
));
2441 socks
->port
= (uint16_t)
2442 tor_parse_long(tbuf
, 10, 1, 65535, &port_ok
, &daddr
);
2444 log_warn(LD_APP
,"NATD handshake failed; port %s is ill-formed or out "
2445 "of range.", escaped(tbuf
));
2446 connection_mark_unattached_ap(conn
, END_STREAM_REASON_INVALID_NATD_DEST
);
2450 socks
->command
= SOCKS_COMMAND_CONNECT
;
2451 socks
->has_finished
= 1;
2453 control_event_stream_status(conn
, STREAM_EVENT_NEW
, 0);
2455 ENTRY_TO_CONN(conn
)->state
= AP_CONN_STATE_CIRCUIT_WAIT
;
2457 return connection_ap_rewrite_and_attach_if_allowed(conn
, NULL
, NULL
);
2460 /** Called on an HTTP CONNECT entry connection when some bytes have arrived,
2461 * but we have not yet received a full HTTP CONNECT request. Try to parse an
2462 * HTTP CONNECT request from the connection's inbuf. On success, set up the
2463 * connection's socks_request field and try to attach the connection. On
2464 * failure, send an HTTP reply, and mark the connection.
2467 connection_ap_process_http_connect(entry_connection_t
*conn
)
2469 if (BUG(ENTRY_TO_CONN(conn
)->state
!= AP_CONN_STATE_HTTP_CONNECT_WAIT
))
2472 char *headers
= NULL
, *body
= NULL
;
2473 char *command
= NULL
, *addrport
= NULL
;
2477 const char *errmsg
= NULL
;
2480 const int http_status
=
2481 fetch_from_buf_http(ENTRY_TO_CONN(conn
)->inbuf
, &headers
, 8192,
2482 &body
, &bodylen
, 1024, 0);
2483 if (http_status
< 0) {
2484 /* Bad http status */
2485 errmsg
= "HTTP/1.0 400 Bad Request\r\n\r\n";
2487 } else if (http_status
== 0) {
2488 /* no HTTP request yet. */
2492 const int cmd_status
= parse_http_command(headers
, &command
, &addrport
);
2493 if (cmd_status
< 0) {
2494 errmsg
= "HTTP/1.0 400 Bad Request\r\n\r\n";
2497 tor_assert(command
);
2498 tor_assert(addrport
);
2499 if (strcasecmp(command
, "connect")) {
2500 errmsg
= "HTTP/1.0 405 Method Not Allowed\r\n\r\n";
2504 tor_assert(conn
->socks_request
);
2505 socks_request_t
*socks
= conn
->socks_request
;
2507 if (tor_addr_port_split(LOG_WARN
, addrport
, &addr
, &port
) < 0) {
2508 errmsg
= "HTTP/1.0 400 Bad Request\r\n\r\n";
2511 if (strlen(addr
) >= MAX_SOCKS_ADDR_LEN
) {
2512 errmsg
= "HTTP/1.0 414 Request-URI Too Long\r\n\r\n";
2516 /* Abuse the 'username' and 'password' fields here. They are already an
2519 char *authorization
= http_get_header(headers
, "Proxy-Authorization: ");
2520 if (authorization
) {
2521 socks
->username
= authorization
; // steal reference
2522 socks
->usernamelen
= strlen(authorization
);
2524 char *isolation
= http_get_header(headers
, "X-Tor-Stream-Isolation: ");
2526 socks
->password
= isolation
; // steal reference
2527 socks
->passwordlen
= strlen(isolation
);
2531 socks
->command
= SOCKS_COMMAND_CONNECT
;
2532 socks
->listener_type
= CONN_TYPE_AP_HTTP_CONNECT_LISTENER
;
2533 strlcpy(socks
->address
, addr
, sizeof(socks
->address
));
2536 control_event_stream_status(conn
, STREAM_EVENT_NEW
, 0);
2538 rv
= connection_ap_rewrite_and_attach_if_allowed(conn
, NULL
, NULL
);
2540 // XXXX send a "100 Continue" message?
2545 if (BUG(errmsg
== NULL
))
2546 errmsg
= "HTTP/1.0 400 Bad Request\r\n\r\n";
2547 log_info(LD_EDGE
, "HTTP tunnel error: saying %s", escaped(errmsg
));
2548 connection_buf_add(errmsg
, strlen(errmsg
), ENTRY_TO_CONN(conn
));
2549 /* Mark it as "has_finished" so that we don't try to send an extra socks
2551 conn
->socks_request
->has_finished
= 1;
2552 connection_mark_unattached_ap(conn
,
2553 END_STREAM_REASON_HTTPPROTOCOL
|
2554 END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
);
2565 /** Iterate over the two bytes of stream_id until we get one that is not
2566 * already in use; return it. Return 0 if can't get a unique stream_id.
2569 get_unique_stream_id_by_circ(origin_circuit_t
*circ
)
2571 edge_connection_t
*tmpconn
;
2572 streamid_t test_stream_id
;
2573 uint32_t attempts
=0;
2576 test_stream_id
= circ
->next_stream_id
++;
2577 if (++attempts
> 1<<16) {
2578 /* Make sure we don't loop forever if all stream_id's are used. */
2579 log_warn(LD_APP
,"No unused stream IDs. Failing.");
2582 if (test_stream_id
== 0)
2584 for (tmpconn
= circ
->p_streams
; tmpconn
; tmpconn
=tmpconn
->next_stream
)
2585 if (tmpconn
->stream_id
== test_stream_id
)
2587 return test_stream_id
;
2590 /** Return true iff <b>conn</b> is linked to a circuit and configured to use
2591 * an exit that supports optimistic data. */
2593 connection_ap_supports_optimistic_data(const entry_connection_t
*conn
)
2595 const edge_connection_t
*edge_conn
= ENTRY_TO_EDGE_CONN(conn
);
2596 /* We can only send optimistic data if we're connected to an open
2598 if (edge_conn
->on_circuit
== NULL
||
2599 edge_conn
->on_circuit
->state
!= CIRCUIT_STATE_OPEN
||
2600 (edge_conn
->on_circuit
->purpose
!= CIRCUIT_PURPOSE_C_GENERAL
&&
2601 edge_conn
->on_circuit
->purpose
!= CIRCUIT_PURPOSE_C_HSDIR_GET
&&
2602 edge_conn
->on_circuit
->purpose
!= CIRCUIT_PURPOSE_S_HSDIR_POST
&&
2603 edge_conn
->on_circuit
->purpose
!= CIRCUIT_PURPOSE_C_REND_JOINED
))
2606 return conn
->may_use_optimistic_data
;
2609 /** Return a bitmask of BEGIN_FLAG_* flags that we should transmit in the
2610 * RELAY_BEGIN cell for <b>ap_conn</b>. */
2612 connection_ap_get_begincell_flags(entry_connection_t
*ap_conn
)
2614 edge_connection_t
*edge_conn
= ENTRY_TO_EDGE_CONN(ap_conn
);
2615 const node_t
*exitnode
= NULL
;
2616 const crypt_path_t
*cpath_layer
= edge_conn
->cpath_layer
;
2619 /* No flags for begindir */
2620 if (ap_conn
->use_begindir
)
2623 /* No flags for hidden services. */
2624 if (edge_conn
->on_circuit
->purpose
!= CIRCUIT_PURPOSE_C_GENERAL
)
2627 /* If only IPv4 is supported, no flags */
2628 if (ap_conn
->entry_cfg
.ipv4_traffic
&& !ap_conn
->entry_cfg
.ipv6_traffic
)
2631 if (! cpath_layer
||
2632 ! cpath_layer
->extend_info
)
2635 if (!ap_conn
->entry_cfg
.ipv4_traffic
)
2636 flags
|= BEGIN_FLAG_IPV4_NOT_OK
;
2638 exitnode
= node_get_by_id(cpath_layer
->extend_info
->identity_digest
);
2640 if (ap_conn
->entry_cfg
.ipv6_traffic
&& exitnode
) {
2642 tor_addr_make_null(&a
, AF_INET6
);
2643 if (compare_tor_addr_to_node_policy(&a
, ap_conn
->socks_request
->port
,
2645 != ADDR_POLICY_REJECTED
) {
2646 /* Only say "IPv6 OK" if the exit node supports IPv6. Otherwise there's
2648 flags
|= BEGIN_FLAG_IPV6_OK
;
2652 if (flags
== BEGIN_FLAG_IPV6_OK
) {
2653 /* When IPv4 and IPv6 are both allowed, consider whether to say we
2654 * prefer IPv6. Otherwise there's no point in declaring a preference */
2655 if (ap_conn
->entry_cfg
.prefer_ipv6
)
2656 flags
|= BEGIN_FLAG_IPV6_PREFERRED
;
2659 if (flags
== BEGIN_FLAG_IPV4_NOT_OK
) {
2660 log_warn(LD_EDGE
, "I'm about to ask a node for a connection that I "
2661 "am telling it to fulfil with neither IPv4 nor IPv6. That's "
2662 "not going to work. Did you perhaps ask for an IPv6 address "
2663 "on an IPv4Only port, or vice versa?");
2669 /** Write a relay begin cell, using destaddr and destport from ap_conn's
2670 * socks_request field, and send it down circ.
2672 * If ap_conn is broken, mark it for close and return -1. Else return 0.
2675 connection_ap_handshake_send_begin
,(entry_connection_t
*ap_conn
))
2677 char payload
[CELL_PAYLOAD_SIZE
];
2680 const or_options_t
*options
= get_options();
2681 origin_circuit_t
*circ
;
2682 edge_connection_t
*edge_conn
= ENTRY_TO_EDGE_CONN(ap_conn
);
2683 connection_t
*base_conn
= TO_CONN(edge_conn
);
2684 tor_assert(edge_conn
->on_circuit
);
2685 circ
= TO_ORIGIN_CIRCUIT(edge_conn
->on_circuit
);
2687 tor_assert(base_conn
->type
== CONN_TYPE_AP
);
2688 tor_assert(base_conn
->state
== AP_CONN_STATE_CIRCUIT_WAIT
);
2689 tor_assert(ap_conn
->socks_request
);
2690 tor_assert(SOCKS_COMMAND_IS_CONNECT(ap_conn
->socks_request
->command
));
2692 edge_conn
->stream_id
= get_unique_stream_id_by_circ(circ
);
2693 if (edge_conn
->stream_id
==0) {
2694 /* XXXX+ Instead of closing this stream, we should make it get
2695 * retried on another circuit. */
2696 connection_mark_unattached_ap(ap_conn
, END_STREAM_REASON_INTERNAL
);
2698 /* Mark this circuit "unusable for new streams". */
2699 mark_circuit_unusable_for_new_conns(circ
);
2703 /* Set up begin cell flags. */
2704 edge_conn
->begincell_flags
= connection_ap_get_begincell_flags(ap_conn
);
2706 tor_snprintf(payload
,RELAY_PAYLOAD_SIZE
, "%s:%d",
2707 (circ
->base_
.purpose
== CIRCUIT_PURPOSE_C_GENERAL
) ?
2708 ap_conn
->socks_request
->address
: "",
2709 ap_conn
->socks_request
->port
);
2710 payload_len
= (int)strlen(payload
)+1;
2711 if (payload_len
<= RELAY_PAYLOAD_SIZE
- 4 && edge_conn
->begincell_flags
) {
2712 set_uint32(payload
+ payload_len
, htonl(edge_conn
->begincell_flags
));
2717 "Sending relay cell %d on circ %u to begin stream %d.",
2718 (int)ap_conn
->use_begindir
,
2719 (unsigned)circ
->base_
.n_circ_id
,
2720 edge_conn
->stream_id
);
2722 begin_type
= ap_conn
->use_begindir
?
2723 RELAY_COMMAND_BEGIN_DIR
: RELAY_COMMAND_BEGIN
;
2725 /* Check that circuits are anonymised, based on their type. */
2726 if (begin_type
== RELAY_COMMAND_BEGIN
) {
2727 /* This connection is a standard OR connection.
2728 * Make sure its path length is anonymous, or that we're in a
2729 * non-anonymous mode. */
2730 assert_circ_anonymity_ok(circ
, options
);
2731 } else if (begin_type
== RELAY_COMMAND_BEGIN_DIR
) {
2732 /* This connection is a begindir directory connection.
2733 * Look at the linked directory connection to access the directory purpose.
2734 * If a BEGINDIR connection is ever not linked, that's a bug. */
2735 if (BUG(!base_conn
->linked
)) {
2738 connection_t
*linked_dir_conn_base
= base_conn
->linked_conn
;
2739 /* If the linked connection has been unlinked by other code, we can't send
2740 * a begin cell on it. */
2741 if (!linked_dir_conn_base
) {
2744 /* Sensitive directory connections must have an anonymous path length.
2745 * Otherwise, directory connections are typically one-hop.
2746 * This matches the earlier check for directory connection path anonymity
2747 * in directory_initiate_request(). */
2748 if (purpose_needs_anonymity(linked_dir_conn_base
->purpose
,
2749 TO_DIR_CONN(linked_dir_conn_base
)->router_purpose
,
2750 TO_DIR_CONN(linked_dir_conn_base
)->requested_resource
)) {
2751 assert_circ_anonymity_ok(circ
, options
);
2754 /* This code was written for the two connection types BEGIN and BEGIN_DIR
2756 tor_assert_unreached();
2759 if (connection_edge_send_command(edge_conn
, begin_type
,
2760 begin_type
== RELAY_COMMAND_BEGIN
? payload
: NULL
,
2761 begin_type
== RELAY_COMMAND_BEGIN
? payload_len
: 0) < 0)
2762 return -1; /* circuit is closed, don't continue */
2764 edge_conn
->package_window
= STREAMWINDOW_START
;
2765 edge_conn
->deliver_window
= STREAMWINDOW_START
;
2766 base_conn
->state
= AP_CONN_STATE_CONNECT_WAIT
;
2767 log_info(LD_APP
,"Address/port sent, ap socket "TOR_SOCKET_T_FORMAT
2769 base_conn
->s
, (unsigned)circ
->base_
.n_circ_id
);
2770 control_event_stream_status(ap_conn
, STREAM_EVENT_SENT_CONNECT
, 0);
2772 /* If there's queued-up data, send it now */
2773 if ((connection_get_inbuf_len(base_conn
) ||
2774 ap_conn
->sending_optimistic_data
) &&
2775 connection_ap_supports_optimistic_data(ap_conn
)) {
2776 log_info(LD_APP
, "Sending up to %ld + %ld bytes of queued-up data",
2777 (long)connection_get_inbuf_len(base_conn
),
2778 ap_conn
->sending_optimistic_data
?
2779 (long)buf_datalen(ap_conn
->sending_optimistic_data
) : 0);
2780 if (connection_edge_package_raw_inbuf(edge_conn
, 1, NULL
) < 0) {
2781 connection_mark_for_close(base_conn
);
2788 /** Write a relay resolve cell, using destaddr and destport from ap_conn's
2789 * socks_request field, and send it down circ.
2791 * If ap_conn is broken, mark it for close and return -1. Else return 0.
2794 connection_ap_handshake_send_resolve(entry_connection_t
*ap_conn
)
2796 int payload_len
, command
;
2797 const char *string_addr
;
2798 char inaddr_buf
[REVERSE_LOOKUP_NAME_BUF_LEN
];
2799 origin_circuit_t
*circ
;
2800 edge_connection_t
*edge_conn
= ENTRY_TO_EDGE_CONN(ap_conn
);
2801 connection_t
*base_conn
= TO_CONN(edge_conn
);
2802 tor_assert(edge_conn
->on_circuit
);
2803 circ
= TO_ORIGIN_CIRCUIT(edge_conn
->on_circuit
);
2805 tor_assert(base_conn
->type
== CONN_TYPE_AP
);
2806 tor_assert(base_conn
->state
== AP_CONN_STATE_CIRCUIT_WAIT
);
2807 tor_assert(ap_conn
->socks_request
);
2808 tor_assert(circ
->base_
.purpose
== CIRCUIT_PURPOSE_C_GENERAL
);
2810 command
= ap_conn
->socks_request
->command
;
2811 tor_assert(SOCKS_COMMAND_IS_RESOLVE(command
));
2813 edge_conn
->stream_id
= get_unique_stream_id_by_circ(circ
);
2814 if (edge_conn
->stream_id
==0) {
2815 /* XXXX+ Instead of closing this stream, we should make it get
2816 * retried on another circuit. */
2817 connection_mark_unattached_ap(ap_conn
, END_STREAM_REASON_INTERNAL
);
2819 /* Mark this circuit "unusable for new streams". */
2820 mark_circuit_unusable_for_new_conns(circ
);
2824 if (command
== SOCKS_COMMAND_RESOLVE
) {
2825 string_addr
= ap_conn
->socks_request
->address
;
2826 payload_len
= (int)strlen(string_addr
)+1;
2828 /* command == SOCKS_COMMAND_RESOLVE_PTR */
2829 const char *a
= ap_conn
->socks_request
->address
;
2833 /* We're doing a reverse lookup. The input could be an IP address, or
2834 * could be an .in-addr.arpa or .ip6.arpa address */
2835 r
= tor_addr_parse_PTR_name(&addr
, a
, AF_UNSPEC
, 1);
2837 log_warn(LD_APP
, "Rejecting ill-formed reverse lookup of %s",
2838 safe_str_client(a
));
2839 connection_mark_unattached_ap(ap_conn
, END_STREAM_REASON_INTERNAL
);
2843 r
= tor_addr_to_PTR_name(inaddr_buf
, sizeof(inaddr_buf
), &addr
);
2845 log_warn(LD_BUG
, "Couldn't generate reverse lookup hostname of %s",
2846 safe_str_client(a
));
2847 connection_mark_unattached_ap(ap_conn
, END_STREAM_REASON_INTERNAL
);
2851 string_addr
= inaddr_buf
;
2852 payload_len
= (int)strlen(inaddr_buf
)+1;
2853 tor_assert(payload_len
<= (int)sizeof(inaddr_buf
));
2857 "Sending relay cell to begin stream %d.", edge_conn
->stream_id
);
2859 if (connection_edge_send_command(edge_conn
,
2860 RELAY_COMMAND_RESOLVE
,
2861 string_addr
, payload_len
) < 0)
2862 return -1; /* circuit is closed, don't continue */
2864 if (!base_conn
->address
) {
2865 /* This might be unnecessary. XXXX */
2866 base_conn
->address
= tor_addr_to_str_dup(&base_conn
->addr
);
2868 base_conn
->state
= AP_CONN_STATE_RESOLVE_WAIT
;
2869 log_info(LD_APP
,"Address sent for resolve, ap socket "TOR_SOCKET_T_FORMAT
2871 base_conn
->s
, (unsigned)circ
->base_
.n_circ_id
);
2872 control_event_stream_status(ap_conn
, STREAM_EVENT_SENT_RESOLVE
, 0);
2876 /** Make an AP connection_t linked to the connection_t <b>partner</b>. make a
2877 * new linked connection pair, and attach one side to the conn, connection_add
2878 * it, initialize it to circuit_wait, and call
2879 * connection_ap_handshake_attach_circuit(conn) on it.
2881 * Return the newly created end of the linked connection pair, or -1 if error.
2883 entry_connection_t
*
2884 connection_ap_make_link(connection_t
*partner
,
2885 char *address
, uint16_t port
,
2887 int session_group
, int isolation_flags
,
2888 int use_begindir
, int want_onehop
)
2890 entry_connection_t
*conn
;
2891 connection_t
*base_conn
;
2893 log_info(LD_APP
,"Making internal %s tunnel to %s:%d ...",
2894 want_onehop
? "direct" : "anonymized",
2895 safe_str_client(address
), port
);
2897 conn
= entry_connection_new(CONN_TYPE_AP
, tor_addr_family(&partner
->addr
));
2898 base_conn
= ENTRY_TO_CONN(conn
);
2899 base_conn
->linked
= 1; /* so that we can add it safely below. */
2901 /* populate conn->socks_request */
2903 /* leave version at zero, so the socks_reply is empty */
2904 conn
->socks_request
->socks_version
= 0;
2905 conn
->socks_request
->has_finished
= 0; /* waiting for 'connected' */
2906 strlcpy(conn
->socks_request
->address
, address
,
2907 sizeof(conn
->socks_request
->address
));
2908 conn
->socks_request
->port
= port
;
2909 conn
->socks_request
->command
= SOCKS_COMMAND_CONNECT
;
2910 conn
->want_onehop
= want_onehop
;
2911 conn
->use_begindir
= use_begindir
;
2913 conn
->chosen_exit_name
= tor_malloc(HEX_DIGEST_LEN
+2);
2914 conn
->chosen_exit_name
[0] = '$';
2916 base16_encode(conn
->chosen_exit_name
+1,HEX_DIGEST_LEN
+1,
2917 digest
, DIGEST_LEN
);
2920 /* Populate isolation fields. */
2921 conn
->socks_request
->listener_type
= CONN_TYPE_DIR_LISTENER
;
2922 conn
->original_dest_address
= tor_strdup(address
);
2923 conn
->entry_cfg
.session_group
= session_group
;
2924 conn
->entry_cfg
.isolation_flags
= isolation_flags
;
2926 base_conn
->address
= tor_strdup("(Tor_internal)");
2927 tor_addr_make_unspec(&base_conn
->addr
);
2928 base_conn
->port
= 0;
2930 connection_link_connections(partner
, base_conn
);
2932 if (connection_add(base_conn
) < 0) { /* no space, forget it */
2933 connection_free(base_conn
);
2937 base_conn
->state
= AP_CONN_STATE_CIRCUIT_WAIT
;
2939 control_event_stream_status(conn
, STREAM_EVENT_NEW
, 0);
2941 /* attaching to a dirty circuit is fine */
2942 connection_ap_mark_as_pending_circuit(conn
);
2943 log_info(LD_APP
,"... application connection created and linked.");
2947 /** Notify any interested controller connections about a new hostname resolve
2948 * or resolve error. Takes the same arguments as does
2949 * connection_ap_handshake_socks_resolved(). */
2951 tell_controller_about_resolved_result(entry_connection_t
*conn
,
2958 expires
= time(NULL
) + ttl
;
2959 if (answer_type
== RESOLVED_TYPE_IPV4
&& answer_len
>= 4) {
2960 char *cp
= tor_dup_ip(ntohl(get_uint32(answer
)));
2961 control_event_address_mapped(conn
->socks_request
->address
,
2962 cp
, expires
, NULL
, 0);
2964 } else if (answer_type
== RESOLVED_TYPE_HOSTNAME
&& answer_len
< 256) {
2965 char *cp
= tor_strndup(answer
, answer_len
);
2966 control_event_address_mapped(conn
->socks_request
->address
,
2967 cp
, expires
, NULL
, 0);
2970 control_event_address_mapped(conn
->socks_request
->address
,
2971 "<error>", time(NULL
)+ttl
,
2977 * As connection_ap_handshake_socks_resolved, but take a tor_addr_t to send
2981 connection_ap_handshake_socks_resolved_addr(entry_connection_t
*conn
,
2982 const tor_addr_t
*answer
,
2986 if (tor_addr_family(answer
) == AF_INET
) {
2987 uint32_t a
= tor_addr_to_ipv4n(answer
); /* network order */
2988 connection_ap_handshake_socks_resolved(conn
,RESOLVED_TYPE_IPV4
,4,
2991 } else if (tor_addr_family(answer
) == AF_INET6
) {
2992 const uint8_t *a
= tor_addr_to_in6_addr8(answer
);
2993 connection_ap_handshake_socks_resolved(conn
,RESOLVED_TYPE_IPV6
,16,
2997 log_warn(LD_BUG
, "Got called with address of unexpected family %d",
2998 tor_addr_family(answer
));
2999 connection_ap_handshake_socks_resolved(conn
,
3000 RESOLVED_TYPE_ERROR
,0,NULL
,-1,-1);
3004 /** Send an answer to an AP connection that has requested a DNS lookup via
3005 * SOCKS. The type should be one of RESOLVED_TYPE_(IPV4|IPV6|HOSTNAME) or -1
3006 * for unreachable; the answer should be in the format specified in the socks
3007 * extensions document. <b>ttl</b> is the ttl for the answer, or -1 on
3008 * certain errors or for values that didn't come via DNS. <b>expires</b> is
3009 * a time when the answer expires, or -1 or TIME_MAX if there's a good TTL.
3011 /* XXXX the use of the ttl and expires fields is nutty. Let's make this
3012 * interface and those that use it less ugly. */
3014 connection_ap_handshake_socks_resolved
,(entry_connection_t
*conn
,
3017 const uint8_t *answer
,
3025 if (answer_type
== RESOLVED_TYPE_IPV4
&& answer_len
== 4) {
3027 tor_addr_from_ipv4n(&a
, get_uint32(answer
));
3028 if (! tor_addr_is_null(&a
)) {
3029 client_dns_set_addressmap(conn
,
3030 conn
->socks_request
->address
, &a
,
3031 conn
->chosen_exit_name
, ttl
);
3033 } else if (answer_type
== RESOLVED_TYPE_IPV6
&& answer_len
== 16) {
3035 tor_addr_from_ipv6_bytes(&a
, (char*)answer
);
3036 if (! tor_addr_is_null(&a
)) {
3037 client_dns_set_addressmap(conn
,
3038 conn
->socks_request
->address
, &a
,
3039 conn
->chosen_exit_name
, ttl
);
3041 } else if (answer_type
== RESOLVED_TYPE_HOSTNAME
&& answer_len
< 256) {
3042 char *cp
= tor_strndup((char*)answer
, answer_len
);
3043 client_dns_set_reverse_addressmap(conn
,
3044 conn
->socks_request
->address
,
3046 conn
->chosen_exit_name
, ttl
);
3051 if (ENTRY_TO_EDGE_CONN(conn
)->is_dns_request
) {
3052 if (conn
->dns_server_request
) {
3053 /* We had a request on our DNS port: answer it. */
3054 dnsserv_resolved(conn
, answer_type
, answer_len
, (char*)answer
, ttl
);
3055 conn
->socks_request
->has_finished
= 1;
3058 /* This must be a request from the controller. Since answers to those
3059 * requests are not cached, they do not generate an ADDRMAP event on
3061 tell_controller_about_resolved_result(conn
, answer_type
, answer_len
,
3062 (char*)answer
, ttl
, expires
);
3063 conn
->socks_request
->has_finished
= 1;
3066 /* We shouldn't need to free conn here; it gets marked by the caller. */
3069 if (conn
->socks_request
->socks_version
== 4) {
3070 buf
[0] = 0x00; /* version */
3071 if (answer_type
== RESOLVED_TYPE_IPV4
&& answer_len
== 4) {
3072 buf
[1] = SOCKS4_GRANTED
;
3073 set_uint16(buf
+2, 0);
3074 memcpy(buf
+4, answer
, 4); /* address */
3075 replylen
= SOCKS4_NETWORK_LEN
;
3076 } else { /* "error" */
3077 buf
[1] = SOCKS4_REJECT
;
3078 memset(buf
+2, 0, 6);
3079 replylen
= SOCKS4_NETWORK_LEN
;
3081 } else if (conn
->socks_request
->socks_version
== 5) {
3083 buf
[0] = 0x05; /* version */
3084 if (answer_type
== RESOLVED_TYPE_IPV4
&& answer_len
== 4) {
3085 buf
[1] = SOCKS5_SUCCEEDED
;
3086 buf
[2] = 0; /* reserved */
3087 buf
[3] = 0x01; /* IPv4 address type */
3088 memcpy(buf
+4, answer
, 4); /* address */
3089 set_uint16(buf
+8, 0); /* port == 0. */
3091 } else if (answer_type
== RESOLVED_TYPE_IPV6
&& answer_len
== 16) {
3092 buf
[1] = SOCKS5_SUCCEEDED
;
3093 buf
[2] = 0; /* reserved */
3094 buf
[3] = 0x04; /* IPv6 address type */
3095 memcpy(buf
+4, answer
, 16); /* address */
3096 set_uint16(buf
+20, 0); /* port == 0. */
3098 } else if (answer_type
== RESOLVED_TYPE_HOSTNAME
&& answer_len
< 256) {
3099 buf
[1] = SOCKS5_SUCCEEDED
;
3100 buf
[2] = 0; /* reserved */
3101 buf
[3] = 0x03; /* Domainname address type */
3102 buf
[4] = (char)answer_len
;
3103 memcpy(buf
+5, answer
, answer_len
); /* address */
3104 set_uint16(buf
+5+answer_len
, 0); /* port == 0. */
3105 replylen
= 5+answer_len
+2;
3107 buf
[1] = SOCKS5_HOST_UNREACHABLE
;
3108 memset(buf
+2, 0, 8);
3112 /* no socks version info; don't send anything back */
3115 connection_ap_handshake_socks_reply(conn
, buf
, replylen
,
3116 (answer_type
== RESOLVED_TYPE_IPV4
||
3117 answer_type
== RESOLVED_TYPE_IPV6
||
3118 answer_type
== RESOLVED_TYPE_HOSTNAME
) ?
3119 0 : END_STREAM_REASON_RESOLVEFAILED
);
3122 /** Send a socks reply to stream <b>conn</b>, using the appropriate
3123 * socks version, etc, and mark <b>conn</b> as completed with SOCKS
3126 * If <b>reply</b> is defined, then write <b>replylen</b> bytes of it to conn
3127 * and return, else reply based on <b>endreason</b> (one of
3128 * END_STREAM_REASON_*). If <b>reply</b> is undefined, <b>endreason</b> can't
3129 * be 0 or REASON_DONE. Send endreason to the controller, if appropriate.
3132 connection_ap_handshake_socks_reply(entry_connection_t
*conn
, char *reply
,
3133 size_t replylen
, int endreason
)
3136 socks5_reply_status_t status
=
3137 stream_end_reason_to_socks5_response(endreason
);
3139 tor_assert(conn
->socks_request
); /* make sure it's an AP stream */
3141 if (!SOCKS_COMMAND_IS_RESOLVE(conn
->socks_request
->command
)) {
3142 control_event_stream_status(conn
, status
==SOCKS5_SUCCEEDED
?
3143 STREAM_EVENT_SUCCEEDED
: STREAM_EVENT_FAILED
,
3147 /* Flag this stream's circuit as having completed a stream successfully
3148 * (for path bias) */
3149 if (status
== SOCKS5_SUCCEEDED
||
3150 endreason
== END_STREAM_REASON_RESOLVEFAILED
||
3151 endreason
== END_STREAM_REASON_CONNECTREFUSED
||
3152 endreason
== END_STREAM_REASON_CONNRESET
||
3153 endreason
== END_STREAM_REASON_NOROUTE
||
3154 endreason
== END_STREAM_REASON_RESOURCELIMIT
) {
3155 if (!conn
->edge_
.on_circuit
||
3156 !CIRCUIT_IS_ORIGIN(conn
->edge_
.on_circuit
)) {
3157 if (endreason
!= END_STREAM_REASON_RESOLVEFAILED
) {
3159 "No origin circuit for successful SOCKS stream "U64_FORMAT
3161 U64_PRINTF_ARG(ENTRY_TO_CONN(conn
)->global_identifier
),
3165 * Else DNS remaps and failed hidden service lookups can send us
3166 * here with END_STREAM_REASON_RESOLVEFAILED; ignore it
3168 * Perhaps we could make the test more precise; we can tell hidden
3169 * services by conn->edge_.renddata != NULL; anything analogous for
3170 * the DNS remap case?
3173 // XXX: Hrmm. It looks like optimistic data can't go through this
3174 // codepath, but someone should probably test it and make sure.
3175 // We don't want to mark optimistically opened streams as successful.
3176 pathbias_mark_use_success(TO_ORIGIN_CIRCUIT(conn
->edge_
.on_circuit
));
3180 if (conn
->socks_request
->has_finished
) {
3181 log_warn(LD_BUG
, "(Harmless.) duplicate calls to "
3182 "connection_ap_handshake_socks_reply.");
3185 if (replylen
) { /* we already have a reply in mind */
3186 connection_buf_add(reply
, replylen
, ENTRY_TO_CONN(conn
));
3187 conn
->socks_request
->has_finished
= 1;
3190 if (conn
->socks_request
->listener_type
==
3191 CONN_TYPE_AP_HTTP_CONNECT_LISTENER
) {
3192 const char *response
= end_reason_to_http_connect_response_line(endreason
);
3194 response
= "HTTP/1.0 400 Bad Request\r\n\r\n";
3196 connection_buf_add(response
, strlen(response
), ENTRY_TO_CONN(conn
));
3197 } else if (conn
->socks_request
->socks_version
== 4) {
3198 memset(buf
,0,SOCKS4_NETWORK_LEN
);
3199 buf
[1] = (status
==SOCKS5_SUCCEEDED
? SOCKS4_GRANTED
: SOCKS4_REJECT
);
3200 /* leave version, destport, destip zero */
3201 connection_buf_add(buf
, SOCKS4_NETWORK_LEN
, ENTRY_TO_CONN(conn
));
3202 } else if (conn
->socks_request
->socks_version
== 5) {
3204 memset(buf
,0,sizeof(buf
));
3205 if (tor_addr_family(&conn
->edge_
.base_
.addr
) == AF_INET
) {
3206 buf
[0] = 5; /* version 5 */
3207 buf
[1] = (char)status
;
3209 buf
[3] = 1; /* ipv4 addr */
3210 /* 4 bytes for the header, 2 bytes for the port, 4 for the address. */
3212 } else { /* AF_INET6. */
3213 buf
[0] = 5; /* version 5 */
3214 buf
[1] = (char)status
;
3216 buf
[3] = 4; /* ipv6 addr */
3217 /* 4 bytes for the header, 2 bytes for the port, 16 for the address. */
3220 connection_buf_add(buf
,buf_len
,ENTRY_TO_CONN(conn
));
3222 /* If socks_version isn't 4 or 5, don't send anything.
3223 * This can happen in the case of AP bridges. */
3224 conn
->socks_request
->has_finished
= 1;
3228 /** Read a RELAY_BEGIN or RELAY_BEGIN_DIR cell from <b>cell</b>, decode it, and
3229 * place the result in <b>bcell</b>. On success return 0; on failure return
3230 * <0 and set *<b>end_reason_out</b> to the end reason we should send back to
3233 * Return -1 in the case where we want to send a RELAY_END cell, and < -1 when
3237 begin_cell_parse(const cell_t
*cell
, begin_cell_t
*bcell
,
3238 uint8_t *end_reason_out
)
3241 const uint8_t *body
, *nul
;
3243 memset(bcell
, 0, sizeof(*bcell
));
3244 *end_reason_out
= END_STREAM_REASON_MISC
;
3246 relay_header_unpack(&rh
, cell
->payload
);
3247 if (rh
.length
> RELAY_PAYLOAD_SIZE
) {
3248 return -2; /*XXXX why not TORPROTOCOL? */
3251 bcell
->stream_id
= rh
.stream_id
;
3253 if (rh
.command
== RELAY_COMMAND_BEGIN_DIR
) {
3254 bcell
->is_begindir
= 1;
3256 } else if (rh
.command
!= RELAY_COMMAND_BEGIN
) {
3257 log_warn(LD_BUG
, "Got an unexpected command %d", (int)rh
.command
);
3258 *end_reason_out
= END_STREAM_REASON_INTERNAL
;
3262 body
= cell
->payload
+ RELAY_HEADER_SIZE
;
3263 nul
= memchr(body
, 0, rh
.length
);
3265 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
3266 "Relay begin cell has no \\0. Closing.");
3267 *end_reason_out
= END_STREAM_REASON_TORPROTOCOL
;
3271 if (tor_addr_port_split(LOG_PROTOCOL_WARN
,
3273 &bcell
->address
,&bcell
->port
)<0) {
3274 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
3275 "Unable to parse addr:port in relay begin cell. Closing.");
3276 *end_reason_out
= END_STREAM_REASON_TORPROTOCOL
;
3279 if (bcell
->port
== 0) {
3280 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
3281 "Missing port in relay begin cell. Closing.");
3282 tor_free(bcell
->address
);
3283 *end_reason_out
= END_STREAM_REASON_TORPROTOCOL
;
3286 if (body
+ rh
.length
>= nul
+ 4)
3287 bcell
->flags
= ntohl(get_uint32(nul
+1));
3292 /** For the given <b>circ</b> and the edge connection <b>conn</b>, setup the
3293 * connection, attach it to the circ and connect it. Return 0 on success
3294 * or END_CIRC_AT_ORIGIN if we can't find the requested hidden service port
3295 * where the caller should close the circuit. */
3297 handle_hs_exit_conn(circuit_t
*circ
, edge_connection_t
*conn
)
3300 origin_circuit_t
*origin_circ
;
3302 assert_circuit_ok(circ
);
3303 tor_assert(circ
->purpose
== CIRCUIT_PURPOSE_S_REND_JOINED
);
3306 log_debug(LD_REND
, "Connecting the hidden service rendezvous circuit "
3307 "to the service destination.");
3309 origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
3310 conn
->base_
.address
= tor_strdup("(rendezvous)");
3311 conn
->base_
.state
= EXIT_CONN_STATE_CONNECTING
;
3313 /* The circuit either has an hs identifier for v3+ or a rend_data for legacy
3315 if (origin_circ
->rend_data
) {
3316 conn
->rend_data
= rend_data_dup(origin_circ
->rend_data
);
3317 tor_assert(connection_edge_is_rendezvous_stream(conn
));
3318 ret
= rend_service_set_connection_addr_port(conn
, origin_circ
);
3319 } else if (origin_circ
->hs_ident
) {
3320 /* Setup the identifier to be the one for the circuit service. */
3322 hs_ident_edge_conn_new(&origin_circ
->hs_ident
->identity_pk
);
3323 tor_assert(connection_edge_is_rendezvous_stream(conn
));
3324 ret
= hs_service_set_conn_addr_port(origin_circ
, conn
);
3326 /* We should never get here if the circuit's purpose is rendezvous. */
3327 tor_assert_nonfatal_unreached();
3331 log_info(LD_REND
, "Didn't find rendezvous service (addr%s, port %d)",
3332 fmt_addr(&TO_CONN(conn
)->addr
), TO_CONN(conn
)->port
);
3333 /* Send back reason DONE because we want to make hidden service port
3334 * scanning harder thus instead of returning that the exit policy
3335 * didn't match, which makes it obvious that the port is closed,
3336 * return DONE and kill the circuit. That way, a user (malicious or
3337 * not) needs one circuit per bad port unless it matches the policy of
3338 * the hidden service. */
3339 relay_send_end_cell_from_edge(conn
->stream_id
, circ
,
3340 END_STREAM_REASON_DONE
,
3341 origin_circ
->cpath
->prev
);
3342 connection_free_(TO_CONN(conn
));
3344 /* Drop the circuit here since it might be someone deliberately
3345 * scanning the hidden service ports. Note that this mitigates port
3346 * scanning by adding more work on the attacker side to successfully
3347 * scan but does not fully solve it. */
3349 return END_CIRC_AT_ORIGIN
;
3355 /* Link the circuit and the connection crypt path. */
3356 conn
->cpath_layer
= origin_circ
->cpath
->prev
;
3358 /* Add it into the linked list of p_streams on this circuit */
3359 conn
->next_stream
= origin_circ
->p_streams
;
3360 origin_circ
->p_streams
= conn
;
3361 conn
->on_circuit
= circ
;
3362 assert_circuit_ok(circ
);
3364 hs_inc_rdv_stream_counter(origin_circ
);
3366 /* Connect tor to the hidden service destination. */
3367 connection_exit_connect(conn
);
3369 /* For path bias: This circuit was used successfully */
3370 pathbias_mark_use_success(origin_circ
);
3374 /** A relay 'begin' or 'begin_dir' cell has arrived, and either we are
3375 * an exit hop for the circuit, or we are the origin and it is a
3378 * Launch a new exit connection and initialize things appropriately.
3380 * If it's a rendezvous stream, call connection_exit_connect() on
3383 * For general streams, call dns_resolve() on it first, and only call
3384 * connection_exit_connect() if the dns answer is already known.
3386 * Note that we don't call connection_add() on the new stream! We wait
3387 * for connection_exit_connect() to do that.
3389 * Return -(some circuit end reason) if we want to tear down <b>circ</b>.
3393 connection_exit_begin_conn(cell_t
*cell
, circuit_t
*circ
)
3395 edge_connection_t
*n_stream
;
3397 char *address
= NULL
;
3399 or_circuit_t
*or_circ
= NULL
;
3400 origin_circuit_t
*origin_circ
= NULL
;
3401 crypt_path_t
*layer_hint
= NULL
;
3402 const or_options_t
*options
= get_options();
3405 uint8_t end_reason
=0;
3407 assert_circuit_ok(circ
);
3408 if (!CIRCUIT_IS_ORIGIN(circ
)) {
3409 or_circ
= TO_OR_CIRCUIT(circ
);
3411 tor_assert(circ
->purpose
== CIRCUIT_PURPOSE_S_REND_JOINED
);
3412 origin_circ
= TO_ORIGIN_CIRCUIT(circ
);
3413 layer_hint
= origin_circ
->cpath
->prev
;
3416 relay_header_unpack(&rh
, cell
->payload
);
3417 if (rh
.length
> RELAY_PAYLOAD_SIZE
)
3418 return -END_CIRC_REASON_TORPROTOCOL
;
3420 if (!server_mode(options
) &&
3421 circ
->purpose
!= CIRCUIT_PURPOSE_S_REND_JOINED
) {
3422 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
3423 "Relay begin cell at non-server. Closing.");
3424 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
3425 END_STREAM_REASON_EXITPOLICY
, NULL
);
3429 rv
= begin_cell_parse(cell
, &bcell
, &end_reason
);
3431 return -END_CIRC_REASON_TORPROTOCOL
;
3432 } else if (rv
== -1) {
3433 tor_free(bcell
.address
);
3434 relay_send_end_cell_from_edge(rh
.stream_id
, circ
, end_reason
, layer_hint
);
3438 if (! bcell
.is_begindir
) {
3439 /* Steal reference */
3440 address
= bcell
.address
;
3443 if (or_circ
&& or_circ
->p_chan
) {
3444 const int client_chan
= channel_is_client(or_circ
->p_chan
);
3446 (!connection_or_digest_is_known_relay(
3447 or_circ
->p_chan
->identity_digest
) &&
3448 should_refuse_unknown_exits(options
)))) {
3449 /* Don't let clients use us as a single-hop proxy. It attracts
3450 * attackers and users who'd be better off with, well, single-hop
3452 log_fn(LOG_PROTOCOL_WARN
, LD_PROTOCOL
,
3453 "Attempt by %s to open a stream %s. Closing.",
3454 safe_str(channel_get_canonical_remote_descr(or_circ
->p_chan
)),
3455 client_chan
? "on first hop of circuit" :
3456 "from unknown relay");
3457 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
3459 END_STREAM_REASON_TORPROTOCOL
:
3460 END_STREAM_REASON_MISC
,
3466 } else if (rh
.command
== RELAY_COMMAND_BEGIN_DIR
) {
3467 if (!directory_permits_begindir_requests(options
) ||
3468 circ
->purpose
!= CIRCUIT_PURPOSE_OR
) {
3469 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
3470 END_STREAM_REASON_NOTDIRECTORY
, layer_hint
);
3473 /* Make sure to get the 'real' address of the previous hop: the
3474 * caller might want to know whether the remote IP address has changed,
3475 * and we might already have corrected base_.addr[ess] for the relay's
3476 * canonical IP address. */
3477 if (or_circ
&& or_circ
->p_chan
)
3478 address
= tor_strdup(channel_get_actual_remote_address(or_circ
->p_chan
));
3480 address
= tor_strdup("127.0.0.1");
3481 port
= 1; /* XXXX This value is never actually used anywhere, and there
3482 * isn't "really" a connection here. But we
3483 * need to set it to something nonzero. */
3485 log_warn(LD_BUG
, "Got an unexpected command %d", (int)rh
.command
);
3486 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
3487 END_STREAM_REASON_INTERNAL
, layer_hint
);
3491 if (! options
->IPv6Exit
) {
3492 /* I don't care if you prefer IPv6; I can't give you any. */
3493 bcell
.flags
&= ~BEGIN_FLAG_IPV6_PREFERRED
;
3494 /* If you don't want IPv4, I can't help. */
3495 if (bcell
.flags
& BEGIN_FLAG_IPV4_NOT_OK
) {
3497 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
3498 END_STREAM_REASON_EXITPOLICY
, layer_hint
);
3503 log_debug(LD_EXIT
,"Creating new exit connection.");
3504 /* The 'AF_INET' here is temporary; we might need to change it later in
3505 * connection_exit_connect(). */
3506 n_stream
= edge_connection_new(CONN_TYPE_EXIT
, AF_INET
);
3508 /* Remember the tunneled request ID in the new edge connection, so that
3509 * we can measure download times. */
3510 n_stream
->dirreq_id
= circ
->dirreq_id
;
3512 n_stream
->base_
.purpose
= EXIT_PURPOSE_CONNECT
;
3513 n_stream
->begincell_flags
= bcell
.flags
;
3514 n_stream
->stream_id
= rh
.stream_id
;
3515 n_stream
->base_
.port
= port
;
3516 /* leave n_stream->s at -1, because it's not yet valid */
3517 n_stream
->package_window
= STREAMWINDOW_START
;
3518 n_stream
->deliver_window
= STREAMWINDOW_START
;
3520 if (circ
->purpose
== CIRCUIT_PURPOSE_S_REND_JOINED
) {
3522 /* We handle this circuit and stream in this function for all supported
3523 * hidden service version. */
3524 return handle_hs_exit_conn(circ
, n_stream
);
3526 tor_strlower(address
);
3527 n_stream
->base_
.address
= address
;
3528 n_stream
->base_
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
3529 /* default to failed, change in dns_resolve if it turns out not to fail */
3531 if (we_are_hibernating()) {
3532 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
3533 END_STREAM_REASON_HIBERNATING
, NULL
);
3534 connection_free_(TO_CONN(n_stream
));
3538 n_stream
->on_circuit
= circ
;
3540 if (rh
.command
== RELAY_COMMAND_BEGIN_DIR
) {
3541 tor_addr_t tmp_addr
;
3542 tor_assert(or_circ
);
3543 if (or_circ
->p_chan
&&
3544 channel_get_addr_if_possible(or_circ
->p_chan
, &tmp_addr
)) {
3545 tor_addr_copy(&n_stream
->base_
.addr
, &tmp_addr
);
3547 return connection_exit_connect_dir(n_stream
);
3550 log_debug(LD_EXIT
,"about to start the dns_resolve().");
3552 /* send it off to the gethostbyname farm */
3553 switch (dns_resolve(n_stream
)) {
3554 case 1: /* resolve worked; now n_stream is attached to circ. */
3555 assert_circuit_ok(circ
);
3556 log_debug(LD_EXIT
,"about to call connection_exit_connect().");
3557 connection_exit_connect(n_stream
);
3559 case -1: /* resolve failed */
3560 relay_send_end_cell_from_edge(rh
.stream_id
, circ
,
3561 END_STREAM_REASON_RESOLVEFAILED
, NULL
);
3562 /* n_stream got freed. don't touch it. */
3564 case 0: /* resolve added to pending list */
3565 assert_circuit_ok(circ
);
3572 * Called when we receive a RELAY_COMMAND_RESOLVE cell 'cell' along the
3573 * circuit <b>circ</b>;
3574 * begin resolving the hostname, and (eventually) reply with a RESOLVED cell.
3577 connection_exit_begin_resolve(cell_t
*cell
, or_circuit_t
*circ
)
3579 edge_connection_t
*dummy_conn
;
3582 assert_circuit_ok(TO_CIRCUIT(circ
));
3583 relay_header_unpack(&rh
, cell
->payload
);
3584 if (rh
.length
> RELAY_PAYLOAD_SIZE
)
3587 /* This 'dummy_conn' only exists to remember the stream ID
3588 * associated with the resolve request; and to make the
3589 * implementation of dns.c more uniform. (We really only need to
3590 * remember the circuit, the stream ID, and the hostname to be
3591 * resolved; but if we didn't store them in a connection like this,
3592 * the housekeeping in dns.c would get way more complicated.)
3594 dummy_conn
= edge_connection_new(CONN_TYPE_EXIT
, AF_INET
);
3595 dummy_conn
->stream_id
= rh
.stream_id
;
3596 dummy_conn
->base_
.address
= tor_strndup(
3597 (char*)cell
->payload
+RELAY_HEADER_SIZE
,
3599 dummy_conn
->base_
.port
= 0;
3600 dummy_conn
->base_
.state
= EXIT_CONN_STATE_RESOLVEFAILED
;
3601 dummy_conn
->base_
.purpose
= EXIT_PURPOSE_RESOLVE
;
3603 dummy_conn
->on_circuit
= TO_CIRCUIT(circ
);
3605 /* send it off to the gethostbyname farm */
3606 switch (dns_resolve(dummy_conn
)) {
3607 case -1: /* Impossible to resolve; a resolved cell was sent. */
3608 /* Connection freed; don't touch it. */
3610 case 1: /* The result was cached; a resolved cell was sent. */
3611 if (!dummy_conn
->base_
.marked_for_close
)
3612 connection_free_(TO_CONN(dummy_conn
));
3614 case 0: /* resolve added to pending list */
3615 assert_circuit_ok(TO_CIRCUIT(circ
));
3621 /** Helper: Return true and set *<b>why_rejected</b> to an optional clarifying
3622 * message message iff we do not allow connections to <b>addr</b>:<b>port</b>.
3625 my_exit_policy_rejects(const tor_addr_t
*addr
,
3627 const char **why_rejected
)
3629 if (router_compare_to_my_exit_policy(addr
, port
)) {
3632 } else if (tor_addr_family(addr
) == AF_INET6
&& !get_options()->IPv6Exit
) {
3633 *why_rejected
= " (IPv6 address without IPv6Exit configured)";
3639 /** Connect to conn's specified addr and port. If it worked, conn
3640 * has now been added to the connection_array.
3642 * Send back a connected cell. Include the resolved IP of the destination
3643 * address, but <em>only</em> if it's a general exit stream. (Rendezvous
3644 * streams must not reveal what IP they connected to.)
3647 connection_exit_connect(edge_connection_t
*edge_conn
)
3649 const tor_addr_t
*addr
;
3651 connection_t
*conn
= TO_CONN(edge_conn
);
3652 int socket_error
= 0, result
;
3653 const char *why_failed_exit_policy
= NULL
;
3655 /* Apply exit policy to non-rendezvous connections. */
3656 if (! connection_edge_is_rendezvous_stream(edge_conn
) &&
3657 my_exit_policy_rejects(&edge_conn
->base_
.addr
,
3658 edge_conn
->base_
.port
,
3659 &why_failed_exit_policy
)) {
3660 if (BUG(!why_failed_exit_policy
))
3661 why_failed_exit_policy
= "";
3662 log_info(LD_EXIT
,"%s:%d failed exit policy%s. Closing.",
3663 escaped_safe_str_client(conn
->address
), conn
->port
,
3664 why_failed_exit_policy
);
3665 connection_edge_end(edge_conn
, END_STREAM_REASON_EXITPOLICY
);
3666 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn
), edge_conn
);
3667 connection_free(conn
);
3671 #ifdef HAVE_SYS_UN_H
3672 if (conn
->socket_family
!= AF_UNIX
) {
3675 #endif /* defined(HAVE_SYS_UN_H) */
3679 if (tor_addr_family(addr
) == AF_INET6
)
3680 conn
->socket_family
= AF_INET6
;
3682 log_debug(LD_EXIT
, "about to try connecting");
3683 result
= connection_connect(conn
, conn
->address
,
3684 addr
, port
, &socket_error
);
3685 #ifdef HAVE_SYS_UN_H
3688 * In the AF_UNIX case, we expect to have already had conn->port = 1,
3689 * tor_addr_make_unspec(conn->addr) (cf. the way we mark in the incoming
3690 * case in connection_handle_listener_read()), and conn->address should
3691 * have the socket path to connect to.
3693 tor_assert(conn
->address
&& strlen(conn
->address
) > 0);
3695 log_debug(LD_EXIT
, "about to try connecting");
3696 result
= connection_connect_unix(conn
, conn
->address
, &socket_error
);
3697 #endif /* defined(HAVE_SYS_UN_H) */
3702 int reason
= errno_to_stream_end_reason(socket_error
);
3703 connection_edge_end(edge_conn
, reason
);
3704 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn
), edge_conn
);
3705 connection_free(conn
);
3709 conn
->state
= EXIT_CONN_STATE_CONNECTING
;
3711 connection_watch_events(conn
, READ_EVENT
| WRITE_EVENT
);
3712 /* writable indicates finish;
3713 * readable/error indicates broken link in windows-land. */
3715 /* case 1: fall through */
3718 conn
->state
= EXIT_CONN_STATE_OPEN
;
3719 if (connection_get_outbuf_len(conn
)) {
3720 /* in case there are any queued data cells, from e.g. optimistic data */
3721 connection_watch_events(conn
, READ_EVENT
|WRITE_EVENT
);
3723 connection_watch_events(conn
, READ_EVENT
);
3726 /* also, deliver a 'connected' cell back through the circuit. */
3727 if (connection_edge_is_rendezvous_stream(edge_conn
)) {
3728 /* don't send an address back! */
3729 connection_edge_send_command(edge_conn
,
3730 RELAY_COMMAND_CONNECTED
,
3732 } else { /* normal stream */
3733 uint8_t connected_payload
[MAX_CONNECTED_CELL_PAYLOAD_LEN
];
3734 int connected_payload_len
=
3735 connected_cell_format_payload(connected_payload
, &conn
->addr
,
3736 edge_conn
->address_ttl
);
3737 if (connected_payload_len
< 0) {
3738 connection_edge_end(edge_conn
, END_STREAM_REASON_INTERNAL
);
3739 circuit_detach_stream(circuit_get_by_edge_conn(edge_conn
), edge_conn
);
3740 connection_free(conn
);
3744 connection_edge_send_command(edge_conn
,
3745 RELAY_COMMAND_CONNECTED
,
3746 (char*)connected_payload
,
3747 connected_payload_len
);
3751 /** Given an exit conn that should attach to us as a directory server, open a
3752 * bridge connection with a linked connection pair, create a new directory
3753 * conn, and join them together. Return 0 on success (or if there was an
3754 * error we could send back an end cell for). Return -(some circuit end
3755 * reason) if the circuit needs to be torn down. Either connects
3756 * <b>exitconn</b>, frees it, or marks it, as appropriate.
3759 connection_exit_connect_dir(edge_connection_t
*exitconn
)
3761 dir_connection_t
*dirconn
= NULL
;
3762 or_circuit_t
*circ
= TO_OR_CIRCUIT(exitconn
->on_circuit
);
3764 log_info(LD_EXIT
, "Opening local connection for anonymized directory exit");
3766 exitconn
->base_
.state
= EXIT_CONN_STATE_OPEN
;
3768 dirconn
= dir_connection_new(tor_addr_family(&exitconn
->base_
.addr
));
3770 tor_addr_copy(&dirconn
->base_
.addr
, &exitconn
->base_
.addr
);
3771 dirconn
->base_
.port
= 0;
3772 dirconn
->base_
.address
= tor_strdup(exitconn
->base_
.address
);
3773 dirconn
->base_
.type
= CONN_TYPE_DIR
;
3774 dirconn
->base_
.purpose
= DIR_PURPOSE_SERVER
;
3775 dirconn
->base_
.state
= DIR_CONN_STATE_SERVER_COMMAND_WAIT
;
3777 /* Note that the new dir conn belongs to the same tunneled request as
3778 * the edge conn, so that we can measure download times. */
3779 dirconn
->dirreq_id
= exitconn
->dirreq_id
;
3781 connection_link_connections(TO_CONN(dirconn
), TO_CONN(exitconn
));
3783 if (connection_add(TO_CONN(exitconn
))<0) {
3784 connection_edge_end(exitconn
, END_STREAM_REASON_RESOURCELIMIT
);
3785 connection_free_(TO_CONN(exitconn
));
3786 connection_free_(TO_CONN(dirconn
));
3790 /* link exitconn to circ, now that we know we can use it. */
3791 exitconn
->next_stream
= circ
->n_streams
;
3792 circ
->n_streams
= exitconn
;
3794 if (connection_add(TO_CONN(dirconn
))<0) {
3795 connection_edge_end(exitconn
, END_STREAM_REASON_RESOURCELIMIT
);
3796 connection_close_immediate(TO_CONN(exitconn
));
3797 connection_mark_for_close(TO_CONN(exitconn
));
3798 connection_free_(TO_CONN(dirconn
));
3802 connection_start_reading(TO_CONN(dirconn
));
3803 connection_start_reading(TO_CONN(exitconn
));
3805 if (connection_edge_send_command(exitconn
,
3806 RELAY_COMMAND_CONNECTED
, NULL
, 0) < 0) {
3807 connection_mark_for_close(TO_CONN(exitconn
));
3808 connection_mark_for_close(TO_CONN(dirconn
));
3815 /** Return 1 if <b>conn</b> is a rendezvous stream, or 0 if
3816 * it is a general stream.
3819 connection_edge_is_rendezvous_stream(const edge_connection_t
*conn
)
3822 /* It should not be possible to set both of these structs */
3823 tor_assert_nonfatal(!(conn
->rend_data
&& conn
->hs_ident
));
3825 if (conn
->rend_data
|| conn
->hs_ident
) {
3831 /** Return 1 if router <b>exit_node</b> is likely to allow stream <b>conn</b>
3832 * to exit from it, or 0 if it probably will not allow it.
3833 * (We might be uncertain if conn's destination address has not yet been
3837 connection_ap_can_use_exit(const entry_connection_t
*conn
,
3838 const node_t
*exit_node
)
3840 const or_options_t
*options
= get_options();
3843 tor_assert(conn
->socks_request
);
3844 tor_assert(exit_node
);
3846 /* If a particular exit node has been requested for the new connection,
3847 * make sure the exit node of the existing circuit matches exactly.
3849 if (conn
->chosen_exit_name
) {
3850 const node_t
*chosen_exit
=
3851 node_get_by_nickname(conn
->chosen_exit_name
, 0);
3852 if (!chosen_exit
|| tor_memneq(chosen_exit
->identity
,
3853 exit_node
->identity
, DIGEST_LEN
)) {
3855 // log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
3856 // conn->chosen_exit_name, exit->nickname);
3861 if (conn
->use_begindir
) {
3862 /* Internal directory fetches do not count as exiting. */
3866 if (conn
->socks_request
->command
== SOCKS_COMMAND_CONNECT
) {
3867 tor_addr_t addr
, *addrp
= NULL
;
3868 addr_policy_result_t r
;
3869 if (0 == tor_addr_parse(&addr
, conn
->socks_request
->address
)) {
3871 } else if (!conn
->entry_cfg
.ipv4_traffic
&& conn
->entry_cfg
.ipv6_traffic
) {
3872 tor_addr_make_null(&addr
, AF_INET6
);
3874 } else if (conn
->entry_cfg
.ipv4_traffic
&& !conn
->entry_cfg
.ipv6_traffic
) {
3875 tor_addr_make_null(&addr
, AF_INET
);
3878 r
= compare_tor_addr_to_node_policy(addrp
, conn
->socks_request
->port
,
3880 if (r
== ADDR_POLICY_REJECTED
)
3881 return 0; /* We know the address, and the exit policy rejects it. */
3882 if (r
== ADDR_POLICY_PROBABLY_REJECTED
&& !conn
->chosen_exit_name
)
3883 return 0; /* We don't know the addr, but the exit policy rejects most
3884 * addresses with this port. Since the user didn't ask for
3885 * this node, err on the side of caution. */
3886 } else if (SOCKS_COMMAND_IS_RESOLVE(conn
->socks_request
->command
)) {
3887 /* Don't send DNS requests to non-exit servers by default. */
3888 if (!conn
->chosen_exit_name
&& node_exit_policy_rejects_all(exit_node
))
3891 if (routerset_contains_node(options
->ExcludeExitNodesUnion_
, exit_node
)) {
3892 /* Not a suitable exit. Refuse it. */
3899 /** If address is of the form "y.onion" with a well-formed handle y:
3900 * Put a NUL after y, lower-case it, and return ONION_V2_HOSTNAME or
3901 * ONION_V3_HOSTNAME depending on the HS version.
3903 * If address is of the form "x.y.onion" with a well-formed handle x:
3904 * Drop "x.", put a NUL after y, lower-case it, and return
3905 * ONION_V2_HOSTNAME or ONION_V3_HOSTNAME depending on the HS version.
3907 * If address is of the form "y.onion" with a badly-formed handle y:
3908 * Return BAD_HOSTNAME and log a message.
3910 * If address is of the form "y.exit":
3911 * Put a NUL after y and return EXIT_HOSTNAME.
3914 * Return NORMAL_HOSTNAME and change nothing.
3917 parse_extended_hostname(char *address
)
3921 char query
[HS_SERVICE_ADDR_LEN_BASE32
+1];
3923 s
= strrchr(address
,'.');
3925 return NORMAL_HOSTNAME
; /* no dot, thus normal */
3926 if (!strcmp(s
+1,"exit")) {
3927 *s
= 0; /* NUL-terminate it */
3928 return EXIT_HOSTNAME
; /* .exit */
3930 if (strcmp(s
+1,"onion"))
3931 return NORMAL_HOSTNAME
; /* neither .exit nor .onion, thus normal */
3933 /* so it is .onion */
3934 *s
= 0; /* NUL-terminate it */
3935 /* locate a 'sub-domain' component, in order to remove it */
3936 q
= strrchr(address
, '.');
3938 goto failed
; /* reject sub-domain, as DNS does */
3940 q
= (NULL
== q
) ? address
: q
+ 1;
3941 if (strlcpy(query
, q
, HS_SERVICE_ADDR_LEN_BASE32
+1) >=
3942 HS_SERVICE_ADDR_LEN_BASE32
+1)
3945 memmove(address
, q
, strlen(q
) + 1 /* also get \0 */);
3947 if (rend_valid_v2_service_id(query
)) {
3948 return ONION_V2_HOSTNAME
; /* success */
3950 if (hs_address_is_valid(query
)) {
3951 return ONION_V3_HOSTNAME
;
3954 /* otherwise, return to previous state and return 0 */
3956 log_warn(LD_APP
, "Invalid onion hostname %s; rejecting",
3957 safe_str_client(address
));
3958 return BAD_HOSTNAME
;
3961 /** Return true iff the (possibly NULL) <b>alen</b>-byte chunk of memory at
3962 * <b>a</b> is equal to the (possibly NULL) <b>blen</b>-byte chunk of memory
3965 memeq_opt(const char *a
, size_t alen
, const char *b
, size_t blen
)
3969 } else if (b
== NULL
) {
3971 } else if (alen
!= blen
) {
3974 return tor_memeq(a
, b
, alen
);
3979 * Return true iff none of the isolation flags and fields in <b>conn</b>
3980 * should prevent it from being attached to <b>circ</b>.
3983 connection_edge_compatible_with_circuit(const entry_connection_t
*conn
,
3984 const origin_circuit_t
*circ
)
3986 const uint8_t iso
= conn
->entry_cfg
.isolation_flags
;
3987 const socks_request_t
*sr
= conn
->socks_request
;
3989 /* If circ has never been used for an isolated connection, we can
3990 * totally use it for this one. */
3991 if (!circ
->isolation_values_set
)
3994 /* If circ has been used for connections having more than one value
3995 * for some field f, it will have the corresponding bit set in
3996 * isolation_flags_mixed. If isolation_flags_mixed has any bits
3997 * in common with iso, then conn must be isolated from at least
3998 * one stream that has been attached to circ. */
3999 if ((iso
& circ
->isolation_flags_mixed
) != 0) {
4000 /* For at least one field where conn is isolated, the circuit
4001 * already has mixed streams. */
4005 if (! conn
->original_dest_address
) {
4006 log_warn(LD_BUG
, "Reached connection_edge_compatible_with_circuit without "
4007 "having set conn->original_dest_address");
4008 ((entry_connection_t
*)conn
)->original_dest_address
=
4009 tor_strdup(conn
->socks_request
->address
);
4012 if ((iso
& ISO_STREAM
) &&
4013 (circ
->associated_isolated_stream_global_id
!=
4014 ENTRY_TO_CONN(conn
)->global_identifier
))
4017 if ((iso
& ISO_DESTPORT
) && conn
->socks_request
->port
!= circ
->dest_port
)
4019 if ((iso
& ISO_DESTADDR
) &&
4020 strcasecmp(conn
->original_dest_address
, circ
->dest_address
))
4022 if ((iso
& ISO_SOCKSAUTH
) &&
4023 (! memeq_opt(sr
->username
, sr
->usernamelen
,
4024 circ
->socks_username
, circ
->socks_username_len
) ||
4025 ! memeq_opt(sr
->password
, sr
->passwordlen
,
4026 circ
->socks_password
, circ
->socks_password_len
)))
4028 if ((iso
& ISO_CLIENTPROTO
) &&
4029 (conn
->socks_request
->listener_type
!= circ
->client_proto_type
||
4030 conn
->socks_request
->socks_version
!= circ
->client_proto_socksver
))
4032 if ((iso
& ISO_CLIENTADDR
) &&
4033 !tor_addr_eq(&ENTRY_TO_CONN(conn
)->addr
, &circ
->client_addr
))
4035 if ((iso
& ISO_SESSIONGRP
) &&
4036 conn
->entry_cfg
.session_group
!= circ
->session_group
)
4038 if ((iso
& ISO_NYM_EPOCH
) && conn
->nym_epoch
!= circ
->nym_epoch
)
4045 * If <b>dry_run</b> is false, update <b>circ</b>'s isolation flags and fields
4046 * to reflect having had <b>conn</b> attached to it, and return 0. Otherwise,
4047 * if <b>dry_run</b> is true, then make no changes to <b>circ</b>, and return
4048 * a bitfield of isolation flags that we would have to set in
4049 * isolation_flags_mixed to add <b>conn</b> to <b>circ</b>, or -1 if
4050 * <b>circ</b> has had no streams attached to it.
4053 connection_edge_update_circuit_isolation(const entry_connection_t
*conn
,
4054 origin_circuit_t
*circ
,
4057 const socks_request_t
*sr
= conn
->socks_request
;
4058 if (! conn
->original_dest_address
) {
4059 log_warn(LD_BUG
, "Reached connection_update_circuit_isolation without "
4060 "having set conn->original_dest_address");
4061 ((entry_connection_t
*)conn
)->original_dest_address
=
4062 tor_strdup(conn
->socks_request
->address
);
4065 if (!circ
->isolation_values_set
) {
4068 circ
->associated_isolated_stream_global_id
=
4069 ENTRY_TO_CONN(conn
)->global_identifier
;
4070 circ
->dest_port
= conn
->socks_request
->port
;
4071 circ
->dest_address
= tor_strdup(conn
->original_dest_address
);
4072 circ
->client_proto_type
= conn
->socks_request
->listener_type
;
4073 circ
->client_proto_socksver
= conn
->socks_request
->socks_version
;
4074 tor_addr_copy(&circ
->client_addr
, &ENTRY_TO_CONN(conn
)->addr
);
4075 circ
->session_group
= conn
->entry_cfg
.session_group
;
4076 circ
->nym_epoch
= conn
->nym_epoch
;
4077 circ
->socks_username
= sr
->username
?
4078 tor_memdup(sr
->username
, sr
->usernamelen
) : NULL
;
4079 circ
->socks_password
= sr
->password
?
4080 tor_memdup(sr
->password
, sr
->passwordlen
) : NULL
;
4081 circ
->socks_username_len
= sr
->usernamelen
;
4082 circ
->socks_password_len
= sr
->passwordlen
;
4084 circ
->isolation_values_set
= 1;
4088 if (conn
->socks_request
->port
!= circ
->dest_port
)
4089 mixed
|= ISO_DESTPORT
;
4090 if (strcasecmp(conn
->original_dest_address
, circ
->dest_address
))
4091 mixed
|= ISO_DESTADDR
;
4092 if (!memeq_opt(sr
->username
, sr
->usernamelen
,
4093 circ
->socks_username
, circ
->socks_username_len
) ||
4094 !memeq_opt(sr
->password
, sr
->passwordlen
,
4095 circ
->socks_password
, circ
->socks_password_len
))
4096 mixed
|= ISO_SOCKSAUTH
;
4097 if ((conn
->socks_request
->listener_type
!= circ
->client_proto_type
||
4098 conn
->socks_request
->socks_version
!= circ
->client_proto_socksver
))
4099 mixed
|= ISO_CLIENTPROTO
;
4100 if (!tor_addr_eq(&ENTRY_TO_CONN(conn
)->addr
, &circ
->client_addr
))
4101 mixed
|= ISO_CLIENTADDR
;
4102 if (conn
->entry_cfg
.session_group
!= circ
->session_group
)
4103 mixed
|= ISO_SESSIONGRP
;
4104 if (conn
->nym_epoch
!= circ
->nym_epoch
)
4105 mixed
|= ISO_NYM_EPOCH
;
4110 if ((mixed
& conn
->entry_cfg
.isolation_flags
) != 0) {
4111 log_warn(LD_BUG
, "Updating a circuit with seemingly incompatible "
4112 "isolation flags.");
4114 circ
->isolation_flags_mixed
|= mixed
;
4120 * Clear the isolation settings on <b>circ</b>.
4122 * This only works on an open circuit that has never had a stream attached to
4123 * it, and whose isolation settings are hypothetical. (We set hypothetical
4124 * isolation settings on circuits as we're launching them, so that we
4125 * know whether they can handle more streams or whether we need to launch
4126 * even more circuits. Once the circuit is open, if it turns out that
4127 * we no longer have any streams to attach to it, we clear the isolation flags
4128 * and data so that other streams can have a chance.)
4131 circuit_clear_isolation(origin_circuit_t
*circ
)
4133 if (circ
->isolation_any_streams_attached
) {
4134 log_warn(LD_BUG
, "Tried to clear the isolation status of a dirty circuit");
4137 if (TO_CIRCUIT(circ
)->state
!= CIRCUIT_STATE_OPEN
) {
4138 log_warn(LD_BUG
, "Tried to clear the isolation status of a non-open "
4143 circ
->isolation_values_set
= 0;
4144 circ
->isolation_flags_mixed
= 0;
4145 circ
->associated_isolated_stream_global_id
= 0;
4146 circ
->client_proto_type
= 0;
4147 circ
->client_proto_socksver
= 0;
4148 circ
->dest_port
= 0;
4149 tor_addr_make_unspec(&circ
->client_addr
);
4150 tor_free(circ
->dest_address
);
4151 circ
->session_group
= -1;
4152 circ
->nym_epoch
= 0;
4153 if (circ
->socks_username
) {
4154 memwipe(circ
->socks_username
, 0x11, circ
->socks_username_len
);
4155 tor_free(circ
->socks_username
);
4157 if (circ
->socks_password
) {
4158 memwipe(circ
->socks_password
, 0x05, circ
->socks_password_len
);
4159 tor_free(circ
->socks_password
);
4161 circ
->socks_username_len
= circ
->socks_password_len
= 0;
4164 /** Free all storage held in module-scoped variables for connection_edge.c */
4166 connection_edge_free_all(void)
4168 untried_pending_connections
= 0;
4169 smartlist_free(pending_entry_connections
);
4170 pending_entry_connections
= NULL
;