rendcommon.c 52 KB

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