rendcommon.c 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449
  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 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_free_pk_env(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_env_t *digest = crypto_new_digest_env();
  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_free_digest_env(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_env_t *digest = crypto_new_digest_env();
  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_free_digest_env(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_env_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_env_t *digest;
  253. crypto_cipher_env_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. cipher = crypto_create_init_cipher(session_key, 1);
  278. enclen = crypto_cipher_encrypt_with_iv(cipher,
  279. enc + 2 + client_entries_len,
  280. CIPHER_IV_LEN + strlen(encoded), encoded, strlen(encoded));
  281. crypto_free_cipher_env(cipher);
  282. if (enclen < 0) {
  283. log_warn(LD_REND, "Could not encrypt introduction point string.");
  284. goto done;
  285. }
  286. memcpy(iv, enc + 2 + client_entries_len, CIPHER_IV_LEN);
  287. /* Encrypt session key for cookies, determine client IDs, and put both
  288. * in a smartlist. */
  289. encrypted_session_keys = smartlist_create();
  290. SMARTLIST_FOREACH_BEGIN(client_cookies, const char *, cookie) {
  291. client_part = tor_malloc_zero(REND_BASIC_AUTH_CLIENT_ENTRY_LEN);
  292. /* Encrypt session key. */
  293. cipher = crypto_create_init_cipher(cookie, 1);
  294. if (crypto_cipher_encrypt(cipher, client_part +
  295. REND_BASIC_AUTH_CLIENT_ID_LEN,
  296. session_key, CIPHER_KEY_LEN) < 0) {
  297. log_warn(LD_REND, "Could not encrypt session key for client.");
  298. crypto_free_cipher_env(cipher);
  299. tor_free(client_part);
  300. goto done;
  301. }
  302. crypto_free_cipher_env(cipher);
  303. /* Determine client ID. */
  304. digest = crypto_new_digest_env();
  305. crypto_digest_add_bytes(digest, cookie, REND_DESC_COOKIE_LEN);
  306. crypto_digest_add_bytes(digest, iv, CIPHER_IV_LEN);
  307. crypto_digest_get_digest(digest, client_part,
  308. REND_BASIC_AUTH_CLIENT_ID_LEN);
  309. crypto_free_digest_env(digest);
  310. /* Put both together. */
  311. smartlist_add(encrypted_session_keys, client_part);
  312. } SMARTLIST_FOREACH_END(cookie);
  313. /* Add some fake client IDs and encrypted session keys. */
  314. for (i = (smartlist_len(client_cookies) - 1) %
  315. REND_BASIC_AUTH_CLIENT_MULTIPLE;
  316. i < REND_BASIC_AUTH_CLIENT_MULTIPLE - 1; i++) {
  317. client_part = tor_malloc_zero(REND_BASIC_AUTH_CLIENT_ENTRY_LEN);
  318. if (crypto_rand(client_part, REND_BASIC_AUTH_CLIENT_ENTRY_LEN) < 0) {
  319. log_warn(LD_REND, "Unable to generate fake client entry.");
  320. tor_free(client_part);
  321. goto done;
  322. }
  323. smartlist_add(encrypted_session_keys, client_part);
  324. }
  325. /* Sort smartlist and put elements in result in order. */
  326. smartlist_sort_digests(encrypted_session_keys);
  327. pos = 2;
  328. SMARTLIST_FOREACH(encrypted_session_keys, const char *, entry, {
  329. memcpy(enc + pos, entry, REND_BASIC_AUTH_CLIENT_ENTRY_LEN);
  330. pos += REND_BASIC_AUTH_CLIENT_ENTRY_LEN;
  331. });
  332. *encrypted_out = enc;
  333. *encrypted_len_out = len;
  334. enc = NULL; /* prevent free. */
  335. r = 0;
  336. done:
  337. tor_free(enc);
  338. if (encrypted_session_keys) {
  339. SMARTLIST_FOREACH(encrypted_session_keys, char *, d, tor_free(d););
  340. smartlist_free(encrypted_session_keys);
  341. }
  342. return r;
  343. }
  344. /** Encrypt the encoded introduction points in <b>encoded</b> using
  345. * authorization type 'stealth' with <b>descriptor_cookie</b> of length
  346. * REND_DESC_COOKIE_LEN and write the result to a newly allocated string
  347. * pointed to by <b>encrypted_out</b> of length <b>encrypted_len_out</b>.
  348. * Return 0 for success, -1 otherwise. */
  349. static int
  350. rend_encrypt_v2_intro_points_stealth(char **encrypted_out,
  351. size_t *encrypted_len_out,
  352. const char *encoded,
  353. const char *descriptor_cookie)
  354. {
  355. int r = -1, enclen;
  356. crypto_cipher_env_t *cipher;
  357. char *enc;
  358. tor_assert(encoded);
  359. tor_assert(descriptor_cookie);
  360. enc = tor_malloc_zero(1 + CIPHER_IV_LEN + strlen(encoded));
  361. enc[0] = 0x02; /* Auth type */
  362. cipher = crypto_create_init_cipher(descriptor_cookie, 1);
  363. enclen = crypto_cipher_encrypt_with_iv(cipher, enc + 1,
  364. CIPHER_IV_LEN+strlen(encoded),
  365. encoded, strlen(encoded));
  366. crypto_free_cipher_env(cipher);
  367. if (enclen < 0) {
  368. log_warn(LD_REND, "Could not encrypt introduction point string.");
  369. goto done;
  370. }
  371. *encrypted_out = enc;
  372. *encrypted_len_out = enclen;
  373. enc = NULL; /* prevent free */
  374. r = 0;
  375. done:
  376. tor_free(enc);
  377. return r;
  378. }
  379. /** Attempt to parse the given <b>desc_str</b> and return true if this
  380. * succeeds, false otherwise. */
  381. static int
  382. rend_desc_v2_is_parsable(rend_encoded_v2_service_descriptor_t *desc)
  383. {
  384. rend_service_descriptor_t *test_parsed = NULL;
  385. char test_desc_id[DIGEST_LEN];
  386. char *test_intro_content = NULL;
  387. size_t test_intro_size;
  388. size_t test_encoded_size;
  389. const char *test_next;
  390. int res = rend_parse_v2_service_descriptor(&test_parsed, test_desc_id,
  391. &test_intro_content,
  392. &test_intro_size,
  393. &test_encoded_size,
  394. &test_next, desc->desc_str);
  395. rend_service_descriptor_free(test_parsed);
  396. tor_free(test_intro_content);
  397. return (res >= 0);
  398. }
  399. /** Free the storage held by an encoded v2 service descriptor. */
  400. void
  401. rend_encoded_v2_service_descriptor_free(
  402. rend_encoded_v2_service_descriptor_t *desc)
  403. {
  404. if (!desc)
  405. return;
  406. tor_free(desc->desc_str);
  407. tor_free(desc);
  408. }
  409. /** Free the storage held by an introduction point info. */
  410. void
  411. rend_intro_point_free(rend_intro_point_t *intro)
  412. {
  413. if (!intro)
  414. return;
  415. extend_info_free(intro->extend_info);
  416. crypto_free_pk_env(intro->intro_key);
  417. tor_free(intro);
  418. }
  419. /** Encode a set of rend_encoded_v2_service_descriptor_t's for <b>desc</b>
  420. * at time <b>now</b> using <b>service_key</b>, depending on
  421. * <b>auth_type</b> a <b>descriptor_cookie</b> and a list of
  422. * <b>client_cookies</b> (which are both <b>NULL</b> if no client
  423. * authorization is performed), and <b>period</b> (e.g. 0 for the current
  424. * period, 1 for the next period, etc.) and add them to the existing list
  425. * <b>descs_out</b>; return the number of seconds that the descriptors will
  426. * be found by clients, or -1 if the encoding was not successful. */
  427. int
  428. rend_encode_v2_descriptors(smartlist_t *descs_out,
  429. rend_service_descriptor_t *desc, time_t now,
  430. uint8_t period, rend_auth_type_t auth_type,
  431. crypto_pk_env_t *client_key,
  432. smartlist_t *client_cookies)
  433. {
  434. char service_id[DIGEST_LEN];
  435. uint32_t time_period;
  436. char *ipos_base64 = NULL, *ipos = NULL, *ipos_encrypted = NULL,
  437. *descriptor_cookie = NULL;
  438. size_t ipos_len = 0, ipos_encrypted_len = 0;
  439. int k;
  440. uint32_t seconds_valid;
  441. crypto_pk_env_t *service_key;
  442. if (!desc) {
  443. log_warn(LD_BUG, "Could not encode v2 descriptor: No desc given.");
  444. return -1;
  445. }
  446. service_key = (auth_type == REND_STEALTH_AUTH) ? client_key : desc->pk;
  447. tor_assert(service_key);
  448. if (auth_type == REND_STEALTH_AUTH) {
  449. descriptor_cookie = smartlist_get(client_cookies, 0);
  450. tor_assert(descriptor_cookie);
  451. }
  452. /* Obtain service_id from public key. */
  453. crypto_pk_get_digest(service_key, service_id);
  454. /* Calculate current time-period. */
  455. time_period = get_time_period(now, period, service_id);
  456. /* Determine how many seconds the descriptor will be valid. */
  457. seconds_valid = period * REND_TIME_PERIOD_V2_DESC_VALIDITY +
  458. get_seconds_valid(now, service_id);
  459. /* Assemble, possibly encrypt, and encode introduction points. */
  460. if (smartlist_len(desc->intro_nodes) > 0) {
  461. if (rend_encode_v2_intro_points(&ipos, desc) < 0) {
  462. log_warn(LD_REND, "Encoding of introduction points did not succeed.");
  463. return -1;
  464. }
  465. switch (auth_type) {
  466. case REND_NO_AUTH:
  467. ipos_len = strlen(ipos);
  468. break;
  469. case REND_BASIC_AUTH:
  470. if (rend_encrypt_v2_intro_points_basic(&ipos_encrypted,
  471. &ipos_encrypted_len, ipos,
  472. client_cookies) < 0) {
  473. log_warn(LD_REND, "Encrypting of introduction points did not "
  474. "succeed.");
  475. tor_free(ipos);
  476. return -1;
  477. }
  478. tor_free(ipos);
  479. ipos = ipos_encrypted;
  480. ipos_len = ipos_encrypted_len;
  481. break;
  482. case REND_STEALTH_AUTH:
  483. if (rend_encrypt_v2_intro_points_stealth(&ipos_encrypted,
  484. &ipos_encrypted_len, ipos,
  485. descriptor_cookie) < 0) {
  486. log_warn(LD_REND, "Encrypting of introduction points did not "
  487. "succeed.");
  488. tor_free(ipos);
  489. return -1;
  490. }
  491. tor_free(ipos);
  492. ipos = ipos_encrypted;
  493. ipos_len = ipos_encrypted_len;
  494. break;
  495. default:
  496. log_warn(LD_REND|LD_BUG, "Unrecognized authorization type %d",
  497. (int)auth_type);
  498. tor_free(ipos);
  499. return -1;
  500. }
  501. /* Base64-encode introduction points. */
  502. ipos_base64 = tor_malloc_zero(ipos_len * 2);
  503. if (base64_encode(ipos_base64, ipos_len * 2, ipos, ipos_len)<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++] = '\n';
  621. desc_str[written++] = 0;
  622. /* Check if we can parse our own descriptor. */
  623. if (!rend_desc_v2_is_parsable(enc)) {
  624. log_warn(LD_BUG, "Could not parse my own descriptor: %s", desc_str);
  625. rend_encoded_v2_service_descriptor_free(enc);
  626. goto err;
  627. }
  628. smartlist_add(descs_out, enc);
  629. }
  630. log_info(LD_REND, "Successfully encoded a v2 descriptor and "
  631. "confirmed that it is parsable.");
  632. goto done;
  633. err:
  634. SMARTLIST_FOREACH(descs_out, rend_encoded_v2_service_descriptor_t *, d,
  635. rend_encoded_v2_service_descriptor_free(d););
  636. smartlist_clear(descs_out);
  637. seconds_valid = -1;
  638. done:
  639. tor_free(ipos_base64);
  640. return seconds_valid;
  641. }
  642. /** Parse a service descriptor at <b>str</b> (<b>len</b> bytes). On
  643. * success, return a newly alloced service_descriptor_t. On failure,
  644. * return NULL.
  645. */
  646. rend_service_descriptor_t *
  647. rend_parse_service_descriptor(const char *str, size_t len)
  648. {
  649. rend_service_descriptor_t *result = NULL;
  650. int i, n_intro_points;
  651. size_t keylen, asn1len;
  652. const char *end, *cp, *eos;
  653. rend_intro_point_t *intro;
  654. result = tor_malloc_zero(sizeof(rend_service_descriptor_t));
  655. cp = str;
  656. end = str+len;
  657. if (end-cp<2) goto truncated;
  658. result->version = 0;
  659. if (end-cp < 2) goto truncated;
  660. asn1len = ntohs(get_uint16(cp));
  661. cp += 2;
  662. if ((size_t)(end-cp) < asn1len) goto truncated;
  663. result->pk = crypto_pk_asn1_decode(cp, asn1len);
  664. if (!result->pk) goto truncated;
  665. cp += asn1len;
  666. if (end-cp < 4) goto truncated;
  667. result->timestamp = (time_t) ntohl(get_uint32(cp));
  668. cp += 4;
  669. result->protocols = 1<<2; /* always use intro format 2 */
  670. if (end-cp < 2) goto truncated;
  671. n_intro_points = ntohs(get_uint16(cp));
  672. cp += 2;
  673. result->intro_nodes = smartlist_create();
  674. for (i=0;i<n_intro_points;++i) {
  675. if (end-cp < 2) goto truncated;
  676. eos = (const char *)memchr(cp,'\0',end-cp);
  677. if (!eos) goto truncated;
  678. /* Write nickname to extend info, but postpone the lookup whether
  679. * we know that router. It's not part of the parsing process. */
  680. intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  681. intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
  682. strlcpy(intro->extend_info->nickname, cp,
  683. sizeof(intro->extend_info->nickname));
  684. smartlist_add(result->intro_nodes, intro);
  685. cp = eos+1;
  686. }
  687. keylen = crypto_pk_keysize(result->pk);
  688. tor_assert(end-cp >= 0);
  689. if ((size_t)(end-cp) < keylen) goto truncated;
  690. if ((size_t)(end-cp) > keylen) {
  691. log_warn(LD_PROTOCOL,
  692. "Signature is %d bytes too long on service descriptor.",
  693. (int)((size_t)(end-cp) - keylen));
  694. goto error;
  695. }
  696. note_crypto_pk_op(REND_CLIENT);
  697. if (crypto_pk_public_checksig_digest(result->pk,
  698. (char*)str,cp-str, /* data */
  699. (char*)cp,end-cp /* signature*/
  700. )<0) {
  701. log_warn(LD_PROTOCOL, "Bad signature on service descriptor.");
  702. goto error;
  703. }
  704. return result;
  705. truncated:
  706. log_warn(LD_PROTOCOL, "Truncated service descriptor.");
  707. error:
  708. rend_service_descriptor_free(result);
  709. return NULL;
  710. }
  711. /** Sets <b>out</b> to the first 10 bytes of the digest of <b>pk</b>,
  712. * base32 encoded. NUL-terminates out. (We use this string to
  713. * identify services in directory requests and .onion URLs.)
  714. */
  715. int
  716. rend_get_service_id(crypto_pk_env_t *pk, char *out)
  717. {
  718. char buf[DIGEST_LEN];
  719. tor_assert(pk);
  720. if (crypto_pk_get_digest(pk, buf) < 0)
  721. return -1;
  722. base32_encode(out, REND_SERVICE_ID_LEN_BASE32+1, buf, REND_SERVICE_ID_LEN);
  723. return 0;
  724. }
  725. /* ==== Rendezvous service descriptor cache. */
  726. /** How old do we let hidden service descriptors get before discarding
  727. * them as too old? */
  728. #define REND_CACHE_MAX_AGE (2*24*60*60)
  729. /** How wrong do we assume our clock may be when checking whether hidden
  730. * services are too old or too new? */
  731. #define REND_CACHE_MAX_SKEW (24*60*60)
  732. /** Map from service id (as generated by rend_get_service_id) to
  733. * rend_cache_entry_t. */
  734. static strmap_t *rend_cache = NULL;
  735. /** Map from descriptor id to rend_cache_entry_t; only for hidden service
  736. * directories. */
  737. static digestmap_t *rend_cache_v2_dir = NULL;
  738. /** Initializes the service descriptor cache.
  739. */
  740. void
  741. rend_cache_init(void)
  742. {
  743. rend_cache = strmap_new();
  744. rend_cache_v2_dir = digestmap_new();
  745. }
  746. /** Helper: free storage held by a single service descriptor cache entry. */
  747. static void
  748. rend_cache_entry_free(rend_cache_entry_t *e)
  749. {
  750. if (!e)
  751. return;
  752. rend_service_descriptor_free(e->parsed);
  753. tor_free(e->desc);
  754. tor_free(e);
  755. }
  756. static void
  757. _rend_cache_entry_free(void *p)
  758. {
  759. rend_cache_entry_free(p);
  760. }
  761. /** Free all storage held by the service descriptor cache. */
  762. void
  763. rend_cache_free_all(void)
  764. {
  765. strmap_free(rend_cache, _rend_cache_entry_free);
  766. digestmap_free(rend_cache_v2_dir, _rend_cache_entry_free);
  767. rend_cache = NULL;
  768. rend_cache_v2_dir = NULL;
  769. }
  770. /** Removes all old entries from the service descriptor cache.
  771. */
  772. void
  773. rend_cache_clean(void)
  774. {
  775. strmap_iter_t *iter;
  776. const char *key;
  777. void *val;
  778. rend_cache_entry_t *ent;
  779. time_t cutoff;
  780. cutoff = time(NULL) - REND_CACHE_MAX_AGE - REND_CACHE_MAX_SKEW;
  781. for (iter = strmap_iter_init(rend_cache); !strmap_iter_done(iter); ) {
  782. strmap_iter_get(iter, &key, &val);
  783. ent = (rend_cache_entry_t*)val;
  784. if (ent->parsed->timestamp < cutoff) {
  785. iter = strmap_iter_next_rmv(rend_cache, iter);
  786. rend_cache_entry_free(ent);
  787. } else {
  788. iter = strmap_iter_next(rend_cache, iter);
  789. }
  790. }
  791. }
  792. /** Remove ALL entries from the rendezvous service descriptor cache.
  793. */
  794. void
  795. rend_cache_purge(void)
  796. {
  797. if (rend_cache)
  798. strmap_free(rend_cache, _rend_cache_entry_free);
  799. rend_cache = strmap_new();
  800. }
  801. /** Remove all old v2 descriptors and those for which this hidden service
  802. * directory is not responsible for any more. */
  803. void
  804. rend_cache_clean_v2_descs_as_dir(void)
  805. {
  806. digestmap_iter_t *iter;
  807. time_t cutoff = time(NULL) - REND_CACHE_MAX_AGE - REND_CACHE_MAX_SKEW;
  808. for (iter = digestmap_iter_init(rend_cache_v2_dir);
  809. !digestmap_iter_done(iter); ) {
  810. const char *key;
  811. void *val;
  812. rend_cache_entry_t *ent;
  813. digestmap_iter_get(iter, &key, &val);
  814. ent = val;
  815. if (ent->parsed->timestamp < cutoff ||
  816. !hid_serv_responsible_for_desc_id(key)) {
  817. char key_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  818. base32_encode(key_base32, sizeof(key_base32), key, DIGEST_LEN);
  819. log_info(LD_REND, "Removing descriptor with ID '%s' from cache",
  820. safe_str_client(key_base32));
  821. iter = digestmap_iter_next_rmv(rend_cache_v2_dir, iter);
  822. rend_cache_entry_free(ent);
  823. } else {
  824. iter = digestmap_iter_next(rend_cache_v2_dir, iter);
  825. }
  826. }
  827. }
  828. /** Determines whether <b>a</b> is in the interval of <b>b</b> (excluded) and
  829. * <b>c</b> (included) in a circular digest ring; returns 1 if this is the
  830. * case, and 0 otherwise.
  831. */
  832. int
  833. rend_id_is_in_interval(const char *a, const char *b, const char *c)
  834. {
  835. int a_b, b_c, c_a;
  836. tor_assert(a);
  837. tor_assert(b);
  838. tor_assert(c);
  839. /* There are five cases in which a is outside the interval ]b,c]: */
  840. a_b = memcmp(a,b,DIGEST_LEN);
  841. if (a_b == 0)
  842. return 0; /* 1. a == b (b is excluded) */
  843. b_c = memcmp(b,c,DIGEST_LEN);
  844. if (b_c == 0)
  845. return 0; /* 2. b == c (interval is empty) */
  846. else if (a_b <= 0 && b_c < 0)
  847. return 0; /* 3. a b c */
  848. c_a = memcmp(c,a,DIGEST_LEN);
  849. if (c_a < 0 && a_b <= 0)
  850. return 0; /* 4. c a b */
  851. else if (b_c < 0 && c_a < 0)
  852. return 0; /* 5. b c a */
  853. /* In the other cases (a c b; b a c; c b a), a is inside the interval. */
  854. return 1;
  855. }
  856. /** Return true iff <b>query</b> is a syntactically valid service ID (as
  857. * generated by rend_get_service_id). */
  858. int
  859. rend_valid_service_id(const char *query)
  860. {
  861. if (strlen(query) != REND_SERVICE_ID_LEN_BASE32)
  862. return 0;
  863. if (strspn(query, BASE32_CHARS) != REND_SERVICE_ID_LEN_BASE32)
  864. return 0;
  865. return 1;
  866. }
  867. /** If we have a cached rend_cache_entry_t for the service ID <b>query</b>
  868. * with <b>version</b>, set *<b>e</b> to that entry and return 1.
  869. * Else return 0. If <b>version</b> is nonnegative, only return an entry
  870. * in that descriptor format version. Otherwise (if <b>version</b> is
  871. * negative), return the most recent format we have.
  872. */
  873. int
  874. rend_cache_lookup_entry(const char *query, int version, rend_cache_entry_t **e)
  875. {
  876. char key[REND_SERVICE_ID_LEN_BASE32+2]; /* <version><query>\0 */
  877. tor_assert(rend_cache);
  878. if (!rend_valid_service_id(query))
  879. return -1;
  880. *e = NULL;
  881. if (version != 0) {
  882. tor_snprintf(key, sizeof(key), "2%s", query);
  883. *e = strmap_get_lc(rend_cache, key);
  884. }
  885. if (!*e && version != 2) {
  886. tor_snprintf(key, sizeof(key), "0%s", query);
  887. *e = strmap_get_lc(rend_cache, key);
  888. }
  889. if (!*e)
  890. return 0;
  891. tor_assert((*e)->parsed && (*e)->parsed->intro_nodes);
  892. /* XXX023 hack for now, to return "not found" if there are no intro
  893. * points remaining. See bug 997. */
  894. if (! rend_client_any_intro_points_usable(*e))
  895. return 0;
  896. return 1;
  897. }
  898. /** <b>query</b> is a base-32'ed service id. If it's malformed, return -1.
  899. * Else look it up.
  900. * - If it is found, point *desc to it, and write its length into
  901. * *desc_len, and return 1.
  902. * - If it is not found, return 0.
  903. * Note: calls to rend_cache_clean or rend_cache_store may invalidate
  904. * *desc.
  905. */
  906. int
  907. rend_cache_lookup_desc(const char *query, int version, const char **desc,
  908. size_t *desc_len)
  909. {
  910. rend_cache_entry_t *e;
  911. int r;
  912. r = rend_cache_lookup_entry(query,version,&e);
  913. if (r <= 0) return r;
  914. *desc = e->desc;
  915. *desc_len = e->len;
  916. return 1;
  917. }
  918. /** Lookup the v2 service descriptor with base32-encoded <b>desc_id</b> and
  919. * copy the pointer to it to *<b>desc</b>. Return 1 on success, 0 on
  920. * well-formed-but-not-found, and -1 on failure.
  921. */
  922. int
  923. rend_cache_lookup_v2_desc_as_dir(const char *desc_id, const char **desc)
  924. {
  925. rend_cache_entry_t *e;
  926. char desc_id_digest[DIGEST_LEN];
  927. tor_assert(rend_cache_v2_dir);
  928. if (base32_decode(desc_id_digest, DIGEST_LEN,
  929. desc_id, REND_DESC_ID_V2_LEN_BASE32) < 0) {
  930. log_warn(LD_REND, "Descriptor ID contains illegal characters: %s",
  931. safe_str(desc_id));
  932. return -1;
  933. }
  934. /* Determine if we are responsible. */
  935. if (hid_serv_responsible_for_desc_id(desc_id_digest) < 0) {
  936. log_info(LD_REND, "Could not answer fetch request for v2 descriptor; "
  937. "either we are no hidden service directory, or we are "
  938. "not responsible for the requested ID.");
  939. return -1;
  940. }
  941. /* Lookup descriptor and return. */
  942. e = digestmap_get(rend_cache_v2_dir, desc_id_digest);
  943. if (e) {
  944. *desc = e->desc;
  945. return 1;
  946. }
  947. return 0;
  948. }
  949. /** Parse *desc, calculate its service id, and store it in the cache.
  950. * If we have a newer v0 descriptor with the same ID, ignore this one.
  951. * If we have an older descriptor with the same ID, replace it.
  952. * If we are acting as client due to the published flag and have any v2
  953. * descriptor with the same ID, reject this one in order to not get
  954. * confused with having both versions for the same service.
  955. *
  956. * Return -2 if it's malformed or otherwise rejected; return -1 if we
  957. * already have a v2 descriptor here; return 0 if it's the same or older
  958. * than one we've already got; return 1 if it's novel.
  959. *
  960. * The published flag tells us if we store the descriptor
  961. * in our role as directory (1) or if we cache it as client (0).
  962. */
  963. int
  964. rend_cache_store(const char *desc, size_t desc_len, int published)
  965. {
  966. rend_cache_entry_t *e;
  967. rend_service_descriptor_t *parsed;
  968. char query[REND_SERVICE_ID_LEN_BASE32+1];
  969. char key[REND_SERVICE_ID_LEN_BASE32+2]; /* 0<query>\0 */
  970. time_t now;
  971. tor_assert(rend_cache);
  972. parsed = rend_parse_service_descriptor(desc,desc_len);
  973. if (!parsed) {
  974. log_warn(LD_PROTOCOL,"Couldn't parse service descriptor.");
  975. return -2;
  976. }
  977. if (rend_get_service_id(parsed->pk, query)<0) {
  978. log_warn(LD_BUG,"Couldn't compute service ID.");
  979. rend_service_descriptor_free(parsed);
  980. return -2;
  981. }
  982. now = time(NULL);
  983. if (parsed->timestamp < now-REND_CACHE_MAX_AGE-REND_CACHE_MAX_SKEW) {
  984. log_fn(LOG_PROTOCOL_WARN, LD_REND,
  985. "Service descriptor %s is too old.",
  986. safe_str_client(query));
  987. rend_service_descriptor_free(parsed);
  988. return -2;
  989. }
  990. if (parsed->timestamp > now+REND_CACHE_MAX_SKEW) {
  991. log_fn(LOG_PROTOCOL_WARN, LD_REND,
  992. "Service descriptor %s is too far in the future.",
  993. safe_str_client(query));
  994. rend_service_descriptor_free(parsed);
  995. return -2;
  996. }
  997. /* Do we have a v2 descriptor and fetched this descriptor as a client? */
  998. tor_snprintf(key, sizeof(key), "2%s", query);
  999. if (!published && strmap_get_lc(rend_cache, key)) {
  1000. log_info(LD_REND, "We already have a v2 descriptor for service %s.",
  1001. safe_str_client(query));
  1002. rend_service_descriptor_free(parsed);
  1003. return -1;
  1004. }
  1005. tor_snprintf(key, sizeof(key), "0%s", query);
  1006. e = (rend_cache_entry_t*) strmap_get_lc(rend_cache, key);
  1007. if (e && e->parsed->timestamp > parsed->timestamp) {
  1008. log_info(LD_REND,"We already have a newer service descriptor %s with the "
  1009. "same ID and version.",
  1010. safe_str_client(query));
  1011. rend_service_descriptor_free(parsed);
  1012. return 0;
  1013. }
  1014. if (e && e->len == desc_len && !memcmp(desc,e->desc,desc_len)) {
  1015. log_info(LD_REND,"We already have this service descriptor %s.",
  1016. safe_str_client(query));
  1017. e->received = time(NULL);
  1018. rend_service_descriptor_free(parsed);
  1019. return 0;
  1020. }
  1021. if (!e) {
  1022. e = tor_malloc_zero(sizeof(rend_cache_entry_t));
  1023. strmap_set_lc(rend_cache, key, e);
  1024. } else {
  1025. rend_service_descriptor_free(e->parsed);
  1026. tor_free(e->desc);
  1027. }
  1028. e->received = time(NULL);
  1029. e->parsed = parsed;
  1030. e->len = desc_len;
  1031. e->desc = tor_malloc(desc_len);
  1032. memcpy(e->desc, desc, desc_len);
  1033. log_debug(LD_REND,"Successfully stored rend desc '%s', len %d.",
  1034. safe_str_client(query), (int)desc_len);
  1035. return 1;
  1036. }
  1037. /** Parse the v2 service descriptor(s) in <b>desc</b> and store it/them to the
  1038. * local rend cache. Don't attempt to decrypt the included list of introduction
  1039. * points (as we don't have a descriptor cookie for it).
  1040. *
  1041. * If we have a newer descriptor with the same ID, ignore this one.
  1042. * If we have an older descriptor with the same ID, replace it.
  1043. * Return -2 if we are not acting as hidden service directory;
  1044. * return -1 if the descriptor(s) were not parsable; return 0 if all
  1045. * descriptors are the same or older than those we've already got;
  1046. * return a positive number for the number of novel stored descriptors.
  1047. */
  1048. int
  1049. rend_cache_store_v2_desc_as_dir(const char *desc)
  1050. {
  1051. rend_service_descriptor_t *parsed;
  1052. char desc_id[DIGEST_LEN];
  1053. char *intro_content;
  1054. size_t intro_size;
  1055. size_t encoded_size;
  1056. char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  1057. int number_parsed = 0, number_stored = 0;
  1058. const char *current_desc = desc;
  1059. const char *next_desc;
  1060. rend_cache_entry_t *e;
  1061. time_t now = time(NULL);
  1062. tor_assert(rend_cache_v2_dir);
  1063. tor_assert(desc);
  1064. if (!hid_serv_acting_as_directory()) {
  1065. /* Cannot store descs, because we are (currently) not acting as
  1066. * hidden service directory. */
  1067. log_info(LD_REND, "Cannot store descs: Not acting as hs dir");
  1068. return -2;
  1069. }
  1070. while (rend_parse_v2_service_descriptor(&parsed, desc_id, &intro_content,
  1071. &intro_size, &encoded_size,
  1072. &next_desc, current_desc) >= 0) {
  1073. number_parsed++;
  1074. /* We don't care about the introduction points. */
  1075. tor_free(intro_content);
  1076. /* For pretty log statements. */
  1077. base32_encode(desc_id_base32, sizeof(desc_id_base32),
  1078. desc_id, DIGEST_LEN);
  1079. /* Is desc ID in the range that we are (directly or indirectly) responsible
  1080. * for? */
  1081. if (!hid_serv_responsible_for_desc_id(desc_id)) {
  1082. log_info(LD_REND, "Service descriptor with desc ID %s is not in "
  1083. "interval that we are responsible for.",
  1084. safe_str_client(desc_id_base32));
  1085. goto skip;
  1086. }
  1087. /* Is descriptor too old? */
  1088. if (parsed->timestamp < now - REND_CACHE_MAX_AGE-REND_CACHE_MAX_SKEW) {
  1089. log_info(LD_REND, "Service descriptor with desc ID %s is too old.",
  1090. safe_str(desc_id_base32));
  1091. goto skip;
  1092. }
  1093. /* Is descriptor too far in the future? */
  1094. if (parsed->timestamp > now + REND_CACHE_MAX_SKEW) {
  1095. log_info(LD_REND, "Service descriptor with desc ID %s is too far in the "
  1096. "future.",
  1097. safe_str(desc_id_base32));
  1098. goto skip;
  1099. }
  1100. /* Do we already have a newer descriptor? */
  1101. e = digestmap_get(rend_cache_v2_dir, desc_id);
  1102. if (e && e->parsed->timestamp > parsed->timestamp) {
  1103. log_info(LD_REND, "We already have a newer service descriptor with the "
  1104. "same desc ID %s and version.",
  1105. safe_str(desc_id_base32));
  1106. goto skip;
  1107. }
  1108. /* Do we already have this descriptor? */
  1109. if (e && !strcmp(desc, e->desc)) {
  1110. log_info(LD_REND, "We already have this service descriptor with desc "
  1111. "ID %s.", safe_str(desc_id_base32));
  1112. e->received = time(NULL);
  1113. goto skip;
  1114. }
  1115. /* Store received descriptor. */
  1116. if (!e) {
  1117. e = tor_malloc_zero(sizeof(rend_cache_entry_t));
  1118. digestmap_set(rend_cache_v2_dir, desc_id, e);
  1119. } else {
  1120. rend_service_descriptor_free(e->parsed);
  1121. tor_free(e->desc);
  1122. }
  1123. e->received = time(NULL);
  1124. e->parsed = parsed;
  1125. e->desc = tor_strndup(current_desc, encoded_size);
  1126. e->len = encoded_size;
  1127. log_info(LD_REND, "Successfully stored service descriptor with desc ID "
  1128. "'%s' and len %d.",
  1129. safe_str(desc_id_base32), (int)encoded_size);
  1130. number_stored++;
  1131. goto advance;
  1132. skip:
  1133. rend_service_descriptor_free(parsed);
  1134. advance:
  1135. /* advance to next descriptor, if available. */
  1136. current_desc = next_desc;
  1137. /* check if there is a next descriptor. */
  1138. if (!current_desc ||
  1139. strcmpstart(current_desc, "rendezvous-service-descriptor "))
  1140. break;
  1141. }
  1142. if (!number_parsed) {
  1143. log_info(LD_REND, "Could not parse any descriptor.");
  1144. return -1;
  1145. }
  1146. log_info(LD_REND, "Parsed %d and added %d descriptor%s.",
  1147. number_parsed, number_stored, number_stored != 1 ? "s" : "");
  1148. return number_stored;
  1149. }
  1150. /** Parse the v2 service descriptor in <b>desc</b>, decrypt the included list
  1151. * of introduction points with <b>descriptor_cookie</b> (which may also be
  1152. * <b>NULL</b> if decryption is not necessary), and store the descriptor to
  1153. * the local cache under its version and service id.
  1154. *
  1155. * If we have a newer v2 descriptor with the same ID, ignore this one.
  1156. * If we have an older descriptor with the same ID, replace it.
  1157. * If we have any v0 descriptor with the same ID, reject this one in order
  1158. * to not get confused with having both versions for the same service.
  1159. * Return -2 if it's malformed or otherwise rejected; return -1 if we
  1160. * already have a v0 descriptor here; return 0 if it's the same or older
  1161. * than one we've already got; return 1 if it's novel.
  1162. */
  1163. int
  1164. rend_cache_store_v2_desc_as_client(const char *desc,
  1165. const rend_data_t *rend_query)
  1166. {
  1167. /*XXXX this seems to have a bit of duplicate code with
  1168. * rend_cache_store_v2_desc_as_dir(). Fix that. */
  1169. /* Though having similar elements, both functions were separated on
  1170. * purpose:
  1171. * - dirs don't care about encoded/encrypted introduction points, clients
  1172. * do.
  1173. * - dirs store descriptors in a separate cache by descriptor ID, whereas
  1174. * clients store them by service ID; both caches are different data
  1175. * structures and have different access methods.
  1176. * - dirs store a descriptor only if they are responsible for its ID,
  1177. * clients do so in every way (because they have requested it before).
  1178. * - dirs can process multiple concatenated descriptors which is required
  1179. * for replication, whereas clients only accept a single descriptor.
  1180. * Thus, combining both methods would result in a lot of if statements
  1181. * which probably would not improve, but worsen code readability. -KL */
  1182. rend_service_descriptor_t *parsed = NULL;
  1183. char desc_id[DIGEST_LEN];
  1184. char *intro_content = NULL;
  1185. size_t intro_size;
  1186. size_t encoded_size;
  1187. const char *next_desc;
  1188. time_t now = time(NULL);
  1189. char key[REND_SERVICE_ID_LEN_BASE32+2];
  1190. char service_id[REND_SERVICE_ID_LEN_BASE32+1];
  1191. rend_cache_entry_t *e;
  1192. int retval;
  1193. tor_assert(rend_cache);
  1194. tor_assert(desc);
  1195. /* Parse the descriptor. */
  1196. if (rend_parse_v2_service_descriptor(&parsed, desc_id, &intro_content,
  1197. &intro_size, &encoded_size,
  1198. &next_desc, desc) < 0) {
  1199. log_warn(LD_REND, "Could not parse descriptor.");
  1200. retval = -2;
  1201. goto err;
  1202. }
  1203. /* Compute service ID from public key. */
  1204. if (rend_get_service_id(parsed->pk, service_id)<0) {
  1205. log_warn(LD_REND, "Couldn't compute service ID.");
  1206. retval = -2;
  1207. goto err;
  1208. }
  1209. /* Decode/decrypt introduction points. */
  1210. if (intro_content) {
  1211. if (rend_query->auth_type != REND_NO_AUTH &&
  1212. !tor_mem_is_zero(rend_query->descriptor_cookie,
  1213. sizeof(rend_query->descriptor_cookie))) {
  1214. char *ipos_decrypted = NULL;
  1215. size_t ipos_decrypted_size;
  1216. if (rend_decrypt_introduction_points(&ipos_decrypted,
  1217. &ipos_decrypted_size,
  1218. rend_query->descriptor_cookie,
  1219. intro_content,
  1220. intro_size) < 0) {
  1221. log_warn(LD_REND, "Failed to decrypt introduction points. We are "
  1222. "probably unable to parse the encoded introduction points.");
  1223. } else {
  1224. /* Replace encrypted with decrypted introduction points. */
  1225. log_info(LD_REND, "Successfully decrypted introduction points.");
  1226. tor_free(intro_content);
  1227. intro_content = ipos_decrypted;
  1228. intro_size = ipos_decrypted_size;
  1229. }
  1230. }
  1231. if (rend_parse_introduction_points(parsed, intro_content,
  1232. intro_size) <= 0) {
  1233. log_warn(LD_REND, "Failed to parse introduction points. Either the "
  1234. "service has published a corrupt descriptor or you have "
  1235. "provided invalid authorization data.");
  1236. retval = -2;
  1237. goto err;
  1238. }
  1239. } else {
  1240. log_info(LD_REND, "Descriptor does not contain any introduction points.");
  1241. parsed->intro_nodes = smartlist_create();
  1242. }
  1243. /* We don't need the encoded/encrypted introduction points any longer. */
  1244. tor_free(intro_content);
  1245. /* Is descriptor too old? */
  1246. if (parsed->timestamp < now - REND_CACHE_MAX_AGE-REND_CACHE_MAX_SKEW) {
  1247. log_warn(LD_REND, "Service descriptor with service ID %s is too old.",
  1248. safe_str_client(service_id));
  1249. retval = -2;
  1250. goto err;
  1251. }
  1252. /* Is descriptor too far in the future? */
  1253. if (parsed->timestamp > now + REND_CACHE_MAX_SKEW) {
  1254. log_warn(LD_REND, "Service descriptor with service ID %s is too far in "
  1255. "the future.", safe_str_client(service_id));
  1256. retval = -2;
  1257. goto err;
  1258. }
  1259. /* Do we have a v0 descriptor? */
  1260. tor_snprintf(key, sizeof(key), "0%s", service_id);
  1261. if (strmap_get_lc(rend_cache, key)) {
  1262. log_info(LD_REND, "We already have a v0 descriptor for service ID %s.",
  1263. safe_str_client(service_id));
  1264. retval = -1;
  1265. goto err;
  1266. }
  1267. /* Do we already have a newer descriptor? */
  1268. tor_snprintf(key, sizeof(key), "2%s", service_id);
  1269. e = (rend_cache_entry_t*) strmap_get_lc(rend_cache, key);
  1270. if (e && e->parsed->timestamp > parsed->timestamp) {
  1271. log_info(LD_REND, "We already have a newer service descriptor for "
  1272. "service ID %s with the same desc ID and version.",
  1273. safe_str_client(service_id));
  1274. retval = 0;
  1275. goto err;
  1276. }
  1277. /* Do we already have this descriptor? */
  1278. if (e && !strcmp(desc, e->desc)) {
  1279. log_info(LD_REND,"We already have this service descriptor %s.",
  1280. safe_str_client(service_id));
  1281. e->received = time(NULL);
  1282. retval = 0;
  1283. goto err;
  1284. }
  1285. if (!e) {
  1286. e = tor_malloc_zero(sizeof(rend_cache_entry_t));
  1287. strmap_set_lc(rend_cache, key, e);
  1288. } else {
  1289. rend_service_descriptor_free(e->parsed);
  1290. tor_free(e->desc);
  1291. }
  1292. e->received = time(NULL);
  1293. e->parsed = parsed;
  1294. e->desc = tor_malloc_zero(encoded_size + 1);
  1295. strlcpy(e->desc, desc, encoded_size + 1);
  1296. e->len = encoded_size;
  1297. log_debug(LD_REND,"Successfully stored rend desc '%s', len %d.",
  1298. safe_str_client(service_id), (int)encoded_size);
  1299. return 1;
  1300. err:
  1301. rend_service_descriptor_free(parsed);
  1302. tor_free(intro_content);
  1303. return retval;
  1304. }
  1305. /** Called when we get a rendezvous-related relay cell on circuit
  1306. * <b>circ</b>. Dispatch on rendezvous relay command. */
  1307. void
  1308. rend_process_relay_cell(circuit_t *circ, const crypt_path_t *layer_hint,
  1309. int command, size_t length,
  1310. const uint8_t *payload)
  1311. {
  1312. or_circuit_t *or_circ = NULL;
  1313. origin_circuit_t *origin_circ = NULL;
  1314. int r = -2;
  1315. if (CIRCUIT_IS_ORIGIN(circ)) {
  1316. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  1317. if (!layer_hint || layer_hint != origin_circ->cpath->prev) {
  1318. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1319. "Relay cell (rend purpose %d) from wrong hop on origin circ",
  1320. command);
  1321. origin_circ = NULL;
  1322. }
  1323. } else {
  1324. or_circ = TO_OR_CIRCUIT(circ);
  1325. }
  1326. switch (command) {
  1327. case RELAY_COMMAND_ESTABLISH_INTRO:
  1328. if (or_circ)
  1329. r = rend_mid_establish_intro(or_circ,payload,length);
  1330. break;
  1331. case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
  1332. if (or_circ)
  1333. r = rend_mid_establish_rendezvous(or_circ,payload,length);
  1334. break;
  1335. case RELAY_COMMAND_INTRODUCE1:
  1336. if (or_circ)
  1337. r = rend_mid_introduce(or_circ,payload,length);
  1338. break;
  1339. case RELAY_COMMAND_INTRODUCE2:
  1340. if (origin_circ)
  1341. r = rend_service_introduce(origin_circ,payload,length);
  1342. break;
  1343. case RELAY_COMMAND_INTRODUCE_ACK:
  1344. if (origin_circ)
  1345. r = rend_client_introduction_acked(origin_circ,payload,length);
  1346. break;
  1347. case RELAY_COMMAND_RENDEZVOUS1:
  1348. if (or_circ)
  1349. r = rend_mid_rendezvous(or_circ,payload,length);
  1350. break;
  1351. case RELAY_COMMAND_RENDEZVOUS2:
  1352. if (origin_circ)
  1353. r = rend_client_receive_rendezvous(origin_circ,payload,length);
  1354. break;
  1355. case RELAY_COMMAND_INTRO_ESTABLISHED:
  1356. if (origin_circ)
  1357. r = rend_service_intro_established(origin_circ,payload,length);
  1358. break;
  1359. case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
  1360. if (origin_circ)
  1361. r = rend_client_rendezvous_acked(origin_circ,payload,length);
  1362. break;
  1363. default:
  1364. tor_fragile_assert();
  1365. }
  1366. if (r == -2)
  1367. log_info(LD_PROTOCOL, "Dropping cell (type %d) for wrong circuit type.",
  1368. command);
  1369. }
  1370. /** Return the number of entries in our rendezvous descriptor cache. */
  1371. int
  1372. rend_cache_size(void)
  1373. {
  1374. return strmap_size(rend_cache);
  1375. }
  1376. /** Allocate and return a new rend_data_t with the same
  1377. * contents as <b>query</b>. */
  1378. rend_data_t *
  1379. rend_data_dup(const rend_data_t *data)
  1380. {
  1381. tor_assert(data);
  1382. return tor_memdup(data, sizeof(rend_data_t));
  1383. }