rendcommon.c 51 KB

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