rendclient.c 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104
  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 "nodelist.h"
  18. #include "relay.h"
  19. #include "rendclient.h"
  20. #include "rendcommon.h"
  21. #include "rephist.h"
  22. #include "router.h"
  23. #include "routerlist.h"
  24. static extend_info_t *rend_client_get_random_intro_impl(
  25. const rend_cache_entry_t *rend_query,
  26. const int strict, const int warnings);
  27. /** Purge all potentially remotely-detectable state held in the hidden
  28. * service client code. Called on SIGNAL NEWNYM. */
  29. void
  30. rend_client_purge_state(void)
  31. {
  32. rend_cache_purge();
  33. rend_client_cancel_descriptor_fetches();
  34. rend_client_purge_last_hid_serv_requests();
  35. }
  36. /** Called when we've established a circuit to an introduction point:
  37. * send the introduction request. */
  38. void
  39. rend_client_introcirc_has_opened(origin_circuit_t *circ)
  40. {
  41. tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
  42. tor_assert(circ->cpath);
  43. log_info(LD_REND,"introcirc is open");
  44. connection_ap_attach_pending();
  45. }
  46. /** Send the establish-rendezvous cell along a rendezvous circuit. if
  47. * it fails, mark the circ for close and return -1. else return 0.
  48. */
  49. static int
  50. rend_client_send_establish_rendezvous(origin_circuit_t *circ)
  51. {
  52. tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND);
  53. tor_assert(circ->rend_data);
  54. log_info(LD_REND, "Sending an ESTABLISH_RENDEZVOUS cell");
  55. if (crypto_rand(circ->rend_data->rend_cookie, REND_COOKIE_LEN) < 0) {
  56. log_warn(LD_BUG, "Internal error: Couldn't produce random cookie.");
  57. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
  58. return -1;
  59. }
  60. if (relay_send_command_from_edge(0, TO_CIRCUIT(circ),
  61. RELAY_COMMAND_ESTABLISH_RENDEZVOUS,
  62. circ->rend_data->rend_cookie,
  63. REND_COOKIE_LEN,
  64. circ->cpath->prev)<0) {
  65. /* circ is already marked for close */
  66. log_warn(LD_GENERAL, "Couldn't send ESTABLISH_RENDEZVOUS cell");
  67. return -1;
  68. }
  69. return 0;
  70. }
  71. /** Extend the introduction circuit <b>circ</b> to another valid
  72. * introduction point for the hidden service it is trying to connect
  73. * to, or mark it and launch a new circuit if we can't extend it.
  74. * Return 0 on success. Return -1 and mark the introduction
  75. * circuit on failure.
  76. *
  77. * On failure, the caller is responsible for marking the associated
  78. * rendezvous circuit for close. */
  79. static int
  80. rend_client_reextend_intro_circuit(origin_circuit_t *circ)
  81. {
  82. extend_info_t *extend_info;
  83. int result;
  84. extend_info = rend_client_get_random_intro(circ->rend_data);
  85. if (!extend_info) {
  86. log_warn(LD_REND,
  87. "No usable introduction points left for %s. Closing.",
  88. safe_str_client(circ->rend_data->onion_address));
  89. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_INTERNAL);
  90. return -1;
  91. }
  92. if (circ->remaining_relay_early_cells) {
  93. log_info(LD_REND,
  94. "Re-extending circ %d, this time to %s.",
  95. circ->_base.n_circ_id,
  96. safe_str_client(extend_info_describe(extend_info)));
  97. result = circuit_extend_to_new_exit(circ, extend_info);
  98. } else {
  99. log_info(LD_REND,
  100. "Building a new introduction circuit, this time to %s.",
  101. safe_str_client(extend_info_describe(extend_info)));
  102. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
  103. if (!circuit_launch_by_extend_info(CIRCUIT_PURPOSE_C_INTRODUCING,
  104. extend_info,
  105. CIRCLAUNCH_IS_INTERNAL)) {
  106. log_warn(LD_REND, "Building introduction circuit failed.");
  107. result = -1;
  108. } else {
  109. result = 0;
  110. }
  111. }
  112. extend_info_free(extend_info);
  113. return result;
  114. }
  115. /** Called when we're trying to connect an ap conn; sends an INTRODUCE1 cell
  116. * down introcirc if possible.
  117. */
  118. int
  119. rend_client_send_introduction(origin_circuit_t *introcirc,
  120. origin_circuit_t *rendcirc)
  121. {
  122. size_t payload_len;
  123. int r, v3_shift = 0;
  124. char payload[RELAY_PAYLOAD_SIZE];
  125. char tmp[RELAY_PAYLOAD_SIZE];
  126. rend_cache_entry_t *entry;
  127. crypt_path_t *cpath;
  128. off_t dh_offset;
  129. crypto_pk_env_t *intro_key = NULL;
  130. tor_assert(introcirc->_base.purpose == CIRCUIT_PURPOSE_C_INTRODUCING);
  131. tor_assert(rendcirc->_base.purpose == CIRCUIT_PURPOSE_C_REND_READY);
  132. tor_assert(introcirc->rend_data);
  133. tor_assert(rendcirc->rend_data);
  134. tor_assert(!rend_cmp_service_ids(introcirc->rend_data->onion_address,
  135. rendcirc->rend_data->onion_address));
  136. if (rend_cache_lookup_entry(introcirc->rend_data->onion_address, -1,
  137. &entry) < 1) {
  138. log_info(LD_REND,
  139. "query %s didn't have valid rend desc in cache. "
  140. "Refetching descriptor.",
  141. safe_str_client(introcirc->rend_data->onion_address));
  142. rend_client_refetch_v2_renddesc(introcirc->rend_data);
  143. {
  144. connection_t *conn;
  145. while ((conn = connection_get_by_type_state_rendquery(CONN_TYPE_AP,
  146. AP_CONN_STATE_CIRCUIT_WAIT,
  147. introcirc->rend_data->onion_address))) {
  148. conn->state = AP_CONN_STATE_RENDDESC_WAIT;
  149. }
  150. }
  151. return -1;
  152. }
  153. /* first 20 bytes of payload are the hash of Bob's pk */
  154. intro_key = NULL;
  155. SMARTLIST_FOREACH(entry->parsed->intro_nodes, rend_intro_point_t *,
  156. intro, {
  157. if (tor_memeq(introcirc->build_state->chosen_exit->identity_digest,
  158. intro->extend_info->identity_digest, DIGEST_LEN)) {
  159. intro_key = intro->intro_key;
  160. break;
  161. }
  162. });
  163. if (!intro_key) {
  164. log_info(LD_REND, "Could not find intro key for %s at %s; we "
  165. "have a v2 rend desc with %d intro points. "
  166. "Trying a different intro point...",
  167. safe_str_client(introcirc->rend_data->onion_address),
  168. safe_str_client(extend_info_describe(
  169. introcirc->build_state->chosen_exit)),
  170. smartlist_len(entry->parsed->intro_nodes));
  171. if (rend_client_reextend_intro_circuit(introcirc)) {
  172. goto perm_err;
  173. } else {
  174. return -1;
  175. }
  176. }
  177. if (crypto_pk_get_digest(intro_key, payload)<0) {
  178. log_warn(LD_BUG, "Internal error: couldn't hash public key.");
  179. goto perm_err;
  180. }
  181. /* Initialize the pending_final_cpath and start the DH handshake. */
  182. cpath = rendcirc->build_state->pending_final_cpath;
  183. if (!cpath) {
  184. cpath = rendcirc->build_state->pending_final_cpath =
  185. tor_malloc_zero(sizeof(crypt_path_t));
  186. cpath->magic = CRYPT_PATH_MAGIC;
  187. if (!(cpath->dh_handshake_state = crypto_dh_new(DH_TYPE_REND))) {
  188. log_warn(LD_BUG, "Internal error: couldn't allocate DH.");
  189. goto perm_err;
  190. }
  191. if (crypto_dh_generate_public(cpath->dh_handshake_state)<0) {
  192. log_warn(LD_BUG, "Internal error: couldn't generate g^x.");
  193. goto perm_err;
  194. }
  195. }
  196. /* If version is 3, write (optional) auth data and timestamp. */
  197. if (entry->parsed->protocols & (1<<3)) {
  198. tmp[0] = 3; /* version 3 of the cell format */
  199. tmp[1] = (uint8_t)introcirc->rend_data->auth_type; /* auth type, if any */
  200. v3_shift = 1;
  201. if (introcirc->rend_data->auth_type != REND_NO_AUTH) {
  202. set_uint16(tmp+2, htons(REND_DESC_COOKIE_LEN));
  203. memcpy(tmp+4, introcirc->rend_data->descriptor_cookie,
  204. REND_DESC_COOKIE_LEN);
  205. v3_shift += 2+REND_DESC_COOKIE_LEN;
  206. }
  207. set_uint32(tmp+v3_shift+1, htonl((uint32_t)time(NULL)));
  208. v3_shift += 4;
  209. } /* if version 2 only write version number */
  210. else if (entry->parsed->protocols & (1<<2)) {
  211. tmp[0] = 2; /* version 2 of the cell format */
  212. }
  213. /* write the remaining items into tmp */
  214. if (entry->parsed->protocols & (1<<3) || entry->parsed->protocols & (1<<2)) {
  215. /* version 2 format */
  216. extend_info_t *extend_info = rendcirc->build_state->chosen_exit;
  217. int klen;
  218. /* nul pads */
  219. set_uint32(tmp+v3_shift+1, tor_addr_to_ipv4h(&extend_info->addr));
  220. set_uint16(tmp+v3_shift+5, htons(extend_info->port));
  221. memcpy(tmp+v3_shift+7, extend_info->identity_digest, DIGEST_LEN);
  222. klen = crypto_pk_asn1_encode(extend_info->onion_key,
  223. tmp+v3_shift+7+DIGEST_LEN+2,
  224. sizeof(tmp)-(v3_shift+7+DIGEST_LEN+2));
  225. set_uint16(tmp+v3_shift+7+DIGEST_LEN, htons(klen));
  226. memcpy(tmp+v3_shift+7+DIGEST_LEN+2+klen, rendcirc->rend_data->rend_cookie,
  227. REND_COOKIE_LEN);
  228. dh_offset = v3_shift+7+DIGEST_LEN+2+klen+REND_COOKIE_LEN;
  229. } else {
  230. /* Version 0. */
  231. strncpy(tmp, rendcirc->build_state->chosen_exit->nickname,
  232. (MAX_NICKNAME_LEN+1)); /* nul pads */
  233. memcpy(tmp+MAX_NICKNAME_LEN+1, rendcirc->rend_data->rend_cookie,
  234. REND_COOKIE_LEN);
  235. dh_offset = MAX_NICKNAME_LEN+1+REND_COOKIE_LEN;
  236. }
  237. if (crypto_dh_get_public(cpath->dh_handshake_state, tmp+dh_offset,
  238. DH_KEY_LEN)<0) {
  239. log_warn(LD_BUG, "Internal error: couldn't extract g^x.");
  240. goto perm_err;
  241. }
  242. note_crypto_pk_op(REND_CLIENT);
  243. /*XXX maybe give crypto_pk_public_hybrid_encrypt a max_len arg,
  244. * to avoid buffer overflows? */
  245. r = crypto_pk_public_hybrid_encrypt(intro_key, payload+DIGEST_LEN,
  246. sizeof(payload)-DIGEST_LEN,
  247. tmp,
  248. (int)(dh_offset+DH_KEY_LEN),
  249. PK_PKCS1_OAEP_PADDING, 0);
  250. if (r<0) {
  251. log_warn(LD_BUG,"Internal error: hybrid pk encrypt failed.");
  252. goto perm_err;
  253. }
  254. payload_len = DIGEST_LEN + r;
  255. tor_assert(payload_len <= RELAY_PAYLOAD_SIZE); /* we overran something */
  256. log_info(LD_REND, "Sending an INTRODUCE1 cell");
  257. if (relay_send_command_from_edge(0, TO_CIRCUIT(introcirc),
  258. RELAY_COMMAND_INTRODUCE1,
  259. payload, payload_len,
  260. introcirc->cpath->prev)<0) {
  261. /* introcirc is already marked for close. leave rendcirc alone. */
  262. log_warn(LD_BUG, "Couldn't send INTRODUCE1 cell");
  263. return -2;
  264. }
  265. /* Now, we wait for an ACK or NAK on this circuit. */
  266. introcirc->_base.purpose = CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT;
  267. /* Set timestamp_dirty, because circuit_expire_building expects it
  268. * to specify when a circuit entered the _C_INTRODUCE_ACK_WAIT
  269. * state. */
  270. introcirc->_base.timestamp_dirty = time(NULL);
  271. return 0;
  272. perm_err:
  273. if (!introcirc->_base.marked_for_close)
  274. circuit_mark_for_close(TO_CIRCUIT(introcirc), END_CIRC_REASON_INTERNAL);
  275. circuit_mark_for_close(TO_CIRCUIT(rendcirc), END_CIRC_REASON_INTERNAL);
  276. return -2;
  277. }
  278. /** Called when a rendezvous circuit is open; sends a establish
  279. * rendezvous circuit as appropriate. */
  280. void
  281. rend_client_rendcirc_has_opened(origin_circuit_t *circ)
  282. {
  283. tor_assert(circ->_base.purpose == CIRCUIT_PURPOSE_C_ESTABLISH_REND);
  284. log_info(LD_REND,"rendcirc is open");
  285. /* generate a rendezvous cookie, store it in circ */
  286. if (rend_client_send_establish_rendezvous(circ) < 0) {
  287. return;
  288. }
  289. }
  290. /** Called when get an ACK or a NAK for a REND_INTRODUCE1 cell.
  291. */
  292. int
  293. rend_client_introduction_acked(origin_circuit_t *circ,
  294. const uint8_t *request, size_t request_len)
  295. {
  296. origin_circuit_t *rendcirc;
  297. (void) request; // XXXX Use this.
  298. if (circ->_base.purpose != CIRCUIT_PURPOSE_C_INTRODUCE_ACK_WAIT) {
  299. log_warn(LD_PROTOCOL,
  300. "Received REND_INTRODUCE_ACK on unexpected circuit %d.",
  301. circ->_base.n_circ_id);
  302. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
  303. return -1;
  304. }
  305. tor_assert(circ->build_state->chosen_exit);
  306. tor_assert(circ->rend_data);
  307. if (request_len == 0) {
  308. /* It's an ACK; the introduction point relayed our introduction request. */
  309. /* Locate the rend circ which is waiting to hear about this ack,
  310. * and tell it.
  311. */
  312. log_info(LD_REND,"Received ack. Telling rend circ...");
  313. rendcirc = circuit_get_by_rend_query_and_purpose(
  314. circ->rend_data->onion_address, CIRCUIT_PURPOSE_C_REND_READY);
  315. if (rendcirc) { /* remember the ack */
  316. rendcirc->_base.purpose = CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED;
  317. /* Set timestamp_dirty, because circuit_expire_building expects
  318. * it to specify when a circuit entered the
  319. * _C_REND_READY_INTRO_ACKED state. */
  320. rendcirc->_base.timestamp_dirty = time(NULL);
  321. } else {
  322. log_info(LD_REND,"...Found no rend circ. Dropping on the floor.");
  323. }
  324. /* close the circuit: we won't need it anymore. */
  325. circ->_base.purpose = CIRCUIT_PURPOSE_C_INTRODUCE_ACKED;
  326. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_FINISHED);
  327. } else {
  328. /* It's a NAK; the introduction point didn't relay our request. */
  329. circ->_base.purpose = CIRCUIT_PURPOSE_C_INTRODUCING;
  330. /* Remove this intro point from the set of viable introduction
  331. * points. If any remain, extend to a new one and try again.
  332. * If none remain, refetch the service descriptor.
  333. */
  334. log_info(LD_REND, "Got nack for %s from %s...",
  335. safe_str_client(circ->rend_data->onion_address),
  336. safe_str_client(extend_info_describe(circ->build_state->chosen_exit)));
  337. if (rend_client_remove_intro_point(circ->build_state->chosen_exit,
  338. circ->rend_data) > 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(time_t now)
  400. {
  401. strmap_iter_t *iter;
  402. time_t cutoff = now - 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. /* Clean request history first. */
  462. directory_clean_last_hid_serv_requests(now);
  463. SMARTLIST_FOREACH(responsible_dirs, routerstatus_t *, dir, {
  464. if (lookup_last_hid_serv_request(dir, desc_id_base32, 0, 0) +
  465. REND_HID_SERV_DIR_REQUERY_PERIOD >= now ||
  466. !router_get_by_id_digest(dir->identity_digest))
  467. SMARTLIST_DEL_CURRENT(responsible_dirs, dir);
  468. });
  469. hs_dir = smartlist_choose(responsible_dirs);
  470. smartlist_free(responsible_dirs);
  471. if (!hs_dir) {
  472. log_info(LD_REND, "Could not pick one of the responsible hidden "
  473. "service directories, because we requested them all "
  474. "recently without success.");
  475. return 0;
  476. }
  477. /* Remember, that we are requesting a descriptor from this hidden service
  478. * directory now. */
  479. lookup_last_hid_serv_request(hs_dir, desc_id_base32, now, 1);
  480. /* Encode descriptor cookie for logging purposes. */
  481. if (rend_query->auth_type != REND_NO_AUTH) {
  482. if (base64_encode(descriptor_cookie_base64,
  483. sizeof(descriptor_cookie_base64),
  484. rend_query->descriptor_cookie, REND_DESC_COOKIE_LEN)<0) {
  485. log_warn(LD_BUG, "Could not base64-encode descriptor cookie.");
  486. return 0;
  487. }
  488. /* Remove == signs and newline. */
  489. descriptor_cookie_base64[strlen(descriptor_cookie_base64)-3] = '\0';
  490. } else {
  491. strlcpy(descriptor_cookie_base64, "(none)",
  492. sizeof(descriptor_cookie_base64));
  493. }
  494. /* Send fetch request. (Pass query and possibly descriptor cookie so that
  495. * they can be written to the directory connection and be referred to when
  496. * the response arrives. */
  497. directory_initiate_command_routerstatus_rend(hs_dir,
  498. DIR_PURPOSE_FETCH_RENDDESC_V2,
  499. ROUTER_PURPOSE_GENERAL,
  500. 1, desc_id_base32, NULL, 0, 0,
  501. rend_query);
  502. log_info(LD_REND, "Sending fetch request for v2 descriptor for "
  503. "service '%s' with descriptor ID '%s', auth type %d, "
  504. "and descriptor cookie '%s' to hidden service "
  505. "directory %s",
  506. rend_query->onion_address, desc_id_base32,
  507. rend_query->auth_type,
  508. (rend_query->auth_type == REND_NO_AUTH ? "[none]" :
  509. escaped_safe_str_client(descriptor_cookie_base64)),
  510. routerstatus_describe(hs_dir));
  511. return 1;
  512. }
  513. /** Unless we already have a descriptor for <b>rend_query</b> with at least
  514. * one (possibly) working introduction point in it, start a connection to a
  515. * hidden service directory to fetch a v2 rendezvous service descriptor. */
  516. void
  517. rend_client_refetch_v2_renddesc(const rend_data_t *rend_query)
  518. {
  519. char descriptor_id[DIGEST_LEN];
  520. int replicas_left_to_try[REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS];
  521. int i, tries_left;
  522. rend_cache_entry_t *e = NULL;
  523. tor_assert(rend_query);
  524. /* Are we configured to fetch descriptors? */
  525. if (!get_options()->FetchHidServDescriptors) {
  526. log_warn(LD_REND, "We received an onion address for a v2 rendezvous "
  527. "service descriptor, but are not fetching service descriptors.");
  528. return;
  529. }
  530. /* Before fetching, check if we already have the descriptor here. */
  531. if (rend_cache_lookup_entry(rend_query->onion_address, -1, &e) > 0) {
  532. log_info(LD_REND, "We would fetch a v2 rendezvous descriptor, but we "
  533. "already have that 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. /** Remove failed_intro from ent. If ent now has no intro points, or
  599. * service is unrecognized, then launch a new renddesc fetch.
  600. *
  601. * Return -1 if error, 0 if no intro points remain or service
  602. * unrecognized, 1 if recognized and some intro points remain.
  603. */
  604. int
  605. rend_client_remove_intro_point(extend_info_t *failed_intro,
  606. const rend_data_t *rend_query)
  607. {
  608. int i, r;
  609. rend_cache_entry_t *ent;
  610. connection_t *conn;
  611. r = rend_cache_lookup_entry(rend_query->onion_address, -1, &ent);
  612. if (r<0) {
  613. log_warn(LD_BUG, "Malformed service ID %s.",
  614. escaped_safe_str_client(rend_query->onion_address));
  615. return -1;
  616. }
  617. if (r==0) {
  618. log_info(LD_REND, "Unknown service %s. Re-fetching descriptor.",
  619. escaped_safe_str_client(rend_query->onion_address));
  620. rend_client_refetch_v2_renddesc(rend_query);
  621. return 0;
  622. }
  623. for (i = 0; i < smartlist_len(ent->parsed->intro_nodes); i++) {
  624. rend_intro_point_t *intro = smartlist_get(ent->parsed->intro_nodes, i);
  625. if (tor_memeq(failed_intro->identity_digest,
  626. intro->extend_info->identity_digest, DIGEST_LEN)) {
  627. rend_intro_point_free(intro);
  628. smartlist_del(ent->parsed->intro_nodes, i);
  629. break;
  630. }
  631. }
  632. if (! rend_client_any_intro_points_usable(ent)) {
  633. log_info(LD_REND,
  634. "No more intro points remain for %s. Re-fetching descriptor.",
  635. escaped_safe_str_client(rend_query->onion_address));
  636. rend_client_refetch_v2_renddesc(rend_query);
  637. /* move all pending streams back to renddesc_wait */
  638. while ((conn = connection_get_by_type_state_rendquery(CONN_TYPE_AP,
  639. AP_CONN_STATE_CIRCUIT_WAIT,
  640. rend_query->onion_address))) {
  641. conn->state = AP_CONN_STATE_RENDDESC_WAIT;
  642. }
  643. return 0;
  644. }
  645. log_info(LD_REND,"%d options left for %s.",
  646. smartlist_len(ent->parsed->intro_nodes),
  647. escaped_safe_str_client(rend_query->onion_address));
  648. return 1;
  649. }
  650. /** Called when we receive a RENDEZVOUS_ESTABLISHED cell; changes the state of
  651. * the circuit to C_REND_READY.
  652. */
  653. int
  654. rend_client_rendezvous_acked(origin_circuit_t *circ, const uint8_t *request,
  655. size_t request_len)
  656. {
  657. (void) request;
  658. (void) request_len;
  659. /* we just got an ack for our establish-rendezvous. switch purposes. */
  660. if (circ->_base.purpose != CIRCUIT_PURPOSE_C_ESTABLISH_REND) {
  661. log_warn(LD_PROTOCOL,"Got a rendezvous ack when we weren't expecting one. "
  662. "Closing circ.");
  663. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
  664. return -1;
  665. }
  666. log_info(LD_REND,"Got rendezvous ack. This circuit is now ready for "
  667. "rendezvous.");
  668. circ->_base.purpose = CIRCUIT_PURPOSE_C_REND_READY;
  669. /* Set timestamp_dirty, because circuit_expire_building expects it
  670. * to specify when a circuit entered the _C_REND_READY state. */
  671. circ->_base.timestamp_dirty = time(NULL);
  672. /* XXXX023 This is a pretty brute-force approach. It'd be better to
  673. * attach only the connections that are waiting on this circuit, rather
  674. * than trying to attach them all. See comments bug 743. */
  675. /* If we already have the introduction circuit built, make sure we send
  676. * the INTRODUCE cell _now_ */
  677. connection_ap_attach_pending();
  678. return 0;
  679. }
  680. /** Bob sent us a rendezvous cell; join the circuits. */
  681. int
  682. rend_client_receive_rendezvous(origin_circuit_t *circ, const uint8_t *request,
  683. size_t request_len)
  684. {
  685. crypt_path_t *hop;
  686. char keys[DIGEST_LEN+CPATH_KEY_MATERIAL_LEN];
  687. if ((circ->_base.purpose != CIRCUIT_PURPOSE_C_REND_READY &&
  688. circ->_base.purpose != CIRCUIT_PURPOSE_C_REND_READY_INTRO_ACKED)
  689. || !circ->build_state->pending_final_cpath) {
  690. log_warn(LD_PROTOCOL,"Got rendezvous2 cell from hidden service, but not "
  691. "expecting it. Closing.");
  692. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
  693. return -1;
  694. }
  695. if (request_len != DH_KEY_LEN+DIGEST_LEN) {
  696. log_warn(LD_PROTOCOL,"Incorrect length (%d) on RENDEZVOUS2 cell.",
  697. (int)request_len);
  698. goto err;
  699. }
  700. log_info(LD_REND,"Got RENDEZVOUS2 cell from hidden service.");
  701. /* first DH_KEY_LEN bytes are g^y from bob. Finish the dh handshake...*/
  702. tor_assert(circ->build_state);
  703. tor_assert(circ->build_state->pending_final_cpath);
  704. hop = circ->build_state->pending_final_cpath;
  705. tor_assert(hop->dh_handshake_state);
  706. if (crypto_dh_compute_secret(LOG_PROTOCOL_WARN,
  707. hop->dh_handshake_state, (char*)request,
  708. DH_KEY_LEN,
  709. keys, DIGEST_LEN+CPATH_KEY_MATERIAL_LEN)<0) {
  710. log_warn(LD_GENERAL, "Couldn't complete DH handshake.");
  711. goto err;
  712. }
  713. /* ... and set up cpath. */
  714. if (circuit_init_cpath_crypto(hop, keys+DIGEST_LEN, 0)<0)
  715. goto err;
  716. /* Check whether the digest is right... */
  717. if (tor_memneq(keys, request+DH_KEY_LEN, DIGEST_LEN)) {
  718. log_warn(LD_PROTOCOL, "Incorrect digest of key material.");
  719. goto err;
  720. }
  721. crypto_dh_free(hop->dh_handshake_state);
  722. hop->dh_handshake_state = NULL;
  723. /* All is well. Extend the circuit. */
  724. circ->_base.purpose = CIRCUIT_PURPOSE_C_REND_JOINED;
  725. hop->state = CPATH_STATE_OPEN;
  726. /* set the windows to default. these are the windows
  727. * that alice thinks bob has.
  728. */
  729. hop->package_window = circuit_initial_package_window();
  730. hop->deliver_window = CIRCWINDOW_START;
  731. onion_append_to_cpath(&circ->cpath, hop);
  732. circ->build_state->pending_final_cpath = NULL; /* prevent double-free */
  733. /* XXXX023 This is a pretty brute-force approach. It'd be better to
  734. * attach only the connections that are waiting on this circuit, rather
  735. * than trying to attach them all. See comments bug 743. */
  736. connection_ap_attach_pending();
  737. memset(keys, 0, sizeof(keys));
  738. return 0;
  739. err:
  740. memset(keys, 0, sizeof(keys));
  741. circuit_mark_for_close(TO_CIRCUIT(circ), END_CIRC_REASON_TORPROTOCOL);
  742. return -1;
  743. }
  744. /** Find all the apconns in state AP_CONN_STATE_RENDDESC_WAIT that are
  745. * waiting on <b>query</b>. If there's a working cache entry here with at
  746. * least one intro point, move them to the next state. */
  747. void
  748. rend_client_desc_trynow(const char *query)
  749. {
  750. edge_connection_t *conn;
  751. rend_cache_entry_t *entry;
  752. time_t now = time(NULL);
  753. smartlist_t *conns = get_connection_array();
  754. SMARTLIST_FOREACH_BEGIN(conns, connection_t *, _conn) {
  755. if (_conn->type != CONN_TYPE_AP ||
  756. _conn->state != AP_CONN_STATE_RENDDESC_WAIT ||
  757. _conn->marked_for_close)
  758. continue;
  759. conn = TO_EDGE_CONN(_conn);
  760. if (!conn->rend_data)
  761. continue;
  762. if (rend_cmp_service_ids(query, conn->rend_data->onion_address))
  763. continue;
  764. assert_connection_ok(TO_CONN(conn), now);
  765. if (rend_cache_lookup_entry(conn->rend_data->onion_address, -1,
  766. &entry) == 1 &&
  767. rend_client_any_intro_points_usable(entry)) {
  768. /* either this fetch worked, or it failed but there was a
  769. * valid entry from before which we should reuse */
  770. log_info(LD_REND,"Rend desc is usable. Launching circuits.");
  771. conn->_base.state = AP_CONN_STATE_CIRCUIT_WAIT;
  772. /* restart their timeout values, so they get a fair shake at
  773. * connecting to the hidden service. */
  774. conn->_base.timestamp_created = now;
  775. conn->_base.timestamp_lastread = now;
  776. conn->_base.timestamp_lastwritten = now;
  777. if (connection_ap_handshake_attach_circuit(conn) < 0) {
  778. /* it will never work */
  779. log_warn(LD_REND,"Rendezvous attempt failed. Closing.");
  780. if (!conn->_base.marked_for_close)
  781. connection_mark_unattached_ap(conn, END_STREAM_REASON_CANT_ATTACH);
  782. }
  783. } else { /* 404, or fetch didn't get that far */
  784. log_notice(LD_REND,"Closing stream for '%s.onion': hidden service is "
  785. "unavailable (try again later).",
  786. safe_str_client(query));
  787. connection_mark_unattached_ap(conn, END_STREAM_REASON_RESOLVEFAILED);
  788. }
  789. } SMARTLIST_FOREACH_END(_conn);
  790. }
  791. /** Return a newly allocated extend_info_t* for a randomly chosen introduction
  792. * point for the named hidden service. Return NULL if all introduction points
  793. * have been tried and failed.
  794. */
  795. extend_info_t *
  796. rend_client_get_random_intro(const rend_data_t *rend_query)
  797. {
  798. extend_info_t *result;
  799. rend_cache_entry_t *entry;
  800. if (rend_cache_lookup_entry(rend_query->onion_address, -1, &entry) < 1) {
  801. log_warn(LD_REND,
  802. "Query '%s' didn't have valid rend desc in cache. Failing.",
  803. safe_str_client(rend_query->onion_address));
  804. return NULL;
  805. }
  806. /* See if we can get a node that complies with ExcludeNodes */
  807. if ((result = rend_client_get_random_intro_impl(entry, 1, 1)))
  808. return result;
  809. /* If not, and StrictNodes is not set, see if we can return any old node
  810. */
  811. if (!get_options()->StrictNodes)
  812. return rend_client_get_random_intro_impl(entry, 0, 1);
  813. return NULL;
  814. }
  815. /** As rend_client_get_random_intro, except assume that StrictNodes is set
  816. * iff <b>strict</b> is true. If <b>warnings</b> is false, don't complain
  817. * to the user when we're out of nodes, even if StrictNodes is true.
  818. */
  819. static extend_info_t *
  820. rend_client_get_random_intro_impl(const rend_cache_entry_t *entry,
  821. const int strict,
  822. const int warnings)
  823. {
  824. int i;
  825. rend_intro_point_t *intro;
  826. const or_options_t *options = get_options();
  827. smartlist_t *usable_nodes;
  828. int n_excluded = 0;
  829. /* We'll keep a separate list of the usable nodes. If this becomes empty,
  830. * no nodes are usable. */
  831. usable_nodes = smartlist_create();
  832. smartlist_add_all(usable_nodes, entry->parsed->intro_nodes);
  833. again:
  834. if (smartlist_len(usable_nodes) == 0) {
  835. if (n_excluded && get_options()->StrictNodes && warnings) {
  836. /* We only want to warn if StrictNodes is really set. Otherwise
  837. * we're just about to retry anyways.
  838. */
  839. log_warn(LD_REND, "All introduction points for hidden service are "
  840. "at excluded relays, and StrictNodes is set. Skipping.");
  841. }
  842. smartlist_free(usable_nodes);
  843. return NULL;
  844. }
  845. i = crypto_rand_int(smartlist_len(usable_nodes));
  846. intro = smartlist_get(usable_nodes, i);
  847. /* Do we need to look up the router or is the extend info complete? */
  848. if (!intro->extend_info->onion_key) {
  849. const node_t *node;
  850. if (tor_digest_is_zero(intro->extend_info->identity_digest))
  851. node = node_get_by_hex_id(intro->extend_info->nickname);
  852. else
  853. node = node_get_by_id(intro->extend_info->identity_digest);
  854. if (!node) {
  855. log_info(LD_REND, "Unknown router with nickname '%s'; trying another.",
  856. intro->extend_info->nickname);
  857. smartlist_del(usable_nodes, i);
  858. goto again;
  859. }
  860. extend_info_free(intro->extend_info);
  861. intro->extend_info = extend_info_from_node(node);
  862. }
  863. /* Check if we should refuse to talk to this router. */
  864. if (options->ExcludeNodes && strict &&
  865. routerset_contains_extendinfo(options->ExcludeNodes,
  866. intro->extend_info)) {
  867. n_excluded++;
  868. smartlist_del(usable_nodes, i);
  869. goto again;
  870. }
  871. smartlist_free(usable_nodes);
  872. return extend_info_dup(intro->extend_info);
  873. }
  874. /** Return true iff any introduction points still listed in <b>entry</b> are
  875. * usable. */
  876. int
  877. rend_client_any_intro_points_usable(const rend_cache_entry_t *entry)
  878. {
  879. return rend_client_get_random_intro_impl(
  880. entry, get_options()->StrictNodes, 0) != NULL;
  881. }
  882. /** Client-side authorizations for hidden services; map of onion address to
  883. * rend_service_authorization_t*. */
  884. static strmap_t *auth_hid_servs = NULL;
  885. /** Look up the client-side authorization for the hidden service with
  886. * <b>onion_address</b>. Return NULL if no authorization is available for
  887. * that address. */
  888. rend_service_authorization_t*
  889. rend_client_lookup_service_authorization(const char *onion_address)
  890. {
  891. tor_assert(onion_address);
  892. if (!auth_hid_servs) return NULL;
  893. return strmap_get(auth_hid_servs, onion_address);
  894. }
  895. /** Helper: Free storage held by rend_service_authorization_t. */
  896. static void
  897. rend_service_authorization_free(rend_service_authorization_t *auth)
  898. {
  899. tor_free(auth);
  900. }
  901. /** Helper for strmap_free. */
  902. static void
  903. rend_service_authorization_strmap_item_free(void *service_auth)
  904. {
  905. rend_service_authorization_free(service_auth);
  906. }
  907. /** Release all the storage held in auth_hid_servs.
  908. */
  909. void
  910. rend_service_authorization_free_all(void)
  911. {
  912. if (!auth_hid_servs) {
  913. return;
  914. }
  915. strmap_free(auth_hid_servs, rend_service_authorization_strmap_item_free);
  916. auth_hid_servs = NULL;
  917. }
  918. /** Parse <b>config_line</b> as a client-side authorization for a hidden
  919. * service and add it to the local map of hidden service authorizations.
  920. * Return 0 for success and -1 for failure. */
  921. int
  922. rend_parse_service_authorization(const or_options_t *options,
  923. int validate_only)
  924. {
  925. config_line_t *line;
  926. int res = -1;
  927. strmap_t *parsed = strmap_new();
  928. smartlist_t *sl = smartlist_create();
  929. rend_service_authorization_t *auth = NULL;
  930. for (line = options->HidServAuth; line; line = line->next) {
  931. char *onion_address, *descriptor_cookie;
  932. char descriptor_cookie_tmp[REND_DESC_COOKIE_LEN+2];
  933. char descriptor_cookie_base64ext[REND_DESC_COOKIE_LEN_BASE64+2+1];
  934. int auth_type_val = 0;
  935. auth = NULL;
  936. SMARTLIST_FOREACH(sl, char *, c, tor_free(c););
  937. smartlist_clear(sl);
  938. smartlist_split_string(sl, line->value, " ",
  939. SPLIT_SKIP_SPACE|SPLIT_IGNORE_BLANK, 3);
  940. if (smartlist_len(sl) < 2) {
  941. log_warn(LD_CONFIG, "Configuration line does not consist of "
  942. "\"onion-address authorization-cookie [service-name]\": "
  943. "'%s'", line->value);
  944. goto err;
  945. }
  946. auth = tor_malloc_zero(sizeof(rend_service_authorization_t));
  947. /* Parse onion address. */
  948. onion_address = smartlist_get(sl, 0);
  949. if (strlen(onion_address) != REND_SERVICE_ADDRESS_LEN ||
  950. strcmpend(onion_address, ".onion")) {
  951. log_warn(LD_CONFIG, "Onion address has wrong format: '%s'",
  952. onion_address);
  953. goto err;
  954. }
  955. strlcpy(auth->onion_address, onion_address, REND_SERVICE_ID_LEN_BASE32+1);
  956. if (!rend_valid_service_id(auth->onion_address)) {
  957. log_warn(LD_CONFIG, "Onion address has wrong format: '%s'",
  958. onion_address);
  959. goto err;
  960. }
  961. /* Parse descriptor cookie. */
  962. descriptor_cookie = smartlist_get(sl, 1);
  963. if (strlen(descriptor_cookie) != REND_DESC_COOKIE_LEN_BASE64) {
  964. log_warn(LD_CONFIG, "Authorization cookie has wrong length: '%s'",
  965. descriptor_cookie);
  966. goto err;
  967. }
  968. /* Add trailing zero bytes (AA) to make base64-decoding happy. */
  969. tor_snprintf(descriptor_cookie_base64ext,
  970. REND_DESC_COOKIE_LEN_BASE64+2+1,
  971. "%sAA", descriptor_cookie);
  972. if (base64_decode(descriptor_cookie_tmp, sizeof(descriptor_cookie_tmp),
  973. descriptor_cookie_base64ext,
  974. strlen(descriptor_cookie_base64ext)) < 0) {
  975. log_warn(LD_CONFIG, "Decoding authorization cookie failed: '%s'",
  976. descriptor_cookie);
  977. goto err;
  978. }
  979. auth_type_val = (descriptor_cookie_tmp[16] >> 4) + 1;
  980. if (auth_type_val < 1 || auth_type_val > 2) {
  981. log_warn(LD_CONFIG, "Authorization cookie has unknown authorization "
  982. "type encoded.");
  983. goto err;
  984. }
  985. auth->auth_type = auth_type_val == 1 ? REND_BASIC_AUTH : REND_STEALTH_AUTH;
  986. memcpy(auth->descriptor_cookie, descriptor_cookie_tmp,
  987. REND_DESC_COOKIE_LEN);
  988. if (strmap_get(parsed, auth->onion_address)) {
  989. log_warn(LD_CONFIG, "Duplicate authorization for the same hidden "
  990. "service.");
  991. goto err;
  992. }
  993. strmap_set(parsed, auth->onion_address, auth);
  994. auth = NULL;
  995. }
  996. res = 0;
  997. goto done;
  998. err:
  999. res = -1;
  1000. done:
  1001. rend_service_authorization_free(auth);
  1002. SMARTLIST_FOREACH(sl, char *, c, tor_free(c););
  1003. smartlist_free(sl);
  1004. if (!validate_only && res == 0) {
  1005. rend_service_authorization_free_all();
  1006. auth_hid_servs = parsed;
  1007. } else {
  1008. strmap_free(parsed, rend_service_authorization_strmap_item_free);
  1009. }
  1010. return res;
  1011. }