rendcommon.c 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503
  1. /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  2. * Copyright (c) 2007-2015, The Tor Project, Inc. */
  3. /* See LICENSE for licensing information */
  4. /**
  5. * \file rendcommon.c
  6. * \brief Rendezvous implementation: shared code between
  7. * introducers, services, clients, and rendezvous points.
  8. **/
  9. #include "or.h"
  10. #include "circuitbuild.h"
  11. #include "config.h"
  12. #include "rendclient.h"
  13. #include "rendcommon.h"
  14. #include "rendmid.h"
  15. #include "rendservice.h"
  16. #include "rephist.h"
  17. #include "routerlist.h"
  18. #include "routerparse.h"
  19. /** Return 0 if one and two are the same service ids, else -1 or 1 */
  20. int
  21. rend_cmp_service_ids(const char *one, const char *two)
  22. {
  23. return strcasecmp(one,two);
  24. }
  25. /** Free the storage held by the service descriptor <b>desc</b>.
  26. */
  27. void
  28. rend_service_descriptor_free(rend_service_descriptor_t *desc)
  29. {
  30. if (!desc)
  31. return;
  32. if (desc->pk)
  33. crypto_pk_free(desc->pk);
  34. if (desc->intro_nodes) {
  35. SMARTLIST_FOREACH(desc->intro_nodes, rend_intro_point_t *, intro,
  36. rend_intro_point_free(intro););
  37. smartlist_free(desc->intro_nodes);
  38. }
  39. if (desc->successful_uploads) {
  40. SMARTLIST_FOREACH(desc->successful_uploads, char *, c, tor_free(c););
  41. smartlist_free(desc->successful_uploads);
  42. }
  43. tor_free(desc);
  44. }
  45. /** Length of the descriptor cookie that is used for versioned hidden
  46. * service descriptors. */
  47. #define REND_DESC_COOKIE_LEN 16
  48. /** Length of the replica number that is used to determine the secret ID
  49. * part of versioned hidden service descriptors. */
  50. #define REND_REPLICA_LEN 1
  51. /** Compute the descriptor ID for <b>service_id</b> of length
  52. * <b>REND_SERVICE_ID_LEN</b> and <b>secret_id_part</b> of length
  53. * <b>DIGEST_LEN</b>, and write it to <b>descriptor_id_out</b> of length
  54. * <b>DIGEST_LEN</b>. */
  55. void
  56. rend_get_descriptor_id_bytes(char *descriptor_id_out,
  57. const char *service_id,
  58. const char *secret_id_part)
  59. {
  60. crypto_digest_t *digest = crypto_digest_new();
  61. crypto_digest_add_bytes(digest, service_id, REND_SERVICE_ID_LEN);
  62. crypto_digest_add_bytes(digest, secret_id_part, DIGEST_LEN);
  63. crypto_digest_get_digest(digest, descriptor_id_out, DIGEST_LEN);
  64. crypto_digest_free(digest);
  65. }
  66. /** Compute the secret ID part for time_period,
  67. * a <b>descriptor_cookie</b> of length
  68. * <b>REND_DESC_COOKIE_LEN</b> which may also be <b>NULL</b> if no
  69. * descriptor_cookie shall be used, and <b>replica</b>, and write it to
  70. * <b>secret_id_part</b> of length DIGEST_LEN. */
  71. static void
  72. get_secret_id_part_bytes(char *secret_id_part, uint32_t time_period,
  73. const char *descriptor_cookie, uint8_t replica)
  74. {
  75. crypto_digest_t *digest = crypto_digest_new();
  76. time_period = htonl(time_period);
  77. crypto_digest_add_bytes(digest, (char*)&time_period, sizeof(uint32_t));
  78. if (descriptor_cookie) {
  79. crypto_digest_add_bytes(digest, descriptor_cookie,
  80. REND_DESC_COOKIE_LEN);
  81. }
  82. crypto_digest_add_bytes(digest, (const char *)&replica, REND_REPLICA_LEN);
  83. crypto_digest_get_digest(digest, secret_id_part, DIGEST_LEN);
  84. crypto_digest_free(digest);
  85. }
  86. /** Return the time period for time <b>now</b> plus a potentially
  87. * intended <b>deviation</b> of one or more periods, based on the first byte
  88. * of <b>service_id</b>. */
  89. static uint32_t
  90. get_time_period(time_t now, uint8_t deviation, const char *service_id)
  91. {
  92. /* The time period is the number of REND_TIME_PERIOD_V2_DESC_VALIDITY
  93. * intervals that have passed since the epoch, offset slightly so that
  94. * each service's time periods start and end at a fraction of that
  95. * period based on their first byte. */
  96. return (uint32_t)
  97. (now + ((uint8_t) *service_id) * REND_TIME_PERIOD_V2_DESC_VALIDITY / 256)
  98. / REND_TIME_PERIOD_V2_DESC_VALIDITY + deviation;
  99. }
  100. /** Compute the time in seconds that a descriptor that is generated
  101. * <b>now</b> for <b>service_id</b> will be valid. */
  102. static uint32_t
  103. get_seconds_valid(time_t now, const char *service_id)
  104. {
  105. uint32_t result = REND_TIME_PERIOD_V2_DESC_VALIDITY -
  106. ((uint32_t)
  107. (now + ((uint8_t) *service_id) * REND_TIME_PERIOD_V2_DESC_VALIDITY / 256)
  108. % REND_TIME_PERIOD_V2_DESC_VALIDITY);
  109. return result;
  110. }
  111. /** Compute the binary <b>desc_id_out</b> (DIGEST_LEN bytes long) for a given
  112. * base32-encoded <b>service_id</b> and optional unencoded
  113. * <b>descriptor_cookie</b> of length REND_DESC_COOKIE_LEN,
  114. * at time <b>now</b> for replica number
  115. * <b>replica</b>. <b>desc_id</b> needs to have <b>DIGEST_LEN</b> bytes
  116. * free. Return 0 for success, -1 otherwise. */
  117. int
  118. rend_compute_v2_desc_id(char *desc_id_out, const char *service_id,
  119. const char *descriptor_cookie, time_t now,
  120. uint8_t replica)
  121. {
  122. char service_id_binary[REND_SERVICE_ID_LEN];
  123. char secret_id_part[DIGEST_LEN];
  124. uint32_t time_period;
  125. if (!service_id ||
  126. strlen(service_id) != REND_SERVICE_ID_LEN_BASE32) {
  127. log_warn(LD_REND, "Could not compute v2 descriptor ID: "
  128. "Illegal service ID: %s",
  129. safe_str(service_id));
  130. return -1;
  131. }
  132. if (replica >= REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS) {
  133. log_warn(LD_REND, "Could not compute v2 descriptor ID: "
  134. "Replica number out of range: %d", replica);
  135. return -1;
  136. }
  137. /* Convert service ID to binary. */
  138. if (base32_decode(service_id_binary, REND_SERVICE_ID_LEN,
  139. service_id, REND_SERVICE_ID_LEN_BASE32) < 0) {
  140. log_warn(LD_REND, "Could not compute v2 descriptor ID: "
  141. "Illegal characters in service ID: %s",
  142. safe_str_client(service_id));
  143. return -1;
  144. }
  145. /* Calculate current time-period. */
  146. time_period = get_time_period(now, 0, service_id_binary);
  147. /* Calculate secret-id-part = h(time-period | replica). */
  148. get_secret_id_part_bytes(secret_id_part, time_period, descriptor_cookie,
  149. replica);
  150. /* Calculate descriptor ID. */
  151. rend_get_descriptor_id_bytes(desc_id_out, service_id_binary, secret_id_part);
  152. return 0;
  153. }
  154. /** Encode the introduction points in <b>desc</b> and write the result to a
  155. * newly allocated string pointed to by <b>encoded</b>. Return 0 for
  156. * success, -1 otherwise. */
  157. static int
  158. rend_encode_v2_intro_points(char **encoded, rend_service_descriptor_t *desc)
  159. {
  160. size_t unenc_len;
  161. char *unenc = NULL;
  162. size_t unenc_written = 0;
  163. int i;
  164. int r = -1;
  165. /* Assemble unencrypted list of introduction points. */
  166. unenc_len = smartlist_len(desc->intro_nodes) * 1000; /* too long, but ok. */
  167. unenc = tor_malloc_zero(unenc_len);
  168. for (i = 0; i < smartlist_len(desc->intro_nodes); i++) {
  169. char id_base32[REND_INTRO_POINT_ID_LEN_BASE32 + 1];
  170. char *onion_key = NULL;
  171. size_t onion_key_len;
  172. crypto_pk_t *intro_key;
  173. char *service_key = NULL;
  174. char *address = NULL;
  175. size_t service_key_len;
  176. int res;
  177. rend_intro_point_t *intro = smartlist_get(desc->intro_nodes, i);
  178. /* Obtain extend info with introduction point details. */
  179. extend_info_t *info = intro->extend_info;
  180. /* Encode introduction point ID. */
  181. base32_encode(id_base32, sizeof(id_base32),
  182. info->identity_digest, DIGEST_LEN);
  183. /* Encode onion key. */
  184. if (crypto_pk_write_public_key_to_string(info->onion_key, &onion_key,
  185. &onion_key_len) < 0) {
  186. log_warn(LD_REND, "Could not write onion key.");
  187. goto done;
  188. }
  189. /* Encode intro key. */
  190. intro_key = intro->intro_key;
  191. if (!intro_key ||
  192. crypto_pk_write_public_key_to_string(intro_key, &service_key,
  193. &service_key_len) < 0) {
  194. log_warn(LD_REND, "Could not write intro key.");
  195. tor_free(onion_key);
  196. goto done;
  197. }
  198. /* Assemble everything for this introduction point. */
  199. address = tor_dup_addr(&info->addr);
  200. res = tor_snprintf(unenc + unenc_written, unenc_len - unenc_written,
  201. "introduction-point %s\n"
  202. "ip-address %s\n"
  203. "onion-port %d\n"
  204. "onion-key\n%s"
  205. "service-key\n%s",
  206. id_base32,
  207. address,
  208. info->port,
  209. onion_key,
  210. service_key);
  211. tor_free(address);
  212. tor_free(onion_key);
  213. tor_free(service_key);
  214. if (res < 0) {
  215. log_warn(LD_REND, "Not enough space for writing introduction point "
  216. "string.");
  217. goto done;
  218. }
  219. /* Update total number of written bytes for unencrypted intro points. */
  220. unenc_written += res;
  221. }
  222. /* Finalize unencrypted introduction points. */
  223. if (unenc_len < unenc_written + 2) {
  224. log_warn(LD_REND, "Not enough space for finalizing introduction point "
  225. "string.");
  226. goto done;
  227. }
  228. unenc[unenc_written++] = '\n';
  229. unenc[unenc_written++] = 0;
  230. *encoded = unenc;
  231. r = 0;
  232. done:
  233. if (r<0)
  234. tor_free(unenc);
  235. return r;
  236. }
  237. /** Encrypt the encoded introduction points in <b>encoded</b> using
  238. * authorization type 'basic' with <b>client_cookies</b> and write the
  239. * result to a newly allocated string pointed to by <b>encrypted_out</b> of
  240. * length <b>encrypted_len_out</b>. Return 0 for success, -1 otherwise. */
  241. static int
  242. rend_encrypt_v2_intro_points_basic(char **encrypted_out,
  243. size_t *encrypted_len_out,
  244. const char *encoded,
  245. smartlist_t *client_cookies)
  246. {
  247. int r = -1, i, pos, enclen, client_blocks;
  248. size_t len, client_entries_len;
  249. char *enc = NULL, iv[CIPHER_IV_LEN], *client_part = NULL,
  250. session_key[CIPHER_KEY_LEN];
  251. smartlist_t *encrypted_session_keys = NULL;
  252. crypto_digest_t *digest;
  253. crypto_cipher_t *cipher;
  254. tor_assert(encoded);
  255. tor_assert(client_cookies && smartlist_len(client_cookies) > 0);
  256. /* Generate session key. */
  257. if (crypto_rand(session_key, CIPHER_KEY_LEN) < 0) {
  258. log_warn(LD_REND, "Unable to generate random session key to encrypt "
  259. "introduction point string.");
  260. goto done;
  261. }
  262. /* Determine length of encrypted introduction points including session
  263. * keys. */
  264. client_blocks = 1 + ((smartlist_len(client_cookies) - 1) /
  265. REND_BASIC_AUTH_CLIENT_MULTIPLE);
  266. client_entries_len = client_blocks * REND_BASIC_AUTH_CLIENT_MULTIPLE *
  267. REND_BASIC_AUTH_CLIENT_ENTRY_LEN;
  268. len = 2 + client_entries_len + CIPHER_IV_LEN + strlen(encoded);
  269. if (client_blocks >= 256) {
  270. log_warn(LD_REND, "Too many clients in introduction point string.");
  271. goto done;
  272. }
  273. enc = tor_malloc_zero(len);
  274. enc[0] = 0x01; /* type of authorization. */
  275. enc[1] = (uint8_t)client_blocks;
  276. /* Encrypt with random session key. */
  277. enclen = crypto_cipher_encrypt_with_iv(session_key,
  278. enc + 2 + client_entries_len,
  279. CIPHER_IV_LEN + strlen(encoded), encoded, strlen(encoded));
  280. if (enclen < 0) {
  281. log_warn(LD_REND, "Could not encrypt introduction point string.");
  282. goto done;
  283. }
  284. memcpy(iv, enc + 2 + client_entries_len, CIPHER_IV_LEN);
  285. /* Encrypt session key for cookies, determine client IDs, and put both
  286. * in a smartlist. */
  287. encrypted_session_keys = smartlist_new();
  288. SMARTLIST_FOREACH_BEGIN(client_cookies, const char *, cookie) {
  289. client_part = tor_malloc_zero(REND_BASIC_AUTH_CLIENT_ENTRY_LEN);
  290. /* Encrypt session key. */
  291. cipher = crypto_cipher_new(cookie);
  292. if (crypto_cipher_encrypt(cipher, client_part +
  293. REND_BASIC_AUTH_CLIENT_ID_LEN,
  294. session_key, CIPHER_KEY_LEN) < 0) {
  295. log_warn(LD_REND, "Could not encrypt session key for client.");
  296. crypto_cipher_free(cipher);
  297. tor_free(client_part);
  298. goto done;
  299. }
  300. crypto_cipher_free(cipher);
  301. /* Determine client ID. */
  302. digest = crypto_digest_new();
  303. crypto_digest_add_bytes(digest, cookie, REND_DESC_COOKIE_LEN);
  304. crypto_digest_add_bytes(digest, iv, CIPHER_IV_LEN);
  305. crypto_digest_get_digest(digest, client_part,
  306. REND_BASIC_AUTH_CLIENT_ID_LEN);
  307. crypto_digest_free(digest);
  308. /* Put both together. */
  309. smartlist_add(encrypted_session_keys, client_part);
  310. } SMARTLIST_FOREACH_END(cookie);
  311. /* Add some fake client IDs and encrypted session keys. */
  312. for (i = (smartlist_len(client_cookies) - 1) %
  313. REND_BASIC_AUTH_CLIENT_MULTIPLE;
  314. i < REND_BASIC_AUTH_CLIENT_MULTIPLE - 1; i++) {
  315. client_part = tor_malloc_zero(REND_BASIC_AUTH_CLIENT_ENTRY_LEN);
  316. if (crypto_rand(client_part, REND_BASIC_AUTH_CLIENT_ENTRY_LEN) < 0) {
  317. log_warn(LD_REND, "Unable to generate fake client entry.");
  318. tor_free(client_part);
  319. goto done;
  320. }
  321. smartlist_add(encrypted_session_keys, client_part);
  322. }
  323. /* Sort smartlist and put elements in result in order. */
  324. smartlist_sort_digests(encrypted_session_keys);
  325. pos = 2;
  326. SMARTLIST_FOREACH(encrypted_session_keys, const char *, entry, {
  327. memcpy(enc + pos, entry, REND_BASIC_AUTH_CLIENT_ENTRY_LEN);
  328. pos += REND_BASIC_AUTH_CLIENT_ENTRY_LEN;
  329. });
  330. *encrypted_out = enc;
  331. *encrypted_len_out = len;
  332. enc = NULL; /* prevent free. */
  333. r = 0;
  334. done:
  335. tor_free(enc);
  336. if (encrypted_session_keys) {
  337. SMARTLIST_FOREACH(encrypted_session_keys, char *, d, tor_free(d););
  338. smartlist_free(encrypted_session_keys);
  339. }
  340. return r;
  341. }
  342. /** Encrypt the encoded introduction points in <b>encoded</b> using
  343. * authorization type 'stealth' with <b>descriptor_cookie</b> of length
  344. * REND_DESC_COOKIE_LEN and write the result to a newly allocated string
  345. * pointed to by <b>encrypted_out</b> of length <b>encrypted_len_out</b>.
  346. * Return 0 for success, -1 otherwise. */
  347. static int
  348. rend_encrypt_v2_intro_points_stealth(char **encrypted_out,
  349. size_t *encrypted_len_out,
  350. const char *encoded,
  351. const char *descriptor_cookie)
  352. {
  353. int r = -1, enclen;
  354. char *enc;
  355. tor_assert(encoded);
  356. tor_assert(descriptor_cookie);
  357. enc = tor_malloc_zero(1 + CIPHER_IV_LEN + strlen(encoded));
  358. enc[0] = 0x02; /* Auth type */
  359. enclen = crypto_cipher_encrypt_with_iv(descriptor_cookie,
  360. enc + 1,
  361. CIPHER_IV_LEN+strlen(encoded),
  362. encoded, strlen(encoded));
  363. if (enclen < 0) {
  364. log_warn(LD_REND, "Could not encrypt introduction point string.");
  365. goto done;
  366. }
  367. *encrypted_out = enc;
  368. *encrypted_len_out = enclen;
  369. enc = NULL; /* prevent free */
  370. r = 0;
  371. done:
  372. tor_free(enc);
  373. return r;
  374. }
  375. /** Attempt to parse the given <b>desc_str</b> and return true if this
  376. * succeeds, false otherwise. */
  377. static int
  378. rend_desc_v2_is_parsable(rend_encoded_v2_service_descriptor_t *desc)
  379. {
  380. rend_service_descriptor_t *test_parsed = NULL;
  381. char test_desc_id[DIGEST_LEN];
  382. char *test_intro_content = NULL;
  383. size_t test_intro_size;
  384. size_t test_encoded_size;
  385. const char *test_next;
  386. int res = rend_parse_v2_service_descriptor(&test_parsed, test_desc_id,
  387. &test_intro_content,
  388. &test_intro_size,
  389. &test_encoded_size,
  390. &test_next, desc->desc_str, 1);
  391. rend_service_descriptor_free(test_parsed);
  392. tor_free(test_intro_content);
  393. return (res >= 0);
  394. }
  395. /** Free the storage held by an encoded v2 service descriptor. */
  396. void
  397. rend_encoded_v2_service_descriptor_free(
  398. rend_encoded_v2_service_descriptor_t *desc)
  399. {
  400. if (!desc)
  401. return;
  402. tor_free(desc->desc_str);
  403. tor_free(desc);
  404. }
  405. /** Free the storage held by an introduction point info. */
  406. void
  407. rend_intro_point_free(rend_intro_point_t *intro)
  408. {
  409. if (!intro)
  410. return;
  411. extend_info_free(intro->extend_info);
  412. crypto_pk_free(intro->intro_key);
  413. if (intro->accepted_intro_rsa_parts != NULL) {
  414. replaycache_free(intro->accepted_intro_rsa_parts);
  415. }
  416. tor_free(intro);
  417. }
  418. /** Encode a set of rend_encoded_v2_service_descriptor_t's for <b>desc</b>
  419. * at time <b>now</b> using <b>service_key</b>, depending on
  420. * <b>auth_type</b> a <b>descriptor_cookie</b> and a list of
  421. * <b>client_cookies</b> (which are both <b>NULL</b> if no client
  422. * authorization is performed), and <b>period</b> (e.g. 0 for the current
  423. * period, 1 for the next period, etc.) and add them to the existing list
  424. * <b>descs_out</b>; return the number of seconds that the descriptors will
  425. * be found by clients, or -1 if the encoding was not successful. */
  426. int
  427. rend_encode_v2_descriptors(smartlist_t *descs_out,
  428. rend_service_descriptor_t *desc, time_t now,
  429. uint8_t period, rend_auth_type_t auth_type,
  430. crypto_pk_t *client_key,
  431. smartlist_t *client_cookies)
  432. {
  433. char service_id[DIGEST_LEN];
  434. uint32_t time_period;
  435. char *ipos_base64 = NULL, *ipos = NULL, *ipos_encrypted = NULL,
  436. *descriptor_cookie = NULL;
  437. size_t ipos_len = 0, ipos_encrypted_len = 0;
  438. int k;
  439. uint32_t seconds_valid;
  440. crypto_pk_t *service_key;
  441. if (!desc) {
  442. log_warn(LD_BUG, "Could not encode v2 descriptor: No desc given.");
  443. return -1;
  444. }
  445. service_key = (auth_type == REND_STEALTH_AUTH) ? client_key : desc->pk;
  446. tor_assert(service_key);
  447. if (auth_type == REND_STEALTH_AUTH) {
  448. descriptor_cookie = smartlist_get(client_cookies, 0);
  449. tor_assert(descriptor_cookie);
  450. }
  451. /* Obtain service_id from public key. */
  452. crypto_pk_get_digest(service_key, service_id);
  453. /* Calculate current time-period. */
  454. time_period = get_time_period(now, period, service_id);
  455. /* Determine how many seconds the descriptor will be valid. */
  456. seconds_valid = period * REND_TIME_PERIOD_V2_DESC_VALIDITY +
  457. get_seconds_valid(now, service_id);
  458. /* Assemble, possibly encrypt, and encode introduction points. */
  459. if (smartlist_len(desc->intro_nodes) > 0) {
  460. if (rend_encode_v2_intro_points(&ipos, desc) < 0) {
  461. log_warn(LD_REND, "Encoding of introduction points did not succeed.");
  462. return -1;
  463. }
  464. switch (auth_type) {
  465. case REND_NO_AUTH:
  466. ipos_len = strlen(ipos);
  467. break;
  468. case REND_BASIC_AUTH:
  469. if (rend_encrypt_v2_intro_points_basic(&ipos_encrypted,
  470. &ipos_encrypted_len, ipos,
  471. client_cookies) < 0) {
  472. log_warn(LD_REND, "Encrypting of introduction points did not "
  473. "succeed.");
  474. tor_free(ipos);
  475. return -1;
  476. }
  477. tor_free(ipos);
  478. ipos = ipos_encrypted;
  479. ipos_len = ipos_encrypted_len;
  480. break;
  481. case REND_STEALTH_AUTH:
  482. if (rend_encrypt_v2_intro_points_stealth(&ipos_encrypted,
  483. &ipos_encrypted_len, ipos,
  484. descriptor_cookie) < 0) {
  485. log_warn(LD_REND, "Encrypting of introduction points did not "
  486. "succeed.");
  487. tor_free(ipos);
  488. return -1;
  489. }
  490. tor_free(ipos);
  491. ipos = ipos_encrypted;
  492. ipos_len = ipos_encrypted_len;
  493. break;
  494. default:
  495. log_warn(LD_REND|LD_BUG, "Unrecognized authorization type %d",
  496. (int)auth_type);
  497. tor_free(ipos);
  498. return -1;
  499. }
  500. /* Base64-encode introduction points. */
  501. ipos_base64 = tor_calloc(ipos_len, 2);
  502. if (base64_encode(ipos_base64, ipos_len * 2, ipos, ipos_len,
  503. BASE64_ENCODE_MULTILINE)<0) {
  504. log_warn(LD_REND, "Could not encode introduction point string to "
  505. "base64. length=%d", (int)ipos_len);
  506. tor_free(ipos_base64);
  507. tor_free(ipos);
  508. return -1;
  509. }
  510. tor_free(ipos);
  511. }
  512. /* Encode REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS descriptors. */
  513. for (k = 0; k < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS; k++) {
  514. char secret_id_part[DIGEST_LEN];
  515. char secret_id_part_base32[REND_SECRET_ID_PART_LEN_BASE32 + 1];
  516. char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  517. char *permanent_key = NULL;
  518. size_t permanent_key_len;
  519. char published[ISO_TIME_LEN+1];
  520. int i;
  521. char protocol_versions_string[16]; /* max len: "0,1,2,3,4,5,6,7\0" */
  522. size_t protocol_versions_written;
  523. size_t desc_len;
  524. char *desc_str = NULL;
  525. int result = 0;
  526. size_t written = 0;
  527. char desc_digest[DIGEST_LEN];
  528. rend_encoded_v2_service_descriptor_t *enc =
  529. tor_malloc_zero(sizeof(rend_encoded_v2_service_descriptor_t));
  530. /* Calculate secret-id-part = h(time-period | cookie | replica). */
  531. get_secret_id_part_bytes(secret_id_part, time_period, descriptor_cookie,
  532. k);
  533. base32_encode(secret_id_part_base32, sizeof(secret_id_part_base32),
  534. secret_id_part, DIGEST_LEN);
  535. /* Calculate descriptor ID. */
  536. rend_get_descriptor_id_bytes(enc->desc_id, service_id, secret_id_part);
  537. base32_encode(desc_id_base32, sizeof(desc_id_base32),
  538. enc->desc_id, DIGEST_LEN);
  539. /* PEM-encode the public key */
  540. if (crypto_pk_write_public_key_to_string(service_key, &permanent_key,
  541. &permanent_key_len) < 0) {
  542. log_warn(LD_BUG, "Could not write public key to string.");
  543. rend_encoded_v2_service_descriptor_free(enc);
  544. goto err;
  545. }
  546. /* Encode timestamp. */
  547. format_iso_time(published, desc->timestamp);
  548. /* Write protocol-versions bitmask to comma-separated value string. */
  549. protocol_versions_written = 0;
  550. for (i = 0; i < 8; i++) {
  551. if (desc->protocols & 1 << i) {
  552. tor_snprintf(protocol_versions_string + protocol_versions_written,
  553. 16 - protocol_versions_written, "%d,", i);
  554. protocol_versions_written += 2;
  555. }
  556. }
  557. if (protocol_versions_written)
  558. protocol_versions_string[protocol_versions_written - 1] = '\0';
  559. else
  560. protocol_versions_string[0]= '\0';
  561. /* Assemble complete descriptor. */
  562. desc_len = 2000 + smartlist_len(desc->intro_nodes) * 1000; /* far too long,
  563. but okay.*/
  564. enc->desc_str = desc_str = tor_malloc_zero(desc_len);
  565. result = tor_snprintf(desc_str, desc_len,
  566. "rendezvous-service-descriptor %s\n"
  567. "version 2\n"
  568. "permanent-key\n%s"
  569. "secret-id-part %s\n"
  570. "publication-time %s\n"
  571. "protocol-versions %s\n",
  572. desc_id_base32,
  573. permanent_key,
  574. secret_id_part_base32,
  575. published,
  576. protocol_versions_string);
  577. tor_free(permanent_key);
  578. if (result < 0) {
  579. log_warn(LD_BUG, "Descriptor ran out of room.");
  580. rend_encoded_v2_service_descriptor_free(enc);
  581. goto err;
  582. }
  583. written = result;
  584. /* Add introduction points. */
  585. if (ipos_base64) {
  586. result = tor_snprintf(desc_str + written, desc_len - written,
  587. "introduction-points\n"
  588. "-----BEGIN MESSAGE-----\n%s"
  589. "-----END MESSAGE-----\n",
  590. ipos_base64);
  591. if (result < 0) {
  592. log_warn(LD_BUG, "could not write introduction points.");
  593. rend_encoded_v2_service_descriptor_free(enc);
  594. goto err;
  595. }
  596. written += result;
  597. }
  598. /* Add signature. */
  599. strlcpy(desc_str + written, "signature\n", desc_len - written);
  600. written += strlen(desc_str + written);
  601. if (crypto_digest(desc_digest, desc_str, written) < 0) {
  602. log_warn(LD_BUG, "could not create digest.");
  603. rend_encoded_v2_service_descriptor_free(enc);
  604. goto err;
  605. }
  606. if (router_append_dirobj_signature(desc_str + written,
  607. desc_len - written,
  608. desc_digest, DIGEST_LEN,
  609. service_key) < 0) {
  610. log_warn(LD_BUG, "Couldn't sign desc.");
  611. rend_encoded_v2_service_descriptor_free(enc);
  612. goto err;
  613. }
  614. written += strlen(desc_str+written);
  615. if (written+2 > desc_len) {
  616. log_warn(LD_BUG, "Could not finish desc.");
  617. rend_encoded_v2_service_descriptor_free(enc);
  618. goto err;
  619. }
  620. desc_str[written++] = 0;
  621. /* Check if we can parse our own descriptor. */
  622. if (!rend_desc_v2_is_parsable(enc)) {
  623. log_warn(LD_BUG, "Could not parse my own descriptor: %s", desc_str);
  624. rend_encoded_v2_service_descriptor_free(enc);
  625. goto err;
  626. }
  627. smartlist_add(descs_out, enc);
  628. }
  629. log_info(LD_REND, "Successfully encoded a v2 descriptor and "
  630. "confirmed that it is parsable.");
  631. goto done;
  632. err:
  633. SMARTLIST_FOREACH(descs_out, rend_encoded_v2_service_descriptor_t *, d,
  634. rend_encoded_v2_service_descriptor_free(d););
  635. smartlist_clear(descs_out);
  636. seconds_valid = -1;
  637. done:
  638. tor_free(ipos_base64);
  639. return seconds_valid;
  640. }
  641. /** Sets <b>out</b> to the first 10 bytes of the digest of <b>pk</b>,
  642. * base32 encoded. NUL-terminates out. (We use this string to
  643. * identify services in directory requests and .onion URLs.)
  644. */
  645. int
  646. rend_get_service_id(crypto_pk_t *pk, char *out)
  647. {
  648. char buf[DIGEST_LEN];
  649. tor_assert(pk);
  650. if (crypto_pk_get_digest(pk, buf) < 0)
  651. return -1;
  652. base32_encode(out, REND_SERVICE_ID_LEN_BASE32+1, buf, REND_SERVICE_ID_LEN);
  653. return 0;
  654. }
  655. /* ==== Rendezvous service descriptor cache. */
  656. /** How old do we let hidden service descriptors get before discarding
  657. * them as too old? */
  658. #define REND_CACHE_MAX_AGE (2*24*60*60)
  659. /** How wrong do we assume our clock may be when checking whether hidden
  660. * services are too old or too new? */
  661. #define REND_CACHE_MAX_SKEW (24*60*60)
  662. /** Map from service id (as generated by rend_get_service_id) to
  663. * rend_cache_entry_t. */
  664. static strmap_t *rend_cache = NULL;
  665. /** Map from descriptor id to rend_cache_entry_t; only for hidden service
  666. * directories. */
  667. static digestmap_t *rend_cache_v2_dir = NULL;
  668. /** DOCDOC */
  669. static size_t rend_cache_total_allocation = 0;
  670. /** Initializes the service descriptor cache.
  671. */
  672. void
  673. rend_cache_init(void)
  674. {
  675. rend_cache = strmap_new();
  676. rend_cache_v2_dir = digestmap_new();
  677. }
  678. /** Return the approximate number of bytes needed to hold <b>e</b>. */
  679. static size_t
  680. rend_cache_entry_allocation(const rend_cache_entry_t *e)
  681. {
  682. if (!e)
  683. return 0;
  684. /* This doesn't count intro_nodes or key size */
  685. return sizeof(*e) + e->len + sizeof(*e->parsed);
  686. }
  687. /** DOCDOC */
  688. size_t
  689. rend_cache_get_total_allocation(void)
  690. {
  691. return rend_cache_total_allocation;
  692. }
  693. /** Decrement the total bytes attributed to the rendezvous cache by n. */
  694. static void
  695. rend_cache_decrement_allocation(size_t n)
  696. {
  697. static int have_underflowed = 0;
  698. if (rend_cache_total_allocation >= n) {
  699. rend_cache_total_allocation -= n;
  700. } else {
  701. rend_cache_total_allocation = 0;
  702. if (! have_underflowed) {
  703. have_underflowed = 1;
  704. log_warn(LD_BUG, "Underflow in rend_cache_decrement_allocation");
  705. }
  706. }
  707. }
  708. /** Increase the total bytes attributed to the rendezvous cache by n. */
  709. static void
  710. rend_cache_increment_allocation(size_t n)
  711. {
  712. static int have_overflowed = 0;
  713. if (rend_cache_total_allocation <= SIZE_MAX - n) {
  714. rend_cache_total_allocation += n;
  715. } else {
  716. rend_cache_total_allocation = SIZE_MAX;
  717. if (! have_overflowed) {
  718. have_overflowed = 1;
  719. log_warn(LD_BUG, "Overflow in rend_cache_increment_allocation");
  720. }
  721. }
  722. }
  723. /** Helper: free storage held by a single service descriptor cache entry. */
  724. static void
  725. rend_cache_entry_free(rend_cache_entry_t *e)
  726. {
  727. if (!e)
  728. return;
  729. rend_cache_decrement_allocation(rend_cache_entry_allocation(e));
  730. rend_service_descriptor_free(e->parsed);
  731. tor_free(e->desc);
  732. tor_free(e);
  733. }
  734. /** Helper: deallocate a rend_cache_entry_t. (Used with strmap_free(), which
  735. * requires a function pointer whose argument is void*). */
  736. static void
  737. rend_cache_entry_free_(void *p)
  738. {
  739. rend_cache_entry_free(p);
  740. }
  741. /** Free all storage held by the service descriptor cache. */
  742. void
  743. rend_cache_free_all(void)
  744. {
  745. strmap_free(rend_cache, rend_cache_entry_free_);
  746. digestmap_free(rend_cache_v2_dir, rend_cache_entry_free_);
  747. rend_cache = NULL;
  748. rend_cache_v2_dir = NULL;
  749. rend_cache_total_allocation = 0;
  750. }
  751. /** Removes all old entries from the service descriptor cache.
  752. */
  753. void
  754. rend_cache_clean(time_t now)
  755. {
  756. strmap_iter_t *iter;
  757. const char *key;
  758. void *val;
  759. rend_cache_entry_t *ent;
  760. time_t cutoff = now - REND_CACHE_MAX_AGE - REND_CACHE_MAX_SKEW;
  761. for (iter = strmap_iter_init(rend_cache); !strmap_iter_done(iter); ) {
  762. strmap_iter_get(iter, &key, &val);
  763. ent = (rend_cache_entry_t*)val;
  764. if (ent->parsed->timestamp < cutoff) {
  765. iter = strmap_iter_next_rmv(rend_cache, iter);
  766. rend_cache_entry_free(ent);
  767. } else {
  768. iter = strmap_iter_next(rend_cache, iter);
  769. }
  770. }
  771. }
  772. /** Remove ALL entries from the rendezvous service descriptor cache.
  773. */
  774. void
  775. rend_cache_purge(void)
  776. {
  777. if (rend_cache) {
  778. log_info(LD_REND, "Purging HS descriptor cache");
  779. strmap_free(rend_cache, rend_cache_entry_free_);
  780. }
  781. rend_cache = strmap_new();
  782. }
  783. /** Remove all old v2 descriptors and those for which this hidden service
  784. * directory is not responsible for any more.
  785. *
  786. * If at all possible, remove at least <b>force_remove</b> bytes of data.
  787. */
  788. void
  789. rend_cache_clean_v2_descs_as_dir(time_t now, size_t force_remove)
  790. {
  791. digestmap_iter_t *iter;
  792. time_t cutoff = now - REND_CACHE_MAX_AGE - REND_CACHE_MAX_SKEW;
  793. const int LAST_SERVED_CUTOFF_STEP = 1800;
  794. time_t last_served_cutoff = cutoff;
  795. size_t bytes_removed = 0;
  796. do {
  797. for (iter = digestmap_iter_init(rend_cache_v2_dir);
  798. !digestmap_iter_done(iter); ) {
  799. const char *key;
  800. void *val;
  801. rend_cache_entry_t *ent;
  802. digestmap_iter_get(iter, &key, &val);
  803. ent = val;
  804. if (ent->parsed->timestamp < cutoff ||
  805. ent->last_served < last_served_cutoff ||
  806. !hid_serv_responsible_for_desc_id(key)) {
  807. char key_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  808. base32_encode(key_base32, sizeof(key_base32), key, DIGEST_LEN);
  809. log_info(LD_REND, "Removing descriptor with ID '%s' from cache",
  810. safe_str_client(key_base32));
  811. bytes_removed += rend_cache_entry_allocation(ent);
  812. iter = digestmap_iter_next_rmv(rend_cache_v2_dir, iter);
  813. rend_cache_entry_free(ent);
  814. } else {
  815. iter = digestmap_iter_next(rend_cache_v2_dir, iter);
  816. }
  817. }
  818. /* In case we didn't remove enough bytes, advance the cutoff a little. */
  819. last_served_cutoff += LAST_SERVED_CUTOFF_STEP;
  820. if (last_served_cutoff > now)
  821. break;
  822. } while (bytes_removed < force_remove);
  823. }
  824. /** Determines whether <b>a</b> is in the interval of <b>b</b> (excluded) and
  825. * <b>c</b> (included) in a circular digest ring; returns 1 if this is the
  826. * case, and 0 otherwise.
  827. */
  828. int
  829. rend_id_is_in_interval(const char *a, const char *b, const char *c)
  830. {
  831. int a_b, b_c, c_a;
  832. tor_assert(a);
  833. tor_assert(b);
  834. tor_assert(c);
  835. /* There are five cases in which a is outside the interval ]b,c]: */
  836. a_b = tor_memcmp(a,b,DIGEST_LEN);
  837. if (a_b == 0)
  838. return 0; /* 1. a == b (b is excluded) */
  839. b_c = tor_memcmp(b,c,DIGEST_LEN);
  840. if (b_c == 0)
  841. return 0; /* 2. b == c (interval is empty) */
  842. else if (a_b <= 0 && b_c < 0)
  843. return 0; /* 3. a b c */
  844. c_a = tor_memcmp(c,a,DIGEST_LEN);
  845. if (c_a < 0 && a_b <= 0)
  846. return 0; /* 4. c a b */
  847. else if (b_c < 0 && c_a < 0)
  848. return 0; /* 5. b c a */
  849. /* In the other cases (a c b; b a c; c b a), a is inside the interval. */
  850. return 1;
  851. }
  852. /** Return true iff <b>query</b> is a syntactically valid service ID (as
  853. * generated by rend_get_service_id). */
  854. int
  855. rend_valid_service_id(const char *query)
  856. {
  857. if (strlen(query) != REND_SERVICE_ID_LEN_BASE32)
  858. return 0;
  859. if (strspn(query, BASE32_CHARS) != REND_SERVICE_ID_LEN_BASE32)
  860. return 0;
  861. return 1;
  862. }
  863. /** Return true iff <b>query</b> is a syntactically valid descriptor ID.
  864. * (as generated by rend_get_descriptor_id_bytes). */
  865. int
  866. rend_valid_descriptor_id(const char *query)
  867. {
  868. if (strlen(query) != REND_DESC_ID_V2_LEN_BASE32) {
  869. goto invalid;
  870. }
  871. if (strspn(query, BASE32_CHARS) != REND_DESC_ID_V2_LEN_BASE32) {
  872. goto invalid;
  873. }
  874. return 1;
  875. invalid:
  876. return 0;
  877. }
  878. /** Lookup in the client cache the given service ID <b>query</b> for
  879. * <b>version</b>.
  880. *
  881. * Return 0 if found and if <b>e</b> is non NULL, set it with the entry
  882. * found. Else, a negative value is returned and <b>e</b> is untouched.
  883. * -EINVAL means that <b>query</b> is not a valid service id.
  884. * -ENOENT means that no entry in the cache was found. */
  885. int
  886. rend_cache_lookup_entry(const char *query, int version, rend_cache_entry_t **e)
  887. {
  888. int ret = 0;
  889. char key[REND_SERVICE_ID_LEN_BASE32 + 2]; /* <version><query>\0 */
  890. rend_cache_entry_t *entry = NULL;
  891. static const int default_version = 2;
  892. tor_assert(rend_cache);
  893. tor_assert(query);
  894. if (!rend_valid_service_id(query)) {
  895. ret = -EINVAL;
  896. goto end;
  897. }
  898. switch (version) {
  899. case 0:
  900. log_warn(LD_REND, "Cache lookup of a v0 renddesc is deprecated.");
  901. break;
  902. case 2:
  903. /* Default is version 2. */
  904. default:
  905. tor_snprintf(key, sizeof(key), "%d%s", default_version, query);
  906. entry = strmap_get_lc(rend_cache, key);
  907. break;
  908. }
  909. if (!entry) {
  910. ret = -ENOENT;
  911. goto end;
  912. }
  913. tor_assert(entry->parsed && entry->parsed->intro_nodes);
  914. if (e) {
  915. *e = entry;
  916. }
  917. end:
  918. return ret;
  919. }
  920. /** Lookup the v2 service descriptor with base32-encoded <b>desc_id</b> and
  921. * copy the pointer to it to *<b>desc</b>. Return 1 on success, 0 on
  922. * well-formed-but-not-found, and -1 on failure.
  923. */
  924. int
  925. rend_cache_lookup_v2_desc_as_dir(const char *desc_id, const char **desc)
  926. {
  927. rend_cache_entry_t *e;
  928. char desc_id_digest[DIGEST_LEN];
  929. tor_assert(rend_cache_v2_dir);
  930. if (base32_decode(desc_id_digest, DIGEST_LEN,
  931. desc_id, REND_DESC_ID_V2_LEN_BASE32) < 0) {
  932. log_fn(LOG_PROTOCOL_WARN, LD_REND,
  933. "Rejecting v2 rendezvous descriptor request -- descriptor ID "
  934. "contains illegal characters: %s",
  935. safe_str(desc_id));
  936. return -1;
  937. }
  938. /* Lookup descriptor and return. */
  939. e = digestmap_get(rend_cache_v2_dir, desc_id_digest);
  940. if (e) {
  941. *desc = e->desc;
  942. e->last_served = approx_time();
  943. return 1;
  944. }
  945. return 0;
  946. }
  947. /* Do not allow more than this many introduction points in a hidden service
  948. * descriptor */
  949. #define MAX_INTRO_POINTS 10
  950. /** Parse the v2 service descriptor(s) in <b>desc</b> and store it/them to the
  951. * local rend cache. Don't attempt to decrypt the included list of introduction
  952. * points (as we don't have a descriptor cookie for it).
  953. *
  954. * If we have a newer descriptor with the same ID, ignore this one.
  955. * If we have an older descriptor with the same ID, replace it.
  956. *
  957. * Return an appropriate rend_cache_store_status_t.
  958. */
  959. rend_cache_store_status_t
  960. rend_cache_store_v2_desc_as_dir(const char *desc)
  961. {
  962. const or_options_t *options = get_options();
  963. rend_service_descriptor_t *parsed;
  964. char desc_id[DIGEST_LEN];
  965. char *intro_content;
  966. size_t intro_size;
  967. size_t encoded_size;
  968. char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  969. int number_parsed = 0, number_stored = 0;
  970. const char *current_desc = desc;
  971. const char *next_desc;
  972. rend_cache_entry_t *e;
  973. time_t now = time(NULL);
  974. tor_assert(rend_cache_v2_dir);
  975. tor_assert(desc);
  976. if (!hid_serv_acting_as_directory()) {
  977. /* Cannot store descs, because we are (currently) not acting as
  978. * hidden service directory. */
  979. log_info(LD_REND, "Cannot store descs: Not acting as hs dir");
  980. return RCS_NOTDIR;
  981. }
  982. while (rend_parse_v2_service_descriptor(&parsed, desc_id, &intro_content,
  983. &intro_size, &encoded_size,
  984. &next_desc, current_desc, 1) >= 0) {
  985. number_parsed++;
  986. /* We don't care about the introduction points. */
  987. tor_free(intro_content);
  988. /* For pretty log statements. */
  989. base32_encode(desc_id_base32, sizeof(desc_id_base32),
  990. desc_id, DIGEST_LEN);
  991. /* Is desc ID in the range that we are (directly or indirectly) responsible
  992. * for? */
  993. if (!hid_serv_responsible_for_desc_id(desc_id)) {
  994. log_info(LD_REND, "Service descriptor with desc ID %s is not in "
  995. "interval that we are responsible for.",
  996. safe_str_client(desc_id_base32));
  997. goto skip;
  998. }
  999. /* Is descriptor too old? */
  1000. if (parsed->timestamp < now - REND_CACHE_MAX_AGE-REND_CACHE_MAX_SKEW) {
  1001. log_info(LD_REND, "Service descriptor with desc ID %s is too old.",
  1002. safe_str(desc_id_base32));
  1003. goto skip;
  1004. }
  1005. /* Is descriptor too far in the future? */
  1006. if (parsed->timestamp > now + REND_CACHE_MAX_SKEW) {
  1007. log_info(LD_REND, "Service descriptor with desc ID %s is too far in the "
  1008. "future.",
  1009. safe_str(desc_id_base32));
  1010. goto skip;
  1011. }
  1012. /* Do we already have a newer descriptor? */
  1013. e = digestmap_get(rend_cache_v2_dir, desc_id);
  1014. if (e && e->parsed->timestamp > parsed->timestamp) {
  1015. log_info(LD_REND, "We already have a newer service descriptor with the "
  1016. "same desc ID %s and version.",
  1017. safe_str(desc_id_base32));
  1018. goto skip;
  1019. }
  1020. /* Do we already have this descriptor? */
  1021. if (e && !strcmp(desc, e->desc)) {
  1022. log_info(LD_REND, "We already have this service descriptor with desc "
  1023. "ID %s.", safe_str(desc_id_base32));
  1024. goto skip;
  1025. }
  1026. /* Store received descriptor. */
  1027. if (!e) {
  1028. e = tor_malloc_zero(sizeof(rend_cache_entry_t));
  1029. digestmap_set(rend_cache_v2_dir, desc_id, e);
  1030. /* Treat something just uploaded as having been served a little
  1031. * while ago, so that flooding with new descriptors doesn't help
  1032. * too much.
  1033. */
  1034. e->last_served = approx_time() - 3600;
  1035. } else {
  1036. rend_cache_decrement_allocation(rend_cache_entry_allocation(e));
  1037. rend_service_descriptor_free(e->parsed);
  1038. tor_free(e->desc);
  1039. }
  1040. e->parsed = parsed;
  1041. e->desc = tor_strndup(current_desc, encoded_size);
  1042. e->len = encoded_size;
  1043. rend_cache_increment_allocation(rend_cache_entry_allocation(e));
  1044. log_info(LD_REND, "Successfully stored service descriptor with desc ID "
  1045. "'%s' and len %d.",
  1046. safe_str(desc_id_base32), (int)encoded_size);
  1047. /* Statistics: Note down this potentially new HS. */
  1048. if (options->HiddenServiceStatistics) {
  1049. rep_hist_stored_maybe_new_hs(e->parsed->pk);
  1050. }
  1051. number_stored++;
  1052. goto advance;
  1053. skip:
  1054. rend_service_descriptor_free(parsed);
  1055. advance:
  1056. /* advance to next descriptor, if available. */
  1057. current_desc = next_desc;
  1058. /* check if there is a next descriptor. */
  1059. if (!current_desc ||
  1060. strcmpstart(current_desc, "rendezvous-service-descriptor "))
  1061. break;
  1062. }
  1063. if (!number_parsed) {
  1064. log_info(LD_REND, "Could not parse any descriptor.");
  1065. return RCS_BADDESC;
  1066. }
  1067. log_info(LD_REND, "Parsed %d and added %d descriptor%s.",
  1068. number_parsed, number_stored, number_stored != 1 ? "s" : "");
  1069. return RCS_OKAY;
  1070. }
  1071. /** Parse the v2 service descriptor in <b>desc</b>, decrypt the included list
  1072. * of introduction points with <b>descriptor_cookie</b> (which may also be
  1073. * <b>NULL</b> if decryption is not necessary), and store the descriptor to
  1074. * the local cache under its version and service id.
  1075. *
  1076. * If we have a newer v2 descriptor with the same ID, ignore this one.
  1077. * If we have an older descriptor with the same ID, replace it.
  1078. * If the descriptor's service ID does not match
  1079. * <b>rend_query</b>-\>onion_address, reject it.
  1080. *
  1081. * If the descriptor's descriptor ID doesn't match <b>desc_id_base32</b>,
  1082. * reject it.
  1083. *
  1084. * Return an appropriate rend_cache_store_status_t. If entry is not NULL,
  1085. * set it with the cache entry pointer of the descriptor.
  1086. */
  1087. rend_cache_store_status_t
  1088. rend_cache_store_v2_desc_as_client(const char *desc,
  1089. const char *desc_id_base32,
  1090. const rend_data_t *rend_query,
  1091. rend_cache_entry_t **entry)
  1092. {
  1093. /*XXXX this seems to have a bit of duplicate code with
  1094. * rend_cache_store_v2_desc_as_dir(). Fix that. */
  1095. /* Though having similar elements, both functions were separated on
  1096. * purpose:
  1097. * - dirs don't care about encoded/encrypted introduction points, clients
  1098. * do.
  1099. * - dirs store descriptors in a separate cache by descriptor ID, whereas
  1100. * clients store them by service ID; both caches are different data
  1101. * structures and have different access methods.
  1102. * - dirs store a descriptor only if they are responsible for its ID,
  1103. * clients do so in every way (because they have requested it before).
  1104. * - dirs can process multiple concatenated descriptors which is required
  1105. * for replication, whereas clients only accept a single descriptor.
  1106. * Thus, combining both methods would result in a lot of if statements
  1107. * which probably would not improve, but worsen code readability. -KL */
  1108. rend_service_descriptor_t *parsed = NULL;
  1109. char desc_id[DIGEST_LEN];
  1110. char *intro_content = NULL;
  1111. size_t intro_size;
  1112. size_t encoded_size;
  1113. const char *next_desc;
  1114. time_t now = time(NULL);
  1115. char key[REND_SERVICE_ID_LEN_BASE32+2];
  1116. char service_id[REND_SERVICE_ID_LEN_BASE32+1];
  1117. char want_desc_id[DIGEST_LEN];
  1118. rend_cache_entry_t *e;
  1119. rend_cache_store_status_t retval = RCS_BADDESC;
  1120. tor_assert(rend_cache);
  1121. tor_assert(desc);
  1122. tor_assert(desc_id_base32);
  1123. memset(want_desc_id, 0, sizeof(want_desc_id));
  1124. if (entry) {
  1125. *entry = NULL;
  1126. }
  1127. if (base32_decode(want_desc_id, sizeof(want_desc_id),
  1128. desc_id_base32, strlen(desc_id_base32)) != 0) {
  1129. log_warn(LD_BUG, "Couldn't decode base32 %s for descriptor id.",
  1130. escaped_safe_str_client(desc_id_base32));
  1131. goto err;
  1132. }
  1133. /* Parse the descriptor. */
  1134. if (rend_parse_v2_service_descriptor(&parsed, desc_id, &intro_content,
  1135. &intro_size, &encoded_size,
  1136. &next_desc, desc, 0) < 0) {
  1137. log_warn(LD_REND, "Could not parse descriptor.");
  1138. goto err;
  1139. }
  1140. /* Compute service ID from public key. */
  1141. if (rend_get_service_id(parsed->pk, service_id)<0) {
  1142. log_warn(LD_REND, "Couldn't compute service ID.");
  1143. goto err;
  1144. }
  1145. if (rend_query->onion_address[0] != '\0' &&
  1146. strcmp(rend_query->onion_address, service_id)) {
  1147. log_warn(LD_REND, "Received service descriptor for service ID %s; "
  1148. "expected descriptor for service ID %s.",
  1149. service_id, safe_str(rend_query->onion_address));
  1150. goto err;
  1151. }
  1152. if (tor_memneq(desc_id, want_desc_id, DIGEST_LEN)) {
  1153. log_warn(LD_REND, "Received service descriptor for %s with incorrect "
  1154. "descriptor ID.", service_id);
  1155. goto err;
  1156. }
  1157. /* Decode/decrypt introduction points. */
  1158. if (intro_content && intro_size > 0) {
  1159. int n_intro_points;
  1160. if (rend_query->auth_type != REND_NO_AUTH &&
  1161. !tor_mem_is_zero(rend_query->descriptor_cookie,
  1162. sizeof(rend_query->descriptor_cookie))) {
  1163. char *ipos_decrypted = NULL;
  1164. size_t ipos_decrypted_size;
  1165. if (rend_decrypt_introduction_points(&ipos_decrypted,
  1166. &ipos_decrypted_size,
  1167. rend_query->descriptor_cookie,
  1168. intro_content,
  1169. intro_size) < 0) {
  1170. log_warn(LD_REND, "Failed to decrypt introduction points. We are "
  1171. "probably unable to parse the encoded introduction points.");
  1172. } else {
  1173. /* Replace encrypted with decrypted introduction points. */
  1174. log_info(LD_REND, "Successfully decrypted introduction points.");
  1175. tor_free(intro_content);
  1176. intro_content = ipos_decrypted;
  1177. intro_size = ipos_decrypted_size;
  1178. }
  1179. }
  1180. n_intro_points = rend_parse_introduction_points(parsed, intro_content,
  1181. intro_size);
  1182. if (n_intro_points <= 0) {
  1183. log_warn(LD_REND, "Failed to parse introduction points. Either the "
  1184. "service has published a corrupt descriptor or you have "
  1185. "provided invalid authorization data.");
  1186. goto err;
  1187. } else if (n_intro_points > MAX_INTRO_POINTS) {
  1188. log_warn(LD_REND, "Found too many introduction points on a hidden "
  1189. "service descriptor for %s. This is probably a (misguided) "
  1190. "attempt to improve reliability, but it could also be an "
  1191. "attempt to do a guard enumeration attack. Rejecting.",
  1192. safe_str_client(service_id));
  1193. goto err;
  1194. }
  1195. } else {
  1196. log_info(LD_REND, "Descriptor does not contain any introduction points.");
  1197. parsed->intro_nodes = smartlist_new();
  1198. }
  1199. /* We don't need the encoded/encrypted introduction points any longer. */
  1200. tor_free(intro_content);
  1201. /* Is descriptor too old? */
  1202. if (parsed->timestamp < now - REND_CACHE_MAX_AGE-REND_CACHE_MAX_SKEW) {
  1203. log_warn(LD_REND, "Service descriptor with service ID %s is too old.",
  1204. safe_str_client(service_id));
  1205. goto err;
  1206. }
  1207. /* Is descriptor too far in the future? */
  1208. if (parsed->timestamp > now + REND_CACHE_MAX_SKEW) {
  1209. log_warn(LD_REND, "Service descriptor with service ID %s is too far in "
  1210. "the future.", safe_str_client(service_id));
  1211. goto err;
  1212. }
  1213. /* Do we already have a newer descriptor? */
  1214. tor_snprintf(key, sizeof(key), "2%s", service_id);
  1215. e = (rend_cache_entry_t*) strmap_get_lc(rend_cache, key);
  1216. if (e && e->parsed->timestamp >= parsed->timestamp) {
  1217. log_info(LD_REND, "We already have a new enough service descriptor for "
  1218. "service ID %s with the same desc ID and version.",
  1219. safe_str_client(service_id));
  1220. goto okay;
  1221. }
  1222. if (!e) {
  1223. e = tor_malloc_zero(sizeof(rend_cache_entry_t));
  1224. strmap_set_lc(rend_cache, key, e);
  1225. } else {
  1226. rend_cache_decrement_allocation(rend_cache_entry_allocation(e));
  1227. rend_service_descriptor_free(e->parsed);
  1228. tor_free(e->desc);
  1229. }
  1230. e->parsed = parsed;
  1231. e->desc = tor_malloc_zero(encoded_size + 1);
  1232. strlcpy(e->desc, desc, encoded_size + 1);
  1233. e->len = encoded_size;
  1234. rend_cache_increment_allocation(rend_cache_entry_allocation(e));
  1235. log_debug(LD_REND,"Successfully stored rend desc '%s', len %d.",
  1236. safe_str_client(service_id), (int)encoded_size);
  1237. if (entry) {
  1238. *entry = e;
  1239. }
  1240. return RCS_OKAY;
  1241. okay:
  1242. if (entry) {
  1243. *entry = e;
  1244. }
  1245. retval = RCS_OKAY;
  1246. err:
  1247. rend_service_descriptor_free(parsed);
  1248. tor_free(intro_content);
  1249. return retval;
  1250. }
  1251. /** Called when we get a rendezvous-related relay cell on circuit
  1252. * <b>circ</b>. Dispatch on rendezvous relay command. */
  1253. void
  1254. rend_process_relay_cell(circuit_t *circ, const crypt_path_t *layer_hint,
  1255. int command, size_t length,
  1256. const uint8_t *payload)
  1257. {
  1258. or_circuit_t *or_circ = NULL;
  1259. origin_circuit_t *origin_circ = NULL;
  1260. int r = -2;
  1261. if (CIRCUIT_IS_ORIGIN(circ)) {
  1262. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  1263. if (!layer_hint || layer_hint != origin_circ->cpath->prev) {
  1264. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1265. "Relay cell (rend purpose %d) from wrong hop on origin circ",
  1266. command);
  1267. origin_circ = NULL;
  1268. }
  1269. } else {
  1270. or_circ = TO_OR_CIRCUIT(circ);
  1271. }
  1272. switch (command) {
  1273. case RELAY_COMMAND_ESTABLISH_INTRO:
  1274. if (or_circ)
  1275. r = rend_mid_establish_intro(or_circ,payload,length);
  1276. break;
  1277. case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
  1278. if (or_circ)
  1279. r = rend_mid_establish_rendezvous(or_circ,payload,length);
  1280. break;
  1281. case RELAY_COMMAND_INTRODUCE1:
  1282. if (or_circ)
  1283. r = rend_mid_introduce(or_circ,payload,length);
  1284. break;
  1285. case RELAY_COMMAND_INTRODUCE2:
  1286. if (origin_circ)
  1287. r = rend_service_introduce(origin_circ,payload,length);
  1288. break;
  1289. case RELAY_COMMAND_INTRODUCE_ACK:
  1290. if (origin_circ)
  1291. r = rend_client_introduction_acked(origin_circ,payload,length);
  1292. break;
  1293. case RELAY_COMMAND_RENDEZVOUS1:
  1294. if (or_circ)
  1295. r = rend_mid_rendezvous(or_circ,payload,length);
  1296. break;
  1297. case RELAY_COMMAND_RENDEZVOUS2:
  1298. if (origin_circ)
  1299. r = rend_client_receive_rendezvous(origin_circ,payload,length);
  1300. break;
  1301. case RELAY_COMMAND_INTRO_ESTABLISHED:
  1302. if (origin_circ)
  1303. r = rend_service_intro_established(origin_circ,payload,length);
  1304. break;
  1305. case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
  1306. if (origin_circ)
  1307. r = rend_client_rendezvous_acked(origin_circ,payload,length);
  1308. break;
  1309. default:
  1310. tor_fragile_assert();
  1311. }
  1312. if (r == -2)
  1313. log_info(LD_PROTOCOL, "Dropping cell (type %d) for wrong circuit type.",
  1314. command);
  1315. }
  1316. /** Allocate and return a new rend_data_t with the same
  1317. * contents as <b>query</b>. */
  1318. rend_data_t *
  1319. rend_data_dup(const rend_data_t *data)
  1320. {
  1321. tor_assert(data);
  1322. return tor_memdup(data, sizeof(rend_data_t));
  1323. }
  1324. /** Compute descriptor ID for each replicas and save them. A valid onion
  1325. * address must be present in the <b>rend_data</b>.
  1326. *
  1327. * Return 0 on success else -1. */
  1328. static int
  1329. compute_desc_id(rend_data_t *rend_data)
  1330. {
  1331. int ret, replica;
  1332. time_t now = time(NULL);
  1333. tor_assert(rend_data);
  1334. /* Compute descriptor ID for each replicas. */
  1335. for (replica = 0; replica < ARRAY_LENGTH(rend_data->descriptor_id);
  1336. replica++) {
  1337. ret = rend_compute_v2_desc_id(rend_data->descriptor_id[replica],
  1338. rend_data->onion_address,
  1339. rend_data->descriptor_cookie,
  1340. now, replica);
  1341. if (ret < 0) {
  1342. goto end;
  1343. }
  1344. }
  1345. end:
  1346. return ret;
  1347. }
  1348. /** Allocate and initialize a rend_data_t object for a service using the
  1349. * given arguments. Only the <b>onion_address</b> is not optional.
  1350. *
  1351. * Return a valid rend_data_t pointer. */
  1352. rend_data_t *
  1353. rend_data_service_create(const char *onion_address, const char *pk_digest,
  1354. const uint8_t *cookie, rend_auth_type_t auth_type)
  1355. {
  1356. rend_data_t *rend_data = tor_malloc_zero(sizeof(*rend_data));
  1357. /* We need at least one else the call is wrong. */
  1358. tor_assert(onion_address != NULL);
  1359. if (pk_digest) {
  1360. memcpy(rend_data->rend_pk_digest, pk_digest,
  1361. sizeof(rend_data->rend_pk_digest));
  1362. }
  1363. if (cookie) {
  1364. memcpy(rend_data->rend_cookie, cookie,
  1365. sizeof(rend_data->rend_cookie));
  1366. }
  1367. strlcpy(rend_data->onion_address, onion_address,
  1368. sizeof(rend_data->onion_address));
  1369. rend_data->auth_type = auth_type;
  1370. return rend_data;
  1371. }
  1372. /** Allocate and initialize a rend_data_t object for a client request using
  1373. * the given arguments. Either an onion address or a descriptor ID is
  1374. * needed. Both can be given but only the onion address will be used to make
  1375. * the descriptor fetch.
  1376. *
  1377. * Return a valid rend_data_t pointer or NULL on error meaning the
  1378. * descriptor IDs couldn't be computed from the given data. */
  1379. rend_data_t *
  1380. rend_data_client_create(const char *onion_address, const char *desc_id,
  1381. const char *cookie, rend_auth_type_t auth_type)
  1382. {
  1383. rend_data_t *rend_data = tor_malloc_zero(sizeof(*rend_data));
  1384. /* We need at least one else the call is wrong. */
  1385. tor_assert(onion_address != NULL || desc_id != NULL);
  1386. if (cookie) {
  1387. memcpy(rend_data->descriptor_cookie, cookie,
  1388. sizeof(rend_data->descriptor_cookie));
  1389. }
  1390. if (desc_id) {
  1391. memcpy(rend_data->desc_id_fetch, desc_id,
  1392. sizeof(rend_data->desc_id_fetch));
  1393. }
  1394. if (onion_address) {
  1395. strlcpy(rend_data->onion_address, onion_address,
  1396. sizeof(rend_data->onion_address));
  1397. if (compute_desc_id(rend_data) < 0) {
  1398. goto error;
  1399. }
  1400. }
  1401. rend_data->auth_type = auth_type;
  1402. return rend_data;
  1403. error:
  1404. rend_data_free(rend_data);
  1405. return NULL;
  1406. }