rendcommon.c 51 KB

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