rendclient.c 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256
  1. /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  2. * Copyright (c) 2007-2018, The Tor Project, Inc. */
  3. /* See LICENSE for licensing information */
  4. /**
  5. * \file rendclient.c
  6. * \brief Client code to access location-hidden services.
  7. **/
  8. #include "or/or.h"
  9. #include "or/circpathbias.h"
  10. #include "or/circuitbuild.h"
  11. #include "or/circuitlist.h"
  12. #include "or/circuituse.h"
  13. #include "or/config.h"
  14. #include "or/connection.h"
  15. #include "or/connection_edge.h"
  16. #include "or/control.h"
  17. #include "lib/crypt_ops/crypto_rand.h"
  18. #include "lib/crypt_ops/crypto_util.h"
  19. #include "or/directory.h"
  20. #include "or/hs_circuit.h"
  21. #include "or/hs_client.h"
  22. #include "or/hs_common.h"
  23. #include "or/main.h"
  24. #include "or/networkstatus.h"
  25. #include "or/nodelist.h"
  26. #include "or/relay.h"
  27. #include "or/rendclient.h"
  28. #include "or/rendcommon.h"
  29. #include "or/rephist.h"
  30. #include "or/router.h"
  31. #include "or/routerlist.h"
  32. #include "or/routerset.h"
  33. #include "or/cpath_build_state_st.h"
  34. #include "or/crypt_path_st.h"
  35. #include "or/dir_connection_st.h"
  36. #include "or/entry_connection_st.h"
  37. #include "or/extend_info_st.h"
  38. #include "or/origin_circuit_st.h"
  39. #include "or/rend_intro_point_st.h"
  40. #include "or/rend_service_descriptor_st.h"
  41. #include "or/routerstatus_st.h"
  42. static extend_info_t *rend_client_get_random_intro_impl(
  43. const rend_cache_entry_t *rend_query,
  44. const int strict, const int warnings);
  45. /** Purge all potentially remotely-detectable state held in the hidden
  46. * service client code. Called on SIGNAL NEWNYM. */
  47. void
  48. rend_client_purge_state(void)
  49. {
  50. rend_cache_purge();
  51. rend_cache_failure_purge();
  52. rend_client_cancel_descriptor_fetches();
  53. hs_purge_last_hid_serv_requests();
  54. }
  55. /** Called when we've established a circuit to an introduction point:
  56. * send the introduction request. */
  57. void
  58. rend_client_introcirc_has_opened(origin_circuit_t *circ)
  59. {
  60. tor_assert(circ->base_.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
  61. tor_assert(circ->cpath);
  62. log_info(LD_REND,"introcirc is open");
  63. connection_ap_attach_pending(1);
  64. }
  65. /** Send the establish-rendezvous cell along a rendezvous circuit. if
  66. * it fails, mark the circ for close and return -1. else return 0.
  67. */
  68. static int
  69. rend_client_send_establish_rendezvous(origin_circuit_t *circ)
  70. {
  71. tor_assert(circ->base_.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND);
  72. tor_assert(circ->rend_data);
  73. log_info(LD_REND, "Sending an ESTABLISH_RENDEZVOUS cell");
  74. crypto_rand(circ->rend_data->rend_cookie, REND_COOKIE_LEN);
  75. /* Set timestamp_dirty, because circuit_expire_building expects it,
  76. * and the rend cookie also means we've used the circ. */
  77. circ->base_.timestamp_dirty = time(NULL);
  78. /* We've attempted to use this circuit. Probe it if we fail */
  79. pathbias_count_use_attempt(circ);
  80. if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
  81. RELAY_COMMAND_ESTABLISH_RENDEZVOUS,
  82. circ->rend_data->rend_cookie,
  83. REND_COOKIE_LEN,
  84. circ->cpath->prev)<0) {
  85. /* circ is already marked for close */
  86. log_warn(LD_GENERAL, "Couldn't send ESTABLISH_RENDEZVOUS cell");
  87. return -1;
  88. }
  89. return 0;
  90. }
  91. /** Called when we're trying to connect an ap conn; sends an INTRODUCE1 cell
  92. * down introcirc if possible.
  93. */
  94. int
  95. rend_client_send_introduction(origin_circuit_t *introcirc,
  96. origin_circuit_t *rendcirc)
  97. {
  98. const or_options_t *options = get_options();
  99. size_t payload_len;
  100. int r, v3_shift = 0;
  101. char payload[RELAY_PAYLOAD_SIZE];
  102. char tmp[RELAY_PAYLOAD_SIZE];
  103. rend_cache_entry_t *entry = NULL;
  104. crypt_path_t *cpath;
  105. off_t dh_offset;
  106. crypto_pk_t *intro_key = NULL;
  107. int status = 0;
  108. const char *onion_address;
  109. tor_assert(introcirc->base_.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
  110. tor_assert(rendcirc->base_.purpose == CIRCUIT_PURPOSE_C_REND_READY);
  111. tor_assert(introcirc->rend_data);
  112. tor_assert(rendcirc->rend_data);
  113. tor_assert(!rend_cmp_service_ids(rend_data_get_address(introcirc->rend_data),
  114. rend_data_get_address(rendcirc->rend_data)));
  115. assert_circ_anonymity_ok(introcirc, options);
  116. assert_circ_anonymity_ok(rendcirc, options);
  117. onion_address = rend_data_get_address(introcirc->rend_data);
  118. r = rend_cache_lookup_entry(onion_address, -1, &entry);
  119. /* An invalid onion address is not possible else we have a big issue. */
  120. tor_assert(r != -EINVAL);
  121. if (r < 0 || !rend_client_any_intro_points_usable(entry)) {
  122. /* If the descriptor is not found or the intro points are not usable
  123. * anymore, trigger a fetch. */
  124. log_info(LD_REND,
  125. "query %s didn't have valid rend desc in cache. "
  126. "Refetching descriptor.",
  127. safe_str_client(onion_address));
  128. rend_client_refetch_v2_renddesc(introcirc->rend_data);
  129. {
  130. connection_t *conn;
  131. while ((conn = connection_get_by_type_state_rendquery(CONN_TYPE_AP,
  132. AP_CONN_STATE_CIRCUIT_WAIT, onion_address))) {
  133. connection_ap_mark_as_non_pending_circuit(TO_ENTRY_CONN(conn));
  134. conn->state = AP_CONN_STATE_RENDDESC_WAIT;
  135. }
  136. }
  137. status = -1;
  138. goto cleanup;
  139. }
  140. /* first 20 bytes of payload are the hash of the service's pk */
  141. intro_key = NULL;
  142. SMARTLIST_FOREACH(entry->parsed->intro_nodes, rend_intro_point_t *,
  143. intro, {
  144. if (tor_memeq(introcirc->build_state->chosen_exit->identity_digest,
  145. intro->extend_info->identity_digest, DIGEST_LEN)) {
  146. intro_key = intro->intro_key;
  147. break;
  148. }
  149. });
  150. if (!intro_key) {
  151. log_info(LD_REND, "Could not find intro key for %s at %s; we "
  152. "have a v2 rend desc with %d intro points. "
  153. "Trying a different intro point...",
  154. safe_str_client(onion_address),
  155. safe_str_client(extend_info_describe(
  156. introcirc->build_state->chosen_exit)),
  157. smartlist_len(entry->parsed->intro_nodes));
  158. if (hs_client_reextend_intro_circuit(introcirc)) {
  159. status = -2;
  160. goto perm_err;
  161. } else {
  162. status = -1;
  163. goto cleanup;
  164. }
  165. }
  166. if (crypto_pk_get_digest(intro_key, payload)<0) {
  167. log_warn(LD_BUG, "Internal error: couldn't hash public key.");
  168. status = -2;
  169. goto perm_err;
  170. }
  171. /* Initialize the pending_final_cpath and start the DH handshake. */
  172. cpath = rendcirc->build_state->pending_final_cpath;
  173. if (!cpath) {
  174. cpath = rendcirc->build_state->pending_final_cpath =
  175. tor_malloc_zero(sizeof(crypt_path_t));
  176. cpath->magic = CRYPT_PATH_MAGIC;
  177. if (!(cpath->rend_dh_handshake_state = crypto_dh_new(DH_TYPE_REND))) {
  178. log_warn(LD_BUG, "Internal error: couldn't allocate DH.");
  179. status = -2;
  180. goto perm_err;
  181. }
  182. if (crypto_dh_generate_public(cpath->rend_dh_handshake_state)<0) {
  183. log_warn(LD_BUG, "Internal error: couldn't generate g^x.");
  184. status = -2;
  185. goto perm_err;
  186. }
  187. }
  188. /* If version is 3, write (optional) auth data and timestamp. */
  189. if (entry->parsed->protocols & (1<<3)) {
  190. tmp[0] = 3; /* version 3 of the cell format */
  191. /* auth type, if any */
  192. tmp[1] = (uint8_t) TO_REND_DATA_V2(introcirc->rend_data)->auth_type;
  193. v3_shift = 1;
  194. if (tmp[1] != REND_NO_AUTH) {
  195. set_uint16(tmp+2, htons(REND_DESC_COOKIE_LEN));
  196. memcpy(tmp+4, TO_REND_DATA_V2(introcirc->rend_data)->descriptor_cookie,
  197. REND_DESC_COOKIE_LEN);
  198. v3_shift += 2+REND_DESC_COOKIE_LEN;
  199. }
  200. /* Once this held a timestamp. */
  201. set_uint32(tmp+v3_shift+1, 0);
  202. v3_shift += 4;
  203. } /* if version 2 only write version number */
  204. else if (entry->parsed->protocols & (1<<2)) {
  205. tmp[0] = 2; /* version 2 of the cell format */
  206. }
  207. /* write the remaining items into tmp */
  208. if (entry->parsed->protocols & (1<<3) || entry->parsed->protocols & (1<<2)) {
  209. /* version 2 format */
  210. extend_info_t *extend_info = rendcirc->build_state->chosen_exit;
  211. int klen;
  212. /* nul pads */
  213. set_uint32(tmp+v3_shift+1, tor_addr_to_ipv4n(&extend_info->addr));
  214. set_uint16(tmp+v3_shift+5, htons(extend_info->port));
  215. memcpy(tmp+v3_shift+7, extend_info->identity_digest, DIGEST_LEN);
  216. klen = crypto_pk_asn1_encode(extend_info->onion_key,
  217. tmp+v3_shift+7+DIGEST_LEN+2,
  218. sizeof(tmp)-(v3_shift+7+DIGEST_LEN+2));
  219. if (klen < 0) {
  220. log_warn(LD_BUG,"Internal error: can't encode public key.");
  221. status = -2;
  222. goto perm_err;
  223. }
  224. set_uint16(tmp+v3_shift+7+DIGEST_LEN, htons(klen));
  225. memcpy(tmp+v3_shift+7+DIGEST_LEN+2+klen, rendcirc->rend_data->rend_cookie,
  226. REND_COOKIE_LEN);
  227. dh_offset = v3_shift+7+DIGEST_LEN+2+klen+REND_COOKIE_LEN;
  228. } else {
  229. /* Version 0. */
  230. strncpy(tmp, rendcirc->build_state->chosen_exit->nickname,
  231. (MAX_NICKNAME_LEN+1)); /* nul pads */
  232. memcpy(tmp+MAX_NICKNAME_LEN+1, rendcirc->rend_data->rend_cookie,
  233. REND_COOKIE_LEN);
  234. dh_offset = MAX_NICKNAME_LEN+1+REND_COOKIE_LEN;
  235. }
  236. if (crypto_dh_get_public(cpath->rend_dh_handshake_state, tmp+dh_offset,
  237. DH_KEY_LEN)<0) {
  238. log_warn(LD_BUG, "Internal error: couldn't extract g^x.");
  239. status = -2;
  240. goto perm_err;
  241. }
  242. /*XXX maybe give crypto_pk_obsolete_public_hybrid_encrypt a max_len arg,
  243. * to avoid buffer overflows? */
  244. r = crypto_pk_obsolete_public_hybrid_encrypt(intro_key, payload+DIGEST_LEN,
  245. sizeof(payload)-DIGEST_LEN,
  246. tmp,
  247. (int)(dh_offset+DH_KEY_LEN),
  248. PK_PKCS1_OAEP_PADDING, 0);
  249. if (r<0) {
  250. log_warn(LD_BUG,"Internal error: hybrid pk encrypt failed.");
  251. status = -2;
  252. goto perm_err;
  253. }
  254. payload_len = DIGEST_LEN + r;
  255. tor_assert(payload_len <= RELAY_PAYLOAD_SIZE); /* we overran something */
  256. /* Copy the rendezvous cookie from rendcirc to introcirc, so that
  257. * when introcirc gets an ack, we can change the state of the right
  258. * rendezvous circuit. */
  259. memcpy(introcirc->rend_data->rend_cookie, rendcirc->rend_data->rend_cookie,
  260. REND_COOKIE_LEN);
  261. log_info(LD_REND, "Sending an INTRODUCE1 cell");
  262. if (relay_send_command_from_edge(0, TO_CIRCUIT(introcirc),
  263. RELAY_COMMAND_INTRODUCE1,
  264. payload, payload_len,
  265. introcirc->cpath->prev)<0) {
  266. /* introcirc is already marked for close. leave rendcirc alone. */
  267. log_warn(LD_BUG, "Couldn't send INTRODUCE1 cell");
  268. status = -2;
  269. goto cleanup;
  270. }
  271. /* Now, we wait for an ACK or NAK on this circuit. */
  272. circuit_change_purpose(TO_CIRCUIT(introcirc),
  273. CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT);
  274. /* Set timestamp_dirty, because circuit_expire_building expects it
  275. * to specify when a circuit entered the _C_INTRODUCE_ACK_WAIT
  276. * state. */
  277. introcirc->base_.timestamp_dirty = time(NULL);
  278. pathbias_count_use_attempt(introcirc);
  279. goto cleanup;
  280. perm_err:
  281. if (!introcirc->base_.marked_for_close)
  282. circuit_mark_for_close(TO_CIRCUIT(introcirc), END_CIRC_REASON_INTERNAL);
  283. circuit_mark_for_close(TO_CIRCUIT(rendcirc), END_CIRC_REASON_INTERNAL);
  284. cleanup:
  285. memwipe(payload, 0, sizeof(payload));
  286. memwipe(tmp, 0, sizeof(tmp));
  287. return status;
  288. }
  289. /** Called when a rendezvous circuit is open; sends a establish
  290. * rendezvous circuit as appropriate. */
  291. void
  292. rend_client_rendcirc_has_opened(origin_circuit_t *circ)
  293. {
  294. tor_assert(circ->base_.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND);
  295. log_info(LD_REND,"rendcirc is open");
  296. /* generate a rendezvous cookie, store it in circ */
  297. if (rend_client_send_establish_rendezvous(circ) < 0) {
  298. return;
  299. }
  300. }
  301. /**
  302. * Called to close other intro circuits we launched in parallel.
  303. */
  304. static void
  305. rend_client_close_other_intros(const uint8_t *rend_pk_digest)
  306. {
  307. /* abort parallel intro circs, if any */
  308. SMARTLIST_FOREACH_BEGIN(circuit_get_global_list(), circuit_t *, c) {
  309. if ((c->purpose == CIRCUIT_PURPOSE_C_INTRODUCING ||
  310. c->purpose == CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) &&
  311. !c->marked_for_close && CIRCUIT_IS_ORIGIN(c)) {
  312. origin_circuit_t *oc = TO_ORIGIN_CIRCUIT(c);
  313. if (oc->rend_data &&
  314. rend_circuit_pk_digest_eq(oc, rend_pk_digest)) {
  315. log_info(LD_REND|LD_CIRC, "Closing introduction circuit %d that we "
  316. "built in parallel (Purpose %d).", oc->global_identifier,
  317. c->purpose);
  318. circuit_mark_for_close(c, END_CIRC_REASON_IP_NOW_REDUNDANT);
  319. }
  320. }
  321. }
  322. SMARTLIST_FOREACH_END(c);
  323. }
  324. /** Called when get an ACK or a NAK for a REND_INTRODUCE1 cell.
  325. */
  326. int
  327. rend_client_introduction_acked(origin_circuit_t *circ,
  328. const uint8_t *request, size_t request_len)
  329. {
  330. const or_options_t *options = get_options();
  331. origin_circuit_t *rendcirc;
  332. (void) request; // XXXX Use this.
  333. tor_assert(circ->build_state);
  334. tor_assert(circ->build_state->chosen_exit);
  335. assert_circ_anonymity_ok(circ, options);
  336. tor_assert(circ->rend_data);
  337. if (request_len == 0) {
  338. /* It's an ACK; the introduction point relayed our introduction request. */
  339. /* Locate the rend circ which is waiting to hear about this ack,
  340. * and tell it.
  341. */
  342. log_info(LD_REND,"Received ack. Telling rend circ...");
  343. rendcirc = circuit_get_ready_rend_circ_by_rend_data(circ->rend_data);
  344. if (rendcirc) { /* remember the ack */
  345. assert_circ_anonymity_ok(rendcirc, options);
  346. circuit_change_purpose(TO_CIRCUIT(rendcirc),
  347. CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED);
  348. /* Set timestamp_dirty, because circuit_expire_building expects
  349. * it to specify when a circuit entered the
  350. * _C_REND_READY_INTRO_ACKED state. */
  351. rendcirc->base_.timestamp_dirty = time(NULL);
  352. } else {
  353. log_info(LD_REND,"...Found no rend circ. Dropping on the floor.");
  354. }
  355. /* close the circuit: we won't need it anymore. */
  356. circuit_change_purpose(TO_CIRCUIT(circ),
  357. CIRCUIT_PURPOSE_C_INTRODUCE_ACKED);
  358. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
  359. /* close any other intros launched in parallel */
  360. rend_client_close_other_intros(rend_data_get_pk_digest(circ->rend_data,
  361. NULL));
  362. } else {
  363. /* It's a NAK; the introduction point didn't relay our request. */
  364. circuit_change_purpose(TO_CIRCUIT(circ), CIRCUIT_PURPOSE_C_INTRODUCING);
  365. /* Remove this intro point from the set of viable introduction
  366. * points. If any remain, extend to a new one and try again.
  367. * If none remain, refetch the service descriptor.
  368. */
  369. log_info(LD_REND, "Got nack for %s from %s...",
  370. safe_str_client(rend_data_get_address(circ->rend_data)),
  371. safe_str_client(extend_info_describe(circ->build_state->chosen_exit)));
  372. if (rend_client_report_intro_point_failure(circ->build_state->chosen_exit,
  373. circ->rend_data,
  374. INTRO_POINT_FAILURE_GENERIC)>0) {
  375. /* There are introduction points left. Re-extend the circuit to
  376. * another intro point and try again. */
  377. int result = hs_client_reextend_intro_circuit(circ);
  378. /* XXXX If that call failed, should we close the rend circuit,
  379. * too? */
  380. return result;
  381. } else {
  382. /* Close circuit because no more intro points are usable thus not
  383. * useful anymore. Change it's purpose before so we don't report an
  384. * intro point failure again triggering an extra descriptor fetch. */
  385. circuit_change_purpose(TO_CIRCUIT(circ),
  386. CIRCUIT_PURPOSE_C_INTRODUCE_ACKED);
  387. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
  388. }
  389. }
  390. return 0;
  391. }
  392. /** Determine the responsible hidden service directories for <b>desc_id</b>
  393. * and fetch the descriptor with that ID from one of them. Only
  394. * send a request to a hidden service directory that we have not yet tried
  395. * during this attempt to connect to this hidden service; on success, return 1,
  396. * in the case that no hidden service directory is left to ask for the
  397. * descriptor, return 0, and in case of a failure -1. */
  398. static int
  399. directory_get_from_hs_dir(const char *desc_id,
  400. const rend_data_t *rend_query,
  401. routerstatus_t *rs_hsdir)
  402. {
  403. routerstatus_t *hs_dir = rs_hsdir;
  404. char *hsdir_fp;
  405. char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  406. char descriptor_cookie_base64[3*REND_DESC_COOKIE_LEN_BASE64];
  407. const rend_data_v2_t *rend_data;
  408. #ifdef ENABLE_TOR2WEB_MODE
  409. const int tor2web_mode = get_options()->Tor2webMode;
  410. const int how_to_fetch = tor2web_mode ? DIRIND_ONEHOP : DIRIND_ANONYMOUS;
  411. #else
  412. const int how_to_fetch = DIRIND_ANONYMOUS;
  413. #endif /* defined(ENABLE_TOR2WEB_MODE) */
  414. tor_assert(desc_id);
  415. tor_assert(rend_query);
  416. rend_data = TO_REND_DATA_V2(rend_query);
  417. base32_encode(desc_id_base32, sizeof(desc_id_base32),
  418. desc_id, DIGEST_LEN);
  419. /* Automatically pick an hs dir if none given. */
  420. if (!rs_hsdir) {
  421. /* Determine responsible dirs. Even if we can't get all we want, work with
  422. * the ones we have. If it's empty, we'll notice in hs_pick_hsdir(). */
  423. smartlist_t *responsible_dirs = smartlist_new();
  424. hid_serv_get_responsible_directories(responsible_dirs, desc_id);
  425. hs_dir = hs_pick_hsdir(responsible_dirs, desc_id_base32);
  426. if (!hs_dir) {
  427. /* No suitable hs dir can be found, stop right now. */
  428. control_event_hsv2_descriptor_failed(rend_query, NULL,
  429. "QUERY_NO_HSDIR");
  430. control_event_hs_descriptor_content(rend_data_get_address(rend_query),
  431. desc_id_base32, NULL, NULL);
  432. return 0;
  433. }
  434. }
  435. /* Add a copy of the HSDir identity digest to the query so we can track it
  436. * on the control port. */
  437. hsdir_fp = tor_memdup(hs_dir->identity_digest,
  438. sizeof(hs_dir->identity_digest));
  439. smartlist_add(rend_query->hsdirs_fp, hsdir_fp);
  440. /* Encode descriptor cookie for logging purposes. Also, if the cookie is
  441. * malformed, no fetch is triggered thus this needs to be done before the
  442. * fetch request. */
  443. if (rend_data->auth_type != REND_NO_AUTH) {
  444. if (base64_encode(descriptor_cookie_base64,
  445. sizeof(descriptor_cookie_base64),
  446. rend_data->descriptor_cookie,
  447. REND_DESC_COOKIE_LEN,
  448. 0)<0) {
  449. log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
  450. control_event_hsv2_descriptor_failed(rend_query, hsdir_fp, "BAD_DESC");
  451. control_event_hs_descriptor_content(rend_data_get_address(rend_query),
  452. desc_id_base32, hsdir_fp, NULL);
  453. return 0;
  454. }
  455. /* Remove == signs. */
  456. descriptor_cookie_base64[strlen(descriptor_cookie_base64)-2] = '\0';
  457. } else {
  458. strlcpy(descriptor_cookie_base64, "(none)",
  459. sizeof(descriptor_cookie_base64));
  460. }
  461. /* Send fetch request. (Pass query and possibly descriptor cookie so that
  462. * they can be written to the directory connection and be referred to when
  463. * the response arrives. */
  464. directory_request_t *req =
  465. directory_request_new(DIR_PURPOSE_FETCH_RENDDESC_V2);
  466. directory_request_set_routerstatus(req, hs_dir);
  467. directory_request_set_indirection(req, how_to_fetch);
  468. directory_request_set_resource(req, desc_id_base32);
  469. directory_request_set_rend_query(req, rend_query);
  470. directory_initiate_request(req);
  471. directory_request_free(req);
  472. log_info(LD_REND, "Sending fetch request for v2 descriptor for "
  473. "service '%s' with descriptor ID '%s', auth type %d, "
  474. "and descriptor cookie '%s' to hidden service "
  475. "directory %s",
  476. rend_data->onion_address, desc_id_base32,
  477. rend_data->auth_type,
  478. (rend_data->auth_type == REND_NO_AUTH ? "[none]" :
  479. escaped_safe_str_client(descriptor_cookie_base64)),
  480. routerstatus_describe(hs_dir));
  481. control_event_hs_descriptor_requested(rend_data->onion_address,
  482. rend_data->auth_type,
  483. hs_dir->identity_digest,
  484. desc_id_base32, NULL);
  485. return 1;
  486. }
  487. /** Remove tracked HSDir requests from our history for this hidden service
  488. * descriptor <b>desc_id</b> (of size DIGEST_LEN) */
  489. static void
  490. purge_v2_hidserv_req(const char *desc_id)
  491. {
  492. char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  493. /* The hsdir request tracker stores v2 keys using the base32 encoded
  494. desc_id. Do it: */
  495. base32_encode(desc_id_base32, sizeof(desc_id_base32), desc_id,
  496. DIGEST_LEN);
  497. hs_purge_hid_serv_from_last_hid_serv_requests(desc_id_base32);
  498. }
  499. /** Fetch a v2 descriptor using the given descriptor id. If any hsdir(s) are
  500. * given, they will be used instead.
  501. *
  502. * On success, 1 is returned. If no hidden service is left to ask, return 0.
  503. * On error, -1 is returned. */
  504. static int
  505. fetch_v2_desc_by_descid(const char *desc_id,
  506. const rend_data_t *rend_query, smartlist_t *hsdirs)
  507. {
  508. int ret;
  509. tor_assert(rend_query);
  510. if (!hsdirs) {
  511. ret = directory_get_from_hs_dir(desc_id, rend_query, NULL);
  512. goto end; /* either success or failure, but we're done */
  513. }
  514. /* Using the given hsdir list, trigger a fetch on each of them. */
  515. SMARTLIST_FOREACH_BEGIN(hsdirs, routerstatus_t *, hs_dir) {
  516. /* This should always be a success. */
  517. ret = directory_get_from_hs_dir(desc_id, rend_query, hs_dir);
  518. tor_assert(ret);
  519. } SMARTLIST_FOREACH_END(hs_dir);
  520. /* Everything went well. */
  521. ret = 0;
  522. end:
  523. return ret;
  524. }
  525. /** Fetch a v2 descriptor using the onion address in the given query object.
  526. * This will compute the descriptor id for each replicas and fetch it on the
  527. * given hsdir(s) if any or the responsible ones that are chosen
  528. * automatically.
  529. *
  530. * On success, 1 is returned. If no hidden service is left to ask, return 0.
  531. * On error, -1 is returned. */
  532. static int
  533. fetch_v2_desc_by_addr(rend_data_t *rend_query, smartlist_t *hsdirs)
  534. {
  535. char descriptor_id[DIGEST_LEN];
  536. int replicas_left_to_try[REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS];
  537. int i, tries_left, ret;
  538. rend_data_v2_t *rend_data = TO_REND_DATA_V2(rend_query);
  539. /* Randomly iterate over the replicas until a descriptor can be fetched
  540. * from one of the consecutive nodes, or no options are left. */
  541. for (i = 0; i < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS; i++) {
  542. replicas_left_to_try[i] = i;
  543. }
  544. tries_left = REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS;
  545. while (tries_left > 0) {
  546. int rand_val = crypto_rand_int(tries_left);
  547. int chosen_replica = replicas_left_to_try[rand_val];
  548. replicas_left_to_try[rand_val] = replicas_left_to_try[--tries_left];
  549. ret = rend_compute_v2_desc_id(descriptor_id,
  550. rend_data->onion_address,
  551. rend_data->auth_type == REND_STEALTH_AUTH ?
  552. rend_data->descriptor_cookie : NULL,
  553. time(NULL), chosen_replica);
  554. if (ret < 0) {
  555. /* Normally, on failure the descriptor_id is untouched but let's be
  556. * safe in general in case the function changes at some point. */
  557. goto end;
  558. }
  559. if (tor_memcmp(descriptor_id, rend_data->descriptor_id[chosen_replica],
  560. sizeof(descriptor_id)) != 0) {
  561. /* Not equal from what we currently have so purge the last hid serv
  562. * request cache and update the descriptor ID with the new value. */
  563. purge_v2_hidserv_req(rend_data->descriptor_id[chosen_replica]);
  564. memcpy(rend_data->descriptor_id[chosen_replica], descriptor_id,
  565. sizeof(rend_data->descriptor_id[chosen_replica]));
  566. }
  567. /* Trigger the fetch with the computed descriptor ID. */
  568. ret = fetch_v2_desc_by_descid(descriptor_id, rend_query, hsdirs);
  569. if (ret != 0) {
  570. /* Either on success or failure, as long as we tried a fetch we are
  571. * done here. */
  572. goto end;
  573. }
  574. }
  575. /* If we come here, there are no hidden service directories left. */
  576. log_info(LD_REND, "Could not pick one of the responsible hidden "
  577. "service directories to fetch descriptors, because "
  578. "we already tried them all unsuccessfully.");
  579. ret = 0;
  580. end:
  581. memwipe(descriptor_id, 0, sizeof(descriptor_id));
  582. return ret;
  583. }
  584. /** Fetch a v2 descriptor using the given query. If any hsdir are specified,
  585. * use them for the fetch.
  586. *
  587. * On success, 1 is returned. If no hidden service is left to ask, return 0.
  588. * On error, -1 is returned. */
  589. int
  590. rend_client_fetch_v2_desc(rend_data_t *query, smartlist_t *hsdirs)
  591. {
  592. int ret;
  593. rend_data_v2_t *rend_data;
  594. const char *onion_address;
  595. tor_assert(query);
  596. /* Get the version 2 data structure of the query. */
  597. rend_data = TO_REND_DATA_V2(query);
  598. onion_address = rend_data_get_address(query);
  599. /* Depending on what's available in the rend data query object, we will
  600. * trigger a fetch by HS address or using a descriptor ID. */
  601. if (onion_address[0] != '\0') {
  602. ret = fetch_v2_desc_by_addr(query, hsdirs);
  603. } else if (!tor_digest_is_zero(rend_data->desc_id_fetch)) {
  604. ret = fetch_v2_desc_by_descid(rend_data->desc_id_fetch, query,
  605. hsdirs);
  606. } else {
  607. /* Query data is invalid. */
  608. ret = -1;
  609. goto error;
  610. }
  611. error:
  612. return ret;
  613. }
  614. /** Unless we already have a descriptor for <b>rend_query</b> with at least
  615. * one (possibly) working introduction point in it, start a connection to a
  616. * hidden service directory to fetch a v2 rendezvous service descriptor. */
  617. void
  618. rend_client_refetch_v2_renddesc(rend_data_t *rend_query)
  619. {
  620. rend_cache_entry_t *e = NULL;
  621. const char *onion_address = rend_data_get_address(rend_query);
  622. tor_assert(rend_query);
  623. /* Before fetching, check if we already have a usable descriptor here. */
  624. if (rend_cache_lookup_entry(onion_address, -1, &e) == 0 &&
  625. rend_client_any_intro_points_usable(e)) {
  626. log_info(LD_REND, "We would fetch a v2 rendezvous descriptor, but we "
  627. "already have a usable descriptor here. Not fetching.");
  628. return;
  629. }
  630. /* Are we configured to fetch descriptors? */
  631. if (!get_options()->FetchHidServDescriptors) {
  632. log_warn(LD_REND, "We received an onion address for a v2 rendezvous "
  633. "service descriptor, but are not fetching service descriptors.");
  634. return;
  635. }
  636. log_debug(LD_REND, "Fetching v2 rendezvous descriptor for service %s",
  637. safe_str_client(onion_address));
  638. rend_client_fetch_v2_desc(rend_query, NULL);
  639. /* We don't need to look the error code because either on failure or
  640. * success, the necessary steps to continue the HS connection will be
  641. * triggered once the descriptor arrives or if all fetch failed. */
  642. return;
  643. }
  644. /** Cancel all rendezvous descriptor fetches currently in progress.
  645. */
  646. void
  647. rend_client_cancel_descriptor_fetches(void)
  648. {
  649. smartlist_t *connection_array = get_connection_array();
  650. SMARTLIST_FOREACH_BEGIN(connection_array, connection_t *, conn) {
  651. if (conn->type == CONN_TYPE_DIR &&
  652. conn->purpose == DIR_PURPOSE_FETCH_RENDDESC_V2) {
  653. /* It's a rendezvous descriptor fetch in progress -- cancel it
  654. * by marking the connection for close.
  655. *
  656. * Even if this connection has already reached EOF, this is
  657. * enough to make sure that if the descriptor hasn't been
  658. * processed yet, it won't be. See the end of
  659. * connection_handle_read; connection_reached_eof (indirectly)
  660. * processes whatever response the connection received. */
  661. const rend_data_t *rd = (TO_DIR_CONN(conn))->rend_data;
  662. if (!rd) {
  663. log_warn(LD_BUG | LD_REND,
  664. "Marking for close dir conn fetching rendezvous "
  665. "descriptor for unknown service!");
  666. } else {
  667. log_debug(LD_REND, "Marking for close dir conn fetching "
  668. "rendezvous descriptor for service %s",
  669. safe_str(rend_data_get_address(rd)));
  670. }
  671. connection_mark_for_close(conn);
  672. }
  673. } SMARTLIST_FOREACH_END(conn);
  674. }
  675. /** Mark <b>failed_intro</b> as a failed introduction point for the
  676. * hidden service specified by <b>rend_query</b>. If the HS now has no
  677. * usable intro points, or we do not have an HS descriptor for it,
  678. * then launch a new renddesc fetch.
  679. *
  680. * If <b>failure_type</b> is INTRO_POINT_FAILURE_GENERIC, remove the
  681. * intro point from (our parsed copy of) the HS descriptor.
  682. *
  683. * If <b>failure_type</b> is INTRO_POINT_FAILURE_TIMEOUT, mark the
  684. * intro point as 'timed out'; it will not be retried until the
  685. * current hidden service connection attempt has ended or it has
  686. * appeared in a newly fetched rendezvous descriptor.
  687. *
  688. * If <b>failure_type</b> is INTRO_POINT_FAILURE_UNREACHABLE,
  689. * increment the intro point's reachability-failure count; if it has
  690. * now failed MAX_INTRO_POINT_REACHABILITY_FAILURES or more times,
  691. * remove the intro point from (our parsed copy of) the HS descriptor.
  692. *
  693. * Return -1 if error, 0 if no usable intro points remain or service
  694. * unrecognized, 1 if recognized and some intro points remain.
  695. */
  696. int
  697. rend_client_report_intro_point_failure(extend_info_t *failed_intro,
  698. rend_data_t *rend_data,
  699. unsigned int failure_type)
  700. {
  701. int i, r;
  702. rend_cache_entry_t *ent;
  703. connection_t *conn;
  704. const char *onion_address = rend_data_get_address(rend_data);
  705. r = rend_cache_lookup_entry(onion_address, -1, &ent);
  706. if (r < 0) {
  707. /* Either invalid onion address or cache entry not found. */
  708. switch (-r) {
  709. case EINVAL:
  710. log_warn(LD_BUG, "Malformed service ID %s.",
  711. escaped_safe_str_client(onion_address));
  712. return -1;
  713. case ENOENT:
  714. log_info(LD_REND, "Unknown service %s. Re-fetching descriptor.",
  715. escaped_safe_str_client(onion_address));
  716. rend_client_refetch_v2_renddesc(rend_data);
  717. return 0;
  718. default:
  719. log_warn(LD_BUG, "Unknown cache lookup returned code: %d", r);
  720. return -1;
  721. }
  722. }
  723. /* The intro points are not checked here if they are usable or not because
  724. * this is called when an intro point circuit is closed thus there must be
  725. * at least one intro point that is usable and is about to be flagged. */
  726. for (i = 0; i < smartlist_len(ent->parsed->intro_nodes); i++) {
  727. rend_intro_point_t *intro = smartlist_get(ent->parsed->intro_nodes, i);
  728. if (tor_memeq(failed_intro->identity_digest,
  729. intro->extend_info->identity_digest, DIGEST_LEN)) {
  730. switch (failure_type) {
  731. default:
  732. log_warn(LD_BUG, "Unknown failure type %u. Removing intro point.",
  733. failure_type);
  734. tor_fragile_assert();
  735. /* fall through */
  736. case INTRO_POINT_FAILURE_GENERIC:
  737. rend_cache_intro_failure_note(failure_type,
  738. (uint8_t *)failed_intro->identity_digest,
  739. onion_address);
  740. rend_intro_point_free(intro);
  741. smartlist_del(ent->parsed->intro_nodes, i);
  742. break;
  743. case INTRO_POINT_FAILURE_TIMEOUT:
  744. intro->timed_out = 1;
  745. break;
  746. case INTRO_POINT_FAILURE_UNREACHABLE:
  747. ++(intro->unreachable_count);
  748. {
  749. int zap_intro_point =
  750. intro->unreachable_count >= MAX_INTRO_POINT_REACHABILITY_FAILURES;
  751. log_info(LD_REND, "Failed to reach this intro point %u times.%s",
  752. intro->unreachable_count,
  753. zap_intro_point ? " Removing from descriptor.": "");
  754. if (zap_intro_point) {
  755. rend_cache_intro_failure_note(
  756. failure_type,
  757. (uint8_t *) failed_intro->identity_digest, onion_address);
  758. rend_intro_point_free(intro);
  759. smartlist_del(ent->parsed->intro_nodes, i);
  760. }
  761. }
  762. break;
  763. }
  764. break;
  765. }
  766. }
  767. if (! rend_client_any_intro_points_usable(ent)) {
  768. log_info(LD_REND,
  769. "No more intro points remain for %s. Re-fetching descriptor.",
  770. escaped_safe_str_client(onion_address));
  771. rend_client_refetch_v2_renddesc(rend_data);
  772. /* move all pending streams back to renddesc_wait */
  773. /* NOTE: We can now do this faster, if we use pending_entry_connections */
  774. while ((conn = connection_get_by_type_state_rendquery(CONN_TYPE_AP,
  775. AP_CONN_STATE_CIRCUIT_WAIT,
  776. onion_address))) {
  777. connection_ap_mark_as_non_pending_circuit(TO_ENTRY_CONN(conn));
  778. conn->state = AP_CONN_STATE_RENDDESC_WAIT;
  779. }
  780. return 0;
  781. }
  782. log_info(LD_REND,"%d options left for %s.",
  783. smartlist_len(ent->parsed->intro_nodes),
  784. escaped_safe_str_client(onion_address));
  785. return 1;
  786. }
  787. /** The service sent us a rendezvous cell; join the circuits. */
  788. int
  789. rend_client_receive_rendezvous(origin_circuit_t *circ, const uint8_t *request,
  790. size_t request_len)
  791. {
  792. if (request_len != DH_KEY_LEN+DIGEST_LEN) {
  793. log_warn(LD_PROTOCOL,"Incorrect length (%d) on RENDEZVOUS2 cell.",
  794. (int)request_len);
  795. goto err;
  796. }
  797. if (hs_circuit_setup_e2e_rend_circ_legacy_client(circ, request) < 0) {
  798. log_warn(LD_GENERAL, "Failed to setup circ");
  799. goto err;
  800. }
  801. return 0;
  802. err:
  803. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
  804. return -1;
  805. }
  806. /** Find all the apconns in state AP_CONN_STATE_RENDDESC_WAIT that are
  807. * waiting on <b>query</b>. If there's a working cache entry here with at
  808. * least one intro point, move them to the next state. */
  809. void
  810. rend_client_desc_trynow(const char *query)
  811. {
  812. entry_connection_t *conn;
  813. rend_cache_entry_t *entry;
  814. const rend_data_t *rend_data;
  815. time_t now = time(NULL);
  816. smartlist_t *conns = get_connection_array();
  817. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
  818. if (base_conn->type != CONN_TYPE_AP ||
  819. base_conn->state != AP_CONN_STATE_RENDDESC_WAIT ||
  820. base_conn->marked_for_close)
  821. continue;
  822. conn = TO_ENTRY_CONN(base_conn);
  823. rend_data = ENTRY_TO_EDGE_CONN(conn)->rend_data;
  824. if (!rend_data)
  825. continue;
  826. const char *onion_address = rend_data_get_address(rend_data);
  827. if (rend_cmp_service_ids(query, onion_address))
  828. continue;
  829. assert_connection_ok(base_conn, now);
  830. if (rend_cache_lookup_entry(onion_address, -1,
  831. &entry) == 0 &&
  832. rend_client_any_intro_points_usable(entry)) {
  833. /* either this fetch worked, or it failed but there was a
  834. * valid entry from before which we should reuse */
  835. log_info(LD_REND,"Rend desc is usable. Launching circuits.");
  836. base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  837. /* restart their timeout values, so they get a fair shake at
  838. * connecting to the hidden service. */
  839. base_conn->timestamp_created = now;
  840. base_conn->timestamp_last_read_allowed = now;
  841. base_conn->timestamp_last_write_allowed = now;
  842. connection_ap_mark_as_pending_circuit(conn);
  843. } else { /* 404, or fetch didn't get that far */
  844. log_notice(LD_REND,"Closing stream for '%s.onion': hidden service is "
  845. "unavailable (try again later).",
  846. safe_str_client(query));
  847. connection_mark_unattached_ap(conn, END_STREAM_REASON_RESOLVEFAILED);
  848. rend_client_note_connection_attempt_ended(rend_data);
  849. }
  850. } SMARTLIST_FOREACH_END(base_conn);
  851. }
  852. /** Clear temporary state used only during an attempt to connect to the
  853. * hidden service with <b>rend_data</b>. Called when a connection attempt
  854. * has ended; it is possible for this to be called multiple times while
  855. * handling an ended connection attempt, and any future changes to this
  856. * function must ensure it remains idempotent. */
  857. void
  858. rend_client_note_connection_attempt_ended(const rend_data_t *rend_data)
  859. {
  860. unsigned int have_onion = 0;
  861. rend_cache_entry_t *cache_entry = NULL;
  862. const char *onion_address = rend_data_get_address(rend_data);
  863. rend_data_v2_t *rend_data_v2 = TO_REND_DATA_V2(rend_data);
  864. if (onion_address[0] != '\0') {
  865. /* Ignore return value; we find an entry, or we don't. */
  866. (void) rend_cache_lookup_entry(onion_address, -1, &cache_entry);
  867. have_onion = 1;
  868. }
  869. /* Clear the timed_out flag on all remaining intro points for this HS. */
  870. if (cache_entry != NULL) {
  871. SMARTLIST_FOREACH(cache_entry->parsed->intro_nodes,
  872. rend_intro_point_t *, ip,
  873. ip->timed_out = 0; );
  874. }
  875. /* Remove the HS's entries in last_hid_serv_requests. */
  876. if (have_onion) {
  877. unsigned int replica;
  878. for (replica = 0; replica < ARRAY_LENGTH(rend_data_v2->descriptor_id);
  879. replica++) {
  880. const char *desc_id = rend_data_v2->descriptor_id[replica];
  881. purge_v2_hidserv_req(desc_id);
  882. }
  883. log_info(LD_REND, "Connection attempt for %s has ended; "
  884. "cleaning up temporary state.",
  885. safe_str_client(onion_address));
  886. } else {
  887. /* We only have an ID for a fetch. Probably used by HSFETCH. */
  888. purge_v2_hidserv_req(rend_data_v2->desc_id_fetch);
  889. }
  890. }
  891. /** Return a newly allocated extend_info_t* for a randomly chosen introduction
  892. * point for the named hidden service. Return NULL if all introduction points
  893. * have been tried and failed.
  894. */
  895. extend_info_t *
  896. rend_client_get_random_intro(const rend_data_t *rend_query)
  897. {
  898. int ret;
  899. extend_info_t *result;
  900. rend_cache_entry_t *entry;
  901. const char *onion_address = rend_data_get_address(rend_query);
  902. ret = rend_cache_lookup_entry(onion_address, -1, &entry);
  903. if (ret < 0 || !rend_client_any_intro_points_usable(entry)) {
  904. log_warn(LD_REND,
  905. "Query '%s' didn't have valid rend desc in cache. Failing.",
  906. safe_str_client(onion_address));
  907. /* XXX: Should we refetch the descriptor here if the IPs are not usable
  908. * anymore ?. */
  909. return NULL;
  910. }
  911. /* See if we can get a node that complies with ExcludeNodes */
  912. if ((result = rend_client_get_random_intro_impl(entry, 1, 1)))
  913. return result;
  914. /* If not, and StrictNodes is not set, see if we can return any old node
  915. */
  916. if (!get_options()->StrictNodes)
  917. return rend_client_get_random_intro_impl(entry, 0, 1);
  918. return NULL;
  919. }
  920. /** As rend_client_get_random_intro, except assume that StrictNodes is set
  921. * iff <b>strict</b> is true. If <b>warnings</b> is false, don't complain
  922. * to the user when we're out of nodes, even if StrictNodes is true.
  923. */
  924. static extend_info_t *
  925. rend_client_get_random_intro_impl(const rend_cache_entry_t *entry,
  926. const int strict,
  927. const int warnings)
  928. {
  929. int i;
  930. rend_intro_point_t *intro;
  931. const or_options_t *options = get_options();
  932. smartlist_t *usable_nodes;
  933. int n_excluded = 0;
  934. /* We'll keep a separate list of the usable nodes. If this becomes empty,
  935. * no nodes are usable. */
  936. usable_nodes = smartlist_new();
  937. smartlist_add_all(usable_nodes, entry->parsed->intro_nodes);
  938. /* Remove the intro points that have timed out during this HS
  939. * connection attempt from our list of usable nodes. */
  940. SMARTLIST_FOREACH(usable_nodes, rend_intro_point_t *, ip,
  941. if (ip->timed_out) {
  942. SMARTLIST_DEL_CURRENT(usable_nodes, ip);
  943. });
  944. again:
  945. if (smartlist_len(usable_nodes) == 0) {
  946. if (n_excluded && get_options()->StrictNodes && warnings) {
  947. /* We only want to warn if StrictNodes is really set. Otherwise
  948. * we're just about to retry anyways.
  949. */
  950. log_warn(LD_REND, "All introduction points for hidden service are "
  951. "at excluded relays, and StrictNodes is set. Skipping.");
  952. }
  953. smartlist_free(usable_nodes);
  954. return NULL;
  955. }
  956. i = crypto_rand_int(smartlist_len(usable_nodes));
  957. intro = smartlist_get(usable_nodes, i);
  958. if (BUG(!intro->extend_info)) {
  959. /* This should never happen, but it isn't fatal, just try another */
  960. smartlist_del(usable_nodes, i);
  961. goto again;
  962. }
  963. /* All version 2 HS descriptors come with a TAP onion key.
  964. * Clients used to try to get the TAP onion key from the consensus, but this
  965. * meant that hidden services could discover which consensus clients have. */
  966. if (!extend_info_supports_tap(intro->extend_info)) {
  967. log_info(LD_REND, "The HS descriptor is missing a TAP onion key for the "
  968. "intro-point relay '%s'; trying another.",
  969. safe_str_client(extend_info_describe(intro->extend_info)));
  970. smartlist_del(usable_nodes, i);
  971. goto again;
  972. }
  973. /* Check if we should refuse to talk to this router. */
  974. if (strict &&
  975. routerset_contains_extendinfo(options->ExcludeNodes,
  976. intro->extend_info)) {
  977. n_excluded++;
  978. smartlist_del(usable_nodes, i);
  979. goto again;
  980. }
  981. smartlist_free(usable_nodes);
  982. return extend_info_dup(intro->extend_info);
  983. }
  984. /** Return true iff any introduction points still listed in <b>entry</b> are
  985. * usable. */
  986. int
  987. rend_client_any_intro_points_usable(const rend_cache_entry_t *entry)
  988. {
  989. extend_info_t *extend_info =
  990. rend_client_get_random_intro_impl(entry, get_options()->StrictNodes, 0);
  991. int rv = (extend_info != NULL);
  992. extend_info_free(extend_info);
  993. return rv;
  994. }
  995. /** Client-side authorizations for hidden services; map of onion address to
  996. * rend_service_authorization_t*. */
  997. static strmap_t *auth_hid_servs = NULL;
  998. /** Look up the client-side authorization for the hidden service with
  999. * <b>onion_address</b>. Return NULL if no authorization is available for
  1000. * that address. */
  1001. rend_service_authorization_t*
  1002. rend_client_lookup_service_authorization(const char *onion_address)
  1003. {
  1004. tor_assert(onion_address);
  1005. if (!auth_hid_servs) return NULL;
  1006. return strmap_get(auth_hid_servs, onion_address);
  1007. }
  1008. #define rend_service_authorization_free(val) \
  1009. FREE_AND_NULL(rend_service_authorization_t, \
  1010. rend_service_authorization_free_, (val))
  1011. /** Helper: Free storage held by rend_service_authorization_t. */
  1012. static void
  1013. rend_service_authorization_free_(rend_service_authorization_t *auth)
  1014. {
  1015. tor_free(auth);
  1016. }
  1017. /** Helper for strmap_free. */
  1018. static void
  1019. rend_service_authorization_free_void(void *service_auth)
  1020. {
  1021. rend_service_authorization_free_(service_auth);
  1022. }
  1023. /** Release all the storage held in auth_hid_servs.
  1024. */
  1025. void
  1026. rend_service_authorization_free_all(void)
  1027. {
  1028. if (!auth_hid_servs) {
  1029. return;
  1030. }
  1031. strmap_free(auth_hid_servs, rend_service_authorization_free_void);
  1032. auth_hid_servs = NULL;
  1033. }
  1034. /** Parse <b>config_line</b> as a client-side authorization for a hidden
  1035. * service and add it to the local map of hidden service authorizations.
  1036. * Return 0 for success and -1 for failure. */
  1037. int
  1038. rend_parse_service_authorization(const or_options_t *options,
  1039. int validate_only)
  1040. {
  1041. config_line_t *line;
  1042. int res = -1;
  1043. strmap_t *parsed = strmap_new();
  1044. smartlist_t *sl = smartlist_new();
  1045. rend_service_authorization_t *auth = NULL;
  1046. char *err_msg = NULL;
  1047. for (line = options->HidServAuth; line; line = line->next) {
  1048. char *onion_address, *descriptor_cookie;
  1049. auth = NULL;
  1050. SMARTLIST_FOREACH(sl, char *, c, tor_free(c););
  1051. smartlist_clear(sl);
  1052. smartlist_split_string(sl, line->value, " ",
  1053. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
  1054. if (smartlist_len(sl) < 2) {
  1055. log_warn(LD_CONFIG, "Configuration line does not consist of "
  1056. "\"onion-address authorization-cookie [service-name]\": "
  1057. "'%s'", line->value);
  1058. goto err;
  1059. }
  1060. auth = tor_malloc_zero(sizeof(rend_service_authorization_t));
  1061. /* Parse onion address. */
  1062. onion_address = smartlist_get(sl, 0);
  1063. if (strlen(onion_address) != REND_SERVICE_ADDRESS_LEN ||
  1064. strcmpend(onion_address, ".onion")) {
  1065. log_warn(LD_CONFIG, "Onion address has wrong format: '%s'",
  1066. onion_address);
  1067. goto err;
  1068. }
  1069. strlcpy(auth->onion_address, onion_address, REND_SERVICE_ID_LEN_BASE32+1);
  1070. if (!rend_valid_v2_service_id(auth->onion_address)) {
  1071. log_warn(LD_CONFIG, "Onion address has wrong format: '%s'",
  1072. onion_address);
  1073. goto err;
  1074. }
  1075. /* Parse descriptor cookie. */
  1076. descriptor_cookie = smartlist_get(sl, 1);
  1077. if (rend_auth_decode_cookie(descriptor_cookie, auth->descriptor_cookie,
  1078. &auth->auth_type, &err_msg) < 0) {
  1079. tor_assert(err_msg);
  1080. log_warn(LD_CONFIG, "%s", err_msg);
  1081. tor_free(err_msg);
  1082. goto err;
  1083. }
  1084. if (strmap_get(parsed, auth->onion_address)) {
  1085. log_warn(LD_CONFIG, "Duplicate authorization for the same hidden "
  1086. "service.");
  1087. goto err;
  1088. }
  1089. strmap_set(parsed, auth->onion_address, auth);
  1090. auth = NULL;
  1091. }
  1092. res = 0;
  1093. goto done;
  1094. err:
  1095. res = -1;
  1096. done:
  1097. rend_service_authorization_free(auth);
  1098. SMARTLIST_FOREACH(sl, char *, c, tor_free(c););
  1099. smartlist_free(sl);
  1100. if (!validate_only && res == 0) {
  1101. rend_service_authorization_free_all();
  1102. auth_hid_servs = parsed;
  1103. } else {
  1104. strmap_free(parsed, rend_service_authorization_free_void);
  1105. }
  1106. return res;
  1107. }
  1108. /* Can Tor client code make direct (non-anonymous) connections to introduction
  1109. * or rendezvous points?
  1110. * Returns true if tor was compiled with NON_ANONYMOUS_MODE_ENABLED, and is
  1111. * configured in Tor2web mode. */
  1112. int
  1113. rend_client_allow_non_anonymous_connection(const or_options_t *options)
  1114. {
  1115. /* Tor2web support needs to be compiled in to a tor binary. */
  1116. #ifdef NON_ANONYMOUS_MODE_ENABLED
  1117. /* Tor2web */
  1118. return options->Tor2webMode ? 1 : 0;
  1119. #else
  1120. (void)options;
  1121. return 0;
  1122. #endif /* defined(NON_ANONYMOUS_MODE_ENABLED) */
  1123. }
  1124. /* At compile-time, was non-anonymous mode enabled via
  1125. * NON_ANONYMOUS_MODE_ENABLED ? */
  1126. int
  1127. rend_client_non_anonymous_mode_enabled(const or_options_t *options)
  1128. {
  1129. (void)options;
  1130. /* Tor2web support needs to be compiled in to a tor binary. */
  1131. #ifdef NON_ANONYMOUS_MODE_ENABLED
  1132. /* Tor2web */
  1133. return 1;
  1134. #else
  1135. return 0;
  1136. #endif /* defined(NON_ANONYMOUS_MODE_ENABLED) */
  1137. }