rendcommon.c 51 KB

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