rendclient.c 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286
  1. /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  2. * Copyright (c) 2007-2012, 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 "circuitbuild.h"
  10. #include "circuitlist.h"
  11. #include "circuituse.h"
  12. #include "config.h"
  13. #include "connection.h"
  14. #include "connection_edge.h"
  15. #include "directory.h"
  16. #include "main.h"
  17. #include "nodelist.h"
  18. #include "relay.h"
  19. #include "rendclient.h"
  20. #include "rendcommon.h"
  21. #include "rephist.h"
  22. #include "router.h"
  23. #include "routerlist.h"
  24. static extend_info_t *rend_client_get_random_intro_impl(
  25. const rend_cache_entry_t *rend_query,
  26. const int strict, const int warnings);
  27. /** Purge all potentially remotely-detectable state held in the hidden
  28. * service client code. Called on SIGNAL NEWNYM. */
  29. void
  30. rend_client_purge_state(void)
  31. {
  32. rend_cache_purge();
  33. rend_client_cancel_descriptor_fetches();
  34. rend_client_purge_last_hid_serv_requests();
  35. }
  36. /** Called when we've established a circuit to an introduction point:
  37. * send the introduction request. */
  38. void
  39. rend_client_introcirc_has_opened(origin_circuit_t *circ)
  40. {
  41. tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
  42. tor_assert(circ->cpath);
  43. log_info(LD_REND,"introcirc is open");
  44. connection_ap_attach_pending();
  45. }
  46. /** Send the establish-rendezvous cell along a rendezvous circuit. if
  47. * it fails, mark the circ for close and return -1. else return 0.
  48. */
  49. static int
  50. rend_client_send_establish_rendezvous(origin_circuit_t *circ)
  51. {
  52. tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND);
  53. tor_assert(circ->rend_data);
  54. log_info(LD_REND, "Sending an ESTABLISH_RENDEZVOUS cell");
  55. if (crypto_rand(circ->rend_data->rend_cookie, REND_COOKIE_LEN) < 0) {
  56. log_warn(LD_BUG, "Internal error: Couldn't produce random cookie.");
  57. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
  58. return -1;
  59. }
  60. if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
  61. RELAY_COMMAND_ESTABLISH_RENDEZVOUS,
  62. circ->rend_data->rend_cookie,
  63. REND_COOKIE_LEN,
  64. circ->cpath->prev)<0) {
  65. /* circ is already marked for close */
  66. log_warn(LD_GENERAL, "Couldn't send ESTABLISH_RENDEZVOUS cell");
  67. return -1;
  68. }
  69. return 0;
  70. }
  71. /** Extend the introduction circuit <b>circ</b> to another valid
  72. * introduction point for the hidden service it is trying to connect
  73. * to, or mark it and launch a new circuit if we can't extend it.
  74. * Return 0 on success or possible success. Return -1 and mark the
  75. * introduction circuit for close on permanent failure.
  76. *
  77. * On failure, the caller is responsible for marking the associated
  78. * rendezvous circuit for close. */
  79. static int
  80. rend_client_reextend_intro_circuit(origin_circuit_t *circ)
  81. {
  82. extend_info_t *extend_info;
  83. int result;
  84. extend_info = rend_client_get_random_intro(circ->rend_data);
  85. if (!extend_info) {
  86. log_warn(LD_REND,
  87. "No usable introduction points left for %s. Closing.",
  88. safe_str_client(circ->rend_data->onion_address));
  89. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
  90. return -1;
  91. }
  92. if (circ->remaining_relay_early_cells) {
  93. log_info(LD_REND,
  94. "Re-extending circ %d, this time to %s.",
  95. circ->_base.n_circ_id,
  96. safe_str_client(extend_info_describe(extend_info)));
  97. result = circuit_extend_to_new_exit(circ, extend_info);
  98. } else {
  99. log_info(LD_REND,
  100. "Closing intro circ %d (out of RELAY_EARLY cells).",
  101. circ->_base.n_circ_id);
  102. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
  103. /* connection_ap_handshake_attach_circuit will launch a new intro circ. */
  104. result = 0;
  105. }
  106. extend_info_free(extend_info);
  107. return result;
  108. }
  109. /** Called when we're trying to connect an ap conn; sends an INTRODUCE1 cell
  110. * down introcirc if possible.
  111. */
  112. int
  113. rend_client_send_introduction(origin_circuit_t *introcirc,
  114. origin_circuit_t *rendcirc)
  115. {
  116. size_t payload_len;
  117. int r, v3_shift = 0;
  118. char payload[RELAY_PAYLOAD_SIZE];
  119. char tmp[RELAY_PAYLOAD_SIZE];
  120. rend_cache_entry_t *entry;
  121. crypt_path_t *cpath;
  122. off_t dh_offset;
  123. crypto_pk_t *intro_key = NULL;
  124. int status = 0;
  125. tor_assert(introcirc->_base.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
  126. tor_assert(rendcirc->_base.purpose == CIRCUIT_PURPOSE_C_REND_READY);
  127. tor_assert(introcirc->rend_data);
  128. tor_assert(rendcirc->rend_data);
  129. tor_assert(!rend_cmp_service_ids(introcirc->rend_data->onion_address,
  130. rendcirc->rend_data->onion_address));
  131. #ifndef NON_ANONYMOUS_MODE_ENABLED
  132. tor_assert(!(introcirc->build_state->onehop_tunnel));
  133. tor_assert(!(rendcirc->build_state->onehop_tunnel));
  134. #endif
  135. if (rend_cache_lookup_entry(introcirc->rend_data->onion_address, -1,
  136. &entry) < 1) {
  137. log_info(LD_REND,
  138. "query %s didn't have valid rend desc in cache. "
  139. "Refetching descriptor.",
  140. safe_str_client(introcirc->rend_data->onion_address));
  141. rend_client_refetch_v2_renddesc(introcirc->rend_data);
  142. {
  143. connection_t *conn;
  144. while ((conn = connection_get_by_type_state_rendquery(CONN_TYPE_AP,
  145. AP_CONN_STATE_CIRCUIT_WAIT,
  146. introcirc->rend_data->onion_address))) {
  147. conn->state = AP_CONN_STATE_RENDDESC_WAIT;
  148. }
  149. }
  150. status = -1;
  151. goto cleanup;
  152. }
  153. /* first 20 bytes of payload are the hash of Bob's pk */
  154. intro_key = NULL;
  155. SMARTLIST_FOREACH(entry->parsed->intro_nodes, rend_intro_point_t *,
  156. intro, {
  157. if (tor_memeq(introcirc->build_state->chosen_exit->identity_digest,
  158. intro->extend_info->identity_digest, DIGEST_LEN)) {
  159. intro_key = intro->intro_key;
  160. break;
  161. }
  162. });
  163. if (!intro_key) {
  164. log_info(LD_REND, "Could not find intro key for %s at %s; we "
  165. "have a v2 rend desc with %d intro points. "
  166. "Trying a different intro point...",
  167. safe_str_client(introcirc->rend_data->onion_address),
  168. safe_str_client(extend_info_describe(
  169. introcirc->build_state->chosen_exit)),
  170. smartlist_len(entry->parsed->intro_nodes));
  171. if (rend_client_reextend_intro_circuit(introcirc)) {
  172. status = -2;
  173. goto perm_err;
  174. } else {
  175. status = -1;
  176. goto cleanup;
  177. }
  178. }
  179. if (crypto_pk_get_digest(intro_key, payload)<0) {
  180. log_warn(LD_BUG, "Internal error: couldn't hash public key.");
  181. status = -2;
  182. goto perm_err;
  183. }
  184. /* Initialize the pending_final_cpath and start the DH handshake. */
  185. cpath = rendcirc->build_state->pending_final_cpath;
  186. if (!cpath) {
  187. cpath = rendcirc->build_state->pending_final_cpath =
  188. tor_malloc_zero(sizeof(crypt_path_t));
  189. cpath->magic = CRYPT_PATH_MAGIC;
  190. if (!(cpath->dh_handshake_state = crypto_dh_new(DH_TYPE_REND))) {
  191. log_warn(LD_BUG, "Internal error: couldn't allocate DH.");
  192. status = -2;
  193. goto perm_err;
  194. }
  195. if (crypto_dh_generate_public(cpath->dh_handshake_state)<0) {
  196. log_warn(LD_BUG, "Internal error: couldn't generate g^x.");
  197. status = -2;
  198. goto perm_err;
  199. }
  200. }
  201. /* If version is 3, write (optional) auth data and timestamp. */
  202. if (entry->parsed->protocols & (1<<3)) {
  203. tmp[0] = 3; /* version 3 of the cell format */
  204. tmp[1] = (uint8_t)introcirc->rend_data->auth_type; /* auth type, if any */
  205. v3_shift = 1;
  206. if (introcirc->rend_data->auth_type != REND_NO_AUTH) {
  207. set_uint16(tmp+2, htons(REND_DESC_COOKIE_LEN));
  208. memcpy(tmp+4, introcirc->rend_data->descriptor_cookie,
  209. REND_DESC_COOKIE_LEN);
  210. v3_shift += 2+REND_DESC_COOKIE_LEN;
  211. }
  212. set_uint32(tmp+v3_shift+1, htonl((uint32_t)time(NULL)));
  213. v3_shift += 4;
  214. } /* if version 2 only write version number */
  215. else if (entry->parsed->protocols & (1<<2)) {
  216. tmp[0] = 2; /* version 2 of the cell format */
  217. }
  218. /* write the remaining items into tmp */
  219. if (entry->parsed->protocols & (1<<3) || entry->parsed->protocols & (1<<2)) {
  220. /* version 2 format */
  221. extend_info_t *extend_info = rendcirc->build_state->chosen_exit;
  222. int klen;
  223. /* nul pads */
  224. set_uint32(tmp+v3_shift+1, tor_addr_to_ipv4h(&extend_info->addr));
  225. set_uint16(tmp+v3_shift+5, htons(extend_info->port));
  226. memcpy(tmp+v3_shift+7, extend_info->identity_digest, DIGEST_LEN);
  227. klen = crypto_pk_asn1_encode(extend_info->onion_key,
  228. tmp+v3_shift+7+DIGEST_LEN+2,
  229. sizeof(tmp)-(v3_shift+7+DIGEST_LEN+2));
  230. set_uint16(tmp+v3_shift+7+DIGEST_LEN, htons(klen));
  231. memcpy(tmp+v3_shift+7+DIGEST_LEN+2+klen, rendcirc->rend_data->rend_cookie,
  232. REND_COOKIE_LEN);
  233. dh_offset = v3_shift+7+DIGEST_LEN+2+klen+REND_COOKIE_LEN;
  234. } else {
  235. /* Version 0. */
  236. strncpy(tmp, rendcirc->build_state->chosen_exit->nickname,
  237. (MAX_NICKNAME_LEN+1)); /* nul pads */
  238. memcpy(tmp+MAX_NICKNAME_LEN+1, rendcirc->rend_data->rend_cookie,
  239. REND_COOKIE_LEN);
  240. dh_offset = MAX_NICKNAME_LEN+1+REND_COOKIE_LEN;
  241. }
  242. if (crypto_dh_get_public(cpath->dh_handshake_state, tmp+dh_offset,
  243. DH_KEY_LEN)<0) {
  244. log_warn(LD_BUG, "Internal error: couldn't extract g^x.");
  245. status = -2;
  246. goto perm_err;
  247. }
  248. note_crypto_pk_op(REND_CLIENT);
  249. /*XXX maybe give crypto_pk_public_hybrid_encrypt a max_len arg,
  250. * to avoid buffer overflows? */
  251. r = crypto_pk_public_hybrid_encrypt(intro_key, payload+DIGEST_LEN,
  252. sizeof(payload)-DIGEST_LEN,
  253. tmp,
  254. (int)(dh_offset+DH_KEY_LEN),
  255. PK_PKCS1_OAEP_PADDING, 0);
  256. if (r<0) {
  257. log_warn(LD_BUG,"Internal error: hybrid pk encrypt failed.");
  258. status = -2;
  259. goto perm_err;
  260. }
  261. payload_len = DIGEST_LEN + r;
  262. tor_assert(payload_len <= RELAY_PAYLOAD_SIZE); /* we overran something */
  263. /* Copy the rendezvous cookie from rendcirc to introcirc, so that
  264. * when introcirc gets an ack, we can change the state of the right
  265. * rendezvous circuit. */
  266. memcpy(introcirc->rend_data->rend_cookie, rendcirc->rend_data->rend_cookie,
  267. REND_COOKIE_LEN);
  268. log_info(LD_REND, "Sending an INTRODUCE1 cell");
  269. if (relay_send_command_from_edge(0, TO_CIRCUIT(introcirc),
  270. RELAY_COMMAND_INTRODUCE1,
  271. payload, payload_len,
  272. introcirc->cpath->prev)<0) {
  273. /* introcirc is already marked for close. leave rendcirc alone. */
  274. log_warn(LD_BUG, "Couldn't send INTRODUCE1 cell");
  275. status = -2;
  276. goto cleanup;
  277. }
  278. /* Now, we wait for an ACK or NAK on this circuit. */
  279. circuit_change_purpose(TO_CIRCUIT(introcirc),
  280. CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT);
  281. /* Set timestamp_dirty, because circuit_expire_building expects it
  282. * to specify when a circuit entered the _C_INTRODUCE_ACK_WAIT
  283. * state. */
  284. introcirc->_base.timestamp_dirty = time(NULL);
  285. goto cleanup;
  286. perm_err:
  287. if (!introcirc->_base.marked_for_close)
  288. circuit_mark_for_close(TO_CIRCUIT(introcirc), END_CIRC_REASON_INTERNAL);
  289. circuit_mark_for_close(TO_CIRCUIT(rendcirc), END_CIRC_REASON_INTERNAL);
  290. cleanup:
  291. memset(payload, 0, sizeof(payload));
  292. memset(tmp, 0, sizeof(tmp));
  293. return status;
  294. }
  295. /** Called when a rendezvous circuit is open; sends a establish
  296. * rendezvous circuit as appropriate. */
  297. void
  298. rend_client_rendcirc_has_opened(origin_circuit_t *circ)
  299. {
  300. tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND);
  301. log_info(LD_REND,"rendcirc is open");
  302. /* generate a rendezvous cookie, store it in circ */
  303. if (rend_client_send_establish_rendezvous(circ) < 0) {
  304. return;
  305. }
  306. }
  307. /** Called when get an ACK or a NAK for a REND_INTRODUCE1 cell.
  308. */
  309. int
  310. rend_client_introduction_acked(origin_circuit_t *circ,
  311. const uint8_t *request, size_t request_len)
  312. {
  313. origin_circuit_t *rendcirc;
  314. (void) request; // XXXX Use this.
  315. if (circ->_base.purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
  316. log_warn(LD_PROTOCOL,
  317. "Received REND_INTRODUCE_ACK on unexpected circuit %d.",
  318. circ->_base.n_circ_id);
  319. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
  320. return -1;
  321. }
  322. tor_assert(circ->build_state->chosen_exit);
  323. #ifndef NON_ANONYMOUS_MODE_ENABLED
  324. tor_assert(!(circ->build_state->onehop_tunnel));
  325. #endif
  326. tor_assert(circ->rend_data);
  327. if (request_len == 0) {
  328. /* It's an ACK; the introduction point relayed our introduction request. */
  329. /* Locate the rend circ which is waiting to hear about this ack,
  330. * and tell it.
  331. */
  332. log_info(LD_REND,"Received ack. Telling rend circ...");
  333. rendcirc = circuit_get_ready_rend_circ_by_rend_data(circ->rend_data);
  334. if (rendcirc) { /* remember the ack */
  335. #ifndef NON_ANONYMOUS_MODE_ENABLED
  336. tor_assert(!(rendcirc->build_state->onehop_tunnel));
  337. #endif
  338. circuit_change_purpose(TO_CIRCUIT(rendcirc),
  339. CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED);
  340. /* Set timestamp_dirty, because circuit_expire_building expects
  341. * it to specify when a circuit entered the
  342. * _C_REND_READY_INTRO_ACKED state. */
  343. rendcirc->_base.timestamp_dirty = time(NULL);
  344. } else {
  345. log_info(LD_REND,"...Found no rend circ. Dropping on the floor.");
  346. }
  347. /* close the circuit: we won't need it anymore. */
  348. circuit_change_purpose(TO_CIRCUIT(circ),
  349. CIRCUIT_PURPOSE_C_INTRODUCE_ACKED);
  350. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
  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(circ->rend_data->onion_address),
  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 = rend_client_reextend_intro_circuit(circ);
  367. /* XXXX If that call failed, should we close the rend circuit,
  368. * too? */
  369. return result;
  370. }
  371. }
  372. return 0;
  373. }
  374. /** The period for which a hidden service directory cannot be queried for
  375. * the same descriptor ID again. */
  376. #define REND_HID_SERV_DIR_REQUERY_PERIOD (15 * 60)
  377. /** Contains the last request times to hidden service directories for
  378. * certain queries; each key is a string consisting of the
  379. * concatenation of a base32-encoded HS directory identity digest, a
  380. * base32-encoded HS descriptor ID, and a hidden service address
  381. * (without the ".onion" part); each value is a pointer to a time_t
  382. * holding the time of the last request for that descriptor ID to that
  383. * HS directory. */
  384. static strmap_t *last_hid_serv_requests_ = NULL;
  385. /** Returns last_hid_serv_requests_, initializing it to a new strmap if
  386. * necessary. */
  387. static strmap_t *
  388. get_last_hid_serv_requests(void)
  389. {
  390. if (!last_hid_serv_requests_)
  391. last_hid_serv_requests_ = strmap_new();
  392. return last_hid_serv_requests_;
  393. }
  394. #define LAST_HID_SERV_REQUEST_KEY_LEN (REND_DESC_ID_V2_LEN_BASE32 + \
  395. REND_DESC_ID_V2_LEN_BASE32 + \
  396. REND_SERVICE_ID_LEN_BASE32)
  397. /** Look up the last request time to hidden service directory <b>hs_dir</b>
  398. * for descriptor ID <b>desc_id_base32</b> for the service specified in
  399. * <b>rend_query</b>. If <b>set</b> is non-zero,
  400. * assign the current time <b>now</b> and return that. Otherwise, return
  401. * the most recent request time, or 0 if no such request has been sent
  402. * before. */
  403. static time_t
  404. lookup_last_hid_serv_request(routerstatus_t *hs_dir,
  405. const char *desc_id_base32,
  406. const rend_data_t *rend_query,
  407. time_t now, int set)
  408. {
  409. char hsdir_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  410. char hsdir_desc_comb_id[LAST_HID_SERV_REQUEST_KEY_LEN + 1];
  411. time_t *last_request_ptr;
  412. strmap_t *last_hid_serv_requests = get_last_hid_serv_requests();
  413. base32_encode(hsdir_id_base32, sizeof(hsdir_id_base32),
  414. hs_dir->identity_digest, DIGEST_LEN);
  415. tor_snprintf(hsdir_desc_comb_id, sizeof(hsdir_desc_comb_id), "%s%s%s",
  416. hsdir_id_base32,
  417. desc_id_base32,
  418. rend_query->onion_address);
  419. /* XXX023 tor_assert(strlen(hsdir_desc_comb_id) ==
  420. LAST_HID_SERV_REQUEST_KEY_LEN); */
  421. if (set) {
  422. time_t *oldptr;
  423. last_request_ptr = tor_malloc_zero(sizeof(time_t));
  424. *last_request_ptr = now;
  425. oldptr = strmap_set(last_hid_serv_requests, hsdir_desc_comb_id,
  426. last_request_ptr);
  427. tor_free(oldptr);
  428. } else
  429. last_request_ptr = strmap_get_lc(last_hid_serv_requests,
  430. hsdir_desc_comb_id);
  431. return (last_request_ptr) ? *last_request_ptr : 0;
  432. }
  433. /** Clean the history of request times to hidden service directories, so that
  434. * it does not contain requests older than REND_HID_SERV_DIR_REQUERY_PERIOD
  435. * seconds any more. */
  436. static void
  437. directory_clean_last_hid_serv_requests(time_t now)
  438. {
  439. strmap_iter_t *iter;
  440. time_t cutoff = now - REND_HID_SERV_DIR_REQUERY_PERIOD;
  441. strmap_t *last_hid_serv_requests = get_last_hid_serv_requests();
  442. for (iter = strmap_iter_init(last_hid_serv_requests);
  443. !strmap_iter_done(iter); ) {
  444. const char *key;
  445. void *val;
  446. time_t *ent;
  447. strmap_iter_get(iter, &key, &val);
  448. ent = (time_t *) val;
  449. if (*ent < cutoff) {
  450. iter = strmap_iter_next_rmv(last_hid_serv_requests, iter);
  451. tor_free(ent);
  452. } else {
  453. iter = strmap_iter_next(last_hid_serv_requests, iter);
  454. }
  455. }
  456. }
  457. /** Remove all requests related to the hidden service named
  458. * <b>onion_address</b> from the history of times of requests to
  459. * hidden service directories. */
  460. static void
  461. purge_hid_serv_from_last_hid_serv_requests(const char *onion_address)
  462. {
  463. strmap_iter_t *iter;
  464. strmap_t *last_hid_serv_requests = get_last_hid_serv_requests();
  465. /* XXX023 tor_assert(strlen(onion_address) == REND_SERVICE_ID_LEN_BASE32); */
  466. for (iter = strmap_iter_init(last_hid_serv_requests);
  467. !strmap_iter_done(iter); ) {
  468. const char *key;
  469. void *val;
  470. strmap_iter_get(iter, &key, &val);
  471. /* XXX023 tor_assert(strlen(key) == LAST_HID_SERV_REQUEST_KEY_LEN); */
  472. if (tor_memeq(key + LAST_HID_SERV_REQUEST_KEY_LEN -
  473. REND_SERVICE_ID_LEN_BASE32,
  474. onion_address,
  475. REND_SERVICE_ID_LEN_BASE32)) {
  476. iter = strmap_iter_next_rmv(last_hid_serv_requests, iter);
  477. tor_free(val);
  478. } else {
  479. iter = strmap_iter_next(last_hid_serv_requests, iter);
  480. }
  481. }
  482. }
  483. /** Purge the history of request times to hidden service directories,
  484. * so that future lookups of an HS descriptor will not fail because we
  485. * accessed all of the HSDir relays responsible for the descriptor
  486. * recently. */
  487. void
  488. rend_client_purge_last_hid_serv_requests(void)
  489. {
  490. /* Don't create the table if it doesn't exist yet (and it may very
  491. * well not exist if the user hasn't accessed any HSes)... */
  492. strmap_t *old_last_hid_serv_requests = last_hid_serv_requests_;
  493. /* ... and let get_last_hid_serv_requests re-create it for us if
  494. * necessary. */
  495. last_hid_serv_requests_ = NULL;
  496. if (old_last_hid_serv_requests != NULL) {
  497. log_info(LD_REND, "Purging client last-HS-desc-request-time table");
  498. strmap_free(old_last_hid_serv_requests, _tor_free);
  499. }
  500. }
  501. /** Determine the responsible hidden service directories for <b>desc_id</b>
  502. * and fetch the descriptor with that ID from one of them. Only
  503. * send a request to a hidden service directory that we have not yet tried
  504. * during this attempt to connect to this hidden service; on success, return 1,
  505. * in the case that no hidden service directory is left to ask for the
  506. * descriptor, return 0, and in case of a failure -1. */
  507. static int
  508. directory_get_from_hs_dir(const char *desc_id, const rend_data_t *rend_query)
  509. {
  510. smartlist_t *responsible_dirs = smartlist_new();
  511. routerstatus_t *hs_dir;
  512. char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  513. time_t now = time(NULL);
  514. char descriptor_cookie_base64[3*REND_DESC_COOKIE_LEN_BASE64];
  515. int tor2web_mode = get_options()->Tor2webMode;
  516. tor_assert(desc_id);
  517. tor_assert(rend_query);
  518. /* Determine responsible dirs. Even if we can't get all we want,
  519. * work with the ones we have. If it's empty, we'll notice below. */
  520. hid_serv_get_responsible_directories(responsible_dirs, desc_id);
  521. base32_encode(desc_id_base32, sizeof(desc_id_base32),
  522. desc_id, DIGEST_LEN);
  523. /* Only select those hidden service directories to which we did not send
  524. * a request recently and for which we have a router descriptor here. */
  525. /* Clean request history first. */
  526. directory_clean_last_hid_serv_requests(now);
  527. SMARTLIST_FOREACH(responsible_dirs, routerstatus_t *, dir, {
  528. time_t last = lookup_last_hid_serv_request(
  529. dir, desc_id_base32, rend_query, 0, 0);
  530. const node_t *node = node_get_by_id(dir->identity_digest);
  531. if (last + REND_HID_SERV_DIR_REQUERY_PERIOD >= now ||
  532. !node || !node_has_descriptor(node))
  533. SMARTLIST_DEL_CURRENT(responsible_dirs, dir);
  534. });
  535. hs_dir = smartlist_choose(responsible_dirs);
  536. smartlist_free(responsible_dirs);
  537. if (!hs_dir) {
  538. log_info(LD_REND, "Could not pick one of the responsible hidden "
  539. "service directories, because we requested them all "
  540. "recently without success.");
  541. return 0;
  542. }
  543. /* Remember that we are requesting a descriptor from this hidden service
  544. * directory now. */
  545. lookup_last_hid_serv_request(hs_dir, desc_id_base32, rend_query, now, 1);
  546. /* Encode descriptor cookie for logging purposes. */
  547. if (rend_query->auth_type != REND_NO_AUTH) {
  548. if (base64_encode(descriptor_cookie_base64,
  549. sizeof(descriptor_cookie_base64),
  550. rend_query->descriptor_cookie, REND_DESC_COOKIE_LEN)<0) {
  551. log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
  552. return 0;
  553. }
  554. /* Remove == signs and newline. */
  555. descriptor_cookie_base64[strlen(descriptor_cookie_base64)-3] = '\0';
  556. } else {
  557. strlcpy(descriptor_cookie_base64, "(none)",
  558. sizeof(descriptor_cookie_base64));
  559. }
  560. /* Send fetch request. (Pass query and possibly descriptor cookie so that
  561. * they can be written to the directory connection and be referred to when
  562. * the response arrives. */
  563. directory_initiate_command_routerstatus_rend(hs_dir,
  564. DIR_PURPOSE_FETCH_RENDDESC_V2,
  565. ROUTER_PURPOSE_GENERAL,
  566. !tor2web_mode, desc_id_base32,
  567. NULL, 0, 0,
  568. rend_query);
  569. log_info(LD_REND, "Sending fetch request for v2 descriptor for "
  570. "service '%s' with descriptor ID '%s', auth type %d, "
  571. "and descriptor cookie '%s' to hidden service "
  572. "directory %s",
  573. rend_query->onion_address, desc_id_base32,
  574. rend_query->auth_type,
  575. (rend_query->auth_type == REND_NO_AUTH ? "[none]" :
  576. escaped_safe_str_client(descriptor_cookie_base64)),
  577. routerstatus_describe(hs_dir));
  578. return 1;
  579. }
  580. /** Unless we already have a descriptor for <b>rend_query</b> with at least
  581. * one (possibly) working introduction point in it, start a connection to a
  582. * hidden service directory to fetch a v2 rendezvous service descriptor. */
  583. void
  584. rend_client_refetch_v2_renddesc(const rend_data_t *rend_query)
  585. {
  586. char descriptor_id[DIGEST_LEN];
  587. int replicas_left_to_try[REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS];
  588. int i, tries_left;
  589. rend_cache_entry_t *e = NULL;
  590. tor_assert(rend_query);
  591. /* Are we configured to fetch descriptors? */
  592. if (!get_options()->FetchHidServDescriptors) {
  593. log_warn(LD_REND, "We received an onion address for a v2 rendezvous "
  594. "service descriptor, but are not fetching service descriptors.");
  595. return;
  596. }
  597. /* Before fetching, check if we already have a usable descriptor here. */
  598. if (rend_cache_lookup_entry(rend_query->onion_address, -1, &e) > 0 &&
  599. rend_client_any_intro_points_usable(e)) {
  600. log_info(LD_REND, "We would fetch a v2 rendezvous descriptor, but we "
  601. "already have a usable descriptor here. Not fetching.");
  602. return;
  603. }
  604. log_debug(LD_REND, "Fetching v2 rendezvous descriptor for service %s",
  605. safe_str_client(rend_query->onion_address));
  606. /* Randomly iterate over the replicas until a descriptor can be fetched
  607. * from one of the consecutive nodes, or no options are left. */
  608. tries_left = REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS;
  609. for (i = 0; i < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS; i++)
  610. replicas_left_to_try[i] = i;
  611. while (tries_left > 0) {
  612. int rand = crypto_rand_int(tries_left);
  613. int chosen_replica = replicas_left_to_try[rand];
  614. replicas_left_to_try[rand] = replicas_left_to_try[--tries_left];
  615. if (rend_compute_v2_desc_id(descriptor_id, rend_query->onion_address,
  616. rend_query->auth_type == REND_STEALTH_AUTH ?
  617. rend_query->descriptor_cookie : NULL,
  618. time(NULL), chosen_replica) < 0) {
  619. log_warn(LD_REND, "Internal error: Computing v2 rendezvous "
  620. "descriptor ID did not succeed.");
  621. /*
  622. * Hmm, can this write anything to descriptor_id and still fail?
  623. * Let's clear it just to be safe.
  624. *
  625. * From here on, any returns should goto done which clears
  626. * descriptor_id so we don't leave key-derived material on the stack.
  627. */
  628. goto done;
  629. }
  630. if (directory_get_from_hs_dir(descriptor_id, rend_query) != 0)
  631. goto done; /* either success or failure, but we're done */
  632. }
  633. /* If we come here, there are no hidden service directories left. */
  634. log_info(LD_REND, "Could not pick one of the responsible hidden "
  635. "service directories to fetch descriptors, because "
  636. "we already tried them all unsuccessfully.");
  637. /* Close pending connections. */
  638. rend_client_desc_trynow(rend_query->onion_address);
  639. done:
  640. memset(descriptor_id, 0, sizeof(descriptor_id));
  641. return;
  642. }
  643. /** Cancel all rendezvous descriptor fetches currently in progress.
  644. */
  645. void
  646. rend_client_cancel_descriptor_fetches(void)
  647. {
  648. smartlist_t *connection_array = get_connection_array();
  649. SMARTLIST_FOREACH_BEGIN(connection_array, connection_t *, conn) {
  650. if (conn->type == CONN_TYPE_DIR &&
  651. (conn->purpose == DIR_PURPOSE_FETCH_RENDDESC ||
  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(rd->onion_address));
  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. const rend_data_t *rend_query,
  699. unsigned int failure_type)
  700. {
  701. int i, r;
  702. rend_cache_entry_t *ent;
  703. connection_t *conn;
  704. r = rend_cache_lookup_entry(rend_query->onion_address, -1, &ent);
  705. if (r<0) {
  706. log_warn(LD_BUG, "Malformed service ID %s.",
  707. escaped_safe_str_client(rend_query->onion_address));
  708. return -1;
  709. }
  710. if (r==0) {
  711. log_info(LD_REND, "Unknown service %s. Re-fetching descriptor.",
  712. escaped_safe_str_client(rend_query->onion_address));
  713. rend_client_refetch_v2_renddesc(rend_query);
  714. return 0;
  715. }
  716. for (i = 0; i < smartlist_len(ent->parsed->intro_nodes); i++) {
  717. rend_intro_point_t *intro = smartlist_get(ent->parsed->intro_nodes, i);
  718. if (tor_memeq(failed_intro->identity_digest,
  719. intro->extend_info->identity_digest, DIGEST_LEN)) {
  720. switch (failure_type) {
  721. default:
  722. log_warn(LD_BUG, "Unknown failure type %u. Removing intro point.",
  723. failure_type);
  724. tor_fragile_assert();
  725. /* fall through */
  726. case INTRO_POINT_FAILURE_GENERIC:
  727. rend_intro_point_free(intro);
  728. smartlist_del(ent->parsed->intro_nodes, i);
  729. break;
  730. case INTRO_POINT_FAILURE_TIMEOUT:
  731. intro->timed_out = 1;
  732. break;
  733. case INTRO_POINT_FAILURE_UNREACHABLE:
  734. ++(intro->unreachable_count);
  735. {
  736. int zap_intro_point =
  737. intro->unreachable_count >= MAX_INTRO_POINT_REACHABILITY_FAILURES;
  738. log_info(LD_REND, "Failed to reach this intro point %u times.%s",
  739. intro->unreachable_count,
  740. zap_intro_point ? " Removing from descriptor.": "");
  741. if (zap_intro_point) {
  742. rend_intro_point_free(intro);
  743. smartlist_del(ent->parsed->intro_nodes, i);
  744. }
  745. }
  746. break;
  747. }
  748. break;
  749. }
  750. }
  751. if (! rend_client_any_intro_points_usable(ent)) {
  752. log_info(LD_REND,
  753. "No more intro points remain for %s. Re-fetching descriptor.",
  754. escaped_safe_str_client(rend_query->onion_address));
  755. rend_client_refetch_v2_renddesc(rend_query);
  756. /* move all pending streams back to renddesc_wait */
  757. while ((conn = connection_get_by_type_state_rendquery(CONN_TYPE_AP,
  758. AP_CONN_STATE_CIRCUIT_WAIT,
  759. rend_query->onion_address))) {
  760. conn->state = AP_CONN_STATE_RENDDESC_WAIT;
  761. }
  762. return 0;
  763. }
  764. log_info(LD_REND,"%d options left for %s.",
  765. smartlist_len(ent->parsed->intro_nodes),
  766. escaped_safe_str_client(rend_query->onion_address));
  767. return 1;
  768. }
  769. /** Called when we receive a RENDEZVOUS_ESTABLISHED cell; changes the state of
  770. * the circuit to C_REND_READY.
  771. */
  772. int
  773. rend_client_rendezvous_acked(origin_circuit_t *circ, const uint8_t *request,
  774. size_t request_len)
  775. {
  776. (void) request;
  777. (void) request_len;
  778. /* we just got an ack for our establish-rendezvous. switch purposes. */
  779. if (circ->_base.purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND) {
  780. log_warn(LD_PROTOCOL,"Got a rendezvous ack when we weren't expecting one. "
  781. "Closing circ.");
  782. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
  783. return -1;
  784. }
  785. log_info(LD_REND,"Got rendezvous ack. This circuit is now ready for "
  786. "rendezvous.");
  787. circuit_change_purpose(TO_CIRCUIT(circ), CIRCUIT_PURPOSE_C_REND_READY);
  788. /* Set timestamp_dirty, because circuit_expire_building expects it
  789. * to specify when a circuit entered the _C_REND_READY state. */
  790. circ->_base.timestamp_dirty = time(NULL);
  791. /* XXXX This is a pretty brute-force approach. It'd be better to
  792. * attach only the connections that are waiting on this circuit, rather
  793. * than trying to attach them all. See comments bug 743. */
  794. /* If we already have the introduction circuit built, make sure we send
  795. * the INTRODUCE cell _now_ */
  796. connection_ap_attach_pending();
  797. return 0;
  798. }
  799. /** Bob sent us a rendezvous cell; join the circuits. */
  800. int
  801. rend_client_receive_rendezvous(origin_circuit_t *circ, const uint8_t *request,
  802. size_t request_len)
  803. {
  804. crypt_path_t *hop;
  805. char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN];
  806. if ((circ->_base.purpose != CIRCUIT_PURPOSE_C_REND_READY &&
  807. circ->_base.purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)
  808. || !circ->build_state->pending_final_cpath) {
  809. log_warn(LD_PROTOCOL,"Got rendezvous2 cell from hidden service, but not "
  810. "expecting it. Closing.");
  811. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
  812. return -1;
  813. }
  814. if (request_len != DH_KEY_LEN+DIGEST_LEN) {
  815. log_warn(LD_PROTOCOL,"Incorrect length (%d) on RENDEZVOUS2 cell.",
  816. (int)request_len);
  817. goto err;
  818. }
  819. log_info(LD_REND,"Got RENDEZVOUS2 cell from hidden service.");
  820. /* first DH_KEY_LEN bytes are g^y from bob. Finish the dh handshake...*/
  821. tor_assert(circ->build_state);
  822. tor_assert(circ->build_state->pending_final_cpath);
  823. hop = circ->build_state->pending_final_cpath;
  824. tor_assert(hop->dh_handshake_state);
  825. if (crypto_dh_compute_secret(LOG_PROTOCOL_WARN,
  826. hop->dh_handshake_state, (char*)request,
  827. DH_KEY_LEN,
  828. keys, DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
  829. log_warn(LD_GENERAL, "Couldn't complete DH handshake.");
  830. goto err;
  831. }
  832. /* ... and set up cpath. */
  833. if (circuit_init_cpath_crypto(hop, keys+DIGEST_LEN, 0)<0)
  834. goto err;
  835. /* Check whether the digest is right... */
  836. if (tor_memneq(keys, request+DH_KEY_LEN, DIGEST_LEN)) {
  837. log_warn(LD_PROTOCOL, "Incorrect digest of key material.");
  838. goto err;
  839. }
  840. crypto_dh_free(hop->dh_handshake_state);
  841. hop->dh_handshake_state = NULL;
  842. /* All is well. Extend the circuit. */
  843. circuit_change_purpose(TO_CIRCUIT(circ), CIRCUIT_PURPOSE_C_REND_JOINED);
  844. hop->state = CPATH_STATE_OPEN;
  845. /* set the windows to default. these are the windows
  846. * that alice thinks bob has.
  847. */
  848. hop->package_window = circuit_initial_package_window();
  849. hop->deliver_window = CIRCWINDOW_START;
  850. /* Now that this circuit has finished connecting to its destination,
  851. * make sure circuit_get_open_circ_or_launch is willing to return it
  852. * so we can actually use it. */
  853. circ->hs_circ_has_timed_out = 0;
  854. onion_append_to_cpath(&circ->cpath, hop);
  855. circ->build_state->pending_final_cpath = NULL; /* prevent double-free */
  856. circuit_try_attaching_streams(circ);
  857. memset(keys, 0, sizeof(keys));
  858. return 0;
  859. err:
  860. memset(keys, 0, sizeof(keys));
  861. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
  862. return -1;
  863. }
  864. /** Find all the apconns in state AP_CONN_STATE_RENDDESC_WAIT that are
  865. * waiting on <b>query</b>. If there's a working cache entry here with at
  866. * least one intro point, move them to the next state. */
  867. void
  868. rend_client_desc_trynow(const char *query)
  869. {
  870. entry_connection_t *conn;
  871. rend_cache_entry_t *entry;
  872. const rend_data_t *rend_data;
  873. time_t now = time(NULL);
  874. smartlist_t *conns = get_connection_array();
  875. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, base_conn) {
  876. if (base_conn->type != CONN_TYPE_AP ||
  877. base_conn->state != AP_CONN_STATE_RENDDESC_WAIT ||
  878. base_conn->marked_for_close)
  879. continue;
  880. conn = TO_ENTRY_CONN(base_conn);
  881. rend_data = ENTRY_TO_EDGE_CONN(conn)->rend_data;
  882. if (!rend_data)
  883. continue;
  884. if (rend_cmp_service_ids(query, rend_data->onion_address))
  885. continue;
  886. assert_connection_ok(base_conn, now);
  887. if (rend_cache_lookup_entry(rend_data->onion_address, -1,
  888. &entry) == 1 &&
  889. rend_client_any_intro_points_usable(entry)) {
  890. /* either this fetch worked, or it failed but there was a
  891. * valid entry from before which we should reuse */
  892. log_info(LD_REND,"Rend desc is usable. Launching circuits.");
  893. base_conn->state = AP_CONN_STATE_CIRCUIT_WAIT;
  894. /* restart their timeout values, so they get a fair shake at
  895. * connecting to the hidden service. */
  896. base_conn->timestamp_created = now;
  897. base_conn->timestamp_lastread = now;
  898. base_conn->timestamp_lastwritten = now;
  899. if (connection_ap_handshake_attach_circuit(conn) < 0) {
  900. /* it will never work */
  901. log_warn(LD_REND,"Rendezvous attempt failed. Closing.");
  902. if (!base_conn->marked_for_close)
  903. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  904. }
  905. } else { /* 404, or fetch didn't get that far */
  906. log_notice(LD_REND,"Closing stream for '%s.onion': hidden service is "
  907. "unavailable (try again later).",
  908. safe_str_client(query));
  909. connection_mark_unattached_ap(conn, END_STREAM_REASON_RESOLVEFAILED);
  910. rend_client_note_connection_attempt_ended(query);
  911. }
  912. } SMARTLIST_FOREACH_END(base_conn);
  913. }
  914. /** Clear temporary state used only during an attempt to connect to
  915. * the hidden service named <b>onion_address</b>. Called when a
  916. * connection attempt has ended; may be called occasionally at other
  917. * times, and should be reasonably harmless. */
  918. void
  919. rend_client_note_connection_attempt_ended(const char *onion_address)
  920. {
  921. rend_cache_entry_t *cache_entry = NULL;
  922. rend_cache_lookup_entry(onion_address, -1, &cache_entry);
  923. log_info(LD_REND, "Connection attempt for %s has ended; "
  924. "cleaning up temporary state.",
  925. safe_str_client(onion_address));
  926. /* Clear the timed_out flag on all remaining intro points for this HS. */
  927. if (cache_entry != NULL) {
  928. SMARTLIST_FOREACH(cache_entry->parsed->intro_nodes,
  929. rend_intro_point_t *, ip,
  930. ip->timed_out = 0; );
  931. }
  932. /* Remove the HS's entries in last_hid_serv_requests. */
  933. purge_hid_serv_from_last_hid_serv_requests(onion_address);
  934. }
  935. /** Return a newly allocated extend_info_t* for a randomly chosen introduction
  936. * point for the named hidden service. Return NULL if all introduction points
  937. * have been tried and failed.
  938. */
  939. extend_info_t *
  940. rend_client_get_random_intro(const rend_data_t *rend_query)
  941. {
  942. extend_info_t *result;
  943. rend_cache_entry_t *entry;
  944. if (rend_cache_lookup_entry(rend_query->onion_address, -1, &entry) < 1) {
  945. log_warn(LD_REND,
  946. "Query '%s' didn't have valid rend desc in cache. Failing.",
  947. safe_str_client(rend_query->onion_address));
  948. return NULL;
  949. }
  950. /* See if we can get a node that complies with ExcludeNodes */
  951. if ((result = rend_client_get_random_intro_impl(entry, 1, 1)))
  952. return result;
  953. /* If not, and StrictNodes is not set, see if we can return any old node
  954. */
  955. if (!get_options()->StrictNodes)
  956. return rend_client_get_random_intro_impl(entry, 0, 1);
  957. return NULL;
  958. }
  959. /** As rend_client_get_random_intro, except assume that StrictNodes is set
  960. * iff <b>strict</b> is true. If <b>warnings</b> is false, don't complain
  961. * to the user when we're out of nodes, even if StrictNodes is true.
  962. */
  963. static extend_info_t *
  964. rend_client_get_random_intro_impl(const rend_cache_entry_t *entry,
  965. const int strict,
  966. const int warnings)
  967. {
  968. int i;
  969. rend_intro_point_t *intro;
  970. const or_options_t *options = get_options();
  971. smartlist_t *usable_nodes;
  972. int n_excluded = 0;
  973. /* We'll keep a separate list of the usable nodes. If this becomes empty,
  974. * no nodes are usable. */
  975. usable_nodes = smartlist_new();
  976. smartlist_add_all(usable_nodes, entry->parsed->intro_nodes);
  977. /* Remove the intro points that have timed out during this HS
  978. * connection attempt from our list of usable nodes. */
  979. SMARTLIST_FOREACH(usable_nodes, rend_intro_point_t *, ip,
  980. if (ip->timed_out) {
  981. SMARTLIST_DEL_CURRENT(usable_nodes, ip);
  982. });
  983. again:
  984. if (smartlist_len(usable_nodes) == 0) {
  985. if (n_excluded && get_options()->StrictNodes && warnings) {
  986. /* We only want to warn if StrictNodes is really set. Otherwise
  987. * we're just about to retry anyways.
  988. */
  989. log_warn(LD_REND, "All introduction points for hidden service are "
  990. "at excluded relays, and StrictNodes is set. Skipping.");
  991. }
  992. smartlist_free(usable_nodes);
  993. return NULL;
  994. }
  995. i = crypto_rand_int(smartlist_len(usable_nodes));
  996. intro = smartlist_get(usable_nodes, i);
  997. /* Do we need to look up the router or is the extend info complete? */
  998. if (!intro->extend_info->onion_key) {
  999. const node_t *node;
  1000. extend_info_t *new_extend_info;
  1001. if (tor_digest_is_zero(intro->extend_info->identity_digest))
  1002. node = node_get_by_hex_id(intro->extend_info->nickname);
  1003. else
  1004. node = node_get_by_id(intro->extend_info->identity_digest);
  1005. if (!node) {
  1006. log_info(LD_REND, "Unknown router with nickname '%s'; trying another.",
  1007. intro->extend_info->nickname);
  1008. smartlist_del(usable_nodes, i);
  1009. goto again;
  1010. }
  1011. new_extend_info = extend_info_from_node(node, 0);
  1012. if (!new_extend_info) {
  1013. log_info(LD_REND, "We don't have a descriptor for the intro-point relay "
  1014. "'%s'; trying another.",
  1015. extend_info_describe(intro->extend_info));
  1016. smartlist_del(usable_nodes, i);
  1017. goto again;
  1018. } else {
  1019. extend_info_free(intro->extend_info);
  1020. intro->extend_info = new_extend_info;
  1021. }
  1022. tor_assert(intro->extend_info != NULL);
  1023. }
  1024. /* Check if we should refuse to talk to this router. */
  1025. if (strict &&
  1026. routerset_contains_extendinfo(options->ExcludeNodes,
  1027. intro->extend_info)) {
  1028. n_excluded++;
  1029. smartlist_del(usable_nodes, i);
  1030. goto again;
  1031. }
  1032. smartlist_free(usable_nodes);
  1033. return extend_info_dup(intro->extend_info);
  1034. }
  1035. /** Return true iff any introduction points still listed in <b>entry</b> are
  1036. * usable. */
  1037. int
  1038. rend_client_any_intro_points_usable(const rend_cache_entry_t *entry)
  1039. {
  1040. extend_info_t *extend_info =
  1041. rend_client_get_random_intro_impl(entry, get_options()->StrictNodes, 0);
  1042. int rv = (extend_info != NULL);
  1043. extend_info_free(extend_info);
  1044. return rv;
  1045. }
  1046. /** Client-side authorizations for hidden services; map of onion address to
  1047. * rend_service_authorization_t*. */
  1048. static strmap_t *auth_hid_servs = NULL;
  1049. /** Look up the client-side authorization for the hidden service with
  1050. * <b>onion_address</b>. Return NULL if no authorization is available for
  1051. * that address. */
  1052. rend_service_authorization_t*
  1053. rend_client_lookup_service_authorization(const char *onion_address)
  1054. {
  1055. tor_assert(onion_address);
  1056. if (!auth_hid_servs) return NULL;
  1057. return strmap_get(auth_hid_servs, onion_address);
  1058. }
  1059. /** Helper: Free storage held by rend_service_authorization_t. */
  1060. static void
  1061. rend_service_authorization_free(rend_service_authorization_t *auth)
  1062. {
  1063. tor_free(auth);
  1064. }
  1065. /** Helper for strmap_free. */
  1066. static void
  1067. rend_service_authorization_strmap_item_free(void *service_auth)
  1068. {
  1069. rend_service_authorization_free(service_auth);
  1070. }
  1071. /** Release all the storage held in auth_hid_servs.
  1072. */
  1073. void
  1074. rend_service_authorization_free_all(void)
  1075. {
  1076. if (!auth_hid_servs) {
  1077. return;
  1078. }
  1079. strmap_free(auth_hid_servs, rend_service_authorization_strmap_item_free);
  1080. auth_hid_servs = NULL;
  1081. }
  1082. /** Parse <b>config_line</b> as a client-side authorization for a hidden
  1083. * service and add it to the local map of hidden service authorizations.
  1084. * Return 0 for success and -1 for failure. */
  1085. int
  1086. rend_parse_service_authorization(const or_options_t *options,
  1087. int validate_only)
  1088. {
  1089. config_line_t *line;
  1090. int res = -1;
  1091. strmap_t *parsed = strmap_new();
  1092. smartlist_t *sl = smartlist_new();
  1093. rend_service_authorization_t *auth = NULL;
  1094. char descriptor_cookie_tmp[REND_DESC_COOKIE_LEN+2];
  1095. char descriptor_cookie_base64ext[REND_DESC_COOKIE_LEN_BASE64+2+1];
  1096. for (line = options->HidServAuth; line; line = line->next) {
  1097. char *onion_address, *descriptor_cookie;
  1098. int auth_type_val = 0;
  1099. auth = NULL;
  1100. SMARTLIST_FOREACH(sl, char *, c, tor_free(c););
  1101. smartlist_clear(sl);
  1102. smartlist_split_string(sl, line->value, " ",
  1103. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
  1104. if (smartlist_len(sl) < 2) {
  1105. log_warn(LD_CONFIG, "Configuration line does not consist of "
  1106. "\"onion-address authorization-cookie [service-name]\": "
  1107. "'%s'", line->value);
  1108. goto err;
  1109. }
  1110. auth = tor_malloc_zero(sizeof(rend_service_authorization_t));
  1111. /* Parse onion address. */
  1112. onion_address = smartlist_get(sl, 0);
  1113. if (strlen(onion_address) != REND_SERVICE_ADDRESS_LEN ||
  1114. strcmpend(onion_address, ".onion")) {
  1115. log_warn(LD_CONFIG, "Onion address has wrong format: '%s'",
  1116. onion_address);
  1117. goto err;
  1118. }
  1119. strlcpy(auth->onion_address, onion_address, REND_SERVICE_ID_LEN_BASE32+1);
  1120. if (!rend_valid_service_id(auth->onion_address)) {
  1121. log_warn(LD_CONFIG, "Onion address has wrong format: '%s'",
  1122. onion_address);
  1123. goto err;
  1124. }
  1125. /* Parse descriptor cookie. */
  1126. descriptor_cookie = smartlist_get(sl, 1);
  1127. if (strlen(descriptor_cookie) != REND_DESC_COOKIE_LEN_BASE64) {
  1128. log_warn(LD_CONFIG, "Authorization cookie has wrong length: '%s'",
  1129. descriptor_cookie);
  1130. goto err;
  1131. }
  1132. /* Add trailing zero bytes (AA) to make base64-decoding happy. */
  1133. tor_snprintf(descriptor_cookie_base64ext,
  1134. REND_DESC_COOKIE_LEN_BASE64+2+1,
  1135. "%sAA", descriptor_cookie);
  1136. if (base64_decode(descriptor_cookie_tmp, sizeof(descriptor_cookie_tmp),
  1137. descriptor_cookie_base64ext,
  1138. strlen(descriptor_cookie_base64ext)) < 0) {
  1139. log_warn(LD_CONFIG, "Decoding authorization cookie failed: '%s'",
  1140. descriptor_cookie);
  1141. goto err;
  1142. }
  1143. auth_type_val = (descriptor_cookie_tmp[16] >> 4) + 1;
  1144. if (auth_type_val < 1 || auth_type_val > 2) {
  1145. log_warn(LD_CONFIG, "Authorization cookie has unknown authorization "
  1146. "type encoded.");
  1147. goto err;
  1148. }
  1149. auth->auth_type = auth_type_val == 1 ? REND_BASIC_AUTH : REND_STEALTH_AUTH;
  1150. memcpy(auth->descriptor_cookie, descriptor_cookie_tmp,
  1151. REND_DESC_COOKIE_LEN);
  1152. if (strmap_get(parsed, auth->onion_address)) {
  1153. log_warn(LD_CONFIG, "Duplicate authorization for the same hidden "
  1154. "service.");
  1155. goto err;
  1156. }
  1157. strmap_set(parsed, auth->onion_address, auth);
  1158. auth = NULL;
  1159. }
  1160. res = 0;
  1161. goto done;
  1162. err:
  1163. res = -1;
  1164. done:
  1165. rend_service_authorization_free(auth);
  1166. SMARTLIST_FOREACH(sl, char *, c, tor_free(c););
  1167. smartlist_free(sl);
  1168. if (!validate_only && res == 0) {
  1169. rend_service_authorization_free_all();
  1170. auth_hid_servs = parsed;
  1171. } else {
  1172. strmap_free(parsed, rend_service_authorization_strmap_item_free);
  1173. }
  1174. memset(descriptor_cookie_tmp, 0, sizeof(descriptor_cookie_tmp));
  1175. memset(descriptor_cookie_base64ext, 0, sizeof(descriptor_cookie_base64ext));
  1176. return res;
  1177. }