rendcommon.c 51 KB

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