rendclient.c 41 KB

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