rendclient.c 43 KB

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