rendcommon.c 51 KB

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