rendcommon.c 52 KB

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