rendclient.c 45 KB

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