rendclient.c 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022
  1. /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  2. * Copyright (c) 2007-2011, 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 "relay.h"
  18. #include "rendclient.h"
  19. #include "rendcommon.h"
  20. #include "rephist.h"
  21. #include "routerlist.h"
  22. static extend_info_t *rend_client_get_random_intro_impl(
  23. const rend_cache_entry_t *rend_query,
  24. const int strict, const int warnings);
  25. /** Called when we've established a circuit to an introduction point:
  26. * send the introduction request. */
  27. void
  28. rend_client_introcirc_has_opened(origin_circuit_t *circ)
  29. {
  30. tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
  31. tor_assert(circ->cpath);
  32. log_info(LD_REND,"introcirc is open");
  33. connection_ap_attach_pending();
  34. }
  35. /** Send the establish-rendezvous cell along a rendezvous circuit. if
  36. * it fails, mark the circ for close and return -1. else return 0.
  37. */
  38. static int
  39. rend_client_send_establish_rendezvous(origin_circuit_t *circ)
  40. {
  41. tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND);
  42. tor_assert(circ->rend_data);
  43. log_info(LD_REND, "Sending an ESTABLISH_RENDEZVOUS cell");
  44. if (crypto_rand(circ->rend_data->rend_cookie, REND_COOKIE_LEN) < 0) {
  45. log_warn(LD_BUG, "Internal error: Couldn't produce random cookie.");
  46. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
  47. return -1;
  48. }
  49. if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
  50. RELAY_COMMAND_ESTABLISH_RENDEZVOUS,
  51. circ->rend_data->rend_cookie,
  52. REND_COOKIE_LEN,
  53. circ->cpath->prev)<0) {
  54. /* circ is already marked for close */
  55. log_warn(LD_GENERAL, "Couldn't send ESTABLISH_RENDEZVOUS cell");
  56. return -1;
  57. }
  58. return 0;
  59. }
  60. /** Called when we're trying to connect an ap conn; sends an INTRODUCE1 cell
  61. * down introcirc if possible.
  62. */
  63. int
  64. rend_client_send_introduction(origin_circuit_t *introcirc,
  65. origin_circuit_t *rendcirc)
  66. {
  67. size_t payload_len;
  68. int r, v3_shift = 0;
  69. char payload[RELAY_PAYLOAD_SIZE];
  70. char tmp[RELAY_PAYLOAD_SIZE];
  71. rend_cache_entry_t *entry;
  72. crypt_path_t *cpath;
  73. off_t dh_offset;
  74. crypto_pk_env_t *intro_key = NULL;
  75. tor_assert(introcirc->_base.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
  76. tor_assert(rendcirc->_base.purpose == CIRCUIT_PURPOSE_C_REND_READY);
  77. tor_assert(introcirc->rend_data);
  78. tor_assert(rendcirc->rend_data);
  79. tor_assert(!rend_cmp_service_ids(introcirc->rend_data->onion_address,
  80. rendcirc->rend_data->onion_address));
  81. if (rend_cache_lookup_entry(introcirc->rend_data->onion_address, -1,
  82. &entry) < 1) {
  83. log_info(LD_REND,
  84. "query %s didn't have valid rend desc in cache. "
  85. "Refetching descriptor.",
  86. safe_str(introcirc->rend_data->onion_address));
  87. rend_client_refetch_v2_renddesc(introcirc->rend_data);
  88. {
  89. connection_t *conn;
  90. while ((conn = connection_get_by_type_state_rendquery(CONN_TYPE_AP,
  91. AP_CONN_STATE_CIRCUIT_WAIT,
  92. introcirc->rend_data->onion_address))) {
  93. conn->state = AP_CONN_STATE_RENDDESC_WAIT;
  94. }
  95. }
  96. return -1;
  97. }
  98. /* first 20 bytes of payload are the hash of Bob's pk */
  99. intro_key = NULL;
  100. SMARTLIST_FOREACH(entry->parsed->intro_nodes, rend_intro_point_t *,
  101. intro, {
  102. if (!memcmp(introcirc->build_state->chosen_exit->identity_digest,
  103. intro->extend_info->identity_digest, DIGEST_LEN)) {
  104. intro_key = intro->intro_key;
  105. break;
  106. }
  107. });
  108. if (!intro_key) {
  109. log_info(LD_REND, "Internal error: could not find intro key; we "
  110. "only have a v2 rend desc with %d intro points.",
  111. smartlist_len(entry->parsed->intro_nodes));
  112. goto perm_err;
  113. }
  114. if (crypto_pk_get_digest(intro_key, payload)<0) {
  115. log_warn(LD_BUG, "Internal error: couldn't hash public key.");
  116. goto perm_err;
  117. }
  118. /* Initialize the pending_final_cpath and start the DH handshake. */
  119. cpath = rendcirc->build_state->pending_final_cpath;
  120. if (!cpath) {
  121. cpath = rendcirc->build_state->pending_final_cpath =
  122. tor_malloc_zero(sizeof(crypt_path_t));
  123. cpath->magic = CRYPT_PATH_MAGIC;
  124. if (!(cpath->dh_handshake_state = crypto_dh_new(DH_TYPE_REND))) {
  125. log_warn(LD_BUG, "Internal error: couldn't allocate DH.");
  126. goto perm_err;
  127. }
  128. if (crypto_dh_generate_public(cpath->dh_handshake_state)<0) {
  129. log_warn(LD_BUG, "Internal error: couldn't generate g^x.");
  130. goto perm_err;
  131. }
  132. }
  133. /* If version is 3, write (optional) auth data and timestamp. */
  134. if (entry->parsed->protocols & (1<<3)) {
  135. tmp[0] = 3; /* version 3 of the cell format */
  136. tmp[1] = (uint8_t)introcirc->rend_data->auth_type; /* auth type, if any */
  137. v3_shift = 1;
  138. if (introcirc->rend_data->auth_type != REND_NO_AUTH) {
  139. set_uint16(tmp+2, htons(REND_DESC_COOKIE_LEN));
  140. memcpy(tmp+4, introcirc->rend_data->descriptor_cookie,
  141. REND_DESC_COOKIE_LEN);
  142. v3_shift += 2+REND_DESC_COOKIE_LEN;
  143. }
  144. set_uint32(tmp+v3_shift+1, htonl((uint32_t)time(NULL)));
  145. v3_shift += 4;
  146. } /* if version 2 only write version number */
  147. else if (entry->parsed->protocols & (1<<2)) {
  148. tmp[0] = 2; /* version 2 of the cell format */
  149. }
  150. /* write the remaining items into tmp */
  151. if (entry->parsed->protocols & (1<<3) || entry->parsed->protocols & (1<<2)) {
  152. /* version 2 format */
  153. extend_info_t *extend_info = rendcirc->build_state->chosen_exit;
  154. int klen;
  155. /* nul pads */
  156. set_uint32(tmp+v3_shift+1, tor_addr_to_ipv4h(&extend_info->addr));
  157. set_uint16(tmp+v3_shift+5, htons(extend_info->port));
  158. memcpy(tmp+v3_shift+7, extend_info->identity_digest, DIGEST_LEN);
  159. klen = crypto_pk_asn1_encode(extend_info->onion_key,
  160. tmp+v3_shift+7+DIGEST_LEN+2,
  161. sizeof(tmp)-(v3_shift+7+DIGEST_LEN+2));
  162. set_uint16(tmp+v3_shift+7+DIGEST_LEN, htons(klen));
  163. memcpy(tmp+v3_shift+7+DIGEST_LEN+2+klen, rendcirc->rend_data->rend_cookie,
  164. REND_COOKIE_LEN);
  165. dh_offset = v3_shift+7+DIGEST_LEN+2+klen+REND_COOKIE_LEN;
  166. } else {
  167. /* Version 0. */
  168. strncpy(tmp, rendcirc->build_state->chosen_exit->nickname,
  169. (MAX_NICKNAME_LEN+1)); /* nul pads */
  170. memcpy(tmp+MAX_NICKNAME_LEN+1, rendcirc->rend_data->rend_cookie,
  171. REND_COOKIE_LEN);
  172. dh_offset = MAX_NICKNAME_LEN+1+REND_COOKIE_LEN;
  173. }
  174. if (crypto_dh_get_public(cpath->dh_handshake_state, tmp+dh_offset,
  175. DH_KEY_LEN)<0) {
  176. log_warn(LD_BUG, "Internal error: couldn't extract g^x.");
  177. goto perm_err;
  178. }
  179. note_crypto_pk_op(REND_CLIENT);
  180. /*XXX maybe give crypto_pk_public_hybrid_encrypt a max_len arg,
  181. * to avoid buffer overflows? */
  182. r = crypto_pk_public_hybrid_encrypt(intro_key, payload+DIGEST_LEN,
  183. sizeof(payload)-DIGEST_LEN,
  184. tmp,
  185. (int)(dh_offset+DH_KEY_LEN),
  186. PK_PKCS1_OAEP_PADDING, 0);
  187. if (r<0) {
  188. log_warn(LD_BUG,"Internal error: hybrid pk encrypt failed.");
  189. goto perm_err;
  190. }
  191. payload_len = DIGEST_LEN + r;
  192. tor_assert(payload_len <= RELAY_PAYLOAD_SIZE); /* we overran something */
  193. log_info(LD_REND, "Sending an INTRODUCE1 cell");
  194. if (relay_send_command_from_edge(0, TO_CIRCUIT(introcirc),
  195. RELAY_COMMAND_INTRODUCE1,
  196. payload, payload_len,
  197. introcirc->cpath->prev)<0) {
  198. /* introcirc is already marked for close. leave rendcirc alone. */
  199. log_warn(LD_BUG, "Couldn't send INTRODUCE1 cell");
  200. return -2;
  201. }
  202. /* Now, we wait for an ACK or NAK on this circuit. */
  203. introcirc->_base.purpose = CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT;
  204. return 0;
  205. perm_err:
  206. circuit_mark_for_close(TO_CIRCUIT(introcirc), END_CIRC_REASON_INTERNAL);
  207. circuit_mark_for_close(TO_CIRCUIT(rendcirc), END_CIRC_REASON_INTERNAL);
  208. return -2;
  209. }
  210. /** Called when a rendezvous circuit is open; sends a establish
  211. * rendezvous circuit as appropriate. */
  212. void
  213. rend_client_rendcirc_has_opened(origin_circuit_t *circ)
  214. {
  215. tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND);
  216. log_info(LD_REND,"rendcirc is open");
  217. /* generate a rendezvous cookie, store it in circ */
  218. if (rend_client_send_establish_rendezvous(circ) < 0) {
  219. return;
  220. }
  221. }
  222. /** Called when get an ACK or a NAK for a REND_INTRODUCE1 cell.
  223. */
  224. int
  225. rend_client_introduction_acked(origin_circuit_t *circ,
  226. const uint8_t *request, size_t request_len)
  227. {
  228. origin_circuit_t *rendcirc;
  229. (void) request; // XXXX Use this.
  230. if (circ->_base.purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
  231. log_warn(LD_PROTOCOL,
  232. "Received REND_INTRODUCE_ACK on unexpected circuit %d.",
  233. circ->_base.n_circ_id);
  234. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
  235. return -1;
  236. }
  237. tor_assert(circ->build_state->chosen_exit);
  238. tor_assert(circ->rend_data);
  239. if (request_len == 0) {
  240. /* It's an ACK; the introduction point relayed our introduction request. */
  241. /* Locate the rend circ which is waiting to hear about this ack,
  242. * and tell it.
  243. */
  244. log_info(LD_REND,"Received ack. Telling rend circ...");
  245. rendcirc = circuit_get_by_rend_query_and_purpose(
  246. circ->rend_data->onion_address, CIRCUIT_PURPOSE_C_REND_READY);
  247. if (rendcirc) { /* remember the ack */
  248. rendcirc->_base.purpose = CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED;
  249. } else {
  250. log_info(LD_REND,"...Found no rend circ. Dropping on the floor.");
  251. }
  252. /* close the circuit: we won't need it anymore. */
  253. circ->_base.purpose = CIRCUIT_PURPOSE_C_INTRODUCE_ACKED;
  254. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
  255. } else {
  256. /* It's a NAK; the introduction point didn't relay our request. */
  257. circ->_base.purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
  258. /* Remove this intro point from the set of viable introduction
  259. * points. If any remain, extend to a new one and try again.
  260. * If none remain, refetch the service descriptor.
  261. */
  262. if (rend_client_remove_intro_point(circ->build_state->chosen_exit,
  263. circ->rend_data) > 0) {
  264. /* There are introduction points left. Re-extend the circuit to
  265. * another intro point and try again. */
  266. extend_info_t *extend_info;
  267. int result;
  268. extend_info = rend_client_get_random_intro(circ->rend_data);
  269. if (!extend_info) {
  270. log_warn(LD_REND, "No introduction points left for %s. Closing.",
  271. escaped_safe_str_client(circ->rend_data->onion_address));
  272. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
  273. return -1;
  274. }
  275. if (circ->remaining_relay_early_cells) {
  276. log_info(LD_REND,
  277. "Got nack for %s from %s. Re-extending circ %d, "
  278. "this time to %s.",
  279. escaped_safe_str_client(circ->rend_data->onion_address),
  280. circ->build_state->chosen_exit->nickname,
  281. circ->_base.n_circ_id, extend_info->nickname);
  282. result = circuit_extend_to_new_exit(circ, extend_info);
  283. } else {
  284. log_info(LD_REND,
  285. "Got nack for %s from %s. Building a new introduction "
  286. "circuit, this time to %s.",
  287. escaped_safe_str_client(circ->rend_data->onion_address),
  288. circ->build_state->chosen_exit->nickname,
  289. extend_info->nickname);
  290. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
  291. if (!circuit_launch_by_extend_info(CIRCUIT_PURPOSE_C_INTRODUCING,
  292. extend_info,
  293. CIRCLAUNCH_IS_INTERNAL)) {
  294. log_warn(LD_REND, "Building introduction circuit failed.");
  295. result = -1;
  296. } else {
  297. result = 0;
  298. }
  299. }
  300. extend_info_free(extend_info);
  301. return result;
  302. }
  303. }
  304. return 0;
  305. }
  306. /** The period for which a hidden service directory cannot be queried for
  307. * the same descriptor ID again. */
  308. #define REND_HID_SERV_DIR_REQUERY_PERIOD (15 * 60)
  309. /** Contains the last request times to hidden service directories for
  310. * certain queries; keys are strings consisting of base32-encoded
  311. * hidden service directory identities and base32-encoded descriptor IDs;
  312. * values are pointers to timestamps of the last requests. */
  313. static strmap_t *last_hid_serv_requests = NULL;
  314. /** Look up the last request time to hidden service directory <b>hs_dir</b>
  315. * for descriptor ID <b>desc_id_base32</b>. If <b>set</b> is non-zero,
  316. * assign the current time <b>now</b> and return that. Otherwise, return
  317. * the most recent request time, or 0 if no such request has been sent
  318. * before. */
  319. static time_t
  320. lookup_last_hid_serv_request(routerstatus_t *hs_dir,
  321. const char *desc_id_base32, time_t now, int set)
  322. {
  323. char hsdir_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  324. char hsdir_desc_comb_id[2 * REND_DESC_ID_V2_LEN_BASE32 + 1];
  325. time_t *last_request_ptr;
  326. base32_encode(hsdir_id_base32, sizeof(hsdir_id_base32),
  327. hs_dir->identity_digest, DIGEST_LEN);
  328. tor_snprintf(hsdir_desc_comb_id, sizeof(hsdir_desc_comb_id), "%s%s",
  329. hsdir_id_base32, desc_id_base32);
  330. if (set) {
  331. time_t *oldptr;
  332. last_request_ptr = tor_malloc_zero(sizeof(time_t));
  333. *last_request_ptr = now;
  334. oldptr = strmap_set(last_hid_serv_requests, hsdir_desc_comb_id,
  335. last_request_ptr);
  336. tor_free(oldptr);
  337. } else
  338. last_request_ptr = strmap_get_lc(last_hid_serv_requests,
  339. hsdir_desc_comb_id);
  340. return (last_request_ptr) ? *last_request_ptr : 0;
  341. }
  342. /** Clean the history of request times to hidden service directories, so that
  343. * it does not contain requests older than REND_HID_SERV_DIR_REQUERY_PERIOD
  344. * seconds any more. */
  345. static void
  346. directory_clean_last_hid_serv_requests(void)
  347. {
  348. strmap_iter_t *iter;
  349. time_t cutoff = time(NULL) - REND_HID_SERV_DIR_REQUERY_PERIOD;
  350. if (!last_hid_serv_requests)
  351. last_hid_serv_requests = strmap_new();
  352. for (iter = strmap_iter_init(last_hid_serv_requests);
  353. !strmap_iter_done(iter); ) {
  354. const char *key;
  355. void *val;
  356. time_t *ent;
  357. strmap_iter_get(iter, &key, &val);
  358. ent = (time_t *) val;
  359. if (*ent < cutoff) {
  360. iter = strmap_iter_next_rmv(last_hid_serv_requests, iter);
  361. tor_free(ent);
  362. } else {
  363. iter = strmap_iter_next(last_hid_serv_requests, iter);
  364. }
  365. }
  366. }
  367. /** Determine the responsible hidden service directories for <b>desc_id</b>
  368. * and fetch the descriptor belonging to that ID from one of them. Only
  369. * send a request to hidden service directories that we did not try within
  370. * the last REND_HID_SERV_DIR_REQUERY_PERIOD seconds; on success, return 1,
  371. * in the case that no hidden service directory is left to ask for the
  372. * descriptor, return 0, and in case of a failure -1. <b>query</b> is only
  373. * passed for pretty log statements. */
  374. static int
  375. directory_get_from_hs_dir(const char *desc_id, const rend_data_t *rend_query)
  376. {
  377. smartlist_t *responsible_dirs = smartlist_create();
  378. routerstatus_t *hs_dir;
  379. char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  380. time_t now = time(NULL);
  381. char descriptor_cookie_base64[3*REND_DESC_COOKIE_LEN_BASE64];
  382. tor_assert(desc_id);
  383. tor_assert(rend_query);
  384. /* Determine responsible dirs. Even if we can't get all we want,
  385. * work with the ones we have. If it's empty, we'll notice below. */
  386. hid_serv_get_responsible_directories(responsible_dirs, desc_id);
  387. base32_encode(desc_id_base32, sizeof(desc_id_base32),
  388. desc_id, DIGEST_LEN);
  389. /* Only select those hidden service directories to which we did not send
  390. * a request recently and for which we have a router descriptor here. */
  391. directory_clean_last_hid_serv_requests(); /* Clean request history first. */
  392. SMARTLIST_FOREACH(responsible_dirs, routerstatus_t *, dir, {
  393. if (lookup_last_hid_serv_request(dir, desc_id_base32, 0, 0) +
  394. REND_HID_SERV_DIR_REQUERY_PERIOD >= now ||
  395. !router_get_by_digest(dir->identity_digest))
  396. SMARTLIST_DEL_CURRENT(responsible_dirs, dir);
  397. });
  398. hs_dir = smartlist_choose(responsible_dirs);
  399. smartlist_free(responsible_dirs);
  400. if (!hs_dir) {
  401. log_info(LD_REND, "Could not pick one of the responsible hidden "
  402. "service directories, because we requested them all "
  403. "recently without success.");
  404. return 0;
  405. }
  406. /* Remember, that we are requesting a descriptor from this hidden service
  407. * directory now. */
  408. lookup_last_hid_serv_request(hs_dir, desc_id_base32, now, 1);
  409. /* Encode descriptor cookie for logging purposes. */
  410. if (rend_query->auth_type != REND_NO_AUTH) {
  411. if (base64_encode(descriptor_cookie_base64,
  412. sizeof(descriptor_cookie_base64),
  413. rend_query->descriptor_cookie, REND_DESC_COOKIE_LEN)<0) {
  414. log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
  415. return 0;
  416. }
  417. /* Remove == signs and newline. */
  418. descriptor_cookie_base64[strlen(descriptor_cookie_base64)-3] = '\0';
  419. } else {
  420. strlcpy(descriptor_cookie_base64, "(none)",
  421. sizeof(descriptor_cookie_base64));
  422. }
  423. /* Send fetch request. (Pass query and possibly descriptor cookie so that
  424. * they can be written to the directory connection and be referred to when
  425. * the response arrives. */
  426. directory_initiate_command_routerstatus_rend(hs_dir,
  427. DIR_PURPOSE_FETCH_RENDDESC_V2,
  428. ROUTER_PURPOSE_GENERAL,
  429. 1, desc_id_base32, NULL, 0, 0,
  430. rend_query);
  431. log_info(LD_REND, "Sending fetch request for v2 descriptor for "
  432. "service '%s' with descriptor ID '%s', auth type %d, "
  433. "and descriptor cookie '%s' to hidden service "
  434. "directory '%s' on port %d.",
  435. rend_query->onion_address, desc_id_base32,
  436. rend_query->auth_type,
  437. (rend_query->auth_type == REND_NO_AUTH ? "[none]" :
  438. escaped_safe_str_client(descriptor_cookie_base64)),
  439. hs_dir->nickname, hs_dir->dir_port);
  440. return 1;
  441. }
  442. /** Unless we already have a descriptor for <b>rend_query</b> with at least
  443. * one (possibly) working introduction point in it, start a connection to a
  444. * hidden service directory to fetch a v2 rendezvous service descriptor. */
  445. void
  446. rend_client_refetch_v2_renddesc(const rend_data_t *rend_query)
  447. {
  448. char descriptor_id[DIGEST_LEN];
  449. int replicas_left_to_try[REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS];
  450. int i, tries_left;
  451. rend_cache_entry_t *e = NULL;
  452. tor_assert(rend_query);
  453. /* Are we configured to fetch descriptors? */
  454. if (!get_options()->FetchHidServDescriptors) {
  455. log_warn(LD_REND, "We received an onion address for a v2 rendezvous "
  456. "service descriptor, but are not fetching service descriptors.");
  457. return;
  458. }
  459. /* Before fetching, check if we already have the descriptor here. */
  460. if (rend_cache_lookup_entry(rend_query->onion_address, -1, &e) > 0) {
  461. log_info(LD_REND, "We would fetch a v2 rendezvous descriptor, but we "
  462. "already have that descriptor here. Not fetching.");
  463. return;
  464. }
  465. log_debug(LD_REND, "Fetching v2 rendezvous descriptor for service %s",
  466. safe_str_client(rend_query->onion_address));
  467. /* Randomly iterate over the replicas until a descriptor can be fetched
  468. * from one of the consecutive nodes, or no options are left. */
  469. tries_left = REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS;
  470. for (i = 0; i < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS; i++)
  471. replicas_left_to_try[i] = i;
  472. while (tries_left > 0) {
  473. int rand = crypto_rand_int(tries_left);
  474. int chosen_replica = replicas_left_to_try[rand];
  475. replicas_left_to_try[rand] = replicas_left_to_try[--tries_left];
  476. if (rend_compute_v2_desc_id(descriptor_id, rend_query->onion_address,
  477. rend_query->auth_type == REND_STEALTH_AUTH ?
  478. rend_query->descriptor_cookie : NULL,
  479. time(NULL), chosen_replica) < 0) {
  480. log_warn(LD_REND, "Internal error: Computing v2 rendezvous "
  481. "descriptor ID did not succeed.");
  482. return;
  483. }
  484. if (directory_get_from_hs_dir(descriptor_id, rend_query) != 0)
  485. return; /* either success or failure, but we're done */
  486. }
  487. /* If we come here, there are no hidden service directories left. */
  488. log_info(LD_REND, "Could not pick one of the responsible hidden "
  489. "service directories to fetch descriptors, because "
  490. "we already tried them all unsuccessfully.");
  491. /* Close pending connections. */
  492. rend_client_desc_trynow(rend_query->onion_address);
  493. return;
  494. }
  495. /** Cancel all rendezvous descriptor fetches currently in progress.
  496. */
  497. void
  498. rend_client_cancel_descriptor_fetches(void)
  499. {
  500. smartlist_t *connection_array = get_connection_array();
  501. SMARTLIST_FOREACH_BEGIN(connection_array, connection_t *, conn) {
  502. if (conn->type == CONN_TYPE_DIR &&
  503. (conn->purpose == DIR_PURPOSE_FETCH_RENDDESC ||
  504. conn->purpose == DIR_PURPOSE_FETCH_RENDDESC_V2)) {
  505. /* It's a rendezvous descriptor fetch in progress -- cancel it
  506. * by marking the connection for close.
  507. *
  508. * Even if this connection has already reached EOF, this is
  509. * enough to make sure that if the descriptor hasn't been
  510. * processed yet, it won't be. See the end of
  511. * connection_handle_read; connection_reached_eof (indirectly)
  512. * processes whatever response the connection received. */
  513. const rend_data_t *rd = (TO_DIR_CONN(conn))->rend_data;
  514. if (!rd) {
  515. log_warn(LD_BUG | LD_REND,
  516. "Marking for close dir conn fetching rendezvous "
  517. "descriptor for unknown service!");
  518. } else {
  519. log_debug(LD_REND, "Marking for close dir conn fetching "
  520. "rendezvous descriptor for service %s",
  521. safe_str(rd->onion_address));
  522. }
  523. connection_mark_for_close(conn);
  524. }
  525. } SMARTLIST_FOREACH_END(conn);
  526. }
  527. /** Remove failed_intro from ent. If ent now has no intro points, or
  528. * service is unrecognized, then launch a new renddesc fetch.
  529. *
  530. * Return -1 if error, 0 if no intro points remain or service
  531. * unrecognized, 1 if recognized and some intro points remain.
  532. */
  533. int
  534. rend_client_remove_intro_point(extend_info_t *failed_intro,
  535. const rend_data_t *rend_query)
  536. {
  537. int i, r;
  538. rend_cache_entry_t *ent;
  539. connection_t *conn;
  540. r = rend_cache_lookup_entry(rend_query->onion_address, -1, &ent);
  541. if (r<0) {
  542. log_warn(LD_BUG, "Malformed service ID %s.",
  543. escaped_safe_str_client(rend_query->onion_address));
  544. return -1;
  545. }
  546. if (r==0) {
  547. log_info(LD_REND, "Unknown service %s. Re-fetching descriptor.",
  548. escaped_safe_str_client(rend_query->onion_address));
  549. rend_client_refetch_v2_renddesc(rend_query);
  550. return 0;
  551. }
  552. for (i = 0; i < smartlist_len(ent->parsed->intro_nodes); i++) {
  553. rend_intro_point_t *intro = smartlist_get(ent->parsed->intro_nodes, i);
  554. if (!memcmp(failed_intro->identity_digest,
  555. intro->extend_info->identity_digest, DIGEST_LEN)) {
  556. rend_intro_point_free(intro);
  557. smartlist_del(ent->parsed->intro_nodes, i);
  558. break;
  559. }
  560. }
  561. if (! rend_client_any_intro_points_usable(ent)) {
  562. log_info(LD_REND,
  563. "No more intro points remain for %s. Re-fetching descriptor.",
  564. escaped_safe_str_client(rend_query->onion_address));
  565. rend_client_refetch_v2_renddesc(rend_query);
  566. /* move all pending streams back to renddesc_wait */
  567. while ((conn = connection_get_by_type_state_rendquery(CONN_TYPE_AP,
  568. AP_CONN_STATE_CIRCUIT_WAIT,
  569. rend_query->onion_address))) {
  570. conn->state = AP_CONN_STATE_RENDDESC_WAIT;
  571. }
  572. return 0;
  573. }
  574. log_info(LD_REND,"%d options left for %s.",
  575. smartlist_len(ent->parsed->intro_nodes),
  576. escaped_safe_str_client(rend_query->onion_address));
  577. return 1;
  578. }
  579. /** Called when we receive a RENDEZVOUS_ESTABLISHED cell; changes the state of
  580. * the circuit to C_REND_READY.
  581. */
  582. int
  583. rend_client_rendezvous_acked(origin_circuit_t *circ, const uint8_t *request,
  584. size_t request_len)
  585. {
  586. (void) request;
  587. (void) request_len;
  588. /* we just got an ack for our establish-rendezvous. switch purposes. */
  589. if (circ->_base.purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND) {
  590. log_warn(LD_PROTOCOL,"Got a rendezvous ack when we weren't expecting one. "
  591. "Closing circ.");
  592. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
  593. return -1;
  594. }
  595. log_info(LD_REND,"Got rendezvous ack. This circuit is now ready for "
  596. "rendezvous.");
  597. circ->_base.purpose = CIRCUIT_PURPOSE_C_REND_READY;
  598. /* XXXX023 This is a pretty brute-force approach. It'd be better to
  599. * attach only the connections that are waiting on this circuit, rather
  600. * than trying to attach them all. See comments bug 743. */
  601. /* If we already have the introduction circuit built, make sure we send
  602. * the INTRODUCE cell _now_ */
  603. connection_ap_attach_pending();
  604. return 0;
  605. }
  606. /** Bob sent us a rendezvous cell; join the circuits. */
  607. int
  608. rend_client_receive_rendezvous(origin_circuit_t *circ, const uint8_t *request,
  609. size_t request_len)
  610. {
  611. crypt_path_t *hop;
  612. char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN];
  613. if ((circ->_base.purpose != CIRCUIT_PURPOSE_C_REND_READY &&
  614. circ->_base.purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)
  615. || !circ->build_state->pending_final_cpath) {
  616. log_warn(LD_PROTOCOL,"Got rendezvous2 cell from hidden service, but not "
  617. "expecting it. Closing.");
  618. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
  619. return -1;
  620. }
  621. if (request_len != DH_KEY_LEN+DIGEST_LEN) {
  622. log_warn(LD_PROTOCOL,"Incorrect length (%d) on RENDEZVOUS2 cell.",
  623. (int)request_len);
  624. goto err;
  625. }
  626. log_info(LD_REND,"Got RENDEZVOUS2 cell from hidden service.");
  627. /* first DH_KEY_LEN bytes are g^y from bob. Finish the dh handshake...*/
  628. tor_assert(circ->build_state);
  629. tor_assert(circ->build_state->pending_final_cpath);
  630. hop = circ->build_state->pending_final_cpath;
  631. tor_assert(hop->dh_handshake_state);
  632. if (crypto_dh_compute_secret(LOG_PROTOCOL_WARN,
  633. hop->dh_handshake_state, (char*)request,
  634. DH_KEY_LEN,
  635. keys, DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
  636. log_warn(LD_GENERAL, "Couldn't complete DH handshake.");
  637. goto err;
  638. }
  639. /* ... and set up cpath. */
  640. if (circuit_init_cpath_crypto(hop, keys+DIGEST_LEN, 0)<0)
  641. goto err;
  642. /* Check whether the digest is right... */
  643. if (memcmp(keys, request+DH_KEY_LEN, DIGEST_LEN)) {
  644. log_warn(LD_PROTOCOL, "Incorrect digest of key material.");
  645. goto err;
  646. }
  647. crypto_dh_free(hop->dh_handshake_state);
  648. hop->dh_handshake_state = NULL;
  649. /* All is well. Extend the circuit. */
  650. circ->_base.purpose = CIRCUIT_PURPOSE_C_REND_JOINED;
  651. hop->state = CPATH_STATE_OPEN;
  652. /* set the windows to default. these are the windows
  653. * that alice thinks bob has.
  654. */
  655. hop->package_window = circuit_initial_package_window();
  656. hop->deliver_window = CIRCWINDOW_START;
  657. onion_append_to_cpath(&circ->cpath, hop);
  658. circ->build_state->pending_final_cpath = NULL; /* prevent double-free */
  659. /* XXXX023 This is a pretty brute-force approach. It'd be better to
  660. * attach only the connections that are waiting on this circuit, rather
  661. * than trying to attach them all. See comments bug 743. */
  662. connection_ap_attach_pending();
  663. memset(keys, 0, sizeof(keys));
  664. return 0;
  665. err:
  666. memset(keys, 0, sizeof(keys));
  667. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
  668. return -1;
  669. }
  670. /** Find all the apconns in state AP_CONN_STATE_RENDDESC_WAIT that are
  671. * waiting on <b>query</b>. If there's a working cache entry here with at
  672. * least one intro point, move them to the next state. */
  673. void
  674. rend_client_desc_trynow(const char *query)
  675. {
  676. edge_connection_t *conn;
  677. rend_cache_entry_t *entry;
  678. time_t now = time(NULL);
  679. smartlist_t *conns = get_connection_array();
  680. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, _conn) {
  681. if (_conn->type != CONN_TYPE_AP ||
  682. _conn->state != AP_CONN_STATE_RENDDESC_WAIT ||
  683. _conn->marked_for_close)
  684. continue;
  685. conn = TO_EDGE_CONN(_conn);
  686. if (!conn->rend_data)
  687. continue;
  688. if (rend_cmp_service_ids(query, conn->rend_data->onion_address))
  689. continue;
  690. assert_connection_ok(TO_CONN(conn), now);
  691. if (rend_cache_lookup_entry(conn->rend_data->onion_address, -1,
  692. &entry) == 1 &&
  693. rend_client_any_intro_points_usable(entry)) {
  694. /* either this fetch worked, or it failed but there was a
  695. * valid entry from before which we should reuse */
  696. log_info(LD_REND,"Rend desc is usable. Launching circuits.");
  697. conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
  698. /* restart their timeout values, so they get a fair shake at
  699. * connecting to the hidden service. */
  700. conn->_base.timestamp_created = now;
  701. conn->_base.timestamp_lastread = now;
  702. conn->_base.timestamp_lastwritten = now;
  703. if (connection_ap_handshake_attach_circuit(conn) < 0) {
  704. /* it will never work */
  705. log_warn(LD_REND,"Rendezvous attempt failed. Closing.");
  706. if (!conn->_base.marked_for_close)
  707. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  708. }
  709. } else { /* 404, or fetch didn't get that far */
  710. log_notice(LD_REND,"Closing stream for '%s.onion': hidden service is "
  711. "unavailable (try again later).",
  712. safe_str_client(query));
  713. connection_mark_unattached_ap(conn, END_STREAM_REASON_RESOLVEFAILED);
  714. }
  715. } SMARTLIST_FOREACH_END(_conn);
  716. }
  717. /** Return a newly allocated extend_info_t* for a randomly chosen introduction
  718. * point for the named hidden service. Return NULL if all introduction points
  719. * have been tried and failed.
  720. */
  721. extend_info_t *
  722. rend_client_get_random_intro(const rend_data_t *rend_query)
  723. {
  724. extend_info_t *result;
  725. rend_cache_entry_t *entry;
  726. if (rend_cache_lookup_entry(rend_query->onion_address, -1, &entry) < 1) {
  727. log_warn(LD_REND,
  728. "Query '%s' didn't have valid rend desc in cache. Failing.",
  729. safe_str_client(rend_query->onion_address));
  730. return NULL;
  731. }
  732. /* See if we can get a node that complies with ExcludeNodes */
  733. if ((result = rend_client_get_random_intro_impl(entry, 1, 1)))
  734. return result;
  735. /* If not, and StrictNodes is not set, see if we can return any old node
  736. */
  737. if (!get_options()->StrictNodes)
  738. return rend_client_get_random_intro_impl(entry, 0, 1);
  739. return NULL;
  740. }
  741. /** As rend_client_get_random_intro, except assume that StrictNodes is set
  742. * iff <b>strict</b> is true. If <b>warnings</b> is false, don't complain
  743. * to the user when we're out of nodes, even if StrictNodes is true.
  744. */
  745. static extend_info_t *
  746. rend_client_get_random_intro_impl(const rend_cache_entry_t *entry,
  747. const int strict,
  748. const int warnings)
  749. {
  750. int i;
  751. rend_intro_point_t *intro;
  752. routerinfo_t *router;
  753. or_options_t *options = get_options();
  754. smartlist_t *usable_nodes;
  755. int n_excluded = 0;
  756. /* We'll keep a separate list of the usable nodes. If this becomes empty,
  757. * no nodes are usable. */
  758. usable_nodes = smartlist_create();
  759. smartlist_add_all(usable_nodes, entry->parsed->intro_nodes);
  760. again:
  761. if (smartlist_len(usable_nodes) == 0) {
  762. if (n_excluded && get_options()->StrictNodes && warnings) {
  763. /* We only want to warn if StrictNodes is really set. Otherwise
  764. * we're just about to retry anyways.
  765. */
  766. log_warn(LD_REND, "All introduction points for hidden service are "
  767. "at excluded relays, and StrictNodes is set. Skipping.");
  768. }
  769. smartlist_free(usable_nodes);
  770. return NULL;
  771. }
  772. i = crypto_rand_int(smartlist_len(usable_nodes));
  773. intro = smartlist_get(usable_nodes, i);
  774. /* Do we need to look up the router or is the extend info complete? */
  775. if (!intro->extend_info->onion_key) {
  776. if (tor_digest_is_zero(intro->extend_info->identity_digest))
  777. router = router_get_by_hexdigest(intro->extend_info->nickname);
  778. else
  779. router = router_get_by_digest(intro->extend_info->identity_digest);
  780. if (!router) {
  781. log_info(LD_REND, "Unknown router with nickname '%s'; trying another.",
  782. intro->extend_info->nickname);
  783. smartlist_del(usable_nodes, i);
  784. goto again;
  785. }
  786. extend_info_free(intro->extend_info);
  787. intro->extend_info = extend_info_from_router(router);
  788. }
  789. /* Check if we should refuse to talk to this router. */
  790. if (options->ExcludeNodes && strict &&
  791. routerset_contains_extendinfo(options->ExcludeNodes,
  792. intro->extend_info)) {
  793. n_excluded++;
  794. smartlist_del(usable_nodes, i);
  795. goto again;
  796. }
  797. smartlist_free(usable_nodes);
  798. return extend_info_dup(intro->extend_info);
  799. }
  800. /** Return true iff any introduction points still listed in <b>entry</b> are
  801. * usable. */
  802. int
  803. rend_client_any_intro_points_usable(const rend_cache_entry_t *entry)
  804. {
  805. return rend_client_get_random_intro_impl(
  806. entry, get_options()->StrictNodes, 0) != NULL;
  807. }
  808. /** Client-side authorizations for hidden services; map of onion address to
  809. * rend_service_authorization_t*. */
  810. static strmap_t *auth_hid_servs = NULL;
  811. /** Look up the client-side authorization for the hidden service with
  812. * <b>onion_address</b>. Return NULL if no authorization is available for
  813. * that address. */
  814. rend_service_authorization_t*
  815. rend_client_lookup_service_authorization(const char *onion_address)
  816. {
  817. tor_assert(onion_address);
  818. if (!auth_hid_servs) return NULL;
  819. return strmap_get(auth_hid_servs, onion_address);
  820. }
  821. /** Helper: Free storage held by rend_service_authorization_t. */
  822. static void
  823. rend_service_authorization_free(rend_service_authorization_t *auth)
  824. {
  825. tor_free(auth);
  826. }
  827. /** Helper for strmap_free. */
  828. static void
  829. rend_service_authorization_strmap_item_free(void *service_auth)
  830. {
  831. rend_service_authorization_free(service_auth);
  832. }
  833. /** Release all the storage held in auth_hid_servs.
  834. */
  835. void
  836. rend_service_authorization_free_all(void)
  837. {
  838. if (!auth_hid_servs) {
  839. return;
  840. }
  841. strmap_free(auth_hid_servs, rend_service_authorization_strmap_item_free);
  842. auth_hid_servs = NULL;
  843. }
  844. /** Parse <b>config_line</b> as a client-side authorization for a hidden
  845. * service and add it to the local map of hidden service authorizations.
  846. * Return 0 for success and -1 for failure. */
  847. int
  848. rend_parse_service_authorization(or_options_t *options, int validate_only)
  849. {
  850. config_line_t *line;
  851. int res = -1;
  852. strmap_t *parsed = strmap_new();
  853. smartlist_t *sl = smartlist_create();
  854. rend_service_authorization_t *auth = NULL;
  855. for (line = options->HidServAuth; line; line = line->next) {
  856. char *onion_address, *descriptor_cookie;
  857. char descriptor_cookie_tmp[REND_DESC_COOKIE_LEN+2];
  858. char descriptor_cookie_base64ext[REND_DESC_COOKIE_LEN_BASE64+2+1];
  859. int auth_type_val = 0;
  860. auth = NULL;
  861. SMARTLIST_FOREACH(sl, char *, c, tor_free(c););
  862. smartlist_clear(sl);
  863. smartlist_split_string(sl, line->value, " ",
  864. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
  865. if (smartlist_len(sl) < 2) {
  866. log_warn(LD_CONFIG, "Configuration line does not consist of "
  867. "\"onion-address authorization-cookie [service-name]\": "
  868. "'%s'", line->value);
  869. goto err;
  870. }
  871. auth = tor_malloc_zero(sizeof(rend_service_authorization_t));
  872. /* Parse onion address. */
  873. onion_address = smartlist_get(sl, 0);
  874. if (strlen(onion_address) != REND_SERVICE_ADDRESS_LEN ||
  875. strcmpend(onion_address, ".onion")) {
  876. log_warn(LD_CONFIG, "Onion address has wrong format: '%s'",
  877. onion_address);
  878. goto err;
  879. }
  880. strlcpy(auth->onion_address, onion_address, REND_SERVICE_ID_LEN_BASE32+1);
  881. if (!rend_valid_service_id(auth->onion_address)) {
  882. log_warn(LD_CONFIG, "Onion address has wrong format: '%s'",
  883. onion_address);
  884. goto err;
  885. }
  886. /* Parse descriptor cookie. */
  887. descriptor_cookie = smartlist_get(sl, 1);
  888. if (strlen(descriptor_cookie) != REND_DESC_COOKIE_LEN_BASE64) {
  889. log_warn(LD_CONFIG, "Authorization cookie has wrong length: '%s'",
  890. descriptor_cookie);
  891. goto err;
  892. }
  893. /* Add trailing zero bytes (AA) to make base64-decoding happy. */
  894. tor_snprintf(descriptor_cookie_base64ext,
  895. REND_DESC_COOKIE_LEN_BASE64+2+1,
  896. "%sAA", descriptor_cookie);
  897. if (base64_decode(descriptor_cookie_tmp, sizeof(descriptor_cookie_tmp),
  898. descriptor_cookie_base64ext,
  899. strlen(descriptor_cookie_base64ext)) < 0) {
  900. log_warn(LD_CONFIG, "Decoding authorization cookie failed: '%s'",
  901. descriptor_cookie);
  902. goto err;
  903. }
  904. auth_type_val = (descriptor_cookie_tmp[16] >> 4) + 1;
  905. if (auth_type_val < 1 || auth_type_val > 2) {
  906. log_warn(LD_CONFIG, "Authorization cookie has unknown authorization "
  907. "type encoded.");
  908. goto err;
  909. }
  910. auth->auth_type = auth_type_val == 1 ? REND_BASIC_AUTH : REND_STEALTH_AUTH;
  911. memcpy(auth->descriptor_cookie, descriptor_cookie_tmp,
  912. REND_DESC_COOKIE_LEN);
  913. if (strmap_get(parsed, auth->onion_address)) {
  914. log_warn(LD_CONFIG, "Duplicate authorization for the same hidden "
  915. "service.");
  916. goto err;
  917. }
  918. strmap_set(parsed, auth->onion_address, auth);
  919. auth = NULL;
  920. }
  921. res = 0;
  922. goto done;
  923. err:
  924. res = -1;
  925. done:
  926. rend_service_authorization_free(auth);
  927. SMARTLIST_FOREACH(sl, char *, c, tor_free(c););
  928. smartlist_free(sl);
  929. if (!validate_only && res == 0) {
  930. rend_service_authorization_free_all();
  931. auth_hid_servs = parsed;
  932. } else {
  933. strmap_free(parsed, rend_service_authorization_strmap_item_free);
  934. }
  935. return res;
  936. }