rendcommon.c 51 KB

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