rendcommon.c 51 KB

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