rendcommon.c 52 KB

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