rendclient.c 41 KB

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