tor  0.4.2.0-alpha-dev
connection_edge.c
Go to the documentation of this file.
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-2019, The Tor Project, Inc. */
5 /* See LICENSE for licensing information */
6 
56 #define CONNECTION_EDGE_PRIVATE
57 
58 #include "core/or/or.h"
59 
60 #include "lib/err/backtrace.h"
61 
62 #include "app/config/config.h"
64 #include "core/mainloop/mainloop.h"
65 #include "core/mainloop/netstatus.h"
66 #include "core/or/channel.h"
67 #include "core/or/circuitbuild.h"
68 #include "core/or/circuitlist.h"
69 #include "core/or/circuituse.h"
70 #include "core/or/circuitpadding.h"
72 #include "core/or/connection_or.h"
73 #include "core/or/policies.h"
74 #include "core/or/reasons.h"
75 #include "core/or/relay.h"
76 #include "core/or/sendme.h"
77 #include "core/proto/proto_http.h"
78 #include "core/proto/proto_socks.h"
79 #include "feature/client/addressmap.h"
80 #include "feature/client/circpathbias.h"
81 #include "feature/client/dnsserv.h"
86 #include "feature/hs/hs_cache.h"
87 #include "feature/hs/hs_circuit.h"
88 #include "feature/hs/hs_client.h"
89 #include "feature/hs/hs_common.h"
94 #include "feature/nodelist/routerset.h"
95 #include "feature/relay/dns.h"
96 #include "feature/relay/router.h"
101 #include "feature/stats/predict_ports.h"
102 #include "feature/stats/rephist.h"
103 #include "lib/buf/buffers.h"
105 
106 #include "core/or/cell_st.h"
107 #include "core/or/cpath_build_state_st.h"
108 #include "feature/dircommon/dir_connection_st.h"
109 #include "core/or/entry_connection_st.h"
110 #include "core/or/extend_info_st.h"
111 #include "feature/nodelist/node_st.h"
112 #include "core/or/or_circuit_st.h"
113 #include "core/or/origin_circuit_st.h"
114 #include "core/or/half_edge_st.h"
115 #include "core/or/socks_request_st.h"
117 
118 #ifdef HAVE_LINUX_TYPES_H
119 #include <linux/types.h>
120 #endif
121 #ifdef HAVE_LINUX_NETFILTER_IPV4_H
122 #include <linux/netfilter_ipv4.h>
123 #define TRANS_NETFILTER
124 #define TRANS_NETFILTER_IPV4
125 #endif
126 
127 #ifdef HAVE_LINUX_IF_H
128 #include <linux/if.h>
129 #endif
130 
131 #ifdef HAVE_LINUX_NETFILTER_IPV6_IP6_TABLES_H
132 #include <linux/netfilter_ipv6/ip6_tables.h>
133 #if defined(IP6T_SO_ORIGINAL_DST)
134 #define TRANS_NETFILTER
135 #define TRANS_NETFILTER_IPV6
136 #endif
137 #endif /* defined(HAVE_LINUX_NETFILTER_IPV6_IP6_TABLES_H) */
138 
139 #ifdef HAVE_FCNTL_H
140 #include <fcntl.h>
141 #endif
142 #ifdef HAVE_SYS_IOCTL_H
143 #include <sys/ioctl.h>
144 #endif
145 #ifdef HAVE_SYS_PARAM_H
146 #include <sys/param.h>
147 #endif
148 
149 #if defined(HAVE_NET_IF_H) && defined(HAVE_NET_PFVAR_H)
150 #include <net/if.h>
151 #include <net/pfvar.h>
152 #define TRANS_PF
153 #endif
154 
155 #ifdef IP_TRANSPARENT
156 #define TRANS_TPROXY
157 #endif
158 
159 #define SOCKS4_GRANTED 90
160 #define SOCKS4_REJECT 91
161 
164 static int connection_exit_connect_dir(edge_connection_t *exitconn);
165 static int consider_plaintext_ports(entry_connection_t *conn, uint16_t port);
167 
172 {
173  tor_assert(c->magic == EDGE_CONNECTION_MAGIC ||
174  c->magic == ENTRY_CONNECTION_MAGIC);
175  return DOWNCAST(edge_connection_t, c);
176 }
177 
179 TO_ENTRY_CONN(connection_t *c)
180 {
181  tor_assert(c->magic == ENTRY_CONNECTION_MAGIC);
182  return (entry_connection_t*) SUBTYPE_P(c, entry_connection_t, edge_.base_);
183 }
184 
186 EDGE_TO_ENTRY_CONN(edge_connection_t *c)
187 {
188  tor_assert(c->base_.magic == ENTRY_CONNECTION_MAGIC);
189  return (entry_connection_t*) SUBTYPE_P(c, entry_connection_t, edge_);
190 }
191 
197 connection_mark_unattached_ap_,(entry_connection_t *conn, int endreason,
198  int line, const char *file))
199 {
200  connection_t *base_conn = ENTRY_TO_CONN(conn);
201  edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
202  tor_assert(base_conn->type == CONN_TYPE_AP);
203  ENTRY_TO_EDGE_CONN(conn)->edge_has_sent_end = 1; /* no circ yet */
204 
205  /* If this is a rendezvous stream and it is failing without ever
206  * being attached to a circuit, assume that an attempt to connect to
207  * the destination hidden service has just ended.
208  *
209  * XXXX This condition doesn't limit to only streams failing
210  * without ever being attached. That sloppiness should be harmless,
211  * but we should fix it someday anyway. */
212  if ((edge_conn->on_circuit != NULL || edge_conn->edge_has_sent_end) &&
214  if (edge_conn->rend_data) {
216  }
217  }
218 
219  if (base_conn->marked_for_close) {
220  /* This call will warn as appropriate. */
221  connection_mark_for_close_(base_conn, line, file);
222  return;
223  }
224 
225  if (!conn->socks_request->has_finished) {
227  log_warn(LD_BUG,
228  "stream (marked at %s:%d) sending two socks replies?",
229  file, line);
230 
231  if (SOCKS_COMMAND_IS_CONNECT(conn->socks_request->command))
232  connection_ap_handshake_socks_reply(conn, NULL, 0, endreason);
233  else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command))
234  connection_ap_handshake_socks_resolved(conn,
235  RESOLVED_TYPE_ERROR_TRANSIENT,
236  0, NULL, -1, -1);
237  else /* unknown or no handshake at all. send no response. */
238  conn->socks_request->has_finished = 1;
239  }
240 
241  connection_mark_and_flush_(base_conn, line, file);
242 
243  ENTRY_TO_EDGE_CONN(conn)->end_reason = endreason;
244 }
245 
248 int
250 {
251  if (connection_get_inbuf_len(TO_CONN(conn)) &&
253  /* it still has stuff to process. don't let it die yet. */
254  return 0;
255  }
256  log_info(LD_EDGE,"conn (fd "TOR_SOCKET_T_FORMAT") reached eof. Closing.",
257  conn->base_.s);
258  if (!conn->base_.marked_for_close) {
259  /* only mark it if not already marked. it's possible to
260  * get the 'end' right around when the client hangs up on us. */
261  connection_edge_end(conn, END_STREAM_REASON_DONE);
262  if (conn->base_.type == CONN_TYPE_AP) {
263  /* eof, so don't send a socks reply back */
264  if (EDGE_TO_ENTRY_CONN(conn)->socks_request)
265  EDGE_TO_ENTRY_CONN(conn)->socks_request->has_finished = 1;
266  }
267  connection_mark_for_close(TO_CONN(conn));
268  }
269  return 0;
270 }
271 
282 int
284 {
285  tor_assert(conn);
286 
287  switch (conn->base_.state) {
289  if (connection_ap_handshake_process_socks(EDGE_TO_ENTRY_CONN(conn)) <0) {
290  /* already marked */
291  return -1;
292  }
293  return 0;
295  if (connection_ap_process_natd(EDGE_TO_ENTRY_CONN(conn)) < 0) {
296  /* already marked */
297  return -1;
298  }
299  return 0;
301  if (connection_ap_process_http_connect(EDGE_TO_ENTRY_CONN(conn)) < 0) {
302  return -1;
303  }
304  return 0;
305  case AP_CONN_STATE_OPEN:
306  if (! conn->base_.linked) {
307  note_user_activity(approx_time());
308  }
309 
310  /* falls through. */
312  if (connection_edge_package_raw_inbuf(conn, package_partial, NULL) < 0) {
313  /* (We already sent an end cell if possible) */
314  connection_mark_for_close(TO_CONN(conn));
315  return -1;
316  }
317  return 0;
319  if (connection_ap_supports_optimistic_data(EDGE_TO_ENTRY_CONN(conn))) {
320  log_info(LD_EDGE,
321  "data from edge while in '%s' state. Sending it anyway. "
322  "package_partial=%d, buflen=%ld",
323  conn_state_to_string(conn->base_.type, conn->base_.state),
324  package_partial,
325  (long)connection_get_inbuf_len(TO_CONN(conn)));
326  if (connection_edge_package_raw_inbuf(conn, package_partial, NULL)<0) {
327  /* (We already sent an end cell if possible) */
328  connection_mark_for_close(TO_CONN(conn));
329  return -1;
330  }
331  return 0;
332  }
333  /* Fall through if the connection is on a circuit without optimistic
334  * data support. */
335  /* Falls through. */
341  log_info(LD_EDGE,
342  "data from edge while in '%s' state. Leaving it on buffer.",
343  conn_state_to_string(conn->base_.type, conn->base_.state));
344  return 0;
345  }
346  log_warn(LD_BUG,"Got unexpected state %d. Closing.",conn->base_.state);
348  connection_edge_end(conn, END_STREAM_REASON_INTERNAL);
349  connection_mark_for_close(TO_CONN(conn));
350  return -1;
351 }
352 
356 int
358 {
359  if (!conn->base_.marked_for_close) {
360  log_info(LD_EDGE, "CircID %u: At an edge. Marking connection for close.",
361  (unsigned) circ_id);
362  if (conn->base_.type == CONN_TYPE_AP) {
363  entry_connection_t *entry_conn = EDGE_TO_ENTRY_CONN(conn);
364  connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_DESTROY);
366  control_event_stream_status(entry_conn, STREAM_EVENT_CLOSED,
367  END_STREAM_REASON_DESTROY);
369  } else {
370  /* closing the circuit, nothing to send an END to */
371  conn->edge_has_sent_end = 1;
372  conn->end_reason = END_STREAM_REASON_DESTROY;
374  connection_mark_and_flush(TO_CONN(conn));
375  }
376  }
377  conn->cpath_layer = NULL;
378  conn->on_circuit = NULL;
379  return 0;
380 }
381 
386 static int
388  uint8_t reason, crypt_path_t *cpath_layer)
389 {
390  char payload[1];
391 
392  if (CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
393  /* Never send the server an informative reason code; it doesn't need to
394  * know why the client stream is failing. */
395  reason = END_STREAM_REASON_MISC;
396  }
397 
398  payload[0] = (char) reason;
399 
400  /* Note: we have to use relay_send_command_from_edge here, not
401  * connection_edge_end or connection_edge_send_command, since those require
402  * that we have a stream connected to a circuit, and we don't connect to a
403  * circuit until we have a pending/successful resolve. */
404  return relay_send_command_from_edge(stream_id, circ, RELAY_COMMAND_END,
405  payload, 1, cpath_layer);
406 }
407 
408 /* If the connection <b>conn</b> is attempting to connect to an external
409  * destination that is an hidden service and the reason is a connection
410  * refused or timeout, log it so the operator can take appropriate actions.
411  * The log statement is a rate limited warning. */
412 static void
413 warn_if_hs_unreachable(const edge_connection_t *conn, uint8_t reason)
414 {
415  tor_assert(conn);
416 
417  if (conn->base_.type == CONN_TYPE_EXIT &&
419  (reason == END_STREAM_REASON_CONNECTREFUSED ||
420  reason == END_STREAM_REASON_TIMEOUT)) {
421 #define WARN_FAILED_HS_CONNECTION 300
422  static ratelim_t warn_limit = RATELIM_INIT(WARN_FAILED_HS_CONNECTION);
423  char *m;
424  if ((m = rate_limit_log(&warn_limit, approx_time()))) {
425  log_warn(LD_EDGE, "Onion service connection to %s failed (%s)",
426  (conn->base_.socket_family == AF_UNIX) ?
427  safe_str(conn->base_.address) :
428  safe_str(fmt_addrport(&conn->base_.addr, conn->base_.port)),
430  tor_free(m);
431  }
432  }
433 }
434 
442 int
444 {
445  char payload[RELAY_PAYLOAD_SIZE];
446  size_t payload_len=1;
447  circuit_t *circ;
448  uint8_t control_reason = reason;
449 
450  if (conn->edge_has_sent_end) {
451  log_warn(LD_BUG,"(Harmless.) Calling connection_edge_end (reason %d) "
452  "on an already ended stream?", reason);
454  return -1;
455  }
456 
457  if (conn->base_.marked_for_close) {
458  log_warn(LD_BUG,
459  "called on conn that's already marked for close at %s:%d.",
460  conn->base_.marked_for_close_file, conn->base_.marked_for_close);
461  return 0;
462  }
463 
464  circ = circuit_get_by_edge_conn(conn);
465  if (circ && CIRCUIT_PURPOSE_IS_CLIENT(circ->purpose)) {
466  /* If this is a client circuit, don't send the server an informative
467  * reason code; it doesn't need to know why the client stream is
468  * failing. */
469  reason = END_STREAM_REASON_MISC;
470  }
471 
472  payload[0] = (char)reason;
473  if (reason == END_STREAM_REASON_EXITPOLICY &&
475  int addrlen;
476  if (tor_addr_family(&conn->base_.addr) == AF_INET) {
477  set_uint32(payload+1, tor_addr_to_ipv4n(&conn->base_.addr));
478  addrlen = 4;
479  } else {
480  memcpy(payload+1, tor_addr_to_in6_addr8(&conn->base_.addr), 16);
481  addrlen = 16;
482  }
483  set_uint32(payload+1+addrlen, htonl(dns_clip_ttl(conn->address_ttl)));
484  payload_len += 4+addrlen;
485  }
486 
487  if (circ && !circ->marked_for_close) {
488  log_debug(LD_EDGE,"Sending end on conn (fd "TOR_SOCKET_T_FORMAT").",
489  conn->base_.s);
490 
491  if (CIRCUIT_IS_ORIGIN(circ)) {
492  origin_circuit_t *origin_circ = TO_ORIGIN_CIRCUIT(circ);
493  connection_half_edge_add(conn, origin_circ);
494  }
495 
496  connection_edge_send_command(conn, RELAY_COMMAND_END,
497  payload, payload_len);
498  /* We'll log warn if the connection was an hidden service and couldn't be
499  * made because the service wasn't available. */
500  warn_if_hs_unreachable(conn, control_reason);
501  } else {
502  log_debug(LD_EDGE,"No circ to send end on conn "
503  "(fd "TOR_SOCKET_T_FORMAT").",
504  conn->base_.s);
505  }
506 
507  conn->edge_has_sent_end = 1;
508  conn->end_reason = control_reason;
509  return 0;
510 }
511 
521 static int
522 connection_half_edge_compare_bsearch(const void *key, const void **member)
523 {
524  const half_edge_t *e2;
525  tor_assert(key);
526  tor_assert(member && *(half_edge_t**)member);
527  e2 = *(const half_edge_t **)member;
528 
529  return *(const streamid_t*)key - e2->stream_id;
530 }
531 
533 static size_t n_half_conns_allocated = 0;
534 
541 STATIC void
543  origin_circuit_t *circ)
544 {
545  half_edge_t *half_conn = NULL;
546  int insert_at = 0;
547  int ignored;
548 
549  /* Double-check for re-insertion. This should not happen,
550  * but this check is cheap compared to the sort anyway */
552  conn->stream_id)) {
553  log_warn(LD_BUG, "Duplicate stream close for stream %d on circuit %d",
554  conn->stream_id, circ->global_identifier);
555  return;
556  }
557 
558  half_conn = tor_malloc_zero(sizeof(half_edge_t));
560 
561  if (!circ->half_streams) {
562  circ->half_streams = smartlist_new();
563  }
564 
565  half_conn->stream_id = conn->stream_id;
566 
567  // How many sendme's should I expect?
568  half_conn->sendmes_pending =
570 
571  // Is there a connected cell pending?
572  half_conn->connected_pending = conn->base_.state ==
574 
575  /* Data should only arrive if we're not waiting on a resolved cell.
576  * It can arrive after waiting on connected, because of optimistic
577  * data. */
578  if (conn->base_.state != AP_CONN_STATE_RESOLVE_WAIT) {
579  // How many more data cells can arrive on this id?
580  half_conn->data_pending = conn->deliver_window;
581  }
582 
583  insert_at = smartlist_bsearch_idx(circ->half_streams, &half_conn->stream_id,
585  &ignored);
586  smartlist_insert(circ->half_streams, insert_at, half_conn);
587 }
588 
590 void
592 {
593  if (!he)
594  return;
596  tor_free(he);
597 }
598 
600 size_t
602 {
603  return n_half_conns_allocated * sizeof(half_edge_t);
604 }
605 
612 STATIC half_edge_t *
614  streamid_t stream_id)
615 {
616  if (!half_conns)
617  return NULL;
618 
619  return smartlist_bsearch(half_conns, &stream_id,
621 }
622 
631 int
633  streamid_t stream_id)
634 {
636  stream_id);
637 
638  if (!half)
639  return 0;
640 
641  if (half->data_pending > 0) {
642  half->data_pending--;
643  return 1;
644  }
645 
646  return 0;
647 }
648 
657 int
659  streamid_t stream_id)
660 {
662  stream_id);
663 
664  if (!half)
665  return 0;
666 
667  if (half->connected_pending) {
668  half->connected_pending = 0;
669  return 1;
670  }
671 
672  return 0;
673 }
674 
683 int
685  streamid_t stream_id)
686 {
688  stream_id);
689 
690  if (!half)
691  return 0;
692 
693  if (half->sendmes_pending > 0) {
694  half->sendmes_pending--;
695  return 1;
696  }
697 
698  return 0;
699 }
700 
708 int
710  streamid_t stream_id)
711 {
712  half_edge_t *half;
713  int found, remove_idx;
714 
715  if (!half_conns)
716  return 0;
717 
718  remove_idx = smartlist_bsearch_idx(half_conns, &stream_id,
720  &found);
721  if (!found)
722  return 0;
723 
724  half = smartlist_get(half_conns, remove_idx);
725  smartlist_del_keeporder(half_conns, remove_idx);
726  half_edge_free(half);
727  return 1;
728 }
729 
735 int
737  streamid_t stream_id)
738 {
739  return connection_half_edge_is_valid_end(half_conns, stream_id);
740 }
741 
746 int
748 {
749  uint8_t reason;
750  tor_assert(conn);
751  reason = errno_to_stream_end_reason(tor_socket_errno(conn->base_.s));
752  return connection_edge_end(conn, reason);
753 }
754 
760 int
762 {
763  switch (conn->base_.state) {
764  case AP_CONN_STATE_OPEN:
765  if (! conn->base_.linked) {
766  note_user_activity(approx_time());
767  }
768 
769  /* falls through. */
772  break;
773  }
774  return 0;
775 }
776 
787 int
789 {
790  tor_assert(conn);
791 
792  switch (conn->base_.state) {
793  case AP_CONN_STATE_OPEN:
796  return 0;
805  return 0;
806  default:
807  log_warn(LD_BUG, "Called in unexpected state %d.",conn->base_.state);
809  return -1;
810  }
811  return 0;
812 }
813 
816 /* 4 zero bytes; 1 type byte; 16 byte IPv6 address; 4 byte TTL. */
817 #define MAX_CONNECTED_CELL_PAYLOAD_LEN 25
818 
825 STATIC int
826 connected_cell_format_payload(uint8_t *payload_out,
827  const tor_addr_t *addr,
828  uint32_t ttl)
829 {
830  const sa_family_t family = tor_addr_family(addr);
831  int connected_payload_len;
832 
833  /* should be needless */
834  memset(payload_out, 0, MAX_CONNECTED_CELL_PAYLOAD_LEN);
835 
836  if (family == AF_INET) {
837  set_uint32(payload_out, tor_addr_to_ipv4n(addr));
838  connected_payload_len = 4;
839  } else if (family == AF_INET6) {
840  set_uint32(payload_out, 0);
841  set_uint8(payload_out + 4, 6);
842  memcpy(payload_out + 5, tor_addr_to_in6_addr8(addr), 16);
843  connected_payload_len = 21;
844  } else {
845  return -1;
846  }
847 
848  set_uint32(payload_out + connected_payload_len, htonl(dns_clip_ttl(ttl)));
849  connected_payload_len += 4;
850 
851  tor_assert(connected_payload_len <= MAX_CONNECTED_CELL_PAYLOAD_LEN);
852 
853  return connected_payload_len;
854 }
855 
856 /* This is an onion service client connection: Export the client circuit ID
857  * according to the HAProxy proxy protocol. */
858 STATIC void
859 export_hs_client_circuit_id(edge_connection_t *edge_conn,
860  hs_circuit_id_protocol_t protocol)
861 {
862  /* We only support HAProxy right now. */
863  if (protocol != HS_CIRCUIT_ID_PROTOCOL_HAPROXY)
864  return;
865 
866  char *buf = NULL;
867  const char dst_ipv6[] = "::1";
868  /* See RFC4193 regarding fc00::/7 */
869  const char src_ipv6_prefix[] = "fc00:dead:beef:4dad:";
870  uint16_t dst_port = 0;
871  uint16_t src_port = 1; /* default value */
872  uint32_t gid = 0; /* default value */
873 
874  /* Generate a GID and source port for this client */
875  if (edge_conn->on_circuit != NULL) {
877  src_port = gid & 0x0000ffff;
878  }
879 
880  /* Grab the original dest port from the hs ident */
881  if (edge_conn->hs_ident) {
882  dst_port = edge_conn->hs_ident->orig_virtual_port;
883  }
884 
885  /* Build the string */
886  tor_asprintf(&buf, "PROXY TCP6 %s:%x:%x %s %d %d\r\n",
887  src_ipv6_prefix,
888  gid >> 16, gid & 0x0000ffff,
889  dst_ipv6, src_port, dst_port);
890 
891  connection_buf_add(buf, strlen(buf), TO_CONN(edge_conn));
892 
893  tor_free(buf);
894 }
895 
899 int
901 {
902  connection_t *conn;
903 
904  tor_assert(edge_conn);
905  tor_assert(edge_conn->base_.type == CONN_TYPE_EXIT);
906  conn = TO_CONN(edge_conn);
908 
909  log_info(LD_EXIT,"Exit connection to %s:%u (%s) established.",
910  escaped_safe_str(conn->address), conn->port,
911  safe_str(fmt_and_decorate_addr(&conn->addr)));
912 
914 
915  conn->state = EXIT_CONN_STATE_OPEN;
916 
917  connection_watch_events(conn, READ_EVENT); /* stop writing, keep reading */
918  if (connection_get_outbuf_len(conn)) /* in case there are any queued relay
919  * cells */
920  connection_start_writing(conn);
921  /* deliver a 'connected' relay cell back through the circuit. */
922  if (connection_edge_is_rendezvous_stream(edge_conn)) {
923  if (connection_edge_send_command(edge_conn,
924  RELAY_COMMAND_CONNECTED, NULL, 0) < 0)
925  return 0; /* circuit is closed, don't continue */
926  } else {
927  uint8_t connected_payload[MAX_CONNECTED_CELL_PAYLOAD_LEN];
928  int connected_payload_len =
929  connected_cell_format_payload(connected_payload, &conn->addr,
930  edge_conn->address_ttl);
931  if (connected_payload_len < 0)
932  return -1;
933 
934  if (connection_edge_send_command(edge_conn,
935  RELAY_COMMAND_CONNECTED,
936  (char*)connected_payload, connected_payload_len) < 0)
937  return 0; /* circuit is closed, don't continue */
938  }
939  tor_assert(edge_conn->package_window > 0);
940  /* in case the server has written anything */
941  return connection_edge_process_inbuf(edge_conn, 1);
942 }
943 
951 
952 static int untried_pending_connections = 0;
953 
959 
961 static void
963 {
964  if (!edge_conn->edge_has_sent_end) {
965  connection_t *conn = TO_CONN(edge_conn);
966  log_warn(LD_BUG, "(Harmless.) Edge connection (marked at %s:%d) "
967  "hasn't sent end yet?",
970  }
971 }
972 
975 void
977 {
978  circuit_t *circ;
979  edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(entry_conn);
980  connection_t *conn = ENTRY_TO_CONN(entry_conn);
981 
983 
984  if (entry_conn->socks_request->has_finished == 0) {
985  /* since conn gets removed right after this function finishes,
986  * there's no point trying to send back a reply at this point. */
987  log_warn(LD_BUG,"Closing stream (marked at %s:%d) without sending"
988  " back a socks reply.",
990  }
991  if (!edge_conn->end_reason) {
992  log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
993  " set end_reason.",
995  }
996  if (entry_conn->dns_server_request) {
997  log_warn(LD_BUG,"Closing stream (marked at %s:%d) without having"
998  " replied to DNS request.",
1000  dnsserv_reject_request(entry_conn);
1001  }
1002 
1003  if (TO_CONN(edge_conn)->state == AP_CONN_STATE_CIRCUIT_WAIT) {
1005  }
1006 
1007 #if 1
1008  /* Check to make sure that this isn't in pending_entry_connections if it
1009  * didn't actually belong there. */
1010  if (TO_CONN(edge_conn)->type == CONN_TYPE_AP) {
1011  connection_ap_warn_and_unmark_if_pending_circ(entry_conn,
1012  "about_to_close");
1013  }
1014 #endif /* 1 */
1015 
1016  control_event_stream_bandwidth(edge_conn);
1017  control_event_stream_status(entry_conn, STREAM_EVENT_CLOSED,
1018  edge_conn->end_reason);
1019  circ = circuit_get_by_edge_conn(edge_conn);
1020  if (circ)
1021  circuit_detach_stream(circ, edge_conn);
1022 }
1023 
1026 void
1028 {
1029  circuit_t *circ;
1030  connection_t *conn = TO_CONN(edge_conn);
1031 
1032  connection_edge_about_to_close(edge_conn);
1033 
1034  circ = circuit_get_by_edge_conn(edge_conn);
1035  if (circ)
1036  circuit_detach_stream(circ, edge_conn);
1037  if (conn->state == EXIT_CONN_STATE_RESOLVING) {
1038  connection_dns_remove(edge_conn);
1039  }
1040 }
1041 
1047 static int
1049 {
1050  int timeout = get_options()->CircuitStreamTimeout;
1051  if (timeout) /* if our config options override the default, use them */
1052  return timeout;
1053  if (conn->num_socks_retries < 2) /* try 0 and try 1 */
1054  return 10;
1055  return 15;
1056 }
1057 
1067 void
1069 {
1070  edge_connection_t *conn;
1071  entry_connection_t *entry_conn;
1072  circuit_t *circ;
1073  time_t now = time(NULL);
1074  const or_options_t *options = get_options();
1075  int severity;
1076  int cutoff;
1077  int seconds_idle, seconds_since_born;
1078  smartlist_t *conns = get_connection_array();
1079 
1080  SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
1081  if (base_conn->type != CONN_TYPE_AP || base_conn->marked_for_close)
1082  continue;
1083  entry_conn = TO_ENTRY_CONN(base_conn);
1084  conn = ENTRY_TO_EDGE_CONN(entry_conn);
1085  /* if it's an internal linked connection, don't yell its status. */
1086  severity = (tor_addr_is_null(&base_conn->addr) && !base_conn->port)
1087  ? LOG_INFO : LOG_NOTICE;
1088  seconds_idle = (int)( now - base_conn->timestamp_last_read_allowed );
1089  seconds_since_born = (int)( now - base_conn->timestamp_created );
1090 
1091  if (base_conn->state == AP_CONN_STATE_OPEN)
1092  continue;
1093 
1094  /* We already consider SocksTimeout in
1095  * connection_ap_handshake_attach_circuit(), but we need to consider
1096  * it here too because controllers that put streams in controller_wait
1097  * state never ask Tor to attach the circuit. */
1098  if (AP_CONN_STATE_IS_UNATTACHED(base_conn->state)) {
1099  if (seconds_since_born >= options->SocksTimeout) {
1100  log_fn(severity, LD_APP,
1101  "Tried for %d seconds to get a connection to %s:%d. "
1102  "Giving up. (%s)",
1103  seconds_since_born,
1104  safe_str_client(entry_conn->socks_request->address),
1105  entry_conn->socks_request->port,
1106  conn_state_to_string(CONN_TYPE_AP, base_conn->state));
1107  connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
1108  }
1109  continue;
1110  }
1111 
1112  /* We're in state connect_wait or resolve_wait now -- waiting for a
1113  * reply to our relay cell. See if we want to retry/give up. */
1114 
1115  cutoff = compute_retry_timeout(entry_conn);
1116  if (seconds_idle < cutoff)
1117  continue;
1118  circ = circuit_get_by_edge_conn(conn);
1119  if (!circ) { /* it's vanished? */
1120  log_info(LD_APP,"Conn is waiting (address %s), but lost its circ.",
1121  safe_str_client(entry_conn->socks_request->address));
1122  connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
1123  continue;
1124  }
1125  if (circ->purpose == CIRCUIT_PURPOSE_C_REND_JOINED) {
1126  if (seconds_idle >= options->SocksTimeout) {
1127  log_fn(severity, LD_REND,
1128  "Rend stream is %d seconds late. Giving up on address"
1129  " '%s.onion'.",
1130  seconds_idle,
1131  safe_str_client(entry_conn->socks_request->address));
1132  /* Roll back path bias use state so that we probe the circuit
1133  * if nothing else succeeds on it */
1135 
1136  connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
1137  connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
1138  }
1139  continue;
1140  }
1141 
1142  if (circ->purpose != CIRCUIT_PURPOSE_C_GENERAL &&
1147  log_warn(LD_BUG, "circuit->purpose == CIRCUIT_PURPOSE_C_GENERAL failed. "
1148  "The purpose on the circuit was %s; it was in state %s, "
1149  "path_state %s.",
1152  CIRCUIT_IS_ORIGIN(circ) ?
1153  pathbias_state_to_string(TO_ORIGIN_CIRCUIT(circ)->path_state) :
1154  "none");
1155  }
1156  log_fn(cutoff < 15 ? LOG_INFO : severity, LD_APP,
1157  "We tried for %d seconds to connect to '%s' using exit %s."
1158  " Retrying on a new circuit.",
1159  seconds_idle,
1160  safe_str_client(entry_conn->socks_request->address),
1161  conn->cpath_layer ?
1163  "*unnamed*");
1164  /* send an end down the circuit */
1165  connection_edge_end(conn, END_STREAM_REASON_TIMEOUT);
1166  /* un-mark it as ending, since we're going to reuse it */
1167  conn->edge_has_sent_end = 0;
1168  conn->end_reason = 0;
1169  /* make us not try this circuit again, but allow
1170  * current streams on it to survive if they can */
1172 
1173  /* give our stream another 'cutoff' seconds to try */
1174  conn->base_.timestamp_last_read_allowed += cutoff;
1175  if (entry_conn->num_socks_retries < 250) /* avoid overflow */
1176  entry_conn->num_socks_retries++;
1177  /* move it back into 'pending' state, and try to attach. */
1178  if (connection_ap_detach_retriable(entry_conn, TO_ORIGIN_CIRCUIT(circ),
1179  END_STREAM_REASON_TIMEOUT)<0) {
1180  if (!base_conn->marked_for_close)
1181  connection_mark_unattached_ap(entry_conn,
1183  }
1184  } SMARTLIST_FOREACH_END(base_conn);
1185 }
1186 
1191 void
1193 {
1194  entry_connection_t *entry_conn;
1195  smartlist_t *conns = get_connection_array();
1196 
1197  if (PREDICT_UNLIKELY(NULL == pending_entry_connections))
1198  pending_entry_connections = smartlist_new();
1199 
1200  SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
1201  if (conn->marked_for_close ||
1202  conn->type != CONN_TYPE_AP ||
1203  conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
1204  continue;
1205 
1206  entry_conn = TO_ENTRY_CONN(conn);
1207  tor_assert(entry_conn);
1208  if (! smartlist_contains(pending_entry_connections, entry_conn)) {
1209  log_warn(LD_BUG, "Found a connection %p that was supposed to be "
1210  "in pending_entry_connections, but wasn't. No worries; "
1211  "adding it.",
1213  untried_pending_connections = 1;
1214  connection_ap_mark_as_pending_circuit(entry_conn);
1215  }
1216 
1217  } SMARTLIST_FOREACH_END(conn);
1218 
1220 }
1221 
1222 #ifdef DEBUGGING_17659
1223 #define UNMARK() do { \
1224  entry_conn->marked_pending_circ_line = 0; \
1225  entry_conn->marked_pending_circ_file = 0; \
1226  } while (0)
1227 #else /* !(defined(DEBUGGING_17659)) */
1228 #define UNMARK() do { } while (0)
1229 #endif /* defined(DEBUGGING_17659) */
1230 
1238 void
1240 {
1241  if (PREDICT_UNLIKELY(!pending_entry_connections)) {
1242  return;
1243  }
1244 
1245  if (untried_pending_connections == 0 && !retry)
1246  return;
1247 
1248  /* Don't allow any modifications to list while we are iterating over
1249  * it. We'll put streams back on this list if we can't attach them
1250  * immediately. */
1252  pending_entry_connections = smartlist_new();
1253 
1254  SMARTLIST_FOREACH_BEGIN(pending,
1255  entry_connection_t *, entry_conn) {
1256  connection_t *conn = ENTRY_TO_CONN(entry_conn);
1257  tor_assert(conn && entry_conn);
1258  if (conn->marked_for_close) {
1259  UNMARK();
1260  continue;
1261  }
1262  if (conn->magic != ENTRY_CONNECTION_MAGIC) {
1263  log_warn(LD_BUG, "%p has impossible magic value %u.",
1264  entry_conn, (unsigned)conn->magic);
1265  UNMARK();
1266  continue;
1267  }
1268  if (conn->state != AP_CONN_STATE_CIRCUIT_WAIT) {
1269  log_warn(LD_BUG, "%p is no longer in circuit_wait. Its current state "
1270  "is %s. Why is it on pending_entry_connections?",
1271  entry_conn,
1272  conn_state_to_string(conn->type, conn->state));
1273  UNMARK();
1274  continue;
1275  }
1276 
1277  /* Okay, we're through the sanity checks. Try to handle this stream. */
1278  if (connection_ap_handshake_attach_circuit(entry_conn) < 0) {
1279  if (!conn->marked_for_close)
1280  connection_mark_unattached_ap(entry_conn,
1282  }
1283 
1284  if (! conn->marked_for_close &&
1285  conn->type == CONN_TYPE_AP &&
1286  conn->state == AP_CONN_STATE_CIRCUIT_WAIT) {
1287  /* Is it still waiting for a circuit? If so, we didn't attach it,
1288  * so it's still pending. Put it back on the list.
1289  */
1290  if (!smartlist_contains(pending_entry_connections, entry_conn)) {
1292  continue;
1293  }
1294  }
1295 
1296  /* If we got here, then we either closed the connection, or
1297  * we attached it. */
1298  UNMARK();
1299  } SMARTLIST_FOREACH_END(entry_conn);
1300 
1301  smartlist_free(pending);
1302  untried_pending_connections = 0;
1303 }
1304 
1305 static void
1306 attach_pending_entry_connections_cb(mainloop_event_t *ev, void *arg)
1307 {
1308  (void)ev;
1309  (void)arg;
1311 }
1312 
1320 void
1322  const char *fname, int lineno)
1323 {
1324  connection_t *conn = ENTRY_TO_CONN(entry_conn);
1326  tor_assert(conn->magic == ENTRY_CONNECTION_MAGIC);
1327  if (conn->marked_for_close)
1328  return;
1329 
1330  if (PREDICT_UNLIKELY(NULL == pending_entry_connections)) {
1331  pending_entry_connections = smartlist_new();
1332  }
1333  if (PREDICT_UNLIKELY(NULL == attach_pending_entry_connections_ev)) {
1335  attach_pending_entry_connections_cb, NULL);
1336  }
1337  if (PREDICT_UNLIKELY(smartlist_contains(pending_entry_connections,
1338  entry_conn))) {
1339  log_warn(LD_BUG, "What?? pending_entry_connections already contains %p! "
1340  "(Called from %s:%d.)",
1341  entry_conn, fname, lineno);
1342 #ifdef DEBUGGING_17659
1343  const char *f2 = entry_conn->marked_pending_circ_file;
1344  log_warn(LD_BUG, "(Previously called from %s:%d.)\n",
1345  f2 ? f2 : "<NULL>",
1346  entry_conn->marked_pending_circ_line);
1347 #endif /* defined(DEBUGGING_17659) */
1348  log_backtrace(LOG_WARN, LD_BUG, "To debug, this may help");
1349  return;
1350  }
1351 
1352 #ifdef DEBUGGING_17659
1353  entry_conn->marked_pending_circ_line = (uint16_t) lineno;
1354  entry_conn->marked_pending_circ_file = fname;
1355 #endif
1356 
1357  untried_pending_connections = 1;
1359 
1361 }
1362 
1364 void
1366 {
1367  if (PREDICT_UNLIKELY(NULL == pending_entry_connections))
1368  return;
1369  UNMARK();
1371 }
1372 
1379 void
1381 {
1382  tor_assert(entry_conn);
1383 
1385  ENTRY_TO_CONN(entry_conn)->state = AP_CONN_STATE_RENDDESC_WAIT;
1386 }
1387 
1388 /* DOCDOC */
1389 void
1390 connection_ap_warn_and_unmark_if_pending_circ(entry_connection_t *entry_conn,
1391  const char *where)
1392 {
1395  log_warn(LD_BUG, "What was %p doing in pending_entry_connections in %s?",
1396  entry_conn, where);
1398  }
1399 }
1400 
1403 /* XXXX We should get rid of this function, and instead attach
1404  * one-hop streams to circ->p_streams so they get marked in
1405  * circuit_mark_for_close like normal p_streams. */
1406 void
1407 connection_ap_fail_onehop(const char *failed_digest,
1408  cpath_build_state_t *build_state)
1409 {
1410  entry_connection_t *entry_conn;
1411  char digest[DIGEST_LEN];
1412  smartlist_t *conns = get_connection_array();
1413  SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
1414  if (conn->marked_for_close ||
1415  conn->type != CONN_TYPE_AP ||
1416  conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
1417  continue;
1418  entry_conn = TO_ENTRY_CONN(conn);
1419  if (!entry_conn->want_onehop)
1420  continue;
1421  if (hexdigest_to_digest(entry_conn->chosen_exit_name, digest) < 0 ||
1422  tor_memneq(digest, failed_digest, DIGEST_LEN))
1423  continue;
1424  if (tor_digest_is_zero(digest)) {
1425  /* we don't know the digest; have to compare addr:port */
1426  tor_addr_t addr;
1427  if (!build_state || !build_state->chosen_exit ||
1428  !entry_conn->socks_request) {
1429  continue;
1430  }
1431  if (tor_addr_parse(&addr, entry_conn->socks_request->address)<0 ||
1432  !tor_addr_eq(&build_state->chosen_exit->addr, &addr) ||
1433  build_state->chosen_exit->port != entry_conn->socks_request->port)
1434  continue;
1435  }
1436  log_info(LD_APP, "Closing one-hop stream to '%s/%s' because the OR conn "
1437  "just failed.", entry_conn->chosen_exit_name,
1438  entry_conn->socks_request->address);
1439  connection_mark_unattached_ap(entry_conn, END_STREAM_REASON_TIMEOUT);
1440  } SMARTLIST_FOREACH_END(conn);
1441 }
1442 
1447 void
1449 {
1450  entry_connection_t *entry_conn;
1451  const node_t *r1, *r2;
1452 
1453  smartlist_t *conns = get_connection_array();
1454  SMARTLIST_FOREACH_BEGIN(conns, connection_t *, conn) {
1455  if (conn->marked_for_close ||
1456  conn->type != CONN_TYPE_AP ||
1457  conn->state != AP_CONN_STATE_CIRCUIT_WAIT)
1458  continue;
1459  entry_conn = TO_ENTRY_CONN(conn);
1460  if (!entry_conn->chosen_exit_optional &&
1461  !entry_conn->chosen_exit_retries)
1462  continue;
1463  r1 = node_get_by_nickname(entry_conn->chosen_exit_name,
1464  NNF_NO_WARN_UNNAMED);
1465  r2 = node_get_by_id(info->identity_digest);
1466  if (!r1 || !r2 || r1 != r2)
1467  continue;
1468  tor_assert(entry_conn->socks_request);
1469  if (entry_conn->chosen_exit_optional) {
1470  log_info(LD_APP, "Giving up on enclave exit '%s' for destination %s.",
1471  safe_str_client(entry_conn->chosen_exit_name),
1473  entry_conn->chosen_exit_optional = 0;
1474  tor_free(entry_conn->chosen_exit_name); /* clears it */
1475  /* if this port is dangerous, warn or reject it now that we don't
1476  * think it'll be using an enclave. */
1477  consider_plaintext_ports(entry_conn, entry_conn->socks_request->port);
1478  }
1479  if (entry_conn->chosen_exit_retries) {
1480  if (--entry_conn->chosen_exit_retries == 0) { /* give up! */
1482  tor_free(entry_conn->chosen_exit_name); /* clears it */
1483  /* if this port is dangerous, warn or reject it now that we don't
1484  * think it'll be using an enclave. */
1485  consider_plaintext_ports(entry_conn, entry_conn->socks_request->port);
1486  }
1487  }
1488  } SMARTLIST_FOREACH_END(conn);
1489 }
1490 
1498 int
1500  origin_circuit_t *circ,
1501  int reason)
1502 {
1503  control_event_stream_status(conn, STREAM_EVENT_FAILED_RETRIABLE, reason);
1504  ENTRY_TO_CONN(conn)->timestamp_last_read_allowed = time(NULL);
1505 
1506  /* Roll back path bias use state so that we probe the circuit
1507  * if nothing else succeeds on it */
1509 
1510  if (conn->pending_optimistic_data) {
1511  buf_set_to_copy(&conn->sending_optimistic_data,
1512  conn->pending_optimistic_data);
1513  }
1514 
1515  if (!get_options()->LeaveStreamsUnattached || conn->use_begindir) {
1516  /* If we're attaching streams ourself, or if this connection is
1517  * a tunneled directory connection, then just attach it. */
1519  circuit_detach_stream(TO_CIRCUIT(circ),ENTRY_TO_EDGE_CONN(conn));
1520  connection_ap_mark_as_pending_circuit(conn);
1521  } else {
1522  CONNECTION_AP_EXPECT_NONPENDING(conn);
1524  circuit_detach_stream(TO_CIRCUIT(circ),ENTRY_TO_EDGE_CONN(conn));
1525  }
1526  return 0;
1527 }
1528 
1531 static int
1533 {
1534  const or_options_t *options = get_options();
1535  int reject = smartlist_contains_int_as_string(
1536  options->RejectPlaintextPorts, port);
1537 
1539  log_warn(LD_APP, "Application request to port %d: this port is "
1540  "commonly used for unencrypted protocols. Please make sure "
1541  "you don't send anything you would mind the rest of the "
1542  "Internet reading!%s", port, reject ? " Closing." : "");
1543  control_event_client_status(LOG_WARN, "DANGEROUS_PORT PORT=%d RESULT=%s",
1544  port, reject ? "REJECT" : "WARN");
1545  }
1546 
1547  if (reject) {
1548  log_info(LD_APP, "Port %d listed in RejectPlaintextPorts. Closing.", port);
1549  connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
1550  return -1;
1551  }
1552 
1553  return 0;
1554 }
1555 
1559 #define TRACKHOSTEXITS_RETRIES 5
1560 
1568 connection_ap_rewrite_and_attach_if_allowed,(entry_connection_t *conn,
1569  origin_circuit_t *circ,
1570  crypt_path_t *cpath))
1571 {
1572  const or_options_t *options = get_options();
1573 
1574  if (options->LeaveStreamsUnattached) {
1575  CONNECTION_AP_EXPECT_NONPENDING(conn);
1577  return 0;
1578  }
1579  return connection_ap_handshake_rewrite_and_attach(conn, circ, cpath);
1580 }
1581 
1582 /* Try to perform any map-based rewriting of the target address in
1583  * <b>conn</b>, filling in the fields of <b>out</b> as we go, and modifying
1584  * conn->socks_request.address as appropriate.
1585  */
1586 STATIC void
1587 connection_ap_handshake_rewrite(entry_connection_t *conn,
1588  rewrite_result_t *out)
1589 {
1590  socks_request_t *socks = conn->socks_request;
1591  const or_options_t *options = get_options();
1592  tor_addr_t addr_tmp;
1593 
1594  /* Initialize all the fields of 'out' to reasonable defaults */
1595  out->automap = 0;
1596  out->exit_source = ADDRMAPSRC_NONE;
1597  out->map_expires = TIME_MAX;
1598  out->end_reason = 0;
1599  out->should_close = 0;
1600  out->orig_address[0] = 0;
1601 
1602  /* We convert all incoming addresses to lowercase. */
1603  tor_strlower(socks->address);
1604  /* Remember the original address. */
1605  strlcpy(out->orig_address, socks->address, sizeof(out->orig_address));
1606  log_debug(LD_APP,"Client asked for %s:%d",
1607  safe_str_client(socks->address),
1608  socks->port);
1609 
1610  /* Check for whether this is a .exit address. By default, those are
1611  * disallowed when they're coming straight from the client, but you're
1612  * allowed to have them in MapAddress commands and so forth. */
1613  if (!strcmpend(socks->address, ".exit")) {
1614  log_warn(LD_APP, "The \".exit\" notation is disabled in Tor due to "
1615  "security risks.");
1616  control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
1617  escaped(socks->address));
1618  out->end_reason = END_STREAM_REASON_TORPROTOCOL;
1619  out->should_close = 1;
1620  return;
1621  }
1622 
1623  /* Remember the original address so we can tell the user about what
1624  * they actually said, not just what it turned into. */
1625  /* XXX yes, this is the same as out->orig_address above. One is
1626  * in the output, and one is in the connection. */
1627  if (! conn->original_dest_address) {
1628  /* Is the 'if' necessary here? XXXX */
1629  conn->original_dest_address = tor_strdup(conn->socks_request->address);
1630  }
1631 
1632  /* First, apply MapAddress and MAPADDRESS mappings. We need to do
1633  * these only for non-reverse lookups, since they don't exist for those.
1634  * We also need to do this before we consider automapping, since we might
1635  * e.g. resolve irc.oftc.net into irconionaddress.onion, at which point
1636  * we'd need to automap it. */
1637  if (socks->command != SOCKS_COMMAND_RESOLVE_PTR) {
1638  const unsigned rewrite_flags = AMR_FLAG_USE_MAPADDRESS;
1639  if (addressmap_rewrite(socks->address, sizeof(socks->address),
1640  rewrite_flags, &out->map_expires, &out->exit_source)) {
1641  control_event_stream_status(conn, STREAM_EVENT_REMAP,
1643  }
1644  }
1645 
1646  /* Now see if we need to create or return an existing Hostname->IP
1647  * automapping. Automapping happens when we're asked to resolve a
1648  * hostname, and AutomapHostsOnResolve is set, and the hostname has a
1649  * suffix listed in AutomapHostsSuffixes. It's a handy feature
1650  * that lets you have Tor assign e.g. IPv6 addresses for .onion
1651  * names, and return them safely from DNSPort.
1652  */
1653  if (socks->command == SOCKS_COMMAND_RESOLVE &&
1654  tor_addr_parse(&addr_tmp, socks->address)<0 &&
1655  options->AutomapHostsOnResolve) {
1656  /* Check the suffix... */
1657  out->automap = addressmap_address_should_automap(socks->address, options);
1658  if (out->automap) {
1659  /* If we get here, then we should apply an automapping for this. */
1660  const char *new_addr;
1661  /* We return an IPv4 address by default, or an IPv6 address if we
1662  * are allowed to do so. */
1663  int addr_type = RESOLVED_TYPE_IPV4;
1664  if (conn->socks_request->socks_version != 4) {
1665  if (!conn->entry_cfg.ipv4_traffic ||
1666  (conn->entry_cfg.ipv6_traffic && conn->entry_cfg.prefer_ipv6) ||
1667  conn->entry_cfg.prefer_ipv6_virtaddr)
1668  addr_type = RESOLVED_TYPE_IPV6;
1669  }
1670  /* Okay, register the target address as automapped, and find the new
1671  * address we're supposed to give as a resolve answer. (Return a cached
1672  * value if we've looked up this address before.
1673  */
1675  addr_type, tor_strdup(socks->address));
1676  if (! new_addr) {
1677  log_warn(LD_APP, "Unable to automap address %s",
1678  escaped_safe_str(socks->address));
1679  out->end_reason = END_STREAM_REASON_INTERNAL;
1680  out->should_close = 1;
1681  return;
1682  }
1683  log_info(LD_APP, "Automapping %s to %s",
1685  safe_str_client(new_addr));
1686  strlcpy(socks->address, new_addr, sizeof(socks->address));
1687  }
1688  }
1689 
1690  /* Now handle reverse lookups, if they're in the cache. This doesn't
1691  * happen too often, since client-side DNS caching is off by default,
1692  * and very deprecated. */
1693  if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
1694  unsigned rewrite_flags = 0;
1695  if (conn->entry_cfg.use_cached_ipv4_answers)
1696  rewrite_flags |= AMR_FLAG_USE_IPV4_DNS;
1697  if (conn->entry_cfg.use_cached_ipv6_answers)
1698  rewrite_flags |= AMR_FLAG_USE_IPV6_DNS;
1699 
1700  if (addressmap_rewrite_reverse(socks->address, sizeof(socks->address),
1701  rewrite_flags, &out->map_expires)) {
1702  char *result = tor_strdup(socks->address);
1703  /* remember _what_ is supposed to have been resolved. */
1704  tor_snprintf(socks->address, sizeof(socks->address), "REVERSE[%s]",
1705  out->orig_address);
1706  connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_HOSTNAME,
1707  strlen(result), (uint8_t*)result,
1708  -1,
1709  out->map_expires);
1710  tor_free(result);
1711  out->end_reason = END_STREAM_REASON_DONE |
1713  out->should_close = 1;
1714  return;
1715  }
1716 
1717  /* Hang on, did we find an answer saying that this is a reverse lookup for
1718  * an internal address? If so, we should reject it if we're configured to
1719  * do so. */
1720  if (options->ClientDNSRejectInternalAddresses) {
1721  /* Don't let clients try to do a reverse lookup on 10.0.0.1. */
1722  tor_addr_t addr;
1723  int ok;
1725  &addr, socks->address, AF_UNSPEC, 1);
1726  if (ok == 1 && tor_addr_is_internal(&addr, 0)) {
1727  connection_ap_handshake_socks_resolved(conn, RESOLVED_TYPE_ERROR,
1728  0, NULL, -1, TIME_MAX);
1729  out->end_reason = END_STREAM_REASON_SOCKSPROTOCOL |
1731  out->should_close = 1;
1732  return;
1733  }
1734  }
1735  }
1736 
1737  /* If we didn't automap it before, then this is still the address that
1738  * came straight from the user, mapped according to any
1739  * MapAddress/MAPADDRESS commands. Now apply other mappings,
1740  * including previously registered Automap entries (IP back to
1741  * hostname), TrackHostExits entries, and client-side DNS cache
1742  * entries (if they're turned on).
1743  */
1744  if (socks->command != SOCKS_COMMAND_RESOLVE_PTR &&
1745  !out->automap) {
1746  unsigned rewrite_flags = AMR_FLAG_USE_AUTOMAP | AMR_FLAG_USE_TRACKEXIT;
1747  addressmap_entry_source_t exit_source2;
1748  if (conn->entry_cfg.use_cached_ipv4_answers)
1749  rewrite_flags |= AMR_FLAG_USE_IPV4_DNS;
1750  if (conn->entry_cfg.use_cached_ipv6_answers)
1751  rewrite_flags |= AMR_FLAG_USE_IPV6_DNS;
1752  if (addressmap_rewrite(socks->address, sizeof(socks->address),
1753  rewrite_flags, &out->map_expires, &exit_source2)) {
1754  control_event_stream_status(conn, STREAM_EVENT_REMAP,
1756  }
1757  if (out->exit_source == ADDRMAPSRC_NONE) {
1758  /* If it wasn't a .exit before, maybe it turned into a .exit. Remember
1759  * the original source of a .exit. */
1760  out->exit_source = exit_source2;
1761  }
1762  }
1763 
1764  /* Check to see whether we're about to use an address in the virtual
1765  * range without actually having gotten it from an Automap. */
1766  if (!out->automap && address_is_in_virtual_range(socks->address)) {
1767  /* This address was probably handed out by
1768  * client_dns_get_unmapped_address, but the mapping was discarded for some
1769  * reason. Or the user typed in a virtual address range manually. We
1770  * *don't* want to send the address through Tor; that's likely to fail,
1771  * and may leak information.
1772  */
1773  log_warn(LD_APP,"Missing mapping for virtual address '%s'. Refusing.",
1774  safe_str_client(socks->address));
1775  out->end_reason = END_STREAM_REASON_INTERNAL;
1776  out->should_close = 1;
1777  return;
1778  }
1779 }
1780 
1783 static int
1785  socks_request_t *socks,
1786  origin_circuit_t *circ,
1787  hostname_type_t addresstype)
1788 {
1789  time_t now = approx_time();
1790  connection_t *base_conn = ENTRY_TO_CONN(conn);
1791 
1792  /* If .onion address requests are disabled, refuse the request */
1793  if (!conn->entry_cfg.onion_traffic) {
1794  log_warn(LD_APP, "Onion address %s requested from a port with .onion "
1795  "disabled", safe_str_client(socks->address));
1796  connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
1797  return -1;
1798  }
1799 
1800  /* Check whether it's RESOLVE or RESOLVE_PTR. We don't handle those
1801  * for hidden service addresses. */
1802  if (SOCKS_COMMAND_IS_RESOLVE(socks->command)) {
1803  /* if it's a resolve request, fail it right now, rather than
1804  * building all the circuits and then realizing it won't work. */
1805  log_warn(LD_APP,
1806  "Resolve requests to hidden services not allowed. Failing.");
1807  connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_ERROR,
1808  0,NULL,-1,TIME_MAX);
1809  connection_mark_unattached_ap(conn,
1812  return -1;
1813  }
1814 
1815  /* If we were passed a circuit, then we need to fail. .onion addresses
1816  * only work when we launch our own circuits for now. */
1817  if (circ) {
1818  log_warn(LD_CONTROL, "Attachstream to a circuit is not "
1819  "supported for .onion addresses currently. Failing.");
1820  connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1821  return -1;
1822  }
1823 
1824  /* Interface: Regardless of HS version after the block below we should have
1825  set onion_address, rend_cache_lookup_result, and descriptor_is_usable. */
1826  const char *onion_address = NULL;
1827  int rend_cache_lookup_result = -ENOENT;
1828  int descriptor_is_usable = 0;
1829 
1830  if (addresstype == ONION_V2_HOSTNAME) { /* it's a v2 hidden service */
1831  rend_cache_entry_t *entry = NULL;
1832  /* Look up if we have client authorization configured for this hidden
1833  * service. If we do, associate it with the rend_data. */
1834  rend_service_authorization_t *client_auth =
1836 
1837  const uint8_t *cookie = NULL;
1838  rend_auth_type_t auth_type = REND_NO_AUTH;
1839  if (client_auth) {
1840  log_info(LD_REND, "Using previously configured client authorization "
1841  "for hidden service request.");
1842  auth_type = client_auth->auth_type;
1843  cookie = client_auth->descriptor_cookie;
1844  }
1845 
1846  /* Fill in the rend_data field so we can start doing a connection to
1847  * a hidden service. */
1848  rend_data_t *rend_data = ENTRY_TO_EDGE_CONN(conn)->rend_data =
1849  rend_data_client_create(socks->address, NULL, (char *) cookie,
1850  auth_type);
1851  if (rend_data == NULL) {
1852  return -1;
1853  }
1854  onion_address = rend_data_get_address(rend_data);
1855  log_info(LD_REND,"Got a hidden service request for ID '%s'",
1856  safe_str_client(onion_address));
1857 
1858  rend_cache_lookup_result = rend_cache_lookup_entry(onion_address,-1,
1859  &entry);
1860  if (!rend_cache_lookup_result && entry) {
1861  descriptor_is_usable = rend_client_any_intro_points_usable(entry);
1862  }
1863  } else { /* it's a v3 hidden service */
1864  tor_assert(addresstype == ONION_V3_HOSTNAME);
1865  const hs_descriptor_t *cached_desc = NULL;
1866  int retval;
1867  /* Create HS conn identifier with HS pubkey */
1868  hs_ident_edge_conn_t *hs_conn_ident =
1869  tor_malloc_zero(sizeof(hs_ident_edge_conn_t));
1870 
1871  retval = hs_parse_address(socks->address, &hs_conn_ident->identity_pk,
1872  NULL, NULL);
1873  if (retval < 0) {
1874  log_warn(LD_GENERAL, "failed to parse hs address");
1875  tor_free(hs_conn_ident);
1876  return -1;
1877  }
1878  ENTRY_TO_EDGE_CONN(conn)->hs_ident = hs_conn_ident;
1879 
1880  onion_address = socks->address;
1881 
1882  /* Check the v3 desc cache */
1883  cached_desc = hs_cache_lookup_as_client(&hs_conn_ident->identity_pk);
1884  if (cached_desc) {
1885  rend_cache_lookup_result = 0;
1886  descriptor_is_usable =
1887  hs_client_any_intro_points_usable(&hs_conn_ident->identity_pk,
1888  cached_desc);
1889  log_info(LD_GENERAL, "Found %s descriptor in cache for %s. %s.",
1890  (descriptor_is_usable) ? "usable" : "unusable",
1891  safe_str_client(onion_address),
1892  (descriptor_is_usable) ? "Not fetching." : "Refecting.");
1893  } else {
1894  rend_cache_lookup_result = -ENOENT;
1895  }
1896  }
1897 
1898  /* Lookup the given onion address. If invalid, stop right now.
1899  * Otherwise, we might have it in the cache or not. */
1900  unsigned int refetch_desc = 0;
1901  if (rend_cache_lookup_result < 0) {
1902  switch (-rend_cache_lookup_result) {
1903  case EINVAL:
1904  /* We should already have rejected this address! */
1905  log_warn(LD_BUG,"Invalid service name '%s'",
1906  safe_str_client(onion_address));
1907  connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
1908  return -1;
1909  case ENOENT:
1910  /* We didn't have this; we should look it up. */
1911  log_info(LD_REND, "No descriptor found in our cache for %s. Fetching.",
1912  safe_str_client(onion_address));
1913  refetch_desc = 1;
1914  break;
1915  default:
1916  log_warn(LD_BUG, "Unknown cache lookup error %d",
1917  rend_cache_lookup_result);
1918  return -1;
1919  }
1920  }
1921 
1922  /* Help predict that we'll want to do hidden service circuits in the
1923  * future. We're not sure if it will need a stable circuit yet, but
1924  * we know we'll need *something*. */
1925  rep_hist_note_used_internal(now, 0, 1);
1926 
1927  /* Now we have a descriptor but is it usable or not? If not, refetch.
1928  * Also, a fetch could have been requested if the onion address was not
1929  * found in the cache previously. */
1930  if (refetch_desc || !descriptor_is_usable) {
1931  edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
1933  base_conn->state = AP_CONN_STATE_RENDDESC_WAIT;
1934  if (addresstype == ONION_V2_HOSTNAME) {
1935  tor_assert(edge_conn->rend_data);
1937  /* Whatever the result of the refetch, we don't go further. */
1938  return 0;
1939  } else {
1940  tor_assert(addresstype == ONION_V3_HOSTNAME);
1941  tor_assert(edge_conn->hs_ident);
1942  /* Attempt to fetch the hsv3 descriptor. Check the retval to see how it
1943  * went and act accordingly. */
1944  int ret = hs_client_refetch_hsdesc(&edge_conn->hs_ident->identity_pk);
1945  switch (ret) {
1946  case HS_CLIENT_FETCH_MISSING_INFO:
1947  /* Keeping the connection in descriptor wait state is fine because
1948  * once we get enough dirinfo or a new live consensus, the HS client
1949  * subsystem is notified and every connection in that state will
1950  * trigger a fetch for the service key. */
1951  case HS_CLIENT_FETCH_LAUNCHED:
1952  case HS_CLIENT_FETCH_PENDING:
1953  case HS_CLIENT_FETCH_HAVE_DESC:
1954  return 0;
1955  case HS_CLIENT_FETCH_ERROR:
1956  case HS_CLIENT_FETCH_NO_HSDIRS:
1957  case HS_CLIENT_FETCH_NOT_ALLOWED:
1958  /* Can't proceed further and better close the SOCKS request. */
1959  return -1;
1960  }
1961  }
1962  }
1963 
1964  /* We have the descriptor! So launch a connection to the HS. */
1965  log_info(LD_REND, "Descriptor is here. Great.");
1966 
1967  base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
1968  /* We'll try to attach it at the next event loop, or whenever
1969  * we call connection_ap_attach_pending() */
1970  connection_ap_mark_as_pending_circuit(conn);
1971  return 0;
1972 }
1973 
1989 int
1991  origin_circuit_t *circ,
1992  crypt_path_t *cpath)
1993 {
1994  socks_request_t *socks = conn->socks_request;
1995  const or_options_t *options = get_options();
1996  connection_t *base_conn = ENTRY_TO_CONN(conn);
1997  time_t now = time(NULL);
1998  rewrite_result_t rr;
1999 
2000  /* First we'll do the rewrite part. Let's see if we get a reasonable
2001  * answer.
2002  */
2003  memset(&rr, 0, sizeof(rr));
2004  connection_ap_handshake_rewrite(conn,&rr);
2005 
2006  if (rr.should_close) {
2007  /* connection_ap_handshake_rewrite told us to close the connection:
2008  * either because it sent back an answer, or because it sent back an
2009  * error */
2010  connection_mark_unattached_ap(conn, rr.end_reason);
2011  if (END_STREAM_REASON_DONE == (rr.end_reason & END_STREAM_REASON_MASK))
2012  return 0;
2013  else
2014  return -1;
2015  }
2016 
2017  const time_t map_expires = rr.map_expires;
2018  const int automap = rr.automap;
2019  const addressmap_entry_source_t exit_source = rr.exit_source;
2020 
2021  /* Now, we parse the address to see if it's an .onion or .exit or
2022  * other special address.
2023  */
2024  const hostname_type_t addresstype = parse_extended_hostname(socks->address);
2025 
2026  /* Now see whether the hostname is bogus. This could happen because of an
2027  * onion hostname whose format we don't recognize. */
2028  if (addresstype == BAD_HOSTNAME) {
2029  control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
2030  escaped(socks->address));
2031  connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2032  return -1;
2033  }
2034 
2035  /* If this is a .exit hostname, strip off the .name.exit part, and
2036  * see whether we're willing to connect there, and and otherwise handle the
2037  * .exit address.
2038  *
2039  * We'll set chosen_exit_name and/or close the connection as appropriate.
2040  */
2041  if (addresstype == EXIT_HOSTNAME) {
2042  /* If StrictNodes is not set, then .exit overrides ExcludeNodes but
2043  * not ExcludeExitNodes. */
2044  routerset_t *excludeset = options->StrictNodes ?
2045  options->ExcludeExitNodesUnion_ : options->ExcludeExitNodes;
2046  const node_t *node = NULL;
2047 
2048  /* If this .exit was added by an AUTOMAP, then it came straight from
2049  * a user. That's not safe. */
2050  if (exit_source == ADDRMAPSRC_AUTOMAP) {
2051  /* Whoops; this one is stale. It must have gotten added earlier?
2052  * (Probably this is not possible, since AllowDotExit no longer
2053  * exists.) */
2054  log_warn(LD_APP,"Stale automapped address for '%s.exit'. Refusing.",
2055  safe_str_client(socks->address));
2056  control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
2057  escaped(socks->address));
2058  connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2059  tor_assert_nonfatal_unreached();
2060  return -1;
2061  }
2062 
2063  /* Double-check to make sure there are no .exits coming from
2064  * impossible/weird sources. */
2065  if (exit_source == ADDRMAPSRC_DNS || exit_source == ADDRMAPSRC_NONE) {
2066  /* It shouldn't be possible to get a .exit address from any of these
2067  * sources. */
2068  log_warn(LD_BUG,"Address '%s.exit', with impossible source for the "
2069  ".exit part. Refusing.",
2070  safe_str_client(socks->address));
2071  control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
2072  escaped(socks->address));
2073  connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2074  return -1;
2075  }
2076 
2077  tor_assert(!automap);
2078 
2079  /* Now, find the character before the .(name) part.
2080  * (The ".exit" part got stripped off by "parse_extended_hostname").
2081  *
2082  * We're going to put the exit name into conn->chosen_exit_name, and
2083  * look up a node correspondingly. */
2084  char *s = strrchr(socks->address,'.');
2085  if (s) {
2086  /* The address was of the form "(stuff).(name).exit */
2087  if (s[1] != '\0') {
2088  /* Looks like a real .exit one. */
2089  conn->chosen_exit_name = tor_strdup(s+1);
2090  node = node_get_by_nickname(conn->chosen_exit_name, 0);
2091 
2092  if (exit_source == ADDRMAPSRC_TRACKEXIT) {
2093  /* We 5 tries before it expires the addressmap */
2095  }
2096  *s = 0;
2097  } else {
2098  /* Oops, the address was (stuff)..exit. That's not okay. */
2099  log_warn(LD_APP,"Malformed exit address '%s.exit'. Refusing.",
2100  safe_str_client(socks->address));
2101  control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
2102  escaped(socks->address));
2103  connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2104  return -1;
2105  }
2106  } else {
2107  /* It looks like they just asked for "foo.exit". That's a special
2108  * form that means (foo's address).foo.exit. */
2109 
2110  conn->chosen_exit_name = tor_strdup(socks->address);
2111  node = node_get_by_nickname(conn->chosen_exit_name, 0);
2112  if (node) {
2113  *socks->address = 0;
2114  node_get_address_string(node, socks->address, sizeof(socks->address));
2115  }
2116  }
2117 
2118  /* Now make sure that the chosen exit exists... */
2119  if (!node) {
2120  log_warn(LD_APP,
2121  "Unrecognized relay in exit address '%s.exit'. Refusing.",
2122  safe_str_client(socks->address));
2123  connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2124  return -1;
2125  }
2126  /* ...and make sure that it isn't excluded. */
2127  if (routerset_contains_node(excludeset, node)) {
2128  log_warn(LD_APP,
2129  "Excluded relay in exit address '%s.exit'. Refusing.",
2130  safe_str_client(socks->address));
2131  connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2132  return -1;
2133  }
2134  /* XXXX-1090 Should we also allow foo.bar.exit if ExitNodes is set and
2135  Bar is not listed in it? I say yes, but our revised manpage branch
2136  implies no. */
2137  }
2138 
2139  /* Now, we handle everything that isn't a .onion address. */
2140  if (addresstype != ONION_V2_HOSTNAME && addresstype != ONION_V3_HOSTNAME) {
2141  /* Not a hidden-service request. It's either a hostname or an IP,
2142  * possibly with a .exit that we stripped off. We're going to check
2143  * if we're allowed to connect/resolve there, and then launch the
2144  * appropriate request. */
2145 
2146  /* Check for funny characters in the address. */
2147  if (address_is_invalid_destination(socks->address, 1)) {
2148  control_event_client_status(LOG_WARN, "SOCKS_BAD_HOSTNAME HOSTNAME=%s",
2149  escaped(socks->address));
2150  log_warn(LD_APP,
2151  "Destination '%s' seems to be an invalid hostname. Failing.",
2152  safe_str_client(socks->address));
2153  connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2154  return -1;
2155  }
2156 
2157  /* socks->address is a non-onion hostname or IP address.
2158  * If we can't do any non-onion requests, refuse the connection.
2159  * If we have a hostname but can't do DNS, refuse the connection.
2160  * If we have an IP address, but we can't use that address family,
2161  * refuse the connection.
2162  *
2163  * If we can do DNS requests, and we can use at least one address family,
2164  * then we have to resolve the address first. Then we'll know if it
2165  * resolves to a usable address family. */
2166 
2167  /* First, check if all non-onion traffic is disabled */
2168  if (!conn->entry_cfg.dns_request && !conn->entry_cfg.ipv4_traffic
2169  && !conn->entry_cfg.ipv6_traffic) {
2170  log_warn(LD_APP, "Refusing to connect to non-hidden-service hostname "
2171  "or IP address %s because Port has OnionTrafficOnly set (or "
2172  "NoDNSRequest, NoIPv4Traffic, and NoIPv6Traffic).",
2173  safe_str_client(socks->address));
2174  connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2175  return -1;
2176  }
2177 
2178  /* Then check if we have a hostname or IP address, and whether DNS or
2179  * the IP address family are permitted. Reject if not. */
2180  tor_addr_t dummy_addr;
2181  int socks_family = tor_addr_parse(&dummy_addr, socks->address);
2182  /* family will be -1 for a non-onion hostname that's not an IP */
2183  if (socks_family == -1) {
2184  if (!conn->entry_cfg.dns_request) {
2185  log_warn(LD_APP, "Refusing to connect to hostname %s "
2186  "because Port has NoDNSRequest set.",
2187  safe_str_client(socks->address));
2188  connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2189  return -1;
2190  }
2191  } else if (socks_family == AF_INET) {
2192  if (!conn->entry_cfg.ipv4_traffic) {
2193  log_warn(LD_APP, "Refusing to connect to IPv4 address %s because "
2194  "Port has NoIPv4Traffic set.",
2195  safe_str_client(socks->address));
2196  connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2197  return -1;
2198  }
2199  } else if (socks_family == AF_INET6) {
2200  if (!conn->entry_cfg.ipv6_traffic) {
2201  log_warn(LD_APP, "Refusing to connect to IPv6 address %s because "
2202  "Port has NoIPv6Traffic set.",
2203  safe_str_client(socks->address));
2204  connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2205  return -1;
2206  }
2207  } else {
2208  tor_assert_nonfatal_unreached_once();
2209  }
2210 
2211  /* See if this is a hostname lookup that we can answer immediately.
2212  * (For example, an attempt to look up the IP address for an IP address.)
2213  */
2214  if (socks->command == SOCKS_COMMAND_RESOLVE) {
2215  tor_addr_t answer;
2216  /* Reply to resolves immediately if we can. */
2217  if (tor_addr_parse(&answer, socks->address) >= 0) {/* is it an IP? */
2218  /* remember _what_ is supposed to have been resolved. */
2219  strlcpy(socks->address, rr.orig_address, sizeof(socks->address));
2221  map_expires);
2222  connection_mark_unattached_ap(conn,
2223  END_STREAM_REASON_DONE |
2225  return 0;
2226  }
2227  tor_assert(!automap);
2228  rep_hist_note_used_resolve(now); /* help predict this next time */
2229  } else if (socks->command == SOCKS_COMMAND_CONNECT) {
2230  /* Now see if this is a connect request that we can reject immediately */
2231 
2232  tor_assert(!automap);
2233  /* Don't allow connections to port 0. */
2234  if (socks->port == 0) {
2235  log_notice(LD_APP,"Application asked to connect to port 0. Refusing.");
2236  connection_mark_unattached_ap(conn, END_STREAM_REASON_TORPROTOCOL);
2237  return -1;
2238  }
2239  /* You can't make connections to internal addresses, by default.
2240  * Exceptions are begindir requests (where the address is meaningless),
2241  * or cases where you've hand-configured a particular exit, thereby
2242  * making the local address meaningful. */
2243  if (options->ClientRejectInternalAddresses &&
2244  !conn->use_begindir && !conn->chosen_exit_name && !circ) {
2245  /* If we reach this point then we don't want to allow internal
2246  * addresses. Check if we got one. */
2247  tor_addr_t addr;
2248  if (tor_addr_hostname_is_local(socks->address) ||
2249  (tor_addr_parse(&addr, socks->address) >= 0 &&
2250  tor_addr_is_internal(&addr, 0))) {
2251  /* If this is an explicit private address with no chosen exit node,
2252  * then we really don't want to try to connect to it. That's
2253  * probably an error. */
2254  if (conn->is_transparent_ap) {
2255 #define WARN_INTRVL_LOOP 300
2256  static ratelim_t loop_warn_limit = RATELIM_INIT(WARN_INTRVL_LOOP);
2257  char *m;
2258  if ((m = rate_limit_log(&loop_warn_limit, approx_time()))) {
2259  log_warn(LD_NET,
2260  "Rejecting request for anonymous connection to private "
2261  "address %s on a TransPort or NATDPort. Possible loop "
2262  "in your NAT rules?%s", safe_str_client(socks->address),
2263  m);
2264  tor_free(m);
2265  }
2266  } else {
2267 #define WARN_INTRVL_PRIV 300
2268  static ratelim_t priv_warn_limit = RATELIM_INIT(WARN_INTRVL_PRIV);
2269  char *m;
2270  if ((m = rate_limit_log(&priv_warn_limit, approx_time()))) {
2271  log_warn(LD_NET,
2272  "Rejecting SOCKS request for anonymous connection to "
2273  "private address %s.%s",
2274  safe_str_client(socks->address),m);
2275  tor_free(m);
2276  }
2277  }
2278  connection_mark_unattached_ap(conn, END_STREAM_REASON_PRIVATE_ADDR);
2279  return -1;
2280  }
2281  } /* end "if we should check for internal addresses" */
2282 
2283  /* Okay. We're still doing a CONNECT, and it wasn't a private
2284  * address. Here we do special handling for literal IP addresses,
2285  * to see if we should reject this preemptively, and to set up
2286  * fields in conn->entry_cfg to tell the exit what AF we want. */
2287  {
2288  tor_addr_t addr;
2289  /* XXX Duplicate call to tor_addr_parse. */
2290  if (tor_addr_parse(&addr, socks->address) >= 0) {
2291  /* If we reach this point, it's an IPv4 or an IPv6 address. */
2292  sa_family_t family = tor_addr_family(&addr);
2293 
2294  if ((family == AF_INET && ! conn->entry_cfg.ipv4_traffic) ||
2295  (family == AF_INET6 && ! conn->entry_cfg.ipv6_traffic)) {
2296  /* You can't do an IPv4 address on a v6-only socks listener,
2297  * or vice versa. */
2298  log_warn(LD_NET, "Rejecting SOCKS request for an IP address "
2299  "family that this listener does not support.");
2300  connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2301  return -1;
2302  } else if (family == AF_INET6 && socks->socks_version == 4) {
2303  /* You can't make a socks4 request to an IPv6 address. Socks4
2304  * doesn't support that. */
2305  log_warn(LD_NET, "Rejecting SOCKS4 request for an IPv6 address.");
2306  connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2307  return -1;
2308  } else if (socks->socks_version == 4 &&
2309  !conn->entry_cfg.ipv4_traffic) {
2310  /* You can't do any kind of Socks4 request when IPv4 is forbidden.
2311  *
2312  * XXX raise this check outside the enclosing block? */
2313  log_warn(LD_NET, "Rejecting SOCKS4 request on a listener with "
2314  "no IPv4 traffic supported.");
2315  connection_mark_unattached_ap(conn, END_STREAM_REASON_ENTRYPOLICY);
2316  return -1;
2317  } else if (family == AF_INET6) {
2318  /* Tell the exit: we won't accept any ipv4 connection to an IPv6
2319  * address. */
2320  conn->entry_cfg.ipv4_traffic = 0;
2321  } else if (family == AF_INET) {
2322  /* Tell the exit: we won't accept any ipv6 connection to an IPv4
2323  * address. */
2324  conn->entry_cfg.ipv6_traffic = 0;
2325  }
2326  }
2327  }
2328 
2329  /* we never allow IPv6 answers on socks4. (TODO: Is this smart?) */
2330  if (socks->socks_version == 4)
2331  conn->entry_cfg.ipv6_traffic = 0;
2332 
2333  /* Still handling CONNECT. Now, check for exit enclaves. (Which we
2334  * don't do on BEGIN_DIR, or when there is a chosen exit.)
2335  *
2336  * TODO: Should we remove this? Exit enclaves are nutty and don't
2337  * work very well
2338  */
2339  if (!conn->use_begindir && !conn->chosen_exit_name && !circ) {
2340  /* see if we can find a suitable enclave exit */
2341  const node_t *r =
2343  if (r) {
2344  log_info(LD_APP,
2345  "Redirecting address %s to exit at enclave router %s",
2346  safe_str_client(socks->address), node_describe(r));
2347  /* use the hex digest, not nickname, in case there are two
2348  routers with this nickname */
2349  conn->chosen_exit_name =
2350  tor_strdup(hex_str(r->identity, DIGEST_LEN));
2351  conn->chosen_exit_optional = 1;
2352  }
2353  }
2354 
2355  /* Still handling CONNECT: warn or reject if it's using a dangerous
2356  * port. */
2357  if (!conn->use_begindir && !conn->chosen_exit_name && !circ)
2358  if (consider_plaintext_ports(conn, socks->port) < 0)
2359  return -1;
2360 
2361  /* Remember the port so that we will predict that more requests
2362  there will happen in the future. */
2363  if (!conn->use_begindir) {
2364  /* help predict this next time */
2365  rep_hist_note_used_port(now, socks->port);
2366  }
2367  } else if (socks->command == SOCKS_COMMAND_RESOLVE_PTR) {
2368  rep_hist_note_used_resolve(now); /* help predict this next time */
2369  /* no extra processing needed */
2370  } else {
2371  /* We should only be doing CONNECT, RESOLVE, or RESOLVE_PTR! */
2373  }
2374 
2375  /* Okay. At this point we've set chosen_exit_name if needed, rewritten the
2376  * address, and decided not to reject it for any number of reasons. Now
2377  * mark the connection as waiting for a circuit, and try to attach it!
2378  */
2379  base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
2380 
2381  /* If we were given a circuit to attach to, try to attach. Otherwise,
2382  * try to find a good one and attach to that. */
2383  int rv;
2384  if (circ) {
2385  rv = connection_ap_handshake_attach_chosen_circuit(conn, circ, cpath);
2386  } else {
2387  /* We'll try to attach it at the next event loop, or whenever
2388  * we call connection_ap_attach_pending() */
2389  connection_ap_mark_as_pending_circuit(conn);
2390  rv = 0;
2391  }
2392 
2393  /* If the above function returned 0 then we're waiting for a circuit.
2394  * if it returned 1, we're attached. Both are okay. But if it returned
2395  * -1, there was an error, so make sure the connection is marked, and
2396  * return -1. */
2397  if (rv < 0) {
2398  if (!base_conn->marked_for_close)
2399  connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
2400  return -1;
2401  }
2402 
2403  return 0;
2404  } else {
2405  /* If we get here, it's a request for a .onion address! */
2406  tor_assert(addresstype == ONION_V2_HOSTNAME ||
2407  addresstype == ONION_V3_HOSTNAME);
2408  tor_assert(!automap);
2409  return connection_ap_handle_onion(conn, socks, circ, addresstype);
2410  }
2411 
2412  return 0; /* unreached but keeps the compiler happy */
2413 }
2414 
2415 #ifdef TRANS_PF
2416 static int pf_socket = -1;
2417 int
2418 get_pf_socket(void)
2419 {
2420  int pf;
2421  /* This should be opened before dropping privileges. */
2422  if (pf_socket >= 0)
2423  return pf_socket;
2424 
2425 #if defined(OpenBSD)
2426  /* only works on OpenBSD */
2427  pf = tor_open_cloexec("/dev/pf", O_RDONLY, 0);
2428 #else
2429  /* works on NetBSD and FreeBSD */
2430  pf = tor_open_cloexec("/dev/pf", O_RDWR, 0);
2431 #endif /* defined(OpenBSD) */
2432 
2433  if (pf < 0) {
2434  log_warn(LD_NET, "open(\"/dev/pf\") failed: %s", strerror(errno));
2435  return -1;
2436  }
2437 
2438  pf_socket = pf;
2439  return pf_socket;
2440 }
2441 #endif /* defined(TRANS_PF) */
2442 
2443 #if defined(TRANS_NETFILTER) || defined(TRANS_PF) || \
2444  defined(TRANS_TPROXY)
2445 
2447 static int
2448 destination_from_socket(entry_connection_t *conn, socks_request_t *req)
2449 {
2450  struct sockaddr_storage orig_dst;
2451  socklen_t orig_dst_len = sizeof(orig_dst);
2452  tor_addr_t addr;
2453 
2454 #ifdef TRANS_TPROXY
2455  if (get_options()->TransProxyType_parsed == TPT_TPROXY) {
2456  if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&orig_dst,
2457  &orig_dst_len) < 0) {
2458  int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
2459  log_warn(LD_NET, "getsockname() failed: %s", tor_socket_strerror(e));
2460  return -1;
2461  }
2462  goto done;
2463  }
2464 #endif /* defined(TRANS_TPROXY) */
2465 
2466 #ifdef TRANS_NETFILTER
2467  int rv = -1;
2468  switch (ENTRY_TO_CONN(conn)->socket_family) {
2469 #ifdef TRANS_NETFILTER_IPV4
2470  case AF_INET:
2471  rv = getsockopt(ENTRY_TO_CONN(conn)->s, SOL_IP, SO_ORIGINAL_DST,
2472  (struct sockaddr*)&orig_dst, &orig_dst_len);
2473  break;
2474 #endif /* defined(TRANS_NETFILTER_IPV4) */
2475 #ifdef TRANS_NETFILTER_IPV6
2476  case AF_INET6:
2477  rv = getsockopt(ENTRY_TO_CONN(conn)->s, SOL_IPV6, IP6T_SO_ORIGINAL_DST,
2478  (struct sockaddr*)&orig_dst, &orig_dst_len);
2479  break;
2480 #endif /* defined(TRANS_NETFILTER_IPV6) */
2481  default:
2482  log_warn(LD_BUG,
2483  "Received transparent data from an unsuported socket family %d",
2484  ENTRY_TO_CONN(conn)->socket_family);
2485  return -1;
2486  }
2487  if (rv < 0) {
2488  int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
2489  log_warn(LD_NET, "getsockopt() failed: %s", tor_socket_strerror(e));
2490  return -1;
2491  }
2492  goto done;
2493 #elif defined(TRANS_PF)
2494  if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&orig_dst,
2495  &orig_dst_len) < 0) {
2496  int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
2497  log_warn(LD_NET, "getsockname() failed: %s", tor_socket_strerror(e));
2498  return -1;
2499  }
2500  goto done;
2501 #else
2502  (void)conn;
2503  (void)req;
2504  log_warn(LD_BUG, "Unable to determine destination from socket.");
2505  return -1;
2506 #endif /* defined(TRANS_NETFILTER) || ... */
2507 
2508  done:
2509  tor_addr_from_sockaddr(&addr, (struct sockaddr*)&orig_dst, &req->port);
2510  tor_addr_to_str(req->address, &addr, sizeof(req->address), 1);
2511 
2512  return 0;
2513 }
2514 #endif /* defined(TRANS_NETFILTER) || defined(TRANS_PF) || ... */
2515 
2516 #ifdef TRANS_PF
2517 static int
2518 destination_from_pf(entry_connection_t *conn, socks_request_t *req)
2519 {
2520  struct sockaddr_storage proxy_addr;
2521  socklen_t proxy_addr_len = sizeof(proxy_addr);
2522  struct sockaddr *proxy_sa = (struct sockaddr*) &proxy_addr;
2523  struct pfioc_natlook pnl;
2524  tor_addr_t addr;
2525  int pf = -1;
2526 
2527  if (getsockname(ENTRY_TO_CONN(conn)->s, (struct sockaddr*)&proxy_addr,
2528  &proxy_addr_len) < 0) {
2529  int e = tor_socket_errno(ENTRY_TO_CONN(conn)->s);
2530  log_warn(LD_NET, "getsockname() to determine transocks destination "
2531  "failed: %s", tor_socket_strerror(e));
2532  return -1;
2533  }
2534 
2535 #ifdef __FreeBSD__
2536  if (get_options()->TransProxyType_parsed == TPT_IPFW) {
2537  /* ipfw(8) is used and in this case getsockname returned the original
2538  destination */
2539  if (tor_addr_from_sockaddr(&addr, proxy_sa, &req->port) < 0) {
2541  return -1;
2542  }
2543 
2544  tor_addr_to_str(req->address, &addr, sizeof(req->address), 0);
2545 
2546  return 0;
2547  }
2548 #endif /* defined(__FreeBSD__) */
2549 
2550  memset(&pnl, 0, sizeof(pnl));
2551  pnl.proto = IPPROTO_TCP;
2552  pnl.direction = PF_OUT;
2553  if (proxy_sa->sa_family == AF_INET) {
2554  struct sockaddr_in *sin = (struct sockaddr_in *)proxy_sa;
2555  pnl.af = AF_INET;
2556  pnl.saddr.v4.s_addr = tor_addr_to_ipv4n(&ENTRY_TO_CONN(conn)->addr);
2557  pnl.sport = htons(ENTRY_TO_CONN(conn)->port);
2558  pnl.daddr.v4.s_addr = sin->sin_addr.s_addr;
2559  pnl.dport = sin->sin_port;
2560  } else if (proxy_sa->sa_family == AF_INET6) {
2561  struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)proxy_sa;
2562  pnl.af = AF_INET6;
2563  memcpy(&pnl.saddr.v6, tor_addr_to_in6(&ENTRY_TO_CONN(conn)->addr),
2564  sizeof(struct in6_addr));
2565  pnl.sport = htons(ENTRY_TO_CONN(conn)->port);
2566  memcpy(&pnl.daddr.v6, &sin6->sin6_addr, sizeof(struct in6_addr));
2567  pnl.dport = sin6->sin6_port;
2568  } else {
2569  log_warn(LD_NET, "getsockname() gave an unexpected address family (%d)",
2570  (int)proxy_sa->sa_family);
2571  return -1;
2572  }
2573 
2574  pf = get_pf_socket();
2575  if (pf<0)
2576  return -1;
2577 
2578  if (ioctl(pf, DIOCNATLOOK, &pnl) < 0) {
2579  log_warn(LD_NET, "ioctl(DIOCNATLOOK) failed: %s", strerror(errno));
2580  return -1;
2581  }
2582 
2583  if (pnl.af == AF_INET) {
2584  tor_addr_from_ipv4n(&addr, pnl.rdaddr.v4.s_addr);
2585  } else if (pnl.af == AF_INET6) {
2586  tor_addr_from_in6(&addr, &pnl.rdaddr.v6);
2587  } else {
2589  return -1;
2590  }
2591 
2592  tor_addr_to_str(req->address, &addr, sizeof(req->address), 1);
2593  req->port = ntohs(pnl.rdport);
2594 
2595  return 0;
2596 }
2597 #endif /* defined(TRANS_PF) */
2598 
2606 static int
2608  socks_request_t *req)
2609 {
2610 #ifdef TRANS_NETFILTER
2611  return destination_from_socket(conn, req);
2612 #elif defined(TRANS_PF)
2613  const or_options_t *options = get_options();
2614 
2615  if (options->TransProxyType_parsed == TPT_PF_DIVERT)
2616  return destination_from_socket(conn, req);
2617 
2618  if (options->TransProxyType_parsed == TPT_DEFAULT ||
2619  options->TransProxyType_parsed == TPT_IPFW)
2620  return destination_from_pf(conn, req);
2621 
2622  (void)conn;
2623  (void)req;
2624  log_warn(LD_BUG, "Proxy destination determination mechanism %s unknown.",
2625  options->TransProxyType);
2626  return -1;
2627 #else
2628  (void)conn;
2629  (void)req;
2630  log_warn(LD_BUG, "Called connection_ap_get_original_destination, but no "
2631  "transparent proxy method was configured.");
2632  return -1;
2633 #endif /* defined(TRANS_NETFILTER) || ... */
2634 }
2635 
2646 static int
2648 {
2649  socks_request_t *socks;
2650  int sockshere;
2651  const or_options_t *options = get_options();
2652  int had_reply = 0;
2653  connection_t *base_conn = ENTRY_TO_CONN(conn);
2654 
2655  tor_assert(conn);
2656  tor_assert(base_conn->type == CONN_TYPE_AP);
2657  tor_assert(base_conn->state == AP_CONN_STATE_SOCKS_WAIT);
2658  tor_assert(conn->socks_request);
2659  socks = conn->socks_request;
2660 
2661  log_debug(LD_APP,"entered.");
2662 
2663  sockshere = fetch_from_buf_socks(base_conn->inbuf, socks,
2664  options->TestSocks, options->SafeSocks);
2665 
2666  if (socks->replylen) {
2667  had_reply = 1;
2668  connection_buf_add((const char*)socks->reply, socks->replylen,
2669  base_conn);
2670  socks->replylen = 0;
2671  if (sockshere == -1) {
2672  /* An invalid request just got a reply, no additional
2673  * one is necessary. */
2674  socks->has_finished = 1;
2675  }
2676  }
2677 
2678  if (sockshere == 0) {
2679  log_debug(LD_APP,"socks handshake not all here yet.");
2680  return 0;
2681  } else if (sockshere == -1) {
2682  if (!had_reply) {
2683  log_warn(LD_APP,"Fetching socks handshake failed. Closing.");
2686  }
2687  connection_mark_unattached_ap(conn,
2690  return -1;
2691  } /* else socks handshake is done, continue processing */
2692 
2693  if (SOCKS_COMMAND_IS_CONNECT(socks->command))
2694  control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2695  else
2696  control_event_stream_status(conn, STREAM_EVENT_NEW_RESOLVE, 0);
2697 
2698  return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
2699 }
2700 
2708 int
2710 {
2711  socks_request_t *socks;
2712 
2713  tor_assert(conn);
2714  tor_assert(conn->socks_request);
2715  socks = conn->socks_request;
2716 
2717  /* pretend that a socks handshake completed so we don't try to
2718  * send a socks reply down a transparent conn */
2719  socks->command = SOCKS_COMMAND_CONNECT;
2720  socks->has_finished = 1;
2721 
2722  log_debug(LD_APP,"entered.");
2723 
2724  if (connection_ap_get_original_destination(conn, socks) < 0) {
2725  log_warn(LD_APP,"Fetching original destination failed. Closing.");
2726  connection_mark_unattached_ap(conn,
2728  return -1;
2729  }
2730  /* we have the original destination */
2731 
2732  control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2733 
2734  return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
2735 }
2736 
2748 static int
2750 {
2751  char tmp_buf[36], *tbuf, *daddr;
2752  size_t tlen = 30;
2753  int err, port_ok;
2754  socks_request_t *socks;
2755 
2756  tor_assert(conn);
2758  tor_assert(conn->socks_request);
2759  socks = conn->socks_request;
2760 
2761  log_debug(LD_APP,"entered.");
2762 
2763  /* look for LF-terminated "[DEST ip_addr port]"
2764  * where ip_addr is a dotted-quad and port is in string form */
2765  err = connection_buf_get_line(ENTRY_TO_CONN(conn), tmp_buf, &tlen);
2766  if (err == 0)
2767  return 0;
2768  if (err < 0) {
2769  log_warn(LD_APP,"NATD handshake failed (DEST too long). Closing");
2770  connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2771  return -1;
2772  }
2773 
2774  if (strcmpstart(tmp_buf, "[DEST ")) {
2775  log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
2776  "said: %s",
2777  escaped(tmp_buf));
2778  connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2779  return -1;
2780  }
2781 
2782  daddr = tbuf = &tmp_buf[0] + 6; /* after end of "[DEST " */
2783  if (!(tbuf = strchr(tbuf, ' '))) {
2784  log_warn(LD_APP,"NATD handshake was ill-formed; closing. The client "
2785  "said: %s",
2786  escaped(tmp_buf));
2787  connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2788  return -1;
2789  }
2790  *tbuf++ = '\0';
2791 
2792  /* pretend that a socks handshake completed so we don't try to
2793  * send a socks reply down a natd conn */
2794  strlcpy(socks->address, daddr, sizeof(socks->address));
2795  socks->port = (uint16_t)
2796  tor_parse_long(tbuf, 10, 1, 65535, &port_ok, &daddr);
2797  if (!port_ok) {
2798  log_warn(LD_APP,"NATD handshake failed; port %s is ill-formed or out "
2799  "of range.", escaped(tbuf));
2800  connection_mark_unattached_ap(conn, END_STREAM_REASON_INVALID_NATD_DEST);
2801  return -1;
2802  }
2803 
2804  socks->command = SOCKS_COMMAND_CONNECT;
2805  socks->has_finished = 1;
2806 
2807  control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2808 
2810 
2811  return connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
2812 }
2813 
2814 static const char HTTP_CONNECT_IS_NOT_AN_HTTP_PROXY_MSG[] =
2815  "HTTP/1.0 405 Method Not Allowed\r\n"
2816  "Content-Type: text/html; charset=iso-8859-1\r\n\r\n"
2817  "<html>\n"
2818  "<head>\n"
2819  "<title>This is an HTTP CONNECT tunnel, not a full HTTP Proxy</title>\n"
2820  "</head>\n"
2821  "<body>\n"
2822  "<h1>This is an HTTP CONNECT tunnel, not an HTTP proxy.</h1>\n"
2823  "<p>\n"
2824  "It appears you have configured your web browser to use this Tor port as\n"
2825  "an HTTP proxy.\n"
2826  "</p><p>\n"
2827  "This is not correct: This port is configured as a CONNECT tunnel, not\n"
2828  "an HTTP proxy. Please configure your client accordingly. You can also\n"
2829  "use HTTPS; then the client should automatically use HTTP CONNECT."
2830  "</p>\n"
2831  "<p>\n"
2832  "See <a href=\"https://www.torproject.org/documentation.html\">"
2833  "https://www.torproject.org/documentation.html</a> for more "
2834  "information.\n"
2835  "</p>\n"
2836  "</body>\n"
2837  "</html>\n";
2838 
2845 STATIC int
2847 {
2848  if (BUG(ENTRY_TO_CONN(conn)->state != AP_CONN_STATE_HTTP_CONNECT_WAIT))
2849  return -1;
2850 
2851  char *headers = NULL, *body = NULL;
2852  char *command = NULL, *addrport = NULL;
2853  char *addr = NULL;
2854  size_t bodylen = 0;
2855 
2856  const char *errmsg = NULL;
2857  int rv = 0;
2858 
2859  const int http_status =
2860  fetch_from_buf_http(ENTRY_TO_CONN(conn)->inbuf, &headers, 8192,
2861  &body, &bodylen, 1024, 0);
2862  if (http_status < 0) {
2863  /* Bad http status */
2864  errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
2865  goto err;
2866  } else if (http_status == 0) {
2867  /* no HTTP request yet. */
2868  goto done;
2869  }
2870 
2871  const int cmd_status = parse_http_command(headers, &command, &addrport);
2872  if (cmd_status < 0) {
2873  errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
2874  goto err;
2875  }
2876  tor_assert(command);
2877  tor_assert(addrport);
2878  if (strcasecmp(command, "connect")) {
2879  errmsg = HTTP_CONNECT_IS_NOT_AN_HTTP_PROXY_MSG;
2880  goto err;
2881  }
2882 
2883  tor_assert(conn->socks_request);
2884  socks_request_t *socks = conn->socks_request;
2885  uint16_t port;
2886  if (tor_addr_port_split(LOG_WARN, addrport, &addr, &port) < 0) {
2887  errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
2888  goto err;
2889  }
2890  if (strlen(addr) >= MAX_SOCKS_ADDR_LEN) {
2891  errmsg = "HTTP/1.0 414 Request-URI Too Long\r\n\r\n";
2892  goto err;
2893  }
2894 
2895  /* Abuse the 'username' and 'password' fields here. They are already an
2896  * abuse. */
2897  {
2898  char *authorization = http_get_header(headers, "Proxy-Authorization: ");
2899  if (authorization) {
2900  socks->username = authorization; // steal reference
2901  socks->usernamelen = strlen(authorization);
2902  }
2903  char *isolation = http_get_header(headers, "X-Tor-Stream-Isolation: ");
2904  if (isolation) {
2905  socks->password = isolation; // steal reference
2906  socks->passwordlen = strlen(isolation);
2907  }
2908  }
2909 
2910  socks->command = SOCKS_COMMAND_CONNECT;
2912  strlcpy(socks->address, addr, sizeof(socks->address));
2913  socks->port = port;
2914 
2915  control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
2916 
2917  rv = connection_ap_rewrite_and_attach_if_allowed(conn, NULL, NULL);
2918 
2919  // XXXX send a "100 Continue" message?
2920 
2921  goto done;
2922 
2923  err:
2924  if (BUG(errmsg == NULL))
2925  errmsg = "HTTP/1.0 400 Bad Request\r\n\r\n";
2926  log_info(LD_EDGE, "HTTP tunnel error: saying %s", escaped(errmsg));
2927  connection_buf_add(errmsg, strlen(errmsg), ENTRY_TO_CONN(conn));
2928  /* Mark it as "has_finished" so that we don't try to send an extra socks
2929  * reply. */
2930  conn->socks_request->has_finished = 1;
2931  connection_mark_unattached_ap(conn,
2934 
2935  done:
2936  tor_free(headers);
2937  tor_free(body);
2938  tor_free(command);
2939  tor_free(addrport);
2940  tor_free(addr);
2941  return rv;
2942 }
2943 
2947 streamid_t
2949 {
2950  edge_connection_t *tmpconn;
2951  streamid_t test_stream_id;
2952  uint32_t attempts=0;
2953 
2954  again:
2955  test_stream_id = circ->next_stream_id++;
2956  if (++attempts > 1<<16) {
2957  /* Make sure we don't loop forever if all stream_id's are used. */
2958  log_warn(LD_APP,"No unused stream IDs. Failing.");
2959  return 0;
2960  }
2961  if (test_stream_id == 0)
2962  goto again;
2963  for (tmpconn = circ->p_streams; tmpconn; tmpconn=tmpconn->next_stream)
2964  if (tmpconn->stream_id == test_stream_id)
2965  goto again;
2966 
2968  test_stream_id))
2969  goto again;
2970 
2971  return test_stream_id;
2972 }
2973 
2976 static int
2978 {
2979  const edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(conn);
2980  /* We can only send optimistic data if we're connected to an open
2981  general circuit. */
2982  if (edge_conn->on_circuit == NULL ||
2983  edge_conn->on_circuit->state != CIRCUIT_STATE_OPEN ||
2984  (edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_GENERAL &&
2988  return 0;
2989 
2990  return conn->may_use_optimistic_data;
2991 }
2992 
2995 static uint32_t
2997 {
2998  edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
2999  const node_t *exitnode = NULL;
3000  const crypt_path_t *cpath_layer = edge_conn->cpath_layer;
3001  uint32_t flags = 0;
3002 
3003  /* No flags for begindir */
3004  if (ap_conn->use_begindir)
3005  return 0;
3006 
3007  /* No flags for hidden services. */
3008  if (edge_conn->on_circuit->purpose != CIRCUIT_PURPOSE_C_GENERAL)
3009  return 0;
3010 
3011  /* If only IPv4 is supported, no flags */
3012  if (ap_conn->entry_cfg.ipv4_traffic && !ap_conn->entry_cfg.ipv6_traffic)
3013  return 0;
3014 
3015  if (! cpath_layer ||
3016  ! cpath_layer->extend_info)
3017  return 0;
3018 
3019  if (!ap_conn->entry_cfg.ipv4_traffic)
3020  flags |= BEGIN_FLAG_IPV4_NOT_OK;
3021 
3022  exitnode = node_get_by_id(cpath_layer->extend_info->identity_digest);
3023 
3024  if (ap_conn->entry_cfg.ipv6_traffic && exitnode) {
3025  tor_addr_t a;
3026  tor_addr_make_null(&a, AF_INET6);
3028  exitnode)
3029  != ADDR_POLICY_REJECTED) {
3030  /* Only say "IPv6 OK" if the exit node supports IPv6. Otherwise there's
3031  * no point. */
3032  flags |= BEGIN_FLAG_IPV6_OK;
3033  }
3034  }
3035 
3036  if (flags == BEGIN_FLAG_IPV6_OK) {
3037  /* When IPv4 and IPv6 are both allowed, consider whether to say we
3038  * prefer IPv6. Otherwise there's no point in declaring a preference */
3039  if (ap_conn->entry_cfg.prefer_ipv6)
3040  flags |= BEGIN_FLAG_IPV6_PREFERRED;
3041  }
3042 
3043  if (flags == BEGIN_FLAG_IPV4_NOT_OK) {
3044  log_warn(LD_EDGE, "I'm about to ask a node for a connection that I "
3045  "am telling it to fulfil with neither IPv4 nor IPv6. That's "
3046  "not going to work. Did you perhaps ask for an IPv6 address "
3047  "on an IPv4Only port, or vice versa?");
3048  }
3049 
3050  return flags;
3051 }
3052 
3059 connection_ap_handshake_send_begin,(entry_connection_t *ap_conn))
3060 {
3061  char payload[CELL_PAYLOAD_SIZE];
3062  int payload_len;
3063  int begin_type;
3064  const or_options_t *options = get_options();
3065  origin_circuit_t *circ;
3066  edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
3067  connection_t *base_conn = TO_CONN(edge_conn);
3068  tor_assert(edge_conn->on_circuit);
3069  circ = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit);
3070 
3071  tor_assert(base_conn->type == CONN_TYPE_AP);
3073  tor_assert(ap_conn->socks_request);
3074  tor_assert(SOCKS_COMMAND_IS_CONNECT(ap_conn->socks_request->command));
3075 
3076  edge_conn->stream_id = get_unique_stream_id_by_circ(circ);
3077  if (edge_conn->stream_id==0) {
3078  /* XXXX+ Instead of closing this stream, we should make it get
3079  * retried on another circuit. */
3080  connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
3081 
3082  /* Mark this circuit "unusable for new streams". */
3084  return -1;
3085  }
3086 
3087  /* Set up begin cell flags. */
3088  edge_conn->begincell_flags = connection_ap_get_begincell_flags(ap_conn);
3089 
3090  tor_snprintf(payload,RELAY_PAYLOAD_SIZE, "%s:%d",
3091  (circ->base_.purpose == CIRCUIT_PURPOSE_C_GENERAL) ?
3092  ap_conn->socks_request->address : "",
3093  ap_conn->socks_request->port);
3094  payload_len = (int)strlen(payload)+1;
3095  if (payload_len <= RELAY_PAYLOAD_SIZE - 4 && edge_conn->begincell_flags) {
3096  set_uint32(payload + payload_len, htonl(edge_conn->begincell_flags));
3097  payload_len += 4;
3098  }
3099 
3100  log_info(LD_APP,
3101  "Sending relay cell %d on circ %u to begin stream %d.",
3102  (int)ap_conn->use_begindir,
3103  (unsigned)circ->base_.n_circ_id,
3104  edge_conn->stream_id);
3105 
3106  begin_type = ap_conn->use_begindir ?
3107  RELAY_COMMAND_BEGIN_DIR : RELAY_COMMAND_BEGIN;
3108 
3109  /* Check that circuits are anonymised, based on their type. */
3110  if (begin_type == RELAY_COMMAND_BEGIN) {
3111  /* This connection is a standard OR connection.
3112  * Make sure its path length is anonymous, or that we're in a
3113  * non-anonymous mode. */
3114  assert_circ_anonymity_ok(circ, options);
3115  } else if (begin_type == RELAY_COMMAND_BEGIN_DIR) {
3116  /* This connection is a begindir directory connection.
3117  * Look at the linked directory connection to access the directory purpose.
3118  * If a BEGINDIR connection is ever not linked, that's a bug. */
3119  if (BUG(!base_conn->linked)) {
3120  return -1;
3121  }
3122  connection_t *linked_dir_conn_base = base_conn->linked_conn;
3123  /* If the linked connection has been unlinked by other code, we can't send
3124  * a begin cell on it. */
3125  if (!linked_dir_conn_base) {
3126  return -1;
3127  }
3128  /* Sensitive directory connections must have an anonymous path length.
3129  * Otherwise, directory connections are typically one-hop.
3130  * This matches the earlier check for directory connection path anonymity
3131  * in directory_initiate_request(). */
3132  if (purpose_needs_anonymity(linked_dir_conn_base->purpose,
3133  TO_DIR_CONN(linked_dir_conn_base)->router_purpose,
3134  TO_DIR_CONN(linked_dir_conn_base)->requested_resource)) {
3135  assert_circ_anonymity_ok(circ, options);
3136  }
3137  } else {
3138  /* This code was written for the two connection types BEGIN and BEGIN_DIR
3139  */
3140  tor_assert_unreached();
3141  }
3142 
3143  if (connection_edge_send_command(edge_conn, begin_type,
3144  begin_type == RELAY_COMMAND_BEGIN ? payload : NULL,
3145  begin_type == RELAY_COMMAND_BEGIN ? payload_len : 0) < 0)
3146  return -1; /* circuit is closed, don't continue */
3147 
3148  edge_conn->package_window = STREAMWINDOW_START;
3149  edge_conn->deliver_window = STREAMWINDOW_START;
3150  base_conn->state = AP_CONN_STATE_CONNECT_WAIT;
3151  log_info(LD_APP,"Address/port sent, ap socket "TOR_SOCKET_T_FORMAT
3152  ", n_circ_id %u",
3153  base_conn->s, (unsigned)circ->base_.n_circ_id);
3154  control_event_stream_status(ap_conn, STREAM_EVENT_SENT_CONNECT, 0);
3155 
3156  /* If there's queued-up data, send it now */
3157  if ((connection_get_inbuf_len(base_conn) ||
3158  ap_conn->sending_optimistic_data) &&
3160  log_info(LD_APP, "Sending up to %ld + %ld bytes of queued-up data",
3161  (long)connection_get_inbuf_len(base_conn),
3162  ap_conn->sending_optimistic_data ?
3163  (long)buf_datalen(ap_conn->sending_optimistic_data) : 0);
3164  if (connection_edge_package_raw_inbuf(edge_conn, 1, NULL) < 0) {
3165  connection_mark_for_close(base_conn);
3166  }
3167  }
3168 
3169  return 0;
3170 }
3171 
3177 int
3179 {
3180  int payload_len, command;
3181  const char *string_addr;
3182  char inaddr_buf[REVERSE_LOOKUP_NAME_BUF_LEN];
3183  origin_circuit_t *circ;
3184  edge_connection_t *edge_conn = ENTRY_TO_EDGE_CONN(ap_conn);
3185  connection_t *base_conn = TO_CONN(edge_conn);
3186  tor_assert(edge_conn->on_circuit);
3187  circ = TO_ORIGIN_CIRCUIT(edge_conn->on_circuit);
3188 
3189  tor_assert(base_conn->type == CONN_TYPE_AP);
3191  tor_assert(ap_conn->socks_request);
3193 
3194  command = ap_conn->socks_request->command;
3195  tor_assert(SOCKS_COMMAND_IS_RESOLVE(command));
3196 
3197  edge_conn->stream_id = get_unique_stream_id_by_circ(circ);
3198  if (edge_conn->stream_id==0) {
3199  /* XXXX+ Instead of closing this stream, we should make it get
3200  * retried on another circuit. */
3201  connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
3202 
3203  /* Mark this circuit "unusable for new streams". */
3205  return -1;
3206  }
3207 
3208  if (command == SOCKS_COMMAND_RESOLVE) {
3209  string_addr = ap_conn->socks_request->address;
3210  payload_len = (int)strlen(string_addr)+1;
3211  } else {
3212  /* command == SOCKS_COMMAND_RESOLVE_PTR */
3213  const char *a = ap_conn->socks_request->address;
3214  tor_addr_t addr;
3215  int r;
3216 
3217  /* We're doing a reverse lookup. The input could be an IP address, or
3218  * could be an .in-addr.arpa or .ip6.arpa address */
3219  r = tor_addr_parse_PTR_name(&addr, a, AF_UNSPEC, 1);
3220  if (r <= 0) {
3221  log_warn(LD_APP, "Rejecting ill-formed reverse lookup of %s",
3222  safe_str_client(a));
3223  connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
3224  return -1;
3225  }
3226 
3227  r = tor_addr_to_PTR_name(inaddr_buf, sizeof(inaddr_buf), &addr);
3228  if (r < 0) {
3229  log_warn(LD_BUG, "Couldn't generate reverse lookup hostname of %s",
3230  safe_str_client(a));
3231  connection_mark_unattached_ap(ap_conn, END_STREAM_REASON_INTERNAL);
3232  return -1;
3233  }
3234 
3235  string_addr = inaddr_buf;
3236  payload_len = (int)strlen(inaddr_buf)+1;
3237  tor_assert(payload_len <= (int)sizeof(inaddr_buf));
3238  }
3239 
3240  log_debug(LD_APP,
3241  "Sending relay cell to begin stream %d.", edge_conn->stream_id);
3242 
3243  if (connection_edge_send_command(edge_conn,
3244  RELAY_COMMAND_RESOLVE,
3245  string_addr, payload_len) < 0)
3246  return -1; /* circuit is closed, don't continue */
3247 
3248  if (!base_conn->address) {
3249  /* This might be unnecessary. XXXX */
3250  base_conn->address = tor_addr_to_str_dup(&base_conn->addr);
3251  }
3252  base_conn->state = AP_CONN_STATE_RESOLVE_WAIT;
3253  log_info(LD_APP,"Address sent for resolve, ap socket "TOR_SOCKET_T_FORMAT
3254  ", n_circ_id %u",
3255  base_conn->s, (unsigned)circ->base_.n_circ_id);
3256  control_event_stream_status(ap_conn, STREAM_EVENT_SENT_RESOLVE, 0);
3257  return 0;
3258 }
3259 
3269  char *address, uint16_t port,
3270  const char *digest,
3271  int session_group, int isolation_flags,
3272  int use_begindir, int want_onehop)
3273 {
3274  entry_connection_t *conn;
3275  connection_t *base_conn;
3276 
3277  log_info(LD_APP,"Making internal %s tunnel to %s:%d ...",
3278  want_onehop ? "direct" : "anonymized",
3279  safe_str_client(address), port);
3280 
3282  base_conn = ENTRY_TO_CONN(conn);
3283  base_conn->linked = 1; /* so that we can add it safely below. */
3284 
3285  /* populate conn->socks_request */
3286 
3287  /* leave version at zero, so the socks_reply is empty */
3288  conn->socks_request->socks_version = 0;
3289  conn->socks_request->has_finished = 0; /* waiting for 'connected' */
3290  strlcpy(conn->socks_request->address, address,
3291  sizeof(conn->socks_request->address));
3292  conn->socks_request->port = port;
3293  conn->socks_request->command = SOCKS_COMMAND_CONNECT;
3294  conn->want_onehop = want_onehop;
3295  conn->use_begindir = use_begindir;
3296  if (use_begindir) {
3297  conn->chosen_exit_name = tor_malloc(HEX_DIGEST_LEN+2);
3298  conn->chosen_exit_name[0] = '$';
3299  tor_assert(digest);
3301  digest, DIGEST_LEN);
3302  }
3303 
3304  /* Populate isolation fields. */
3306  conn->original_dest_address = tor_strdup(address);
3307  conn->entry_cfg.session_group = session_group;
3308  conn->entry_cfg.isolation_flags = isolation_flags;
3309 
3310  base_conn->address = tor_strdup("(Tor_internal)");
3311  tor_addr_make_unspec(&base_conn->addr);
3312  base_conn->port = 0;
3313 
3314  connection_link_connections(partner, base_conn);
3315 
3316  if (connection_add(base_conn) < 0) { /* no space, forget it */
3317  connection_free(base_conn);
3318  return NULL;
3319  }
3320 
3321  base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
3322 
3323  control_event_stream_status(conn, STREAM_EVENT_NEW, 0);
3324 
3325  /* attaching to a dirty circuit is fine */
3326  connection_ap_mark_as_pending_circuit(conn);
3327  log_info(LD_APP,"... application connection created and linked.");
3328  return conn;
3329 }
3330 
3334 static void
3336  int answer_type,
3337  size_t answer_len,
3338  const char *answer,
3339  int ttl,
3340  time_t expires)
3341 {
3342  expires = time(NULL) + ttl;
3343  if (answer_type == RESOLVED_TYPE_IPV4 && answer_len >= 4) {
3344  char *cp = tor_dup_ip(ntohl(get_uint32(answer)));
3346  cp, expires, NULL, 0);
3347  tor_free(cp);
3348  } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
3349  char *cp = tor_strndup(answer, answer_len);
3351  cp, expires, NULL, 0);
3352  tor_free(cp);
3353  } else {
3355  "<error>", time(NULL)+ttl,
3356  "error=yes", 0);
3357  }
3358 }
3359 
3364 void
3366  const tor_addr_t *answer,
3367  int ttl,
3368  time_t expires)
3369 {
3370  if (tor_addr_family(answer) == AF_INET) {
3371  uint32_t a = tor_addr_to_ipv4n(answer); /* network order */
3372  connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV4,4,
3373  (uint8_t*)&a,
3374  ttl, expires);
3375  } else if (tor_addr_family(answer) == AF_INET6) {
3376  const uint8_t *a = tor_addr_to_in6_addr8(answer);
3377  connection_ap_handshake_socks_resolved(conn,RESOLVED_TYPE_IPV6,16,
3378  a,
3379  ttl, expires);
3380  } else {
3381  log_warn(LD_BUG, "Got called with address of unexpected family %d",
3382  tor_addr_family(answer));
3383  connection_ap_handshake_socks_resolved(conn,
3384  RESOLVED_TYPE_ERROR,0,NULL,-1,-1);
3385  }
3386 }
3387 
3395 /* XXXX the use of the ttl and expires fields is nutty. Let's make this
3396  * interface and those that use it less ugly. */
3398 connection_ap_handshake_socks_resolved,(entry_connection_t *conn,
3399  int answer_type,
3400  size_t answer_len,
3401  const uint8_t *answer,
3402  int ttl,
3403  time_t expires))
3404 {
3405  char buf[384];
3406  size_t replylen;
3407 
3408  if (ttl >= 0) {
3409  if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
3410  tor_addr_t a;
3411  tor_addr_from_ipv4n(&a, get_uint32(answer));
3412  if (! tor_addr_is_null(&a)) {
3414  conn->socks_request->address, &a,
3415  conn->chosen_exit_name, ttl);
3416  }
3417  } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
3418  tor_addr_t a;
3419  tor_addr_from_ipv6_bytes(&a, (char*)answer);
3420  if (! tor_addr_is_null(&a)) {
3422  conn->socks_request->address, &a,
3423  conn->chosen_exit_name, ttl);
3424  }
3425  } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
3426  char *cp = tor_strndup((char*)answer, answer_len);
3428  conn->socks_request->address,
3429  cp,
3430  conn->chosen_exit_name, ttl);
3431  tor_free(cp);
3432  }
3433  }
3434 
3435  if (ENTRY_TO_EDGE_CONN(conn)->is_dns_request) {
3436  if (conn->dns_server_request) {
3437  /* We had a request on our DNS port: answer it. */
3438  dnsserv_resolved(conn, answer_type, answer_len, (char*)answer, ttl);
3439  conn->socks_request->has_finished = 1;
3440  return;
3441  } else {
3442  /* This must be a request from the controller. Since answers to those
3443  * requests are not cached, they do not generate an ADDRMAP event on
3444  * their own. */
3445  tell_controller_about_resolved_result(conn, answer_type, answer_len,
3446  (char*)answer, ttl, expires);
3447  conn->socks_request->has_finished = 1;
3448  return;
3449  }
3450  /* We shouldn't need to free conn here; it gets marked by the caller. */
3451  }
3452 
3453  if (conn->socks_request->socks_version == 4) {
3454  buf[0] = 0x00; /* version */
3455  if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
3456  buf[1] = SOCKS4_GRANTED;
3457  set_uint16(buf+2, 0);
3458  memcpy(buf+4, answer, 4); /* address */
3459  replylen = SOCKS4_NETWORK_LEN;
3460  } else { /* "error" */
3461  buf[1] = SOCKS4_REJECT;
3462  memset(buf+2, 0, 6);
3463  replylen = SOCKS4_NETWORK_LEN;
3464  }
3465  } else if (conn->socks_request->socks_version == 5) {
3466  /* SOCKS5 */
3467  buf[0] = 0x05; /* version */
3468  if (answer_type == RESOLVED_TYPE_IPV4 && answer_len == 4) {
3469  buf[1] = SOCKS5_SUCCEEDED;
3470  buf[2] = 0; /* reserved */
3471  buf[3] = 0x01; /* IPv4 address type */
3472  memcpy(buf+4, answer, 4); /* address */
3473  set_uint16(buf+8, 0); /* port == 0. */
3474  replylen = 10;
3475  } else if (answer_type == RESOLVED_TYPE_IPV6 && answer_len == 16) {
3476  buf[1] = SOCKS5_SUCCEEDED;
3477  buf[2] = 0; /* reserved */
3478  buf[3] = 0x04; /* IPv6 address type */
3479  memcpy(buf+4, answer, 16); /* address */
3480  set_uint16(buf+20, 0); /* port == 0. */
3481  replylen = 22;
3482  } else if (answer_type == RESOLVED_TYPE_HOSTNAME && answer_len < 256) {
3483  buf[1] = SOCKS5_SUCCEEDED;
3484  buf[2] = 0; /* reserved */
3485  buf[3] = 0x03; /* Domainname address type */
3486  buf[4] = (char)answer_len;
3487  memcpy(buf+5, answer, answer_len); /* address */
3488  set_uint16(buf+5+answer_len, 0); /* port == 0. */
3489  replylen = 5+answer_len+2;
3490  } else {
3491  buf[1] = SOCKS5_HOST_UNREACHABLE;
3492  memset(buf+2, 0, 8);
3493  replylen = 10;
3494  }
3495  } else {
3496  /* no socks version info; don't send anything back */
3497  return;
3498  }
3499  connection_ap_handshake_socks_reply(conn, buf, replylen,
3500  (answer_type == RESOLVED_TYPE_IPV4 ||
3501  answer_type == RESOLVED_TYPE_IPV6 ||
3502  answer_type == RESOLVED_TYPE_HOSTNAME) ?
3503  0 : END_STREAM_REASON_RESOLVEFAILED);
3504 }
3505 
3515 void
3517  size_t replylen, int endreason)
3518 {
3519  char buf[256];
3520  socks5_reply_status_t status =
3522 
3523  tor_assert(conn->socks_request); /* make sure it's an AP stream */
3524 
3525  if (!SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
3526  control_event_stream_status(conn, status==SOCKS5_SUCCEEDED ?
3527  STREAM_EVENT_SUCCEEDED : STREAM_EVENT_FAILED,
3528  endreason);
3529  }
3530 
3531  /* Flag this stream's circuit as having completed a stream successfully
3532  * (for path bias) */
3533  if (status == SOCKS5_SUCCEEDED ||
3534  endreason == END_STREAM_REASON_RESOLVEFAILED ||
3535  endreason == END_STREAM_REASON_CONNECTREFUSED ||
3536  endreason == END_STREAM_REASON_CONNRESET ||
3537  endreason == END_STREAM_REASON_NOROUTE ||
3538  endreason == END_STREAM_REASON_RESOURCELIMIT) {
3539  if (!conn->edge_.on_circuit ||
3540  !CIRCUIT_IS_ORIGIN(conn->edge_.on_circuit)) {
3541  if (endreason != END_STREAM_REASON_RESOLVEFAILED) {
3542  log_info(LD_BUG,
3543  "No origin circuit for successful SOCKS stream %"PRIu64
3544  ". Reason: %d",
3545  (ENTRY_TO_CONN(conn)->global_identifier),
3546  endreason);
3547  }
3548  /*
3549  * Else DNS remaps and failed hidden service lookups can send us
3550  * here with END_STREAM_REASON_RESOLVEFAILED; ignore it
3551  *
3552  * Perhaps we could make the test more precise; we can tell hidden
3553  * services by conn->edge_.renddata != NULL; anything analogous for
3554  * the DNS remap case?
3555  */
3556  } else {
3557  // XXX: Hrmm. It looks like optimistic data can't go through this
3558  // codepath, but someone should probably test it and make sure.
3559  // We don't want to mark optimistically opened streams as successful.
3561  }
3562  }
3563 
3564  if (conn->socks_request->has_finished) {
3565  log_warn(LD_BUG, "(Harmless.) duplicate calls to "
3566  "connection_ap_handshake_socks_reply.");
3567  return;
3568  }
3569  if (replylen) { /* we already have a reply in mind */
3570  connection_buf_add(reply, replylen, ENTRY_TO_CONN(conn));
3571  conn->socks_request->has_finished = 1;
3572  return;
3573  }
3574  if (conn->socks_request->listener_type ==
3576  const char *response = end_reason_to_http_connect_response_line(endreason);
3577  if (!response) {
3578  response = "HTTP/1.0 400 Bad Request\r\n\r\n";
3579  }
3580  connection_buf_add(response, strlen(response), ENTRY_TO_CONN(conn));
3581  } else if (conn->socks_request->socks_version == 4) {
3582  memset(buf,0,SOCKS4_NETWORK_LEN);
3583  buf[1] = (status==SOCKS5_SUCCEEDED ? SOCKS4_GRANTED : SOCKS4_REJECT);
3584  /* leave version, destport, destip zero */
3585  connection_buf_add(buf, SOCKS4_NETWORK_LEN, ENTRY_TO_CONN(conn));
3586  } else if (conn->socks_request->socks_version == 5) {
3587  size_t buf_len;
3588  memset(buf,0,sizeof(buf));
3589  if (tor_addr_family(&conn->edge_.base_.addr) == AF_INET) {
3590  buf[0] = 5; /* version 5 */
3591  buf[1] = (char)status;
3592  buf[2] = 0;
3593  buf[3] = 1; /* ipv4 addr */
3594  /* 4 bytes for the header, 2 bytes for the port, 4 for the address. */
3595  buf_len = 10;
3596  } else { /* AF_INET6. */
3597  buf[0] = 5; /* version 5 */
3598  buf[1] = (char)status;
3599  buf[2] = 0;
3600  buf[3] = 4; /* ipv6 addr */
3601  /* 4 bytes for the header, 2 bytes for the port, 16 for the address. */
3602  buf_len = 22;
3603  }
3604  connection_buf_add(buf,buf_len,ENTRY_TO_CONN(conn));
3605  }
3606  /* If socks_version isn't 4 or 5, don't send anything.
3607  * This can happen in the case of AP bridges. */
3608  conn->socks_request->has_finished = 1;
3609  return;
3610 }
3611 
3620 STATIC int
3621 begin_cell_parse(const cell_t *cell, begin_cell_t *bcell,
3622  uint8_t *end_reason_out)
3623 {
3624  relay_header_t rh;
3625  const uint8_t *body, *nul;
3626 
3627  memset(bcell, 0, sizeof(*bcell));
3628  *end_reason_out = END_STREAM_REASON_MISC;
3629 
3630  relay_header_unpack(&rh, cell->payload);
3631  if (rh.length > RELAY_PAYLOAD_SIZE) {
3632  return -2; /*XXXX why not TORPROTOCOL? */
3633  }
3634 
3635  bcell->stream_id = rh.stream_id;
3636 
3637  if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
3638  bcell->is_begindir = 1;
3639  return 0;
3640  } else if (rh.command != RELAY_COMMAND_BEGIN) {
3641  log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
3642  *end_reason_out = END_STREAM_REASON_INTERNAL;
3643  return -1;
3644  }
3645 
3646  body = cell->payload + RELAY_HEADER_SIZE;
3647  nul = memchr(body, 0, rh.length);
3648  if (! nul) {
3649  log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
3650  "Relay begin cell has no \\0. Closing.");
3651  *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
3652  return -1;
3653  }
3654 
3655  if (tor_addr_port_split(LOG_PROTOCOL_WARN,
3656  (char*)(body),
3657  &bcell->address,&bcell->port)<0) {
3658  log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
3659  "Unable to parse addr:port in relay begin cell. Closing.");
3660  *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
3661  return -1;
3662  }
3663  if (bcell->port == 0) {
3664  log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
3665  "Missing port in relay begin cell. Closing.");
3666  tor_free(bcell->address);
3667  *end_reason_out = END_STREAM_REASON_TORPROTOCOL;
3668  return -1;
3669  }
3670  if (body + rh.length >= nul + 4)
3671  bcell->flags = ntohl(get_uint32(nul+1));
3672 
3673  return 0;
3674 }
3675 
3680 static int
3682 {
3683  int ret;
3684  origin_circuit_t *origin_circ;
3685 
3686  assert_circuit_ok(circ);
3688  tor_assert(conn);
3689 
3690  log_debug(LD_REND, "Connecting the hidden service rendezvous circuit "
3691  "to the service destination.");
3692 
3693  origin_circ = TO_ORIGIN_CIRCUIT(circ);
3694  conn->base_.address = tor_strdup("(rendezvous)");
3695  conn->base_.state = EXIT_CONN_STATE_CONNECTING;
3696 
3697  /* The circuit either has an hs identifier for v3+ or a rend_data for legacy
3698  * service. */
3699  if (origin_circ->rend_data) {
3700  conn->rend_data = rend_data_dup(origin_circ->rend_data);
3702  ret = rend_service_set_connection_addr_port(conn, origin_circ);
3703  } else if (origin_circ->hs_ident) {
3704  /* Setup the identifier to be the one for the circuit service. */
3705  conn->hs_ident =
3706  hs_ident_edge_conn_new(&origin_circ->hs_ident->identity_pk);
3708  ret = hs_service_set_conn_addr_port(origin_circ, conn);
3709  } else {
3710  /* We should never get here if the circuit's purpose is rendezvous. */
3711  tor_assert_nonfatal_unreached();
3712  return -1;
3713  }
3714  if (ret < 0) {
3715  log_info(LD_REND, "Didn't find rendezvous service (addr%s, port %d)",
3716  fmt_addr(&TO_CONN(conn)->addr), TO_CONN(conn)->port);
3717  /* Send back reason DONE because we want to make hidden service port
3718  * scanning harder thus instead of returning that the exit policy
3719  * didn't match, which makes it obvious that the port is closed,
3720  * return DONE and kill the circuit. That way, a user (malicious or
3721  * not) needs one circuit per bad port unless it matches the policy of
3722  * the hidden service. */
3724  END_STREAM_REASON_DONE,
3725  origin_circ->cpath->prev);
3726  connection_free_(TO_CONN(conn));
3727 
3728  /* Drop the circuit here since it might be someone deliberately
3729  * scanning the hidden service ports. Note that this mitigates port
3730  * scanning by adding more work on the attacker side to successfully
3731  * scan but does not fully solve it. */
3732  if (ret < -1) {
3733  return END_CIRC_AT_ORIGIN;
3734  } else {
3735  return 0;
3736  }
3737  }
3738 
3739  /* Link the circuit and the connection crypt path. */
3740  conn->cpath_layer = origin_circ->cpath->prev;
3741 
3742  /* If this is the first stream on this circuit, tell circpad */
3743  if (!origin_circ->p_streams)
3745 
3746  /* Add it into the linked list of p_streams on this circuit */
3747  conn->next_stream = origin_circ->p_streams;
3748  origin_circ->p_streams = conn;
3749  conn->on_circuit = circ;
3750  assert_circuit_ok(circ);
3751 
3752  hs_inc_rdv_stream_counter(origin_circ);
3753 
3754  /* If it's an onion service connection, we might want to include the proxy
3755  * protocol header: */
3756  if (conn->hs_ident) {
3757  hs_circuit_id_protocol_t circuit_id_protocol =
3758  hs_service_exports_circuit_id(&conn->hs_ident->identity_pk);
3759  export_hs_client_circuit_id(conn, circuit_id_protocol);
3760  }
3761 
3762  /* Connect tor to the hidden service destination. */
3764 
3765  /* For path bias: This circuit was used successfully */
3766  pathbias_mark_use_success(origin_circ);
3767  return 0;
3768 }
3769 
3788 int
3790 {
3791  edge_connection_t *n_stream;
3792  relay_header_t rh;
3793  char *address = NULL;
3794  uint16_t port = 0;
3795  or_circuit_t *or_circ = NULL;
3796  origin_circuit_t *origin_circ = NULL;
3797  crypt_path_t *layer_hint = NULL;
3798  const or_options_t *options = get_options();
3799  begin_cell_t bcell;
3800  int rv;
3801  uint8_t end_reason=0;
3802 
3803  assert_circuit_ok(circ);
3804  if (!CIRCUIT_IS_ORIGIN(circ)) {
3805  or_circ = TO_OR_CIRCUIT(circ);
3806  } else {
3808  origin_circ = TO_ORIGIN_CIRCUIT(circ);
3809  layer_hint = origin_circ->cpath->prev;
3810  }
3811 
3812  relay_header_unpack(&rh, cell->payload);
3813  if (rh.length > RELAY_PAYLOAD_SIZE)
3814  return -END_CIRC_REASON_TORPROTOCOL;
3815 
3816  if (!server_mode(options) &&
3818  log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
3819  "Relay begin cell at non-server. Closing.");
3821  END_STREAM_REASON_EXITPOLICY, NULL);
3822  return 0;
3823  }
3824 
3825  rv = begin_cell_parse(cell, &bcell, &end_reason);
3826  if (rv < -1) {
3827  return -END_CIRC_REASON_TORPROTOCOL;
3828  } else if (rv == -1) {
3829  tor_free(bcell.address);
3830  relay_send_end_cell_from_edge(rh.stream_id, circ, end_reason, layer_hint);
3831  return 0;
3832  }
3833 
3834  if (! bcell.is_begindir) {
3835  /* Steal reference */
3836  tor_assert(bcell.address);
3837  address = bcell.address;
3838  port = bcell.port;
3839 
3840  if (or_circ && or_circ->p_chan) {
3841  const int client_chan = channel_is_client(or_circ->p_chan);
3842  if ((client_chan ||
3844  or_circ->p_chan->identity_digest) &&
3845  should_refuse_unknown_exits(options)))) {
3846  /* Don't let clients use us as a single-hop proxy. It attracts
3847  * attackers and users who'd be better off with, well, single-hop
3848  * proxies. */
3849  log_fn(LOG_PROTOCOL_WARN, LD_PROTOCOL,
3850  "Attempt by %s to open a stream %s. Closing.",
3851  safe_str(channel_get_canonical_remote_descr(or_circ->p_chan)),
3852  client_chan ? "on first hop of circuit" :
3853  "from unknown relay");
3855  client_chan ?
3856  END_STREAM_REASON_TORPROTOCOL :
3857  END_STREAM_REASON_MISC,
3858  NULL);
3859  tor_free(address);
3860  return 0;
3861  }
3862  }
3863  } else if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
3864  if (!directory_permits_begindir_requests(options) ||
3865  circ->purpose != CIRCUIT_PURPOSE_OR) {
3867  END_STREAM_REASON_NOTDIRECTORY, layer_hint);
3868  return 0;
3869  }
3870  /* Make sure to get the 'real' address of the previous hop: the
3871  * caller might want to know whether the remote IP address has changed,
3872  * and we might already have corrected base_.addr[ess] for the relay's
3873  * canonical IP address. */
3874  if (or_circ && or_circ->p_chan)
3875  address = tor_strdup(channel_get_actual_remote_address(or_circ->p_chan));
3876  else
3877  address = tor_strdup("127.0.0.1");
3878  port = 1; /* XXXX This value is never actually used anywhere, and there
3879  * isn't "really" a connection here. But we
3880  * need to set it to something nonzero. */
3881  } else {
3882  log_warn(LD_BUG, "Got an unexpected command %d", (int)rh.command);
3884  END_STREAM_REASON_INTERNAL, layer_hint);
3885  return 0;
3886  }
3887 
3888  if (! options->IPv6Exit) {
3889  /* I don't care if you prefer IPv6; I can't give you any. */
3890  bcell.flags &= ~BEGIN_FLAG_IPV6_PREFERRED;
3891  /* If you don't want IPv4, I can't help. */
3892  if (bcell.flags & BEGIN_FLAG_IPV4_NOT_OK) {
3893  tor_free(address);
3895  END_STREAM_REASON_EXITPOLICY, layer_hint);
3896  return 0;
3897  }
3898  }
3899 
3900  log_debug(LD_EXIT,"Creating new exit connection.");
3901  /* The 'AF_INET' here is temporary; we might need to change it later in
3902  * connection_exit_connect(). */
3903  n_stream = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
3904 
3905  /* Remember the tunneled request ID in the new edge connection, so that
3906  * we can measure download times. */
3907  n_stream->dirreq_id = circ->dirreq_id;
3908 
3909  n_stream->base_.purpose = EXIT_PURPOSE_CONNECT;
3910  n_stream->begincell_flags = bcell.flags;
3911  n_stream->stream_id = rh.stream_id;
3912  n_stream->base_.port = port;
3913  /* leave n_stream->s at -1, because it's not yet valid */
3914  n_stream->package_window = STREAMWINDOW_START;
3915  n_stream->deliver_window = STREAMWINDOW_START;
3916 
3917  if (circ->purpose == CIRCUIT_PURPOSE_S_REND_JOINED) {
3918  int ret;
3919  tor_free(address);
3920  /* We handle this circuit and stream in this function for all supported
3921  * hidden service version. */
3922  ret = handle_hs_exit_conn(circ, n_stream);
3923 
3924  if (ret == 0) {
3925  /* This was a valid cell. Count it as delivered + overhead. */
3926  circuit_read_valid_data(origin_circ, rh.length);
3927  }
3928  return ret;
3929  }
3930  tor_strlower(address);
3931  n_stream->base_.address = address;
3932  n_stream->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
3933  /* default to failed, change in dns_resolve if it turns out not to fail */
3934 
3935  /* If we're hibernating or shutting down, we refuse to open new streams. */
3936  if (we_are_hibernating()) {
3938  END_STREAM_REASON_HIBERNATING, NULL);
3939  connection_free_(TO_CONN(n_stream));
3940  return 0;
3941  }
3942 
3943  n_stream->on_circuit = circ;
3944 
3945  if (rh.command == RELAY_COMMAND_BEGIN_DIR) {
3946  tor_addr_t tmp_addr;
3947  tor_assert(or_circ);
3948  if (or_circ->p_chan &&
3949  channel_get_addr_if_possible(or_circ->p_chan, &tmp_addr)) {
3950  tor_addr_copy(&n_stream->base_.addr, &tmp_addr);
3951  }
3952  return connection_exit_connect_dir(n_stream);
3953  }
3954 
3955  log_debug(LD_EXIT,"about to start the dns_resolve().");
3956 
3957  /* send it off to the gethostbyname farm */
3958  switch (dns_resolve(n_stream)) {
3959  case 1: /* resolve worked; now n_stream is attached to circ. */
3960  assert_circuit_ok(circ);
3961  log_debug(LD_EXIT,"about to call connection_exit_connect().");
3962  connection_exit_connect(n_stream);
3963  return 0;
3964  case -1: /* resolve failed */
3966  END_STREAM_REASON_RESOLVEFAILED, NULL);
3967  /* n_stream got freed. don't touch it. */
3968  break;
3969  case 0: /* resolve added to pending list */
3970  assert_circuit_ok(circ);
3971  break;
3972  }
3973  return 0;
3974 }
3975 
3981 int
3983 {
3984  edge_connection_t *dummy_conn;
3985  relay_header_t rh;
3986 
3987  assert_circuit_ok(TO_CIRCUIT(circ));
3988  relay_header_unpack(&rh, cell->payload);
3989  if (rh.length > RELAY_PAYLOAD_SIZE)
3990  return -1;
3991 
3992  /* This 'dummy_conn' only exists to remember the stream ID
3993  * associated with the resolve request; and to make the
3994  * implementation of dns.c more uniform. (We really only need to
3995  * remember the circuit, the stream ID, and the hostname to be
3996  * resolved; but if we didn't store them in a connection like this,
3997  * the housekeeping in dns.c would get way more complicated.)
3998  */
3999  dummy_conn = edge_connection_new(CONN_TYPE_EXIT, AF_INET);
4000  dummy_conn->stream_id = rh.stream_id;
4001  dummy_conn->base_.address = tor_strndup(
4002  (char*)cell->payload+RELAY_HEADER_SIZE,
4003  rh.length);
4004  dummy_conn->base_.port = 0;
4005  dummy_conn->base_.state = EXIT_CONN_STATE_RESOLVEFAILED;
4006  dummy_conn->base_.purpose = EXIT_PURPOSE_RESOLVE;
4007 
4008  dummy_conn->on_circuit = TO_CIRCUIT(circ);
4009 
4010  /* send it off to the gethostbyname farm */
4011  switch (dns_resolve(dummy_conn)) {
4012  case -1: /* Impossible to resolve; a resolved cell was sent. */
4013  /* Connection freed; don't touch it. */
4014  return 0;
4015  case 1: /* The result was cached; a resolved cell was sent. */
4016  if (!dummy_conn->base_.marked_for_close)
4017  connection_free_(TO_CONN(dummy_conn));
4018  return 0;
4019  case 0: /* resolve added to pending list */
4020  assert_circuit_ok(TO_CIRCUIT(circ));
4021  break;
4022  }
4023  return 0;
4024 }
4025 
4029 static int
4031  uint16_t port,
4032  const char **why_rejected)
4033 {
4034  if (router_compare_to_my_exit_policy(addr, port)) {
4035  *why_rejected = "";
4036  return 1;
4037  } else if (tor_addr_family(addr) == AF_INET6 && !get_options()->IPv6Exit) {
4038  *why_rejected = " (IPv6 address without IPv6Exit configured)";
4039  return 1;
4040  }
4041  return 0;
4042 }
4043 
4051 void
4053 {
4054  const tor_addr_t *addr;
4055  uint16_t port;
4056  connection_t *conn = TO_CONN(edge_conn);
4057  int socket_error = 0, result;
4058  const char *why_failed_exit_policy = NULL;
4059 
4060  /* Apply exit policy to non-rendezvous connections. */
4061  if (! connection_edge_is_rendezvous_stream(edge_conn) &&
4062  my_exit_policy_rejects(&edge_conn->base_.addr,
4063  edge_conn->base_.port,
4064  &why_failed_exit_policy)) {
4065  if (BUG(!why_failed_exit_policy))
4066  why_failed_exit_policy = "";
4067  log_info(LD_EXIT,"%s:%d failed exit policy%s. Closing.",
4068  escaped_safe_str_client(conn->address), conn->port,
4069  why_failed_exit_policy);
4070  connection_edge_end(edge_conn, END_STREAM_REASON_EXITPOLICY);
4071  circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
4072  connection_free(conn);
4073  return;
4074  }
4075 
4076 #ifdef HAVE_SYS_UN_H
4077  if (conn->socket_family != AF_UNIX) {
4078 #else
4079  {
4080 #endif /* defined(HAVE_SYS_UN_H) */
4081  addr = &conn->addr;
4082  port = conn->port;
4083 
4084  if (tor_addr_family(addr) == AF_INET6)
4085  conn->socket_family = AF_INET6;
4086 
4087  log_debug(LD_EXIT, "about to try connecting");
4088  result = connection_connect(conn, conn->address,
4089  addr, port, &socket_error);
4090 #ifdef HAVE_SYS_UN_H
4091  } else {
4092  /*
4093  * In the AF_UNIX case, we expect to have already had conn->port = 1,
4094  * tor_addr_make_unspec(conn->addr) (cf. the way we mark in the incoming
4095  * case in connection_handle_listener_read()), and conn->address should
4096  * have the socket path to connect to.
4097  */
4098  tor_assert(conn->address && strlen(conn->address) > 0);
4099 
4100  log_debug(LD_EXIT, "about to try connecting");
4101  result = connection_connect_unix(conn, conn->address, &socket_error);
4102 #endif /* defined(HAVE_SYS_UN_H) */
4103  }
4104 
4105  switch (result) {
4106  case -1: {
4107  int reason = errno_to_stream_end_reason(socket_error);
4108  connection_edge_end(edge_conn, reason);
4109  circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
4110  connection_free(conn);
4111  return;
4112  }
4113  case 0:
4115 
4117  /* writable indicates finish;
4118  * readable/error indicates broken link in windows-land. */
4119  return;
4120  /* case 1: fall through */
4121  }
4122 
4123  conn->state = EXIT_CONN_STATE_OPEN;
4124  if (connection_get_outbuf_len(conn)) {
4125  /* in case there are any queued data cells, from e.g. optimistic data */
4127  } else {
4129  }
4130 
4131  /* also, deliver a 'connected' cell back through the circuit. */
4132  if (connection_edge_is_rendezvous_stream(edge_conn)) {
4133  /* don't send an address back! */
4134  connection_edge_send_command(edge_conn,
4135  RELAY_COMMAND_CONNECTED,
4136  NULL, 0);
4137  } else { /* normal stream */
4138  uint8_t connected_payload[MAX_CONNECTED_CELL_PAYLOAD_LEN];
4139  int connected_payload_len =
4140  connected_cell_format_payload(connected_payload, &conn->addr,
4141  edge_conn->address_ttl);
4142  if (connected_payload_len < 0) {
4143  connection_edge_end(edge_conn, END_STREAM_REASON_INTERNAL);
4144  circuit_detach_stream(circuit_get_by_edge_conn(edge_conn), edge_conn);
4145  connection_free(conn);
4146  return;
4147  }
4148 
4149  connection_edge_send_command(edge_conn,
4150  RELAY_COMMAND_CONNECTED,
4151  (char*)connected_payload,
4152  connected_payload_len);
4153  }
4154 }
4155 
4163 static int
4165 {
4166  dir_connection_t *dirconn = NULL;
4167  or_circuit_t *circ = TO_OR_CIRCUIT(exitconn->on_circuit);
4168 
4169  log_info(LD_EXIT, "Opening local connection for anonymized directory exit");
4170 
4171  exitconn->base_.state = EXIT_CONN_STATE_OPEN;
4172 
4173  dirconn = dir_connection_new(tor_addr_family(&exitconn->base_.addr));
4174 
4175  tor_addr_copy(&dirconn->base_.addr, &exitconn->base_.addr);
4176  dirconn->base_.port = 0;
4177  dirconn->base_.address = tor_strdup(exitconn->base_.address);
4178  dirconn->base_.type = CONN_TYPE_DIR;
4179  dirconn->base_.purpose = DIR_PURPOSE_SERVER;
4180  dirconn->base_.state = DIR_CONN_STATE_SERVER_COMMAND_WAIT;
4181 
4182  /* Note that the new dir conn belongs to the same tunneled request as
4183  * the edge conn, so that we can measure download times. */
4184  dirconn->dirreq_id = exitconn->dirreq_id;
4185 
4186  connection_link_connections(TO_CONN(dirconn), TO_CONN(exitconn));
4187 
4188  if (connection_add(TO_CONN(exitconn))<0) {
4189  connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
4190  connection_free_(TO_CONN(exitconn));
4191  connection_free_(TO_CONN(dirconn));
4192  return 0;
4193  }
4194 
4195  /* link exitconn to circ, now that we know we can use it. */
4196  exitconn->next_stream = circ->n_streams;
4197  circ->n_streams = exitconn;
4198 
4199  if (connection_add(TO_CONN(dirconn))<0) {
4200  connection_edge_end(exitconn, END_STREAM_REASON_RESOURCELIMIT);
4202  connection_mark_for_close(TO_CONN(exitconn));
4203  connection_free_(TO_CONN(dirconn));
4204  return 0;
4205  }
4206 
4207  connection_start_reading(TO_CONN(dirconn));
4208  connection_start_reading(TO_CONN(exitconn));
4209 
4210  if (connection_edge_send_command(exitconn,
4211  RELAY_COMMAND_CONNECTED, NULL, 0) < 0) {
4212  connection_mark_for_close(TO_CONN(exitconn));
4213  connection_mark_for_close(TO_CONN(dirconn));
4214  return 0;
4215  }
4216 
4217  return 0;
4218 }
4219 
4223 int
4225 {
4226  tor_assert(conn);
4227  /* It should not be possible to set both of these structs */
4228  tor_assert_nonfatal(!(conn->rend_data && conn->hs_ident));
4229 
4230  if (conn->rend_data || conn->hs_ident) {
4231  return 1;
4232  }
4233  return 0;
4234 }
4235 
4241 int
4243  const node_t *exit_node)
4244 {
4245  const or_options_t *options = get_options();
4246 
4247  tor_assert(conn);
4248  tor_assert(conn->socks_request);
4249  tor_assert(exit_node);
4250 
4251  /* If a particular exit node has been requested for the new connection,
4252  * make sure the exit node of the existing circuit matches exactly.
4253  */
4254  if (conn->chosen_exit_name) {
4255  const node_t *chosen_exit =
4256  node_get_by_nickname(conn->chosen_exit_name, 0);
4257  if (!chosen_exit || tor_memneq(chosen_exit->identity,
4258  exit_node->identity, DIGEST_LEN)) {
4259  /* doesn't match */
4260 // log_debug(LD_APP,"Requested node '%s', considering node '%s'. No.",
4261 // conn->chosen_exit_name, exit->nickname);
4262  return 0;
4263  }
4264  }
4265 
4266  if (conn->use_begindir) {
4267  /* Internal directory fetches do not count as exiting. */
4268  return 1;
4269  }
4270 
4271  if (conn->socks_request->command == SOCKS_COMMAND_CONNECT) {
4272  tor_addr_t addr, *addrp = NULL;
4274  if (0 == tor_addr_parse(&addr, conn->socks_request->address)) {
4275  addrp = &addr;
4276  } else if (!conn->entry_cfg.ipv4_traffic && conn->entry_cfg.ipv6_traffic) {
4277  tor_addr_make_null(&addr, AF_INET6);
4278  addrp = &addr;
4279  } else if (conn->entry_cfg.ipv4_traffic && !conn->entry_cfg.ipv6_traffic) {
4280  tor_addr_make_null(&addr, AF_INET);
4281  addrp = &addr;
4282  }
4284  exit_node);
4285  if (r == ADDR_POLICY_REJECTED)
4286  return 0; /* We know the address, and the exit policy rejects it. */
4288  return 0; /* We don't know the addr, but the exit policy rejects most
4289  * addresses with this port. Since the user didn't ask for
4290  * this node, err on the side of caution. */
4291  } else if (SOCKS_COMMAND_IS_RESOLVE(conn->socks_request->command)) {
4292  /* Don't send DNS requests to non-exit servers by default. */
4293  if (!conn->chosen_exit_name && node_exit_policy_rejects_all(exit_node))
4294  return 0;
4295  }
4296  if (routerset_contains_node(options->ExcludeExitNodesUnion_, exit_node)) {
4297  /* Not a suitable exit. Refuse it. */
4298  return 0;
4299  }
4300 
4301  return 1;
4302 }
4303 
4323 {
4324  char *s;
4325  char *q;
4326  char query[HS_SERVICE_ADDR_LEN_BASE32+1];
4327 
4328  s = strrchr(address,'.');
4329  if (!s)
4330  return NORMAL_HOSTNAME; /* no dot, thus normal */
4331  if (!strcmp(s+1,"exit")) {
4332  *s = 0; /* NUL-terminate it */
4333  return EXIT_HOSTNAME; /* .exit */
4334  }
4335  if (strcmp(s+1,"onion"))
4336  return NORMAL_HOSTNAME; /* neither .exit nor .onion, thus normal */
4337 
4338  /* so it is .onion */
4339  *s = 0; /* NUL-terminate it */
4340  /* locate a 'sub-domain' component, in order to remove it */
4341  q = strrchr(address, '.');
4342  if (q == address) {
4343  goto failed; /* reject sub-domain, as DNS does */
4344  }
4345  q = (NULL == q) ? address : q + 1;
4346  if (strlcpy(query, q, HS_SERVICE_ADDR_LEN_BASE32+1) >=
4347  HS_SERVICE_ADDR_LEN_BASE32+1)
4348  goto failed;
4349  if (q != address) {
4350  memmove(address, q, strlen(q) + 1 /* also get \0 */);
4351  }
4352  if (rend_valid_v2_service_id(query)) {
4353  return ONION_V2_HOSTNAME; /* success */
4354  }
4355  if (hs_address_is_valid(query)) {
4356  return ONION_V3_HOSTNAME;
4357  }
4358  failed:
4359  /* otherwise, return to previous state and return 0 */
4360  *s = '.';
4361  log_warn(LD_APP, "Invalid onion hostname %s; rejecting",
4362  safe_str_client(address));
4363  return BAD_HOSTNAME;
4364 }
4365 
4369 static int
4370 memeq_opt(const char *a, size_t alen, const char *b, size_t blen)
4371 {
4372  if (a == NULL) {
4373  return (b == NULL);
4374  } else if (b == NULL) {
4375  return 0;
4376  } else if (alen != blen) {
4377  return 0;
4378  } else {
4379  return tor_memeq(a, b, alen);
4380  }
4381 }
4382 
4387 int
4389  const origin_circuit_t *circ)
4390 {
4391  const uint8_t iso = conn->entry_cfg.isolation_flags;
4392  const socks_request_t *sr = conn->socks_request;
4393 
4394  /* If circ has never been used for an isolated connection, we can
4395  * totally use it for this one. */
4396  if (!circ->isolation_values_set)
4397  return 1;
4398 
4399  /* If circ has been used for connections having more than one value
4400  * for some field f, it will have the corresponding bit set in
4401  * isolation_flags_mixed. If isolation_flags_mixed has any bits
4402  * in common with iso, then conn must be isolated from at least
4403  * one stream that has been attached to circ. */
4404  if ((iso & circ->isolation_flags_mixed) != 0) {
4405  /* For at least one field where conn is isolated, the circuit
4406  * already has mixed streams. */
4407  return 0;
4408  }
4409 
4410  if (! conn->original_dest_address) {
4411  log_warn(LD_BUG, "Reached connection_edge_compatible_with_circuit without "
4412  "having set conn->original_dest_address");
4413  ((entry_connection_t*)conn)->original_dest_address =
4414  tor_strdup(conn->socks_request->address);
4415  }
4416 
4417  if ((iso & ISO_STREAM) &&
4419  ENTRY_TO_CONN(conn)->global_identifier))
4420  return 0;
4421 
4422  if ((iso & ISO_DESTPORT) && conn->socks_request->port != circ->dest_port)
4423  return 0;
4424  if ((iso & ISO_DESTADDR) &&
4425  strcasecmp(conn->original_dest_address, circ->dest_address))
4426  return 0;
4427  if ((iso & ISO_SOCKSAUTH) &&
4428  (! memeq_opt(sr->username, sr->usernamelen,
4429  circ->socks_username, circ->socks_username_len) ||
4430  ! memeq_opt(sr->password, sr->passwordlen,
4431  circ->socks_password, circ->socks_password_len)))
4432  return 0;
4433  if ((iso & ISO_CLIENTPROTO) &&
4434  (conn->socks_request->listener_type != circ->client_proto_type ||
4435  conn->socks_request->socks_version != circ->client_proto_socksver))
4436  return 0;
4437  if ((iso & ISO_CLIENTADDR) &&
4438  !tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr))
4439  return 0;
4440  if ((iso & ISO_SESSIONGRP) &&
4441  conn->entry_cfg.session_group != circ->session_group)
4442  return 0;
4443  if ((iso & ISO_NYM_EPOCH) && conn->nym_epoch != circ->nym_epoch)
4444  return 0;
4445 
4446  return 1;
4447 }
4448 
4457 int
4459  origin_circuit_t *circ,
4460  int dry_run)
4461 {
4462  const socks_request_t *sr = conn->socks_request;
4463  if (! conn->original_dest_address) {
4464  log_warn(LD_BUG, "Reached connection_update_circuit_isolation without "
4465  "having set conn->original_dest_address");
4466  ((entry_connection_t*)conn)->original_dest_address =
4467  tor_strdup(conn->socks_request->address);
4468  }
4469 
4470  if (!circ->isolation_values_set) {
4471  if (dry_run)
4472  return -1;
4474  ENTRY_TO_CONN(conn)->global_identifier;
4475  circ->dest_port = conn->socks_request->port;
4476  circ->dest_address = tor_strdup(conn->original_dest_address);
4477  circ->client_proto_type = conn->socks_request->listener_type;
4478  circ->client_proto_socksver = conn->socks_request->socks_version;
4479  tor_addr_copy(&circ->client_addr, &ENTRY_TO_CONN(conn)->addr);
4480  circ->session_group = conn->entry_cfg.session_group;
4481  circ->nym_epoch = conn->nym_epoch;
4482  circ->socks_username = sr->username ?
4483  tor_memdup(sr->username, sr->usernamelen) : NULL;
4484  circ->socks_password = sr->password ?
4485  tor_memdup(sr->password, sr->passwordlen) : NULL;
4486  circ->socks_username_len = sr->usernamelen;
4487  circ->socks_password_len = sr->passwordlen;
4488 
4489  circ->isolation_values_set = 1;
4490  return 0;
4491  } else {
4492  uint8_t mixed = 0;
4493  if (conn->socks_request->port != circ->dest_port)
4494  mixed |= ISO_DESTPORT;
4495  if (strcasecmp(conn->original_dest_address, circ->dest_address))
4496  mixed |= ISO_DESTADDR;
4497  if (!memeq_opt(sr->username, sr->usernamelen,
4498  circ->socks_username, circ->socks_username_len) ||
4499  !memeq_opt(sr->password, sr->passwordlen,
4500  circ->socks_password, circ->socks_password_len))
4501  mixed |= ISO_SOCKSAUTH;
4502  if ((conn->socks_request->listener_type != circ->client_proto_type ||
4503  conn->socks_request->socks_version != circ->client_proto_socksver))
4504  mixed |= ISO_CLIENTPROTO;
4505  if (!tor_addr_eq(&ENTRY_TO_CONN(conn)->addr, &circ->client_addr))
4506  mixed |= ISO_CLIENTADDR;
4507  if (conn->entry_cfg.session_group != circ->session_group)
4508  mixed |= ISO_SESSIONGRP;
4509  if (conn->nym_epoch != circ->nym_epoch)
4510  mixed |= ISO_NYM_EPOCH;
4511 
4512  if (dry_run)
4513  return mixed;
4514 
4515  if ((mixed & conn->entry_cfg.isolation_flags) != 0) {
4516  log_warn(LD_BUG, "Updating a circuit with seemingly incompatible "
4517  "isolation flags.");
4518  }
4519  circ->isolation_flags_mixed |= mixed;
4520  return 0;
4521  }
4522 }
4523 
4535 void
4537 {
4538  if (circ->isolation_any_streams_attached) {
4539  log_warn(LD_BUG, "Tried to clear the isolation status of a dirty circuit");
4540  return;
4541  }
4542  if (TO_CIRCUIT(circ)->state != CIRCUIT_STATE_OPEN) {
4543  log_warn(LD_BUG, "Tried to clear the isolation status of a non-open "
4544  "circuit");
4545  return;
4546  }
4547 
4548  circ->isolation_values_set = 0;
4549  circ->isolation_flags_mixed = 0;
4551  circ->client_proto_type = 0;
4552  circ->client_proto_socksver = 0;
4553  circ->dest_port = 0;
4554  tor_addr_make_unspec(&circ->client_addr);
4555  tor_free(circ->dest_address);
4556  circ->session_group = -1;
4557  circ->nym_epoch = 0;
4558  if (circ->socks_username) {
4559  memwipe(circ->socks_username, 0x11, circ->socks_username_len);
4560  tor_free(circ->socks_username);
4561  }
4562  if (circ->socks_password) {
4563  memwipe(circ->socks_password, 0x05, circ->socks_password_len);
4564  tor_free(circ->socks_password);
4565  }
4566  circ->socks_username_len = circ->socks_password_len = 0;
4567 }
4568 
4577 void
4579 {
4580  if (!conn) {
4581  return;
4582  }
4583 
4584  connection_edge_end(conn, reason);
4585  connection_mark_for_close(TO_CONN(conn));
4586 }
4587 
4589 void
4591 {
4592  untried_pending_connections = 0;
4593  smartlist_free(pending_entry_connections);
4595  mainloop_event_free(attach_pending_entry_connections_ev);
4596 }
#define RELAY_PAYLOAD_SIZE
Definition: or.h:605
tor_socket_t s
Definition: connection_st.h:88
Header file for dirserv.c.
#define AP_CONN_STATE_CONNECT_WAIT
void rep_hist_note_used_internal(time_t now, int need_uptime, int need_capacity)
#define DIR_PURPOSE_SERVER
Definition: directory.h:62
int channel_is_client(const channel_t *chan)
Definition: channel.c:2924
static mainloop_event_t * attach_pending_entry_connections_ev
#define CONN_TYPE_DIR_LISTENER
Definition: connection.h:33
void tor_addr_from_ipv4n(tor_addr_t *dest, uint32_t v4addr)
Definition: address.c:874
Header file for rendcommon.c.
rend_data_t * rend_data
enum or_options_t::@29 TransProxyType_parsed
#define BEGIN_FLAG_IPV6_PREFERRED
const char * tor_addr_to_str(char *dest, const tor_addr_t *addr, size_t len, int decorate)
Definition: address.c:328
STATIC half_edge_t * connection_half_edge_find_stream_id(const smartlist_t *half_conns, streamid_t stream_id)
const char * channel_get_canonical_remote_descr(channel_t *chan)
Definition: channel.c:2847
#define AP_CONN_STATE_RESOLVE_WAIT
#define CIRCUIT_PURPOSE_C_MEASURE_TIMEOUT
Definition: circuitlist.h:94
unsigned int chosen_exit_retries
int connection_edge_update_circuit_isolation(const entry_connection_t *conn, origin_circuit_t *circ, int dry_run)
Header file containing common data for the whole HS subsytem.
unsigned int has_finished
uint8_t payload[CELL_PAYLOAD_SIZE]
Definition: cell_st.h:16
int tor_addr_to_PTR_name(char *out, size_t outlen, const tor_addr_t *addr)
Definition: address.c:470
Definition: node_st.h:28
#define ISO_STREAM
Definition: or.h:974
#define SMARTLIST_FOREACH_BEGIN(sl, type, var)
uint16_t sa_family_t
Definition: inaddr_st.h:77
Header for backtrace.c.
#define TO_CONN(c)
Definition: or.h:735
void connection_ap_about_to_close(entry_connection_t *entry_conn)
int tor_open_cloexec(const char *path, int flags, unsigned mode)
Definition: files.c:54
int routerset_contains_node(const routerset_t *set, const node_t *node)
Definition: routerset.c:338
void tor_addr_make_unspec(tor_addr_t *a)
Definition: address.c:225
const char * escaped_safe_str(const char *address)
Definition: config.c:1149
void connection_dns_remove(edge_connection_t *conn)
Definition: dns.c:1012
uint8_t reply[MAX_SOCKS_REPLY_LEN]
#define TRACKHOSTEXITS_RETRIES
addr_policy_result_t
Definition: policies.h:38
Header file containing client data for the HS subsytem.
tor_addr_t addr
#define EXIT_PURPOSE_CONNECT
#define EXIT_CONN_STATE_RESOLVING
const char * extend_info_describe(const extend_info_t *ei)
Definition: describe.c:204
uint16_t marked_for_close
Definition: circuit_st.h:178
void rep_hist_note_exit_stream_opened(uint16_t port)
Definition: rephist.c:1799
Header file for connection.c.
#define connection_mark_and_flush_(c, line, file)
Definition: connection.h:148
static void set_uint16(void *cp, uint16_t v)
Definition: bytes.h:73
#define EXIT_CONN_STATE_RESOLVEFAILED
uint64_t associated_isolated_stream_global_id
#define ISO_DESTPORT
Definition: or.h:960
int tor_addr_parse_PTR_name(tor_addr_t *result, const char *address, int family, int accept_regular)
Definition: address.c:380
Definition: cell_st.h:12
#define LD_GENERAL
Definition: log.h:60
int should_refuse_unknown_exits(const or_options_t *options)
Definition: router.c:1331
#define CIRCUIT_IS_ORIGIN(c)
Definition: circuitlist.h:145
void connection_ap_mark_as_pending_circuit_(entry_connection_t *entry_conn, const char *fname, int lineno)
dir_connection_t * dir_connection_new(int socket_family)
Definition: connection.c:360
addr_policy_result_t compare_tor_addr_to_node_policy(const tor_addr_t *addr, uint16_t port, const node_t *node)
Definition: policies.c:3004
#define DOWNCAST(to, ptr)
Definition: or.h:110
#define END_STREAM_REASON_FLAG_ALREADY_SENT_CLOSED
Definition: or.h:279
uint8_t state
Definition: connection_st.h:44
const char * circuit_purpose_to_string(uint8_t purpose)
Definition: circuitlist.c:898
void connection_link_connections(connection_t *conn_a, connection_t *conn_b)
Definition: connection.c:539
int AutomapHostsOnResolve
int connection_exit_begin_resolve(cell_t *cell, or_circuit_t *circ)
#define LOG_INFO
Definition: log.h:43
Header file for describe.c.
static uint32_t tor_addr_to_ipv4n(const tor_addr_t *a)
Definition: address.h:145
Header file for nodelist.c.
int connection_edge_package_raw_inbuf(edge_connection_t *conn, int package_partial, int *max_cells)
Definition: relay.c:2143
streamid_t get_unique_stream_id_by_circ(origin_circuit_t *circ)
static int connection_exit_connect_dir(edge_connection_t *exitconn)
struct smartlist_t * WarnPlaintextPorts
void rend_client_note_connection_attempt_ended(const rend_data_t *rend_data)
Definition: rendclient.c:967
int tor_addr_hostname_is_local(const char *name)
Definition: address.c:1985
crypt_path_t * cpath
void tor_addr_make_null(tor_addr_t *a, sa_family_t family)
Definition: address.c:235
static int memeq_opt(const char *a, size_t alen, const char *b, size_t blen)
void relay_header_unpack(relay_header_t *dest, const uint8_t *src)
Definition: relay.c:488
Header file for directory.c.
void smartlist_add(smartlist_t *sl, void *element)
static int connection_ap_supports_optimistic_data(const entry_connection_t *)
int strcmpend(const char *s1, const char *s2)
Definition: util_string.c:242
char address[MAX_SOCKS_ADDR_LEN]
rend_service_authorization_t * rend_client_lookup_service_authorization(const char *onion_address)
Definition: rendclient.c:1129
int addressmap_address_should_automap(const char *address, const or_options_t *options)
Definition: addressmap.c:250
char * rate_limit_log(ratelim_t *lim, time_t now)
Definition: ratelim.c:41
#define AP_CONN_STATE_RENDDESC_WAIT
int connection_edge_destroy(circid_t circ_id, edge_connection_t *conn)
int connection_or_digest_is_known_relay(const char *id_digest)
#define SUBTYPE_P(p, subtype, basemember)
int smartlist_contains(const smartlist_t *sl, const void *element)
#define TO_CIRCUIT(x)
Definition: or.h:951
Header file for config.c.
edge_connection_t * edge_connection_new(int type, int socket_family)
Definition: connection.c:415
#define fmt_and_decorate_addr(a)
Definition: address.h:214
int connection_edge_finished_connecting(edge_connection_t *edge_conn)
int control_event_stream_bandwidth(edge_connection_t *edge_conn)
#define LD_EDGE
Definition: log.h:92
int sendmes_pending
Definition: half_edge_st.h:23
size_t half_streams_get_total_allocation(void)
struct connection_t * linked_conn
#define END_STREAM_REASON_CANT_ATTACH
Definition: or.h:250
uint16_t port
void connection_ap_mark_as_waiting_for_renddesc(entry_connection_t *entry_conn)
addressmap_entry_source_t
Definition: or.h:1023
int strcmpstart(const char *s1, const char *s2)
Definition: util_string.c:206
#define tor_free(p)
Definition: malloc.h:52
#define tor_fragile_assert()
Definition: util_bug.h:241
#define END_STREAM_REASON_HTTPPROTOCOL
Definition: or.h:269
#define LOG_NOTICE
Definition: log.h:48
mainloop_event_t * mainloop_event_postloop_new(void(*cb)(mainloop_event_t *, void *), void *userdata)
int smartlist_contains_int_as_string(const smartlist_t *sl, int num)
Definition: smartlist.c:147
void client_dns_set_addressmap(entry_connection_t *for_conn, const char *address, const tor_addr_t *val, const char *exitname, int ttl)
Definition: addressmap.c:724
const char * conn_state_to_string(int type, int state)
Definition: connection.c:275
Header file for mainloop.c.
void mainloop_event_activate(mainloop_event_t *event)
uint8_t purpose
Definition: circuit_st.h:100
void memwipe(void *mem, uint8_t byte, size_t sz)
Definition: crypto_util.c:57
#define ISO_DESTADDR
Definition: or.h:962
#define EXIT_PURPOSE_RESOLVE
STATIC void connection_half_edge_add(const edge_connection_t *conn, origin_circuit_t *circ)
void clear_trackexithost_mappings(const char *exitname)
Definition: addressmap.c:175
hs_circuit_id_protocol_t hs_service_exports_circuit_id(const ed25519_public_key_t *pk)
Definition: hs_service.c:3773
int addressmap_rewrite(char *address, size_t maxlen, unsigned flags, time_t *expires_out, addressmap_entry_source_t *exit_source_out)
Definition: addressmap.c:384
struct buf_t * pending_optimistic_data
int connection_ap_handshake_attach_circuit(entry_connection_t *conn)
Definition: circuituse.c:2813
unsigned int purpose
Definition: connection_st.h:46
int connection_edge_send_command(edge_connection_t *fromconn, uint8_t relay_command, const char *payload, size_t payload_len)
Definition: relay.c:729
edge_connection_t * TO_EDGE_CONN(connection_t *c)
routerset_t * ExcludeExitNodes
Definition: or_options_st.h:89
static void set_uint32(void *cp, uint32_t v)
Definition: bytes.h:82
rend_auth_type_t
Definition: or.h:402
#define ENTRY_TO_CONN(c)
Definition: or.h:738
#define MAX_CONNECTED_CELL_PAYLOAD_LEN
void connection_ap_handshake_socks_reply(entry_connection_t *conn, char *reply, size_t replylen, int endreason)
static uint32_t get_uint32(const void *cp)
Definition: bytes.h:49
static int handle_hs_exit_conn(circuit_t *circ, edge_connection_t *conn)
Header file for dnsserv.c.
void connection_ap_attach_pending(int retry)
#define CIRCUIT_PURPOSE_C_HSDIR_GET
Definition: circuitlist.h:91
STATIC int begin_cell_parse(const cell_t *cell, begin_cell_t *bcell, uint8_t *end_reason_out)
void smartlist_del_keeporder(smartlist_t *sl, int idx)
unsigned int linked
Definition: connection_st.h:70
int connection_edge_finished_flushing(edge_connection_t *conn)
streamid_t stream_id
Definition: or.h:640
socks_request_t * socks_request
uint32_t dns_clip_ttl(uint32_t ttl)
Definition: dns.c:275
#define STREAMWINDOW_START
Definition: or.h:508
hostname_type_t parse_extended_hostname(char *address)
Header file for hibernate.c.
struct crypt_path_t * cpath_layer
Header file for policies.c.
channel_t * p_chan
Definition: or_circuit_st.h:37
static uint32_t connection_ap_get_begincell_flags(entry_connection_t *ap_conn)
#define STREAMWINDOW_INCREMENT
Definition: or.h:511
Definition: rendcache.h:29
int directory_permits_begindir_requests(const or_options_t *options)
Definition: dirserv.c:159
#define LD_APP
Definition: log.h:76
#define END_STREAM_REASON_INVALID_NATD_DEST
Definition: or.h:262
struct buf_t * inbuf
Definition: connection_st.h:93
Common functions for cryptographic routines.
Header file for channel.c.
tor_assert(buffer)
edge_connection_t * n_streams
Definition: or_circuit_st.h:39
socks5_reply_status_t stream_end_reason_to_socks5_response(int reason)
Definition: reasons.c:100
#define LD_CONTROL
Definition: log.h:78
int address_is_invalid_destination(const char *address, int client)
Definition: addressmap.c:1078
int connection_exit_begin_conn(cell_t *cell, circuit_t *circ)
void circpad_machine_event_circ_has_streams(origin_circuit_t *circ)
int connection_half_edge_is_valid_sendme(const smartlist_t *half_conns, streamid_t stream_id)
uint8_t state
Definition: circuit_st.h:99
streamid_t stream_id
Definition: half_edge_st.h:19
#define ISO_CLIENTADDR
Definition: or.h:968
int ClientRejectInternalAddresses
Header file for routermode.c.
int connection_ap_can_use_exit(const entry_connection_t *conn, const node_t *exit_node)
#define REVERSE_LOOKUP_NAME_BUF_LEN
Definition: address.h:258
int tor_memeq(const void *a, const void *b, size_t sz)
Definition: di_ops.c:107
void half_edge_free_(half_edge_t *he)
int tor_asprintf(char **strp, const char *fmt,...)
Definition: printf.c:75
const char * fmt_addrport(const tor_addr_t *addr, uint16_t port)
Definition: address.c:1169
circid_t n_circ_id
Definition: circuit_st.h:67
int connection_edge_compatible_with_circuit(const entry_connection_t *conn, const origin_circuit_t *circ)
dir_connection_t * TO_DIR_CONN(connection_t *c)
Definition: directory.c:85
#define ISO_SOCKSAUTH
Definition: or.h:964
unsigned int use_cached_ipv4_answers
Header file for circuitpadding.c.
#define DIGEST_LEN
Definition: digest_sizes.h:20
void tor_addr_from_ipv6_bytes(tor_addr_t *dest, const char *ipv6_bytes)
Definition: address.c:885
static int connection_ap_handshake_process_socks(entry_connection_t *conn)
const char * node_describe(const node_t *node)
Definition: describe.c:143
char identity[DIGEST_LEN]
Definition: node_st.h:40
#define END_CIRC_AT_ORIGIN
Definition: or.h:305
static int connection_ap_get_original_destination(entry_connection_t *conn, socks_request_t *req)
Master header file for Tor-specific functionality.
int purpose_needs_anonymity(uint8_t dir_purpose, uint8_t router_purpose, const char *resource)
Definition: directory.c:98
#define CIRCUIT_STATE_OPEN
Definition: circuitlist.h:31
void connection_close_immediate(connection_t *conn)
Definition: connection.c:844
void circuit_discard_optional_exit_enclaves(extend_info_t *info)
const char * hex_str(const char *from, size_t fromlen)
Definition: binascii.c:34
static smartlist_t * pending_entry_connections
uint16_t streamid_t
Definition: or.h:610
void connection_exit_about_to_close(edge_connection_t *edge_conn)
Header file for circuitbuild.c.
int control_event_stream_status(entry_connection_t *conn, stream_status_event_t tp, int reason_code)
const char * channel_get_actual_remote_address(channel_t *chan)
Definition: channel.c:2830
#define END_STREAM_REASON_PRIVATE_ADDR
Definition: or.h:265
#define BEGIN_FLAG_IPV4_NOT_OK
int tor_addr_parse(tor_addr_t *addr, const char *src)
Definition: address.c:1255
uint16_t marked_for_close
unsigned int chosen_exit_optional
#define AP_CONN_STATE_CIRCUIT_WAIT
int hexdigest_to_digest(const char *hexdigest, char *digest)
Definition: routerlist.c:663
entry_connection_t * entry_connection_new(int type, int socket_family)
Definition: connection.c:396
Header file for rephist.c.
void smartlist_remove(smartlist_t *sl, const void *element)
void connection_edge_end_close(edge_connection_t *conn, uint8_t reason)
int rend_valid_v2_service_id(const char *query)
Definition: rendcommon.c:719
#define AP_CONN_STATE_HTTP_CONNECT_WAIT
#define LOG_WARN
Definition: log.h:51
int tor_addr_is_null(const tor_addr_t *addr)
Definition: address.c:770
unsigned int type
Definition: connection_st.h:45
void pathbias_mark_use_rollback(origin_circuit_t *circ)
Definition: circpathbias.c:700
int connection_ap_process_transparent(entry_connection_t *conn)
int dns_resolve(edge_connection_t *exitconn)
Definition: dns.c:634
unsigned int edge_has_sent_end
#define END_STREAM_REASON_CANT_FETCH_ORIG_DEST
Definition: or.h:259
int connected_pending
Definition: half_edge_st.h:30
Header file for circuituse.c.
void base16_encode(char *dest, size_t destlen, const char *src, size_t srclen)
Definition: binascii.c:478
void circuit_clear_isolation(origin_circuit_t *circ)
socks5_reply_status_t
Definition: socks5_status.h:20
smartlist_t * half_streams
void tor_strlower(char *s)
Definition: util_string.c:127
int connection_connect(connection_t *conn, const char *address, const tor_addr_t *addr, uint16_t port, int *socket_error)
Definition: connection.c:2179
#define AP_CONN_STATE_SOCKS_WAIT
#define LD_REND
Definition: log.h:82
Header file for circuitlist.c.
#define CIRCUIT_PURPOSE_PATH_BIAS_TESTING
Definition: circuitlist.h:121
const node_t * router_find_exact_exit_enclave(const char *address, uint16_t port)
Definition: nodelist.c:2174
Header file for rendservice.c.
#define ISO_CLIENTPROTO
Definition: or.h:966
int control_event_client_status(int severity, const char *format,...)
static size_t n_half_conns_allocated
int rend_cache_lookup_entry(const char *query, int version, rend_cache_entry_t **e)
Definition: rendcache.c:511
int connection_state_is_open(connection_t *conn)
Definition: connection.c:4642
void * smartlist_bsearch(const smartlist_t *sl, const void *key, int(*compare)(const void *key, const void **member))
Definition: smartlist.c:411
char * TransProxyType
int tor_digest_is_zero(const char *digest)
Definition: util_string.c:96
#define END_STREAM_REASON_FLAG_ALREADY_SOCKS_REPLIED
Definition: or.h:283
#define DIR_CONN_STATE_SERVER_COMMAND_WAIT
Definition: directory.h:27
int address_is_in_virtual_range(const char *address)
Definition: addressmap.c:856
#define CONN_TYPE_AP_HTTP_CONNECT_LISTENER
Definition: connection.h:55
int connection_edge_is_rendezvous_stream(const edge_connection_t *conn)
int addressmap_rewrite_reverse(char *address, size_t maxlen, unsigned flags, time_t *expires_out)
Definition: addressmap.c:504
#define HEX_DIGEST_LEN
Definition: crypto_digest.h:35
int connection_edge_flushed_some(edge_connection_t *conn)
unsigned int prefer_ipv6_virtaddr
uint64_t dirreq_id
Definition: circuit_st.h:193
hs_circuit_id_protocol_t
Definition: hs_service.h:185
uint16_t length
Definition: or.h:642
entry_connection_t * connection_ap_make_link(connection_t *partner, char *address, uint16_t port, const char *digest, int session_group, int isolation_flags, int use_begindir, int want_onehop)
uint8_t command
Definition: or.h:638
Header file containing circuit data for the whole HS subsytem.
struct crypt_path_t * prev
Definition: crypt_path_st.h:70
Header file for sendme.c.
char * http_get_header(const char *headers, const char *which)
Definition: directory.c:298
const char * end_reason_to_http_connect_response_line(int endreason)
Definition: reasons.c:457
void connection_ap_mark_as_non_pending_circuit(entry_connection_t *entry_conn)
Header file for connection_edge.c.
hostname_type_t
routerset_t * ExcludeExitNodesUnion_
Definition: or_options_st.h:94
origin_circuit_t * TO_ORIGIN_CIRCUIT(circuit_t *x)
Definition: circuitlist.c:163
#define REMAP_STREAM_SOURCE_CACHE
const char * circuit_state_to_string(int state)
Definition: circuitlist.c:757
int tor_snprintf(char *str, size_t size, const char *format,...)
Definition: printf.c:27
char * tor_addr_to_str_dup(const tor_addr_t *addr)
Definition: address.c:1134
int router_compare_to_my_exit_policy(const tor_addr_t *addr, uint16_t port)
Definition: router.c:1545
#define CELL_PAYLOAD_SIZE
Definition: or.h:576
struct hs_ident_circuit_t * hs_ident
void dnsserv_resolved(entry_connection_t *conn, int answer_type, size_t answer_len, const char *answer, int ttl)
Definition: dnsserv.c:339
#define END_STREAM_REASON_SOCKSPROTOCOL
Definition: or.h:256
void connection_exit_connect(edge_connection_t *edge_conn)
void tor_addr_from_in6(tor_addr_t *dest, const struct in6_addr *in6)
Definition: address.c:896
streamid_t next_stream_id
#define ISO_NYM_EPOCH
Definition: or.h:972
Header file for relay.c.
edge_connection_t * p_streams
char identity_digest[DIGEST_LEN]
struct evdns_server_request * dns_server_request
#define CIRCUIT_PURPOSE_S_HSDIR_POST
Definition: circuitlist.h:113
Header file for router.c.
const char * escaped(const char *s)
Definition: escape.c:126
static const struct in6_addr * tor_addr_to_in6(const tor_addr_t *a)
Definition: address.h:111
time_t timestamp_last_read_allowed
Definition: connection_st.h:98
const char * stream_end_reason_to_string(int reason)
Definition: reasons.c:64
static int connection_ap_handle_onion(entry_connection_t *conn, socks_request_t *socks, origin_circuit_t *circ, hostname_type_t addresstype)
#define CIRCUIT_PURPOSE_C_REND_JOINED
Definition: circuitlist.h:89
#define CIRCUIT_PURPOSE_IS_CLIENT(p)
Definition: circuitlist.h:141
int hs_client_refetch_hsdesc(const ed25519_public_key_t *identity_pk)
Definition: hs_client.c:1344
#define ISO_SESSIONGRP
Definition: or.h:970
#define fmt_addr(a)
Definition: address.h:211
static int consider_plaintext_ports(entry_connection_t *conn, uint16_t port)
uint32_t circid_t
Definition: or.h:608
#define CIRCUIT_PURPOSE_OR
Definition: circuitlist.h:38
#define log_fn(severity, domain, args,...)
Definition: log.h:274
unsigned int isolation_values_set
void client_dns_set_reverse_addressmap(entry_connection_t *for_conn, const char *address, const char *v, const char *exitname, int ttl)
Definition: addressmap.c:763
int LeaveStreamsUnattached
#define END_STREAM_REASON_MASK
Definition: or.h:272
#define AP_CONN_STATE_CONTROLLER_WAIT
void rep_hist_note_used_resolve(time_t now)
#define CONN_TYPE_EXIT
Definition: connection.h:26
const hs_descriptor_t * hs_cache_lookup_as_client(const ed25519_public_key_t *key)
Definition: hs_cache.c:757
void mark_circuit_unusable_for_new_conns(origin_circuit_t *circ)
Definition: circuituse.c:3105
int connection_half_edge_is_valid_end(smartlist_t *half_conns, streamid_t stream_id)
#define EXIT_CONN_STATE_OPEN
int connection_ap_handshake_attach_chosen_circuit(entry_connection_t *conn, origin_circuit_t *circ, crypt_path_t *cpath)
Definition: circuituse.c:2728
#define AP_CONN_STATE_OPEN
or_circuit_t * TO_OR_CIRCUIT(circuit_t *x)
Definition: circuitlist.c:151
static int my_exit_policy_rejects(const tor_addr_t *addr, uint16_t port, const char **why_rejected)
MOCK_IMPL(void, connection_mark_unattached_ap_,(entry_connection_t *conn, int endreason, int line, const char *file))
void connection_mark_for_close_(connection_t *conn, int line, const char *file)
Definition: connection.c:878
int connection_edge_end(edge_connection_t *conn, uint8_t reason)
#define tor_addr_eq(a, b)
Definition: address.h:244
void connection_ap_handshake_socks_resolved_addr(entry_connection_t *conn, const tor_addr_t *answer, int ttl, time_t expires)
int data_pending
Definition: half_edge_st.h:27
#define CIRCUIT_PURPOSE_C_GENERAL
Definition: circuitlist.h:71
time_t approx_time(void)
Definition: approx_time.c:32
unsigned int is_transparent_ap
void connection_ap_fail_onehop(const char *failed_digest, cpath_build_state_t *build_state)
unsigned int isolation_any_streams_attached
const char * pathbias_state_to_string(path_state_t state)
Definition: circpathbias.c:265
uint32_t magic
Definition: connection_st.h:41
int node_exit_policy_rejects_all(const node_t *node)
Definition: nodelist.c:1430
int connection_edge_process_inbuf(edge_connection_t *conn, int package_partial)
struct smartlist_t * RejectPlaintextPorts
static int relay_send_end_cell_from_edge(streamid_t stream_id, circuit_t *circ, uint8_t reason, crypt_path_t *cpath_layer)
STATIC int connected_cell_format_payload(uint8_t *payload_out, const tor_addr_t *addr, uint32_t ttl)
const char * marked_for_close_file
Header file for hs_cache.c.
extend_info_t * extend_info
Definition: crypt_path_st.h:56
long tor_parse_long(const char *s, int base, long min, long max, int *ok, char **next)
Definition: parse_int.c:56
int ClientDNSRejectInternalAddresses
void rep_hist_note_used_port(time_t now, uint16_t port)
int connection_ap_handshake_rewrite_and_attach(entry_connection_t *conn, origin_circuit_t *circ, crypt_path_t *cpath)
void node_get_address_string(const node_t *node, char *buf, size_t len)
Definition: nodelist.c:1569
static void connection_edge_about_to_close(edge_connection_t *edge_conn)
Header file for buffers.c.
int rend_client_any_intro_points_usable(const rend_cache_entry_t *entry)
Definition: rendclient.c:1110
Header file for reasons.c.
int connection_half_edge_is_valid_resolved(smartlist_t *half_conns, streamid_t stream_id)
#define CONN_TYPE_DIR
Definition: connection.h:35
circuit_t * circuit_get_by_edge_conn(edge_connection_t *conn)
Definition: circuitlist.c:1572
Header file for connection_or.c.
struct circuit_t * on_circuit
void circuit_read_valid_data(origin_circuit_t *circ, uint16_t relay_body_len)
Definition: circuituse.c:3150
static void tell_controller_about_resolved_result(entry_connection_t *conn, int answer_type, size_t answer_len, const char *answer, int ttl, time_t expires)
void circuit_detach_stream(circuit_t *circ, edge_connection_t *conn)
Definition: circuituse.c:1392
#define LD_NET
Definition: log.h:64
int connection_edge_reached_eof(edge_connection_t *conn)
void smartlist_insert(smartlist_t *sl, int idx, void *val)
int connection_ap_handshake_send_resolve(entry_connection_t *ap_conn)
extend_info_t * chosen_exit
#define tor_addr_to_in6_addr8(x)
Definition: address.h:129
void connection_watch_events(connection_t *conn, watchable_events_t events)
Definition: mainloop.c:493
char identity_digest[DIGEST_LEN]
Definition: channel.h:384
void connection_ap_expire_beginning(void)
#define AP_CONN_STATE_IS_UNATTACHED(s)
struct edge_connection_t * next_stream
Header for compat_libevent.c.
tor_addr_t addr
unsigned int may_use_optimistic_data
void tor_addr_copy(tor_addr_t *dest, const tor_addr_t *src)
Definition: address.c:904
int rend_service_set_connection_addr_port(edge_connection_t *conn, origin_circuit_t *circ)
Definition: rendservice.c:4405
#define CIRCUIT_PURPOSE_S_REND_JOINED
Definition: circuitlist.h:111
#define CONN_TYPE_AP
Definition: connection.h:31
int connection_ap_detach_retriable(entry_connection_t *conn, origin_circuit_t *circ, int reason)
#define AP_CONN_STATE_NATD_WAIT
uint8_t errno_to_stream_end_reason(int e)
Definition: reasons.c:177
#define BEGIN_FLAG_IPV6_OK
Header file for rendclient.c.
Header file for control_events.c.
#define LD_PROTOCOL
Definition: log.h:70
rend_data_t * rend_data
int connection_buf_get_line(connection_t *conn, char *data, size_t *data_len)
Definition: connection.c:3892
int buf_set_to_copy(buf_t **output, const buf_t *input)
Definition: buffers.c:888
int parse_http_command(const char *headers, char **command_out, char **url_out)
Definition: directory.c:244
void rend_client_refetch_v2_renddesc(rend_data_t *rend_query)
Definition: rendclient.c:709
const char * addressmap_register_virtual_address(int type, char *new_address)
Definition: addressmap.c:996
static int connection_half_edge_compare_bsearch(const void *key, const void **member)
#define RELAY_HEADER_SIZE
Definition: or.h:603
void pathbias_mark_use_success(origin_circuit_t *circ)
Definition: circpathbias.c:661
static int compute_retry_timeout(entry_connection_t *conn)
void connection_ap_rescan_and_attach_pending(void)
int tor_addr_from_sockaddr(tor_addr_t *a, const struct sockaddr *sa, uint16_t *port_out)
Definition: address.c:165
void sendme_connection_edge_consider_sending(edge_connection_t *conn)
Definition: sendme.c:375
static int connection_ap_process_natd(entry_connection_t *conn)
int control_event_address_mapped(const char *from, const char *to, time_t expires, const char *error, const int cached)
Header file for networkstatus.c.
#define LD_BUG
Definition: log.h:84
Header file for dns.c.
#define EXIT_CONN_STATE_CONNECTING
STATIC int connection_ap_process_http_connect(entry_connection_t *conn)
int smartlist_bsearch_idx(const smartlist_t *sl, const void *key, int(*compare)(const void *key, const void **member), int *found_out)
Definition: smartlist.c:428
Header file for routerlist.c.
const char * escaped_safe_str_client(const char *address)
Definition: config.c:1137
int connection_half_edge_is_valid_connected(const smartlist_t *half_conns, streamid_t stream_id)
void connection_edge_free_all(void)
int connection_half_edge_is_valid_data(const smartlist_t *half_conns, streamid_t stream_id)
void dnsserv_reject_request(entry_connection_t *conn)
Definition: dnsserv.c:289
static sa_family_t tor_addr_family(const tor_addr_t *a)
Definition: address.h:179
#define SOCKS4_NETWORK_LEN
Definition: or.h:563
int connection_edge_end_errno(edge_connection_t *conn)
int tor_addr_port_split(int severity, const char *addrport, char **address_out, uint16_t *port_out)
Definition: address.c:1818
char * tor_dup_ip(uint32_t addr)
Definition: address.c:1948