rendcommon.c 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471
  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_pk_free(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_t *digest = crypto_digest_new();
  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_digest_free(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_t *digest = crypto_digest_new();
  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_digest_free(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_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_t *digest;
  253. crypto_cipher_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_cipher_free(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_new();
  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_cipher_free(cipher);
  299. tor_free(client_part);
  300. goto done;
  301. }
  302. crypto_cipher_free(cipher);
  303. /* Determine client ID. */
  304. digest = crypto_digest_new();
  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_digest_free(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_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_cipher_free(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_pk_free(intro->intro_key);
  417. if (intro->accepted_intro_rsa_parts != NULL) {
  418. digestmap_free(intro->accepted_intro_rsa_parts, _tor_free);
  419. }
  420. tor_free(intro);
  421. }
  422. /** Encode a set of rend_encoded_v2_service_descriptor_t's for <b>desc</b>
  423. * at time <b>now</b> using <b>service_key</b>, depending on
  424. * <b>auth_type</b> a <b>descriptor_cookie</b> and a list of
  425. * <b>client_cookies</b> (which are both <b>NULL</b> if no client
  426. * authorization is performed), and <b>period</b> (e.g. 0 for the current
  427. * period, 1 for the next period, etc.) and add them to the existing list
  428. * <b>descs_out</b>; return the number of seconds that the descriptors will
  429. * be found by clients, or -1 if the encoding was not successful. */
  430. int
  431. rend_encode_v2_descriptors(smartlist_t *descs_out,
  432. rend_service_descriptor_t *desc, time_t now,
  433. uint8_t period, rend_auth_type_t auth_type,
  434. crypto_pk_t *client_key,
  435. smartlist_t *client_cookies)
  436. {
  437. char service_id[DIGEST_LEN];
  438. uint32_t time_period;
  439. char *ipos_base64 = NULL, *ipos = NULL, *ipos_encrypted = NULL,
  440. *descriptor_cookie = NULL;
  441. size_t ipos_len = 0, ipos_encrypted_len = 0;
  442. int k;
  443. uint32_t seconds_valid;
  444. crypto_pk_t *service_key;
  445. if (!desc) {
  446. log_warn(LD_BUG, "Could not encode v2 descriptor: No desc given.");
  447. return -1;
  448. }
  449. service_key = (auth_type == REND_STEALTH_AUTH) ? client_key : desc->pk;
  450. tor_assert(service_key);
  451. if (auth_type == REND_STEALTH_AUTH) {
  452. descriptor_cookie = smartlist_get(client_cookies, 0);
  453. tor_assert(descriptor_cookie);
  454. }
  455. /* Obtain service_id from public key. */
  456. crypto_pk_get_digest(service_key, service_id);
  457. /* Calculate current time-period. */
  458. time_period = get_time_period(now, period, service_id);
  459. /* Determine how many seconds the descriptor will be valid. */
  460. seconds_valid = period * REND_TIME_PERIOD_V2_DESC_VALIDITY +
  461. get_seconds_valid(now, service_id);
  462. /* Assemble, possibly encrypt, and encode introduction points. */
  463. if (smartlist_len(desc->intro_nodes) > 0) {
  464. if (rend_encode_v2_intro_points(&ipos, desc) < 0) {
  465. log_warn(LD_REND, "Encoding of introduction points did not succeed.");
  466. return -1;
  467. }
  468. switch (auth_type) {
  469. case REND_NO_AUTH:
  470. ipos_len = strlen(ipos);
  471. break;
  472. case REND_BASIC_AUTH:
  473. if (rend_encrypt_v2_intro_points_basic(&ipos_encrypted,
  474. &ipos_encrypted_len, ipos,
  475. client_cookies) < 0) {
  476. log_warn(LD_REND, "Encrypting of introduction points did not "
  477. "succeed.");
  478. tor_free(ipos);
  479. return -1;
  480. }
  481. tor_free(ipos);
  482. ipos = ipos_encrypted;
  483. ipos_len = ipos_encrypted_len;
  484. break;
  485. case REND_STEALTH_AUTH:
  486. if (rend_encrypt_v2_intro_points_stealth(&ipos_encrypted,
  487. &ipos_encrypted_len, ipos,
  488. descriptor_cookie) < 0) {
  489. log_warn(LD_REND, "Encrypting of introduction points did not "
  490. "succeed.");
  491. tor_free(ipos);
  492. return -1;
  493. }
  494. tor_free(ipos);
  495. ipos = ipos_encrypted;
  496. ipos_len = ipos_encrypted_len;
  497. break;
  498. default:
  499. log_warn(LD_REND|LD_BUG, "Unrecognized authorization type %d",
  500. (int)auth_type);
  501. tor_free(ipos);
  502. return -1;
  503. }
  504. /* Base64-encode introduction points. */
  505. ipos_base64 = tor_malloc_zero(ipos_len * 2);
  506. if (base64_encode(ipos_base64, ipos_len * 2, ipos, ipos_len)<0) {
  507. log_warn(LD_REND, "Could not encode introduction point string to "
  508. "base64. length=%d", (int)ipos_len);
  509. tor_free(ipos_base64);
  510. tor_free(ipos);
  511. return -1;
  512. }
  513. tor_free(ipos);
  514. }
  515. /* Encode REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS descriptors. */
  516. for (k = 0; k < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS; k++) {
  517. char secret_id_part[DIGEST_LEN];
  518. char secret_id_part_base32[REND_SECRET_ID_PART_LEN_BASE32 + 1];
  519. char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  520. char *permanent_key = NULL;
  521. size_t permanent_key_len;
  522. char published[ISO_TIME_LEN+1];
  523. int i;
  524. char protocol_versions_string[16]; /* max len: "0,1,2,3,4,5,6,7\0" */
  525. size_t protocol_versions_written;
  526. size_t desc_len;
  527. char *desc_str = NULL;
  528. int result = 0;
  529. size_t written = 0;
  530. char desc_digest[DIGEST_LEN];
  531. rend_encoded_v2_service_descriptor_t *enc =
  532. tor_malloc_zero(sizeof(rend_encoded_v2_service_descriptor_t));
  533. /* Calculate secret-id-part = h(time-period + cookie + replica). */
  534. get_secret_id_part_bytes(secret_id_part, time_period, descriptor_cookie,
  535. k);
  536. base32_encode(secret_id_part_base32, sizeof(secret_id_part_base32),
  537. secret_id_part, DIGEST_LEN);
  538. /* Calculate descriptor ID. */
  539. rend_get_descriptor_id_bytes(enc->desc_id, service_id, secret_id_part);
  540. base32_encode(desc_id_base32, sizeof(desc_id_base32),
  541. enc->desc_id, DIGEST_LEN);
  542. /* PEM-encode the public key */
  543. if (crypto_pk_write_public_key_to_string(service_key, &permanent_key,
  544. &permanent_key_len) < 0) {
  545. log_warn(LD_BUG, "Could not write public key to string.");
  546. rend_encoded_v2_service_descriptor_free(enc);
  547. goto err;
  548. }
  549. /* Encode timestamp. */
  550. format_iso_time(published, desc->timestamp);
  551. /* Write protocol-versions bitmask to comma-separated value string. */
  552. protocol_versions_written = 0;
  553. for (i = 0; i < 8; i++) {
  554. if (desc->protocols & 1 << i) {
  555. tor_snprintf(protocol_versions_string + protocol_versions_written,
  556. 16 - protocol_versions_written, "%d,", i);
  557. protocol_versions_written += 2;
  558. }
  559. }
  560. if (protocol_versions_written)
  561. protocol_versions_string[protocol_versions_written - 1] = '\0';
  562. else
  563. protocol_versions_string[0]= '\0';
  564. /* Assemble complete descriptor. */
  565. desc_len = 2000 + smartlist_len(desc->intro_nodes) * 1000; /* far too long,
  566. but okay.*/
  567. enc->desc_str = desc_str = tor_malloc_zero(desc_len);
  568. result = tor_snprintf(desc_str, desc_len,
  569. "rendezvous-service-descriptor %s\n"
  570. "version 2\n"
  571. "permanent-key\n%s"
  572. "secret-id-part %s\n"
  573. "publication-time %s\n"
  574. "protocol-versions %s\n",
  575. desc_id_base32,
  576. permanent_key,
  577. secret_id_part_base32,
  578. published,
  579. protocol_versions_string);
  580. tor_free(permanent_key);
  581. if (result < 0) {
  582. log_warn(LD_BUG, "Descriptor ran out of room.");
  583. rend_encoded_v2_service_descriptor_free(enc);
  584. goto err;
  585. }
  586. written = result;
  587. /* Add introduction points. */
  588. if (ipos_base64) {
  589. result = tor_snprintf(desc_str + written, desc_len - written,
  590. "introduction-points\n"
  591. "-----BEGIN MESSAGE-----\n%s"
  592. "-----END MESSAGE-----\n",
  593. ipos_base64);
  594. if (result < 0) {
  595. log_warn(LD_BUG, "could not write introduction points.");
  596. rend_encoded_v2_service_descriptor_free(enc);
  597. goto err;
  598. }
  599. written += result;
  600. }
  601. /* Add signature. */
  602. strlcpy(desc_str + written, "signature\n", desc_len - written);
  603. written += strlen(desc_str + written);
  604. if (crypto_digest(desc_digest, desc_str, written) < 0) {
  605. log_warn(LD_BUG, "could not create digest.");
  606. rend_encoded_v2_service_descriptor_free(enc);
  607. goto err;
  608. }
  609. if (router_append_dirobj_signature(desc_str + written,
  610. desc_len - written,
  611. desc_digest, DIGEST_LEN,
  612. service_key) < 0) {
  613. log_warn(LD_BUG, "Couldn't sign desc.");
  614. rend_encoded_v2_service_descriptor_free(enc);
  615. goto err;
  616. }
  617. written += strlen(desc_str+written);
  618. if (written+2 > desc_len) {
  619. log_warn(LD_BUG, "Could not finish desc.");
  620. rend_encoded_v2_service_descriptor_free(enc);
  621. goto err;
  622. }
  623. desc_str[written++] = '\n';
  624. desc_str[written++] = 0;
  625. /* Check if we can parse our own descriptor. */
  626. if (!rend_desc_v2_is_parsable(enc)) {
  627. log_warn(LD_BUG, "Could not parse my own descriptor: %s", desc_str);
  628. rend_encoded_v2_service_descriptor_free(enc);
  629. goto err;
  630. }
  631. smartlist_add(descs_out, enc);
  632. }
  633. log_info(LD_REND, "Successfully encoded a v2 descriptor and "
  634. "confirmed that it is parsable.");
  635. goto done;
  636. err:
  637. SMARTLIST_FOREACH(descs_out, rend_encoded_v2_service_descriptor_t *, d,
  638. rend_encoded_v2_service_descriptor_free(d););
  639. smartlist_clear(descs_out);
  640. seconds_valid = -1;
  641. done:
  642. tor_free(ipos_base64);
  643. return seconds_valid;
  644. }
  645. /** Parse a service descriptor at <b>str</b> (<b>len</b> bytes). On
  646. * success, return a newly alloced service_descriptor_t. On failure,
  647. * return NULL.
  648. */
  649. rend_service_descriptor_t *
  650. rend_parse_service_descriptor(const char *str, size_t len)
  651. {
  652. rend_service_descriptor_t *result = NULL;
  653. int i, n_intro_points;
  654. size_t keylen, asn1len;
  655. const char *end, *cp, *eos;
  656. rend_intro_point_t *intro;
  657. result = tor_malloc_zero(sizeof(rend_service_descriptor_t));
  658. cp = str;
  659. end = str+len;
  660. if (end-cp<2) goto truncated;
  661. result->version = 0;
  662. if (end-cp < 2) goto truncated;
  663. asn1len = ntohs(get_uint16(cp));
  664. cp += 2;
  665. if ((size_t)(end-cp) < asn1len) goto truncated;
  666. result->pk = crypto_pk_asn1_decode(cp, asn1len);
  667. if (!result->pk) goto truncated;
  668. cp += asn1len;
  669. if (end-cp < 4) goto truncated;
  670. result->timestamp = (time_t) ntohl(get_uint32(cp));
  671. cp += 4;
  672. result->protocols = 1<<2; /* always use intro format 2 */
  673. if (end-cp < 2) goto truncated;
  674. n_intro_points = ntohs(get_uint16(cp));
  675. cp += 2;
  676. result->intro_nodes = smartlist_new();
  677. for (i=0;i<n_intro_points;++i) {
  678. if (end-cp < 2) goto truncated;
  679. eos = (const char *)memchr(cp,'\0',end-cp);
  680. if (!eos) goto truncated;
  681. /* Write nickname to extend info, but postpone the lookup whether
  682. * we know that router. It's not part of the parsing process. */
  683. intro = tor_malloc_zero(sizeof(rend_intro_point_t));
  684. intro->extend_info = tor_malloc_zero(sizeof(extend_info_t));
  685. strlcpy(intro->extend_info->nickname, cp,
  686. sizeof(intro->extend_info->nickname));
  687. smartlist_add(result->intro_nodes, intro);
  688. cp = eos+1;
  689. }
  690. keylen = crypto_pk_keysize(result->pk);
  691. tor_assert(end-cp >= 0);
  692. if ((size_t)(end-cp) < keylen) goto truncated;
  693. if ((size_t)(end-cp) > keylen) {
  694. log_warn(LD_PROTOCOL,
  695. "Signature is %d bytes too long on service descriptor.",
  696. (int)((size_t)(end-cp) - keylen));
  697. goto error;
  698. }
  699. note_crypto_pk_op(REND_CLIENT);
  700. if (crypto_pk_public_checksig_digest(result->pk,
  701. (char*)str,cp-str, /* data */
  702. (char*)cp,end-cp /* signature*/
  703. )<0) {
  704. log_warn(LD_PROTOCOL, "Bad signature on service descriptor.");
  705. goto error;
  706. }
  707. return result;
  708. truncated:
  709. log_warn(LD_PROTOCOL, "Truncated service descriptor.");
  710. error:
  711. rend_service_descriptor_free(result);
  712. return NULL;
  713. }
  714. /** Sets <b>out</b> to the first 10 bytes of the digest of <b>pk</b>,
  715. * base32 encoded. NUL-terminates out. (We use this string to
  716. * identify services in directory requests and .onion URLs.)
  717. */
  718. int
  719. rend_get_service_id(crypto_pk_t *pk, char *out)
  720. {
  721. char buf[DIGEST_LEN];
  722. tor_assert(pk);
  723. if (crypto_pk_get_digest(pk, buf) < 0)
  724. return -1;
  725. base32_encode(out, REND_SERVICE_ID_LEN_BASE32+1, buf, REND_SERVICE_ID_LEN);
  726. return 0;
  727. }
  728. /* ==== Rendezvous service descriptor cache. */
  729. /** How old do we let hidden service descriptors get before discarding
  730. * them as too old? */
  731. #define REND_CACHE_MAX_AGE (2*24*60*60)
  732. /** How wrong do we assume our clock may be when checking whether hidden
  733. * services are too old or too new? */
  734. #define REND_CACHE_MAX_SKEW (24*60*60)
  735. /** Map from service id (as generated by rend_get_service_id) to
  736. * rend_cache_entry_t. */
  737. static strmap_t *rend_cache = NULL;
  738. /** Map from descriptor id to rend_cache_entry_t; only for hidden service
  739. * directories. */
  740. static digestmap_t *rend_cache_v2_dir = NULL;
  741. /** Initializes the service descriptor cache.
  742. */
  743. void
  744. rend_cache_init(void)
  745. {
  746. rend_cache = strmap_new();
  747. rend_cache_v2_dir = digestmap_new();
  748. }
  749. /** Helper: free storage held by a single service descriptor cache entry. */
  750. static void
  751. rend_cache_entry_free(rend_cache_entry_t *e)
  752. {
  753. if (!e)
  754. return;
  755. rend_service_descriptor_free(e->parsed);
  756. tor_free(e->desc);
  757. tor_free(e);
  758. }
  759. static void
  760. _rend_cache_entry_free(void *p)
  761. {
  762. rend_cache_entry_free(p);
  763. }
  764. /** Free all storage held by the service descriptor cache. */
  765. void
  766. rend_cache_free_all(void)
  767. {
  768. strmap_free(rend_cache, _rend_cache_entry_free);
  769. digestmap_free(rend_cache_v2_dir, _rend_cache_entry_free);
  770. rend_cache = NULL;
  771. rend_cache_v2_dir = NULL;
  772. }
  773. /** Removes all old entries from the service descriptor cache.
  774. */
  775. void
  776. rend_cache_clean(time_t now)
  777. {
  778. strmap_iter_t *iter;
  779. const char *key;
  780. void *val;
  781. rend_cache_entry_t *ent;
  782. time_t cutoff = now - REND_CACHE_MAX_AGE - REND_CACHE_MAX_SKEW;
  783. for (iter = strmap_iter_init(rend_cache); !strmap_iter_done(iter); ) {
  784. strmap_iter_get(iter, &key, &val);
  785. ent = (rend_cache_entry_t*)val;
  786. if (ent->parsed->timestamp < cutoff) {
  787. iter = strmap_iter_next_rmv(rend_cache, iter);
  788. rend_cache_entry_free(ent);
  789. } else {
  790. iter = strmap_iter_next(rend_cache, iter);
  791. }
  792. }
  793. }
  794. /** Remove ALL entries from the rendezvous service descriptor cache.
  795. */
  796. void
  797. rend_cache_purge(void)
  798. {
  799. if (rend_cache) {
  800. log_info(LD_REND, "Purging client/v0-HS-authority HS descriptor cache");
  801. strmap_free(rend_cache, _rend_cache_entry_free);
  802. }
  803. rend_cache = strmap_new();
  804. }
  805. /** Remove all old v2 descriptors and those for which this hidden service
  806. * directory is not responsible for any more. */
  807. void
  808. rend_cache_clean_v2_descs_as_dir(time_t now)
  809. {
  810. digestmap_iter_t *iter;
  811. time_t cutoff = now - REND_CACHE_MAX_AGE - REND_CACHE_MAX_SKEW;
  812. for (iter = digestmap_iter_init(rend_cache_v2_dir);
  813. !digestmap_iter_done(iter); ) {
  814. const char *key;
  815. void *val;
  816. rend_cache_entry_t *ent;
  817. digestmap_iter_get(iter, &key, &val);
  818. ent = val;
  819. if (ent->parsed->timestamp < cutoff ||
  820. !hid_serv_responsible_for_desc_id(key)) {
  821. char key_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  822. base32_encode(key_base32, sizeof(key_base32), key, DIGEST_LEN);
  823. log_info(LD_REND, "Removing descriptor with ID '%s' from cache",
  824. safe_str_client(key_base32));
  825. iter = digestmap_iter_next_rmv(rend_cache_v2_dir, iter);
  826. rend_cache_entry_free(ent);
  827. } else {
  828. iter = digestmap_iter_next(rend_cache_v2_dir, iter);
  829. }
  830. }
  831. }
  832. /** Determines whether <b>a</b> is in the interval of <b>b</b> (excluded) and
  833. * <b>c</b> (included) in a circular digest ring; returns 1 if this is the
  834. * case, and 0 otherwise.
  835. */
  836. int
  837. rend_id_is_in_interval(const char *a, const char *b, const char *c)
  838. {
  839. int a_b, b_c, c_a;
  840. tor_assert(a);
  841. tor_assert(b);
  842. tor_assert(c);
  843. /* There are five cases in which a is outside the interval ]b,c]: */
  844. a_b = tor_memcmp(a,b,DIGEST_LEN);
  845. if (a_b == 0)
  846. return 0; /* 1. a == b (b is excluded) */
  847. b_c = tor_memcmp(b,c,DIGEST_LEN);
  848. if (b_c == 0)
  849. return 0; /* 2. b == c (interval is empty) */
  850. else if (a_b <= 0 && b_c < 0)
  851. return 0; /* 3. a b c */
  852. c_a = tor_memcmp(c,a,DIGEST_LEN);
  853. if (c_a < 0 && a_b <= 0)
  854. return 0; /* 4. c a b */
  855. else if (b_c < 0 && c_a < 0)
  856. return 0; /* 5. b c a */
  857. /* In the other cases (a c b; b a c; c b a), a is inside the interval. */
  858. return 1;
  859. }
  860. /** Return true iff <b>query</b> is a syntactically valid service ID (as
  861. * generated by rend_get_service_id). */
  862. int
  863. rend_valid_service_id(const char *query)
  864. {
  865. if (strlen(query) != REND_SERVICE_ID_LEN_BASE32)
  866. return 0;
  867. if (strspn(query, BASE32_CHARS) != REND_SERVICE_ID_LEN_BASE32)
  868. return 0;
  869. return 1;
  870. }
  871. /** If we have a cached rend_cache_entry_t for the service ID <b>query</b>
  872. * with <b>version</b>, set *<b>e</b> to that entry and return 1.
  873. * Else return 0. If <b>version</b> is nonnegative, only return an entry
  874. * in that descriptor format version. Otherwise (if <b>version</b> is
  875. * negative), return the most recent format we have.
  876. */
  877. int
  878. rend_cache_lookup_entry(const char *query, int version, rend_cache_entry_t **e)
  879. {
  880. char key[REND_SERVICE_ID_LEN_BASE32+2]; /* <version><query>\0 */
  881. tor_assert(rend_cache);
  882. if (!rend_valid_service_id(query))
  883. return -1;
  884. *e = NULL;
  885. if (version != 0) {
  886. tor_snprintf(key, sizeof(key), "2%s", query);
  887. *e = strmap_get_lc(rend_cache, key);
  888. }
  889. if (!*e && version != 2) {
  890. tor_snprintf(key, sizeof(key), "0%s", query);
  891. *e = strmap_get_lc(rend_cache, key);
  892. }
  893. if (!*e)
  894. return 0;
  895. tor_assert((*e)->parsed && (*e)->parsed->intro_nodes);
  896. /* XXX023 hack for now, to return "not found" if there are no intro
  897. * points remaining. See bug 997. */
  898. if (! rend_client_any_intro_points_usable(*e))
  899. return 0;
  900. return 1;
  901. }
  902. /** <b>query</b> is a base-32'ed service id. If it's malformed, return -1.
  903. * Else look it up.
  904. * - If it is found, point *desc to it, and write its length into
  905. * *desc_len, and return 1.
  906. * - If it is not found, return 0.
  907. * Note: calls to rend_cache_clean or rend_cache_store may invalidate
  908. * *desc.
  909. */
  910. int
  911. rend_cache_lookup_desc(const char *query, int version, const char **desc,
  912. size_t *desc_len)
  913. {
  914. rend_cache_entry_t *e;
  915. int r;
  916. r = rend_cache_lookup_entry(query,version,&e);
  917. if (r <= 0) return r;
  918. *desc = e->desc;
  919. *desc_len = e->len;
  920. return 1;
  921. }
  922. /** Lookup the v2 service descriptor with base32-encoded <b>desc_id</b> and
  923. * copy the pointer to it to *<b>desc</b>. Return 1 on success, 0 on
  924. * well-formed-but-not-found, and -1 on failure.
  925. */
  926. int
  927. rend_cache_lookup_v2_desc_as_dir(const char *desc_id, const char **desc)
  928. {
  929. rend_cache_entry_t *e;
  930. char desc_id_digest[DIGEST_LEN];
  931. tor_assert(rend_cache_v2_dir);
  932. if (base32_decode(desc_id_digest, DIGEST_LEN,
  933. desc_id, REND_DESC_ID_V2_LEN_BASE32) < 0) {
  934. log_fn(LOG_PROTOCOL_WARN, LD_REND,
  935. "Rejecting v2 rendezvous descriptor request -- descriptor ID "
  936. "contains illegal characters: %s",
  937. safe_str(desc_id));
  938. return -1;
  939. }
  940. /* Lookup descriptor and return. */
  941. e = digestmap_get(rend_cache_v2_dir, desc_id_digest);
  942. if (e) {
  943. *desc = e->desc;
  944. return 1;
  945. }
  946. return 0;
  947. }
  948. /** Parse *desc, calculate its service id, and store it in the cache.
  949. * If we have a newer v0 descriptor with the same ID, ignore this one.
  950. * If we have an older descriptor with the same ID, replace it.
  951. * If we are acting as client due to the published flag and have any v2
  952. * descriptor with the same ID, reject this one in order to not get
  953. * confused with having both versions for the same service.
  954. *
  955. * Return -2 if it's malformed or otherwise rejected; return -1 if we
  956. * already have a v2 descriptor here; return 0 if it's the same or older
  957. * than one we've already got; return 1 if it's novel.
  958. *
  959. * The published flag tells us if we store the descriptor
  960. * in our role as directory (1) or if we cache it as client (0).
  961. *
  962. * If <b>service_id</b> is non-NULL and the descriptor is not for that
  963. * service ID, reject it. <b>service_id</b> must be specified if and
  964. * only if <b>published</b> is 0 (we fetched this descriptor).
  965. */
  966. int
  967. rend_cache_store(const char *desc, size_t desc_len, int published,
  968. const char *service_id)
  969. {
  970. rend_cache_entry_t *e;
  971. rend_service_descriptor_t *parsed;
  972. char query[REND_SERVICE_ID_LEN_BASE32+1];
  973. char key[REND_SERVICE_ID_LEN_BASE32+2]; /* 0<query>\0 */
  974. time_t now;
  975. tor_assert(rend_cache);
  976. parsed = rend_parse_service_descriptor(desc,desc_len);
  977. if (!parsed) {
  978. log_warn(LD_PROTOCOL,"Couldn't parse service descriptor.");
  979. return -2;
  980. }
  981. if (rend_get_service_id(parsed->pk, query)<0) {
  982. log_warn(LD_BUG,"Couldn't compute service ID.");
  983. rend_service_descriptor_free(parsed);
  984. return -2;
  985. }
  986. if ((service_id != NULL) && strcmp(query, service_id)) {
  987. log_warn(LD_REND, "Received service descriptor for service ID %s; "
  988. "expected descriptor for service ID %s.",
  989. query, safe_str(service_id));
  990. rend_service_descriptor_free(parsed);
  991. return -2;
  992. }
  993. now = time(NULL);
  994. if (parsed->timestamp < now-REND_CACHE_MAX_AGE-REND_CACHE_MAX_SKEW) {
  995. log_fn(LOG_PROTOCOL_WARN, LD_REND,
  996. "Service descriptor %s is too old.",
  997. safe_str_client(query));
  998. rend_service_descriptor_free(parsed);
  999. return -2;
  1000. }
  1001. if (parsed->timestamp > now+REND_CACHE_MAX_SKEW) {
  1002. log_fn(LOG_PROTOCOL_WARN, LD_REND,
  1003. "Service descriptor %s is too far in the future.",
  1004. safe_str_client(query));
  1005. rend_service_descriptor_free(parsed);
  1006. return -2;
  1007. }
  1008. /* Do we have a v2 descriptor and fetched this descriptor as a client? */
  1009. tor_snprintf(key, sizeof(key), "2%s", query);
  1010. if (!published && strmap_get_lc(rend_cache, key)) {
  1011. log_info(LD_REND, "We already have a v2 descriptor for service %s.",
  1012. safe_str_client(query));
  1013. rend_service_descriptor_free(parsed);
  1014. return -1;
  1015. }
  1016. tor_snprintf(key, sizeof(key), "0%s", query);
  1017. e = (rend_cache_entry_t*) strmap_get_lc(rend_cache, key);
  1018. if (e && e->parsed->timestamp > parsed->timestamp) {
  1019. log_info(LD_REND,"We already have a newer service descriptor %s with the "
  1020. "same ID and version.",
  1021. safe_str_client(query));
  1022. rend_service_descriptor_free(parsed);
  1023. return 0;
  1024. }
  1025. if (e && e->len == desc_len && tor_memeq(desc,e->desc,desc_len)) {
  1026. log_info(LD_REND,"We already have this service descriptor %s.",
  1027. safe_str_client(query));
  1028. e->received = time(NULL);
  1029. rend_service_descriptor_free(parsed);
  1030. return 0;
  1031. }
  1032. if (!e) {
  1033. e = tor_malloc_zero(sizeof(rend_cache_entry_t));
  1034. strmap_set_lc(rend_cache, key, e);
  1035. } else {
  1036. rend_service_descriptor_free(e->parsed);
  1037. tor_free(e->desc);
  1038. }
  1039. e->received = time(NULL);
  1040. e->parsed = parsed;
  1041. e->len = desc_len;
  1042. e->desc = tor_malloc(desc_len);
  1043. memcpy(e->desc, desc, desc_len);
  1044. log_debug(LD_REND,"Successfully stored rend desc '%s', len %d.",
  1045. safe_str_client(query), (int)desc_len);
  1046. return 1;
  1047. }
  1048. /** Parse the v2 service descriptor(s) in <b>desc</b> and store it/them to the
  1049. * local rend cache. Don't attempt to decrypt the included list of introduction
  1050. * points (as we don't have a descriptor cookie for it).
  1051. *
  1052. * If we have a newer descriptor with the same ID, ignore this one.
  1053. * If we have an older descriptor with the same ID, replace it.
  1054. * Return -2 if we are not acting as hidden service directory;
  1055. * return -1 if the descriptor(s) were not parsable; return 0 if all
  1056. * descriptors are the same or older than those we've already got;
  1057. * return a positive number for the number of novel stored descriptors.
  1058. */
  1059. int
  1060. rend_cache_store_v2_desc_as_dir(const char *desc)
  1061. {
  1062. rend_service_descriptor_t *parsed;
  1063. char desc_id[DIGEST_LEN];
  1064. char *intro_content;
  1065. size_t intro_size;
  1066. size_t encoded_size;
  1067. char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  1068. int number_parsed = 0, number_stored = 0;
  1069. const char *current_desc = desc;
  1070. const char *next_desc;
  1071. rend_cache_entry_t *e;
  1072. time_t now = time(NULL);
  1073. tor_assert(rend_cache_v2_dir);
  1074. tor_assert(desc);
  1075. if (!hid_serv_acting_as_directory()) {
  1076. /* Cannot store descs, because we are (currently) not acting as
  1077. * hidden service directory. */
  1078. log_info(LD_REND, "Cannot store descs: Not acting as hs dir");
  1079. return -2;
  1080. }
  1081. while (rend_parse_v2_service_descriptor(&parsed, desc_id, &intro_content,
  1082. &intro_size, &encoded_size,
  1083. &next_desc, current_desc) >= 0) {
  1084. number_parsed++;
  1085. /* We don't care about the introduction points. */
  1086. tor_free(intro_content);
  1087. /* For pretty log statements. */
  1088. base32_encode(desc_id_base32, sizeof(desc_id_base32),
  1089. desc_id, DIGEST_LEN);
  1090. /* Is desc ID in the range that we are (directly or indirectly) responsible
  1091. * for? */
  1092. if (!hid_serv_responsible_for_desc_id(desc_id)) {
  1093. log_info(LD_REND, "Service descriptor with desc ID %s is not in "
  1094. "interval that we are responsible for.",
  1095. safe_str_client(desc_id_base32));
  1096. goto skip;
  1097. }
  1098. /* Is descriptor too old? */
  1099. if (parsed->timestamp < now - REND_CACHE_MAX_AGE-REND_CACHE_MAX_SKEW) {
  1100. log_info(LD_REND, "Service descriptor with desc ID %s is too old.",
  1101. safe_str(desc_id_base32));
  1102. goto skip;
  1103. }
  1104. /* Is descriptor too far in the future? */
  1105. if (parsed->timestamp > now + REND_CACHE_MAX_SKEW) {
  1106. log_info(LD_REND, "Service descriptor with desc ID %s is too far in the "
  1107. "future.",
  1108. safe_str(desc_id_base32));
  1109. goto skip;
  1110. }
  1111. /* Do we already have a newer descriptor? */
  1112. e = digestmap_get(rend_cache_v2_dir, desc_id);
  1113. if (e && e->parsed->timestamp > parsed->timestamp) {
  1114. log_info(LD_REND, "We already have a newer service descriptor with the "
  1115. "same desc ID %s and version.",
  1116. safe_str(desc_id_base32));
  1117. goto skip;
  1118. }
  1119. /* Do we already have this descriptor? */
  1120. if (e && !strcmp(desc, e->desc)) {
  1121. log_info(LD_REND, "We already have this service descriptor with desc "
  1122. "ID %s.", safe_str(desc_id_base32));
  1123. e->received = time(NULL);
  1124. goto skip;
  1125. }
  1126. /* Store received descriptor. */
  1127. if (!e) {
  1128. e = tor_malloc_zero(sizeof(rend_cache_entry_t));
  1129. digestmap_set(rend_cache_v2_dir, desc_id, e);
  1130. } else {
  1131. rend_service_descriptor_free(e->parsed);
  1132. tor_free(e->desc);
  1133. }
  1134. e->received = time(NULL);
  1135. e->parsed = parsed;
  1136. e->desc = tor_strndup(current_desc, encoded_size);
  1137. e->len = encoded_size;
  1138. log_info(LD_REND, "Successfully stored service descriptor with desc ID "
  1139. "'%s' and len %d.",
  1140. safe_str(desc_id_base32), (int)encoded_size);
  1141. number_stored++;
  1142. goto advance;
  1143. skip:
  1144. rend_service_descriptor_free(parsed);
  1145. advance:
  1146. /* advance to next descriptor, if available. */
  1147. current_desc = next_desc;
  1148. /* check if there is a next descriptor. */
  1149. if (!current_desc ||
  1150. strcmpstart(current_desc, "rendezvous-service-descriptor "))
  1151. break;
  1152. }
  1153. if (!number_parsed) {
  1154. log_info(LD_REND, "Could not parse any descriptor.");
  1155. return -1;
  1156. }
  1157. log_info(LD_REND, "Parsed %d and added %d descriptor%s.",
  1158. number_parsed, number_stored, number_stored != 1 ? "s" : "");
  1159. return number_stored;
  1160. }
  1161. /** Parse the v2 service descriptor in <b>desc</b>, decrypt the included list
  1162. * of introduction points with <b>descriptor_cookie</b> (which may also be
  1163. * <b>NULL</b> if decryption is not necessary), and store the descriptor to
  1164. * the local cache under its version and service id.
  1165. *
  1166. * If we have a newer v2 descriptor with the same ID, ignore this one.
  1167. * If we have an older descriptor with the same ID, replace it.
  1168. * If we have any v0 descriptor with the same ID, reject this one in order
  1169. * to not get confused with having both versions for the same service.
  1170. * If the descriptor's service ID does not match
  1171. * <b>rend_query</b>-\>onion_address, reject it.
  1172. * Return -2 if it's malformed or otherwise rejected; return -1 if we
  1173. * already have a v0 descriptor here; return 0 if it's the same or older
  1174. * than one we've already got; return 1 if it's novel.
  1175. */
  1176. int
  1177. rend_cache_store_v2_desc_as_client(const char *desc,
  1178. const rend_data_t *rend_query)
  1179. {
  1180. /*XXXX this seems to have a bit of duplicate code with
  1181. * rend_cache_store_v2_desc_as_dir(). Fix that. */
  1182. /* Though having similar elements, both functions were separated on
  1183. * purpose:
  1184. * - dirs don't care about encoded/encrypted introduction points, clients
  1185. * do.
  1186. * - dirs store descriptors in a separate cache by descriptor ID, whereas
  1187. * clients store them by service ID; both caches are different data
  1188. * structures and have different access methods.
  1189. * - dirs store a descriptor only if they are responsible for its ID,
  1190. * clients do so in every way (because they have requested it before).
  1191. * - dirs can process multiple concatenated descriptors which is required
  1192. * for replication, whereas clients only accept a single descriptor.
  1193. * Thus, combining both methods would result in a lot of if statements
  1194. * which probably would not improve, but worsen code readability. -KL */
  1195. rend_service_descriptor_t *parsed = NULL;
  1196. char desc_id[DIGEST_LEN];
  1197. char *intro_content = NULL;
  1198. size_t intro_size;
  1199. size_t encoded_size;
  1200. const char *next_desc;
  1201. time_t now = time(NULL);
  1202. char key[REND_SERVICE_ID_LEN_BASE32+2];
  1203. char service_id[REND_SERVICE_ID_LEN_BASE32+1];
  1204. rend_cache_entry_t *e;
  1205. int retval;
  1206. tor_assert(rend_cache);
  1207. tor_assert(desc);
  1208. /* Parse the descriptor. */
  1209. if (rend_parse_v2_service_descriptor(&parsed, desc_id, &intro_content,
  1210. &intro_size, &encoded_size,
  1211. &next_desc, desc) < 0) {
  1212. log_warn(LD_REND, "Could not parse descriptor.");
  1213. retval = -2;
  1214. goto err;
  1215. }
  1216. /* Compute service ID from public key. */
  1217. if (rend_get_service_id(parsed->pk, service_id)<0) {
  1218. log_warn(LD_REND, "Couldn't compute service ID.");
  1219. retval = -2;
  1220. goto err;
  1221. }
  1222. if (strcmp(rend_query->onion_address, service_id)) {
  1223. log_warn(LD_REND, "Received service descriptor for service ID %s; "
  1224. "expected descriptor for service ID %s.",
  1225. service_id, safe_str(rend_query->onion_address));
  1226. retval = -2;
  1227. goto err;
  1228. }
  1229. /* Decode/decrypt introduction points. */
  1230. if (intro_content) {
  1231. if (rend_query->auth_type != REND_NO_AUTH &&
  1232. !tor_mem_is_zero(rend_query->descriptor_cookie,
  1233. sizeof(rend_query->descriptor_cookie))) {
  1234. char *ipos_decrypted = NULL;
  1235. size_t ipos_decrypted_size;
  1236. if (rend_decrypt_introduction_points(&ipos_decrypted,
  1237. &ipos_decrypted_size,
  1238. rend_query->descriptor_cookie,
  1239. intro_content,
  1240. intro_size) < 0) {
  1241. log_warn(LD_REND, "Failed to decrypt introduction points. We are "
  1242. "probably unable to parse the encoded introduction points.");
  1243. } else {
  1244. /* Replace encrypted with decrypted introduction points. */
  1245. log_info(LD_REND, "Successfully decrypted introduction points.");
  1246. tor_free(intro_content);
  1247. intro_content = ipos_decrypted;
  1248. intro_size = ipos_decrypted_size;
  1249. }
  1250. }
  1251. if (rend_parse_introduction_points(parsed, intro_content,
  1252. intro_size) <= 0) {
  1253. log_warn(LD_REND, "Failed to parse introduction points. Either the "
  1254. "service has published a corrupt descriptor or you have "
  1255. "provided invalid authorization data.");
  1256. retval = -2;
  1257. goto err;
  1258. }
  1259. } else {
  1260. log_info(LD_REND, "Descriptor does not contain any introduction points.");
  1261. parsed->intro_nodes = smartlist_new();
  1262. }
  1263. /* We don't need the encoded/encrypted introduction points any longer. */
  1264. tor_free(intro_content);
  1265. /* Is descriptor too old? */
  1266. if (parsed->timestamp < now - REND_CACHE_MAX_AGE-REND_CACHE_MAX_SKEW) {
  1267. log_warn(LD_REND, "Service descriptor with service ID %s is too old.",
  1268. safe_str_client(service_id));
  1269. retval = -2;
  1270. goto err;
  1271. }
  1272. /* Is descriptor too far in the future? */
  1273. if (parsed->timestamp > now + REND_CACHE_MAX_SKEW) {
  1274. log_warn(LD_REND, "Service descriptor with service ID %s is too far in "
  1275. "the future.", safe_str_client(service_id));
  1276. retval = -2;
  1277. goto err;
  1278. }
  1279. /* Do we have a v0 descriptor? */
  1280. tor_snprintf(key, sizeof(key), "0%s", service_id);
  1281. if (strmap_get_lc(rend_cache, key)) {
  1282. log_info(LD_REND, "We already have a v0 descriptor for service ID %s.",
  1283. safe_str_client(service_id));
  1284. retval = -1;
  1285. goto err;
  1286. }
  1287. /* Do we already have a newer descriptor? */
  1288. tor_snprintf(key, sizeof(key), "2%s", service_id);
  1289. e = (rend_cache_entry_t*) strmap_get_lc(rend_cache, key);
  1290. if (e && e->parsed->timestamp > parsed->timestamp) {
  1291. log_info(LD_REND, "We already have a newer service descriptor for "
  1292. "service ID %s with the same desc ID and version.",
  1293. safe_str_client(service_id));
  1294. retval = 0;
  1295. goto err;
  1296. }
  1297. /* Do we already have this descriptor? */
  1298. if (e && !strcmp(desc, e->desc)) {
  1299. log_info(LD_REND,"We already have this service descriptor %s.",
  1300. safe_str_client(service_id));
  1301. e->received = time(NULL);
  1302. retval = 0;
  1303. goto err;
  1304. }
  1305. if (!e) {
  1306. e = tor_malloc_zero(sizeof(rend_cache_entry_t));
  1307. strmap_set_lc(rend_cache, key, e);
  1308. } else {
  1309. rend_service_descriptor_free(e->parsed);
  1310. tor_free(e->desc);
  1311. }
  1312. e->received = time(NULL);
  1313. e->parsed = parsed;
  1314. e->desc = tor_malloc_zero(encoded_size + 1);
  1315. strlcpy(e->desc, desc, encoded_size + 1);
  1316. e->len = encoded_size;
  1317. log_debug(LD_REND,"Successfully stored rend desc '%s', len %d.",
  1318. safe_str_client(service_id), (int)encoded_size);
  1319. return 1;
  1320. err:
  1321. rend_service_descriptor_free(parsed);
  1322. tor_free(intro_content);
  1323. return retval;
  1324. }
  1325. /** Called when we get a rendezvous-related relay cell on circuit
  1326. * <b>circ</b>. Dispatch on rendezvous relay command. */
  1327. void
  1328. rend_process_relay_cell(circuit_t *circ, const crypt_path_t *layer_hint,
  1329. int command, size_t length,
  1330. const uint8_t *payload)
  1331. {
  1332. or_circuit_t *or_circ = NULL;
  1333. origin_circuit_t *origin_circ = NULL;
  1334. int r = -2;
  1335. if (CIRCUIT_IS_ORIGIN(circ)) {
  1336. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  1337. if (!layer_hint || layer_hint != origin_circ->cpath->prev) {
  1338. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  1339. "Relay cell (rend purpose %d) from wrong hop on origin circ",
  1340. command);
  1341. origin_circ = NULL;
  1342. }
  1343. } else {
  1344. or_circ = TO_OR_CIRCUIT(circ);
  1345. }
  1346. switch (command) {
  1347. case RELAY_COMMAND_ESTABLISH_INTRO:
  1348. if (or_circ)
  1349. r = rend_mid_establish_intro(or_circ,payload,length);
  1350. break;
  1351. case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
  1352. if (or_circ)
  1353. r = rend_mid_establish_rendezvous(or_circ,payload,length);
  1354. break;
  1355. case RELAY_COMMAND_INTRODUCE1:
  1356. if (or_circ)
  1357. r = rend_mid_introduce(or_circ,payload,length);
  1358. break;
  1359. case RELAY_COMMAND_INTRODUCE2:
  1360. if (origin_circ)
  1361. r = rend_service_introduce(origin_circ,payload,length);
  1362. break;
  1363. case RELAY_COMMAND_INTRODUCE_ACK:
  1364. if (origin_circ)
  1365. r = rend_client_introduction_acked(origin_circ,payload,length);
  1366. break;
  1367. case RELAY_COMMAND_RENDEZVOUS1:
  1368. if (or_circ)
  1369. r = rend_mid_rendezvous(or_circ,payload,length);
  1370. break;
  1371. case RELAY_COMMAND_RENDEZVOUS2:
  1372. if (origin_circ)
  1373. r = rend_client_receive_rendezvous(origin_circ,payload,length);
  1374. break;
  1375. case RELAY_COMMAND_INTRO_ESTABLISHED:
  1376. if (origin_circ)
  1377. r = rend_service_intro_established(origin_circ,payload,length);
  1378. break;
  1379. case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
  1380. if (origin_circ)
  1381. r = rend_client_rendezvous_acked(origin_circ,payload,length);
  1382. break;
  1383. default:
  1384. tor_fragile_assert();
  1385. }
  1386. if (r == -2)
  1387. log_info(LD_PROTOCOL, "Dropping cell (type %d) for wrong circuit type.",
  1388. command);
  1389. }
  1390. /** Return the number of entries in our rendezvous descriptor cache. */
  1391. int
  1392. rend_cache_size(void)
  1393. {
  1394. return strmap_size(rend_cache);
  1395. }
  1396. /** Allocate and return a new rend_data_t with the same
  1397. * contents as <b>query</b>. */
  1398. rend_data_t *
  1399. rend_data_dup(const rend_data_t *data)
  1400. {
  1401. tor_assert(data);
  1402. return tor_memdup(data, sizeof(rend_data_t));
  1403. }