rendcommon.c 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055
  1. /* Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  2. * Copyright (c) 2007-2017, 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. #define RENDCOMMON_PRIVATE
  10. #include "or.h"
  11. #include "circuitbuild.h"
  12. #include "circuitlist.h"
  13. #include "circuituse.h"
  14. #include "config.h"
  15. #include "control.h"
  16. #include "crypto_rand.h"
  17. #include "crypto_util.h"
  18. #include "hs_client.h"
  19. #include "hs_common.h"
  20. #include "hs_intropoint.h"
  21. #include "networkstatus.h"
  22. #include "rendclient.h"
  23. #include "rendcommon.h"
  24. #include "rendmid.h"
  25. #include "rendservice.h"
  26. #include "rephist.h"
  27. #include "router.h"
  28. #include "routerlist.h"
  29. #include "routerparse.h"
  30. #include "cpath_build_state_st.h"
  31. #include "crypt_path_st.h"
  32. #include "networkstatus_st.h"
  33. #include "origin_circuit_st.h"
  34. #include "rend_encoded_v2_service_descriptor_st.h"
  35. #include "rend_intro_point_st.h"
  36. #include "rend_service_descriptor_st.h"
  37. #include "routerstatus_st.h"
  38. /** Return 0 if one and two are the same service ids, else -1 or 1 */
  39. int
  40. rend_cmp_service_ids(const char *one, const char *two)
  41. {
  42. return strcasecmp(one,two);
  43. }
  44. /** Free the storage held by the service descriptor <b>desc</b>.
  45. */
  46. void
  47. rend_service_descriptor_free_(rend_service_descriptor_t *desc)
  48. {
  49. if (!desc)
  50. return;
  51. if (desc->pk)
  52. crypto_pk_free(desc->pk);
  53. if (desc->intro_nodes) {
  54. SMARTLIST_FOREACH(desc->intro_nodes, rend_intro_point_t *, intro,
  55. rend_intro_point_free(intro););
  56. smartlist_free(desc->intro_nodes);
  57. }
  58. if (desc->successful_uploads) {
  59. SMARTLIST_FOREACH(desc->successful_uploads, char *, c, tor_free(c););
  60. smartlist_free(desc->successful_uploads);
  61. }
  62. tor_free(desc);
  63. }
  64. /** Length of the descriptor cookie that is used for versioned hidden
  65. * service descriptors. */
  66. #define REND_DESC_COOKIE_LEN 16
  67. /** Length of the replica number that is used to determine the secret ID
  68. * part of versioned hidden service descriptors. */
  69. #define REND_REPLICA_LEN 1
  70. /** Compute the descriptor ID for <b>service_id</b> of length
  71. * <b>REND_SERVICE_ID_LEN</b> and <b>secret_id_part</b> of length
  72. * <b>DIGEST_LEN</b>, and write it to <b>descriptor_id_out</b> of length
  73. * <b>DIGEST_LEN</b>. */
  74. void
  75. rend_get_descriptor_id_bytes(char *descriptor_id_out,
  76. const char *service_id,
  77. const char *secret_id_part)
  78. {
  79. crypto_digest_t *digest = crypto_digest_new();
  80. crypto_digest_add_bytes(digest, service_id, REND_SERVICE_ID_LEN);
  81. crypto_digest_add_bytes(digest, secret_id_part, DIGEST_LEN);
  82. crypto_digest_get_digest(digest, descriptor_id_out, DIGEST_LEN);
  83. crypto_digest_free(digest);
  84. }
  85. /** Compute the secret ID part for time_period,
  86. * a <b>descriptor_cookie</b> of length
  87. * <b>REND_DESC_COOKIE_LEN</b> which may also be <b>NULL</b> if no
  88. * descriptor_cookie shall be used, and <b>replica</b>, and write it to
  89. * <b>secret_id_part</b> of length DIGEST_LEN. */
  90. static void
  91. get_secret_id_part_bytes(char *secret_id_part, uint32_t time_period,
  92. const char *descriptor_cookie, uint8_t replica)
  93. {
  94. crypto_digest_t *digest = crypto_digest_new();
  95. time_period = htonl(time_period);
  96. crypto_digest_add_bytes(digest, (char*)&time_period, sizeof(uint32_t));
  97. if (descriptor_cookie) {
  98. crypto_digest_add_bytes(digest, descriptor_cookie,
  99. REND_DESC_COOKIE_LEN);
  100. }
  101. crypto_digest_add_bytes(digest, (const char *)&replica, REND_REPLICA_LEN);
  102. crypto_digest_get_digest(digest, secret_id_part, DIGEST_LEN);
  103. crypto_digest_free(digest);
  104. }
  105. /** Return the time period for time <b>now</b> plus a potentially
  106. * intended <b>deviation</b> of one or more periods, based on the first byte
  107. * of <b>service_id</b>. */
  108. static uint32_t
  109. get_time_period(time_t now, uint8_t deviation, const char *service_id)
  110. {
  111. /* The time period is the number of REND_TIME_PERIOD_V2_DESC_VALIDITY
  112. * intervals that have passed since the epoch, offset slightly so that
  113. * each service's time periods start and end at a fraction of that
  114. * period based on their first byte. */
  115. return (uint32_t)
  116. (now + ((uint8_t) *service_id) * REND_TIME_PERIOD_V2_DESC_VALIDITY / 256)
  117. / REND_TIME_PERIOD_V2_DESC_VALIDITY + deviation;
  118. }
  119. /** Compute the time in seconds that a descriptor that is generated
  120. * <b>now</b> for <b>service_id</b> will be valid. */
  121. static uint32_t
  122. get_seconds_valid(time_t now, const char *service_id)
  123. {
  124. uint32_t result = REND_TIME_PERIOD_V2_DESC_VALIDITY -
  125. ((uint32_t)
  126. (now + ((uint8_t) *service_id) * REND_TIME_PERIOD_V2_DESC_VALIDITY / 256)
  127. % REND_TIME_PERIOD_V2_DESC_VALIDITY);
  128. return result;
  129. }
  130. /** Compute the binary <b>desc_id_out</b> (DIGEST_LEN bytes long) for a given
  131. * base32-encoded <b>service_id</b> and optional unencoded
  132. * <b>descriptor_cookie</b> of length REND_DESC_COOKIE_LEN,
  133. * at time <b>now</b> for replica number
  134. * <b>replica</b>. <b>desc_id</b> needs to have <b>DIGEST_LEN</b> bytes
  135. * free. Return 0 for success, -1 otherwise. */
  136. int
  137. rend_compute_v2_desc_id(char *desc_id_out, const char *service_id,
  138. const char *descriptor_cookie, time_t now,
  139. uint8_t replica)
  140. {
  141. char service_id_binary[REND_SERVICE_ID_LEN];
  142. char secret_id_part[DIGEST_LEN];
  143. uint32_t time_period;
  144. if (!service_id ||
  145. strlen(service_id) != REND_SERVICE_ID_LEN_BASE32) {
  146. log_warn(LD_REND, "Could not compute v2 descriptor ID: "
  147. "Illegal service ID: %s",
  148. safe_str(service_id));
  149. return -1;
  150. }
  151. if (replica >= REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS) {
  152. log_warn(LD_REND, "Could not compute v2 descriptor ID: "
  153. "Replica number out of range: %d", replica);
  154. return -1;
  155. }
  156. /* Convert service ID to binary. */
  157. if (base32_decode(service_id_binary, REND_SERVICE_ID_LEN,
  158. service_id, REND_SERVICE_ID_LEN_BASE32) < 0) {
  159. log_warn(LD_REND, "Could not compute v2 descriptor ID: "
  160. "Illegal characters in service ID: %s",
  161. safe_str_client(service_id));
  162. return -1;
  163. }
  164. /* Calculate current time-period. */
  165. time_period = get_time_period(now, 0, service_id_binary);
  166. /* Calculate secret-id-part = h(time-period | desc-cookie | replica). */
  167. get_secret_id_part_bytes(secret_id_part, time_period, descriptor_cookie,
  168. replica);
  169. /* Calculate descriptor ID: H(permanent-id | secret-id-part) */
  170. rend_get_descriptor_id_bytes(desc_id_out, service_id_binary, secret_id_part);
  171. return 0;
  172. }
  173. /** Encode the introduction points in <b>desc</b> and write the result to a
  174. * newly allocated string pointed to by <b>encoded</b>. Return 0 for
  175. * success, -1 otherwise. */
  176. static int
  177. rend_encode_v2_intro_points(char **encoded, rend_service_descriptor_t *desc)
  178. {
  179. size_t unenc_len;
  180. char *unenc = NULL;
  181. size_t unenc_written = 0;
  182. int i;
  183. int r = -1;
  184. /* Assemble unencrypted list of introduction points. */
  185. unenc_len = smartlist_len(desc->intro_nodes) * 1000; /* too long, but ok. */
  186. unenc = tor_malloc_zero(unenc_len);
  187. for (i = 0; i < smartlist_len(desc->intro_nodes); i++) {
  188. char id_base32[REND_INTRO_POINT_ID_LEN_BASE32 + 1];
  189. char *onion_key = NULL;
  190. size_t onion_key_len;
  191. crypto_pk_t *intro_key;
  192. char *service_key = NULL;
  193. char *address = NULL;
  194. size_t service_key_len;
  195. int res;
  196. rend_intro_point_t *intro = smartlist_get(desc->intro_nodes, i);
  197. /* Obtain extend info with introduction point details. */
  198. extend_info_t *info = intro->extend_info;
  199. /* Encode introduction point ID. */
  200. base32_encode(id_base32, sizeof(id_base32),
  201. info->identity_digest, DIGEST_LEN);
  202. /* Encode onion key. */
  203. if (crypto_pk_write_public_key_to_string(info->onion_key, &onion_key,
  204. &onion_key_len) < 0) {
  205. log_warn(LD_REND, "Could not write onion key.");
  206. goto done;
  207. }
  208. /* Encode intro key. */
  209. intro_key = intro->intro_key;
  210. if (!intro_key ||
  211. crypto_pk_write_public_key_to_string(intro_key, &service_key,
  212. &service_key_len) < 0) {
  213. log_warn(LD_REND, "Could not write intro key.");
  214. tor_free(onion_key);
  215. goto done;
  216. }
  217. /* Assemble everything for this introduction point. */
  218. address = tor_addr_to_str_dup(&info->addr);
  219. res = tor_snprintf(unenc + unenc_written, unenc_len - unenc_written,
  220. "introduction-point %s\n"
  221. "ip-address %s\n"
  222. "onion-port %d\n"
  223. "onion-key\n%s"
  224. "service-key\n%s",
  225. id_base32,
  226. address,
  227. info->port,
  228. onion_key,
  229. service_key);
  230. tor_free(address);
  231. tor_free(onion_key);
  232. tor_free(service_key);
  233. if (res < 0) {
  234. log_warn(LD_REND, "Not enough space for writing introduction point "
  235. "string.");
  236. goto done;
  237. }
  238. /* Update total number of written bytes for unencrypted intro points. */
  239. unenc_written += res;
  240. }
  241. /* Finalize unencrypted introduction points. */
  242. if (unenc_len < unenc_written + 2) {
  243. log_warn(LD_REND, "Not enough space for finalizing introduction point "
  244. "string.");
  245. goto done;
  246. }
  247. unenc[unenc_written++] = '\n';
  248. unenc[unenc_written++] = 0;
  249. *encoded = unenc;
  250. r = 0;
  251. done:
  252. if (r<0)
  253. tor_free(unenc);
  254. return r;
  255. }
  256. /** Encrypt the encoded introduction points in <b>encoded</b> using
  257. * authorization type 'basic' with <b>client_cookies</b> and write the
  258. * result to a newly allocated string pointed to by <b>encrypted_out</b> of
  259. * length <b>encrypted_len_out</b>. Return 0 for success, -1 otherwise. */
  260. static int
  261. rend_encrypt_v2_intro_points_basic(char **encrypted_out,
  262. size_t *encrypted_len_out,
  263. const char *encoded,
  264. smartlist_t *client_cookies)
  265. {
  266. int r = -1, i, pos, enclen, client_blocks;
  267. size_t len, client_entries_len;
  268. char *enc = NULL, iv[CIPHER_IV_LEN], *client_part = NULL,
  269. session_key[CIPHER_KEY_LEN];
  270. smartlist_t *encrypted_session_keys = NULL;
  271. crypto_digest_t *digest;
  272. crypto_cipher_t *cipher;
  273. tor_assert(encoded);
  274. tor_assert(client_cookies && smartlist_len(client_cookies) > 0);
  275. /* Generate session key. */
  276. crypto_rand(session_key, CIPHER_KEY_LEN);
  277. /* Determine length of encrypted introduction points including session
  278. * keys. */
  279. client_blocks = 1 + ((smartlist_len(client_cookies) - 1) /
  280. REND_BASIC_AUTH_CLIENT_MULTIPLE);
  281. client_entries_len = client_blocks * REND_BASIC_AUTH_CLIENT_MULTIPLE *
  282. REND_BASIC_AUTH_CLIENT_ENTRY_LEN;
  283. len = 2 + client_entries_len + CIPHER_IV_LEN + strlen(encoded);
  284. if (client_blocks >= 256) {
  285. log_warn(LD_REND, "Too many clients in introduction point string.");
  286. goto done;
  287. }
  288. enc = tor_malloc_zero(len);
  289. enc[0] = 0x01; /* type of authorization. */
  290. enc[1] = (uint8_t)client_blocks;
  291. /* Encrypt with random session key. */
  292. enclen = crypto_cipher_encrypt_with_iv(session_key,
  293. enc + 2 + client_entries_len,
  294. CIPHER_IV_LEN + strlen(encoded), encoded, strlen(encoded));
  295. if (enclen < 0) {
  296. log_warn(LD_REND, "Could not encrypt introduction point string.");
  297. goto done;
  298. }
  299. memcpy(iv, enc + 2 + client_entries_len, CIPHER_IV_LEN);
  300. /* Encrypt session key for cookies, determine client IDs, and put both
  301. * in a smartlist. */
  302. encrypted_session_keys = smartlist_new();
  303. SMARTLIST_FOREACH_BEGIN(client_cookies, const char *, cookie) {
  304. client_part = tor_malloc_zero(REND_BASIC_AUTH_CLIENT_ENTRY_LEN);
  305. /* Encrypt session key. */
  306. cipher = crypto_cipher_new(cookie);
  307. if (crypto_cipher_encrypt(cipher, client_part +
  308. REND_BASIC_AUTH_CLIENT_ID_LEN,
  309. session_key, CIPHER_KEY_LEN) < 0) {
  310. log_warn(LD_REND, "Could not encrypt session key for client.");
  311. crypto_cipher_free(cipher);
  312. tor_free(client_part);
  313. goto done;
  314. }
  315. crypto_cipher_free(cipher);
  316. /* Determine client ID. */
  317. digest = crypto_digest_new();
  318. crypto_digest_add_bytes(digest, cookie, REND_DESC_COOKIE_LEN);
  319. crypto_digest_add_bytes(digest, iv, CIPHER_IV_LEN);
  320. crypto_digest_get_digest(digest, client_part,
  321. REND_BASIC_AUTH_CLIENT_ID_LEN);
  322. crypto_digest_free(digest);
  323. /* Put both together. */
  324. smartlist_add(encrypted_session_keys, client_part);
  325. } SMARTLIST_FOREACH_END(cookie);
  326. /* Add some fake client IDs and encrypted session keys. */
  327. for (i = (smartlist_len(client_cookies) - 1) %
  328. REND_BASIC_AUTH_CLIENT_MULTIPLE;
  329. i < REND_BASIC_AUTH_CLIENT_MULTIPLE - 1; i++) {
  330. client_part = tor_malloc_zero(REND_BASIC_AUTH_CLIENT_ENTRY_LEN);
  331. crypto_rand(client_part, REND_BASIC_AUTH_CLIENT_ENTRY_LEN);
  332. smartlist_add(encrypted_session_keys, client_part);
  333. }
  334. /* Sort smartlist and put elements in result in order. */
  335. smartlist_sort_digests(encrypted_session_keys);
  336. pos = 2;
  337. SMARTLIST_FOREACH(encrypted_session_keys, const char *, entry, {
  338. memcpy(enc + pos, entry, REND_BASIC_AUTH_CLIENT_ENTRY_LEN);
  339. pos += REND_BASIC_AUTH_CLIENT_ENTRY_LEN;
  340. });
  341. *encrypted_out = enc;
  342. *encrypted_len_out = len;
  343. enc = NULL; /* prevent free. */
  344. r = 0;
  345. done:
  346. tor_free(enc);
  347. if (encrypted_session_keys) {
  348. SMARTLIST_FOREACH(encrypted_session_keys, char *, d, tor_free(d););
  349. smartlist_free(encrypted_session_keys);
  350. }
  351. return r;
  352. }
  353. /** Encrypt the encoded introduction points in <b>encoded</b> using
  354. * authorization type 'stealth' with <b>descriptor_cookie</b> of length
  355. * REND_DESC_COOKIE_LEN and write the result to a newly allocated string
  356. * pointed to by <b>encrypted_out</b> of length <b>encrypted_len_out</b>.
  357. * Return 0 for success, -1 otherwise. */
  358. static int
  359. rend_encrypt_v2_intro_points_stealth(char **encrypted_out,
  360. size_t *encrypted_len_out,
  361. const char *encoded,
  362. const char *descriptor_cookie)
  363. {
  364. int r = -1, enclen;
  365. char *enc;
  366. tor_assert(encoded);
  367. tor_assert(descriptor_cookie);
  368. enc = tor_malloc_zero(1 + CIPHER_IV_LEN + strlen(encoded));
  369. enc[0] = 0x02; /* Auth type */
  370. enclen = crypto_cipher_encrypt_with_iv(descriptor_cookie,
  371. enc + 1,
  372. CIPHER_IV_LEN+strlen(encoded),
  373. encoded, strlen(encoded));
  374. if (enclen < 0) {
  375. log_warn(LD_REND, "Could not encrypt introduction point string.");
  376. goto done;
  377. }
  378. *encrypted_out = enc;
  379. *encrypted_len_out = enclen;
  380. enc = NULL; /* prevent free */
  381. r = 0;
  382. done:
  383. tor_free(enc);
  384. return r;
  385. }
  386. /** Attempt to parse the given <b>desc_str</b> and return true if this
  387. * succeeds, false otherwise. */
  388. STATIC int
  389. rend_desc_v2_is_parsable(rend_encoded_v2_service_descriptor_t *desc)
  390. {
  391. rend_service_descriptor_t *test_parsed = NULL;
  392. char test_desc_id[DIGEST_LEN];
  393. char *test_intro_content = NULL;
  394. size_t test_intro_size;
  395. size_t test_encoded_size;
  396. const char *test_next;
  397. int res = rend_parse_v2_service_descriptor(&test_parsed, test_desc_id,
  398. &test_intro_content,
  399. &test_intro_size,
  400. &test_encoded_size,
  401. &test_next, desc->desc_str, 1);
  402. rend_service_descriptor_free(test_parsed);
  403. tor_free(test_intro_content);
  404. return (res >= 0);
  405. }
  406. /** Free the storage held by an encoded v2 service descriptor. */
  407. void
  408. rend_encoded_v2_service_descriptor_free_(
  409. rend_encoded_v2_service_descriptor_t *desc)
  410. {
  411. if (!desc)
  412. return;
  413. tor_free(desc->desc_str);
  414. tor_free(desc);
  415. }
  416. /** Free the storage held by an introduction point info. */
  417. void
  418. rend_intro_point_free_(rend_intro_point_t *intro)
  419. {
  420. if (!intro)
  421. return;
  422. extend_info_free(intro->extend_info);
  423. crypto_pk_free(intro->intro_key);
  424. if (intro->accepted_intro_rsa_parts != NULL) {
  425. replaycache_free(intro->accepted_intro_rsa_parts);
  426. }
  427. tor_free(intro);
  428. }
  429. /** Encode a set of rend_encoded_v2_service_descriptor_t's for <b>desc</b>
  430. * at time <b>now</b> using <b>service_key</b>, depending on
  431. * <b>auth_type</b> a <b>descriptor_cookie</b> and a list of
  432. * <b>client_cookies</b> (which are both <b>NULL</b> if no client
  433. * authorization is performed), and <b>period</b> (e.g. 0 for the current
  434. * period, 1 for the next period, etc.) and add them to the existing list
  435. * <b>descs_out</b>; return the number of seconds that the descriptors will
  436. * be found by clients, or -1 if the encoding was not successful. */
  437. int
  438. rend_encode_v2_descriptors(smartlist_t *descs_out,
  439. rend_service_descriptor_t *desc, time_t now,
  440. uint8_t period, rend_auth_type_t auth_type,
  441. crypto_pk_t *client_key,
  442. smartlist_t *client_cookies)
  443. {
  444. char service_id[DIGEST_LEN];
  445. char service_id_base32[REND_SERVICE_ID_LEN_BASE32+1];
  446. uint32_t time_period;
  447. char *ipos_base64 = NULL, *ipos = NULL, *ipos_encrypted = NULL,
  448. *descriptor_cookie = NULL;
  449. size_t ipos_len = 0, ipos_encrypted_len = 0;
  450. int k;
  451. uint32_t seconds_valid;
  452. crypto_pk_t *service_key;
  453. if (!desc) {
  454. log_warn(LD_BUG, "Could not encode v2 descriptor: No desc given.");
  455. return -1;
  456. }
  457. service_key = (auth_type == REND_STEALTH_AUTH) ? client_key : desc->pk;
  458. tor_assert(service_key);
  459. if (auth_type == REND_STEALTH_AUTH) {
  460. descriptor_cookie = smartlist_get(client_cookies, 0);
  461. tor_assert(descriptor_cookie);
  462. }
  463. /* Obtain service_id from public key. */
  464. if (crypto_pk_get_digest(service_key, service_id) < 0) {
  465. log_warn(LD_BUG, "Couldn't compute service key digest.");
  466. return -1;
  467. }
  468. /* Calculate current time-period. */
  469. time_period = get_time_period(now, period, service_id);
  470. /* Determine how many seconds the descriptor will be valid. */
  471. seconds_valid = period * REND_TIME_PERIOD_V2_DESC_VALIDITY +
  472. get_seconds_valid(now, service_id);
  473. /* Assemble, possibly encrypt, and encode introduction points. */
  474. if (smartlist_len(desc->intro_nodes) > 0) {
  475. if (rend_encode_v2_intro_points(&ipos, desc) < 0) {
  476. log_warn(LD_REND, "Encoding of introduction points did not succeed.");
  477. return -1;
  478. }
  479. switch (auth_type) {
  480. case REND_NO_AUTH:
  481. ipos_len = strlen(ipos);
  482. break;
  483. case REND_BASIC_AUTH:
  484. if (rend_encrypt_v2_intro_points_basic(&ipos_encrypted,
  485. &ipos_encrypted_len, ipos,
  486. client_cookies) < 0) {
  487. log_warn(LD_REND, "Encrypting of introduction points did not "
  488. "succeed.");
  489. tor_free(ipos);
  490. return -1;
  491. }
  492. tor_free(ipos);
  493. ipos = ipos_encrypted;
  494. ipos_len = ipos_encrypted_len;
  495. break;
  496. case REND_STEALTH_AUTH:
  497. if (rend_encrypt_v2_intro_points_stealth(&ipos_encrypted,
  498. &ipos_encrypted_len, ipos,
  499. descriptor_cookie) < 0) {
  500. log_warn(LD_REND, "Encrypting of introduction points did not "
  501. "succeed.");
  502. tor_free(ipos);
  503. return -1;
  504. }
  505. tor_free(ipos);
  506. ipos = ipos_encrypted;
  507. ipos_len = ipos_encrypted_len;
  508. break;
  509. default:
  510. log_warn(LD_REND|LD_BUG, "Unrecognized authorization type %d",
  511. (int)auth_type);
  512. tor_free(ipos);
  513. return -1;
  514. }
  515. /* Base64-encode introduction points. */
  516. ipos_base64 = tor_calloc(ipos_len, 2);
  517. if (base64_encode(ipos_base64, ipos_len * 2, ipos, ipos_len,
  518. BASE64_ENCODE_MULTILINE)<0) {
  519. log_warn(LD_REND, "Could not encode introduction point string to "
  520. "base64. length=%d", (int)ipos_len);
  521. tor_free(ipos_base64);
  522. tor_free(ipos);
  523. return -1;
  524. }
  525. tor_free(ipos);
  526. }
  527. /* Encode REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS descriptors. */
  528. for (k = 0; k < REND_NUMBER_OF_NON_CONSECUTIVE_REPLICAS; k++) {
  529. char secret_id_part[DIGEST_LEN];
  530. char secret_id_part_base32[REND_SECRET_ID_PART_LEN_BASE32 + 1];
  531. char desc_id_base32[REND_DESC_ID_V2_LEN_BASE32 + 1];
  532. char *permanent_key = NULL;
  533. size_t permanent_key_len;
  534. char published[ISO_TIME_LEN+1];
  535. int i;
  536. char protocol_versions_string[16]; /* max len: "0,1,2,3,4,5,6,7\0" */
  537. size_t protocol_versions_written;
  538. size_t desc_len;
  539. char *desc_str = NULL;
  540. int result = 0;
  541. size_t written = 0;
  542. char desc_digest[DIGEST_LEN];
  543. rend_encoded_v2_service_descriptor_t *enc =
  544. tor_malloc_zero(sizeof(rend_encoded_v2_service_descriptor_t));
  545. /* Calculate secret-id-part = h(time-period | cookie | replica). */
  546. get_secret_id_part_bytes(secret_id_part, time_period, descriptor_cookie,
  547. k);
  548. base32_encode(secret_id_part_base32, sizeof(secret_id_part_base32),
  549. secret_id_part, DIGEST_LEN);
  550. /* Calculate descriptor ID. */
  551. rend_get_descriptor_id_bytes(enc->desc_id, service_id, secret_id_part);
  552. base32_encode(desc_id_base32, sizeof(desc_id_base32),
  553. enc->desc_id, DIGEST_LEN);
  554. /* PEM-encode the public key */
  555. if (crypto_pk_write_public_key_to_string(service_key, &permanent_key,
  556. &permanent_key_len) < 0) {
  557. log_warn(LD_BUG, "Could not write public key to string.");
  558. rend_encoded_v2_service_descriptor_free(enc);
  559. goto err;
  560. }
  561. /* Encode timestamp. */
  562. format_iso_time(published, desc->timestamp);
  563. /* Write protocol-versions bitmask to comma-separated value string. */
  564. protocol_versions_written = 0;
  565. for (i = 0; i < 8; i++) {
  566. if (desc->protocols & 1 << i) {
  567. tor_snprintf(protocol_versions_string + protocol_versions_written,
  568. 16 - protocol_versions_written, "%d,", i);
  569. protocol_versions_written += 2;
  570. }
  571. }
  572. if (protocol_versions_written)
  573. protocol_versions_string[protocol_versions_written - 1] = '\0';
  574. else
  575. protocol_versions_string[0]= '\0';
  576. /* Assemble complete descriptor. */
  577. desc_len = 2000 + smartlist_len(desc->intro_nodes) * 1000; /* far too long,
  578. but okay.*/
  579. enc->desc_str = desc_str = tor_malloc_zero(desc_len);
  580. result = tor_snprintf(desc_str, desc_len,
  581. "rendezvous-service-descriptor %s\n"
  582. "version 2\n"
  583. "permanent-key\n%s"
  584. "secret-id-part %s\n"
  585. "publication-time %s\n"
  586. "protocol-versions %s\n",
  587. desc_id_base32,
  588. permanent_key,
  589. secret_id_part_base32,
  590. published,
  591. protocol_versions_string);
  592. tor_free(permanent_key);
  593. if (result < 0) {
  594. log_warn(LD_BUG, "Descriptor ran out of room.");
  595. rend_encoded_v2_service_descriptor_free(enc);
  596. goto err;
  597. }
  598. written = result;
  599. /* Add introduction points. */
  600. if (ipos_base64) {
  601. result = tor_snprintf(desc_str + written, desc_len - written,
  602. "introduction-points\n"
  603. "-----BEGIN MESSAGE-----\n%s"
  604. "-----END MESSAGE-----\n",
  605. ipos_base64);
  606. if (result < 0) {
  607. log_warn(LD_BUG, "could not write introduction points.");
  608. rend_encoded_v2_service_descriptor_free(enc);
  609. goto err;
  610. }
  611. written += result;
  612. }
  613. /* Add signature. */
  614. strlcpy(desc_str + written, "signature\n", desc_len - written);
  615. written += strlen(desc_str + written);
  616. if (crypto_digest(desc_digest, desc_str, written) < 0) {
  617. log_warn(LD_BUG, "could not create digest.");
  618. rend_encoded_v2_service_descriptor_free(enc);
  619. goto err;
  620. }
  621. if (router_append_dirobj_signature(desc_str + written,
  622. desc_len - written,
  623. desc_digest, DIGEST_LEN,
  624. service_key) < 0) {
  625. log_warn(LD_BUG, "Couldn't sign desc.");
  626. rend_encoded_v2_service_descriptor_free(enc);
  627. goto err;
  628. }
  629. written += strlen(desc_str+written);
  630. if (written+2 > desc_len) {
  631. log_warn(LD_BUG, "Could not finish desc.");
  632. rend_encoded_v2_service_descriptor_free(enc);
  633. goto err;
  634. }
  635. desc_str[written++] = 0;
  636. /* Check if we can parse our own descriptor. */
  637. if (!rend_desc_v2_is_parsable(enc)) {
  638. log_warn(LD_BUG, "Could not parse my own descriptor: %s", desc_str);
  639. rend_encoded_v2_service_descriptor_free(enc);
  640. goto err;
  641. }
  642. smartlist_add(descs_out, enc);
  643. /* Add the uploaded descriptor to the local service's descriptor cache */
  644. rend_cache_store_v2_desc_as_service(enc->desc_str);
  645. base32_encode(service_id_base32, sizeof(service_id_base32),
  646. service_id, REND_SERVICE_ID_LEN);
  647. control_event_hs_descriptor_created(service_id_base32, desc_id_base32, k);
  648. }
  649. log_info(LD_REND, "Successfully encoded a v2 descriptor and "
  650. "confirmed that it is parsable.");
  651. goto done;
  652. err:
  653. SMARTLIST_FOREACH(descs_out, rend_encoded_v2_service_descriptor_t *, d,
  654. rend_encoded_v2_service_descriptor_free(d););
  655. smartlist_clear(descs_out);
  656. seconds_valid = -1;
  657. done:
  658. tor_free(ipos_base64);
  659. return seconds_valid;
  660. }
  661. /** Sets <b>out</b> to the first 10 bytes of the digest of <b>pk</b>,
  662. * base32 encoded. NUL-terminates out. (We use this string to
  663. * identify services in directory requests and .onion URLs.)
  664. */
  665. int
  666. rend_get_service_id(crypto_pk_t *pk, char *out)
  667. {
  668. char buf[DIGEST_LEN];
  669. tor_assert(pk);
  670. if (crypto_pk_get_digest(pk, buf) < 0)
  671. return -1;
  672. base32_encode(out, REND_SERVICE_ID_LEN_BASE32+1, buf, REND_SERVICE_ID_LEN);
  673. return 0;
  674. }
  675. /** Return true iff <b>query</b> is a syntactically valid service ID (as
  676. * generated by rend_get_service_id). */
  677. int
  678. rend_valid_v2_service_id(const char *query)
  679. {
  680. if (strlen(query) != REND_SERVICE_ID_LEN_BASE32)
  681. return 0;
  682. if (strspn(query, BASE32_CHARS) != REND_SERVICE_ID_LEN_BASE32)
  683. return 0;
  684. return 1;
  685. }
  686. /** Return true iff <b>query</b> is a syntactically valid descriptor ID.
  687. * (as generated by rend_get_descriptor_id_bytes). */
  688. int
  689. rend_valid_descriptor_id(const char *query)
  690. {
  691. if (strlen(query) != REND_DESC_ID_V2_LEN_BASE32) {
  692. goto invalid;
  693. }
  694. if (strspn(query, BASE32_CHARS) != REND_DESC_ID_V2_LEN_BASE32) {
  695. goto invalid;
  696. }
  697. return 1;
  698. invalid:
  699. return 0;
  700. }
  701. /** Return true iff <b>client_name</b> is a syntactically valid name
  702. * for rendezvous client authentication. */
  703. int
  704. rend_valid_client_name(const char *client_name)
  705. {
  706. size_t len = strlen(client_name);
  707. if (len < 1 || len > REND_CLIENTNAME_MAX_LEN) {
  708. return 0;
  709. }
  710. if (strspn(client_name, REND_LEGAL_CLIENTNAME_CHARACTERS) != len) {
  711. return 0;
  712. }
  713. return 1;
  714. }
  715. /** Called when we get a rendezvous-related relay cell on circuit
  716. * <b>circ</b>. Dispatch on rendezvous relay command. */
  717. void
  718. rend_process_relay_cell(circuit_t *circ, const crypt_path_t *layer_hint,
  719. int command, size_t length,
  720. const uint8_t *payload)
  721. {
  722. or_circuit_t *or_circ = NULL;
  723. origin_circuit_t *origin_circ = NULL;
  724. int r = -2;
  725. if (CIRCUIT_IS_ORIGIN(circ)) {
  726. origin_circ = TO_ORIGIN_CIRCUIT(circ);
  727. if (!layer_hint || layer_hint != origin_circ->cpath->prev) {
  728. log_fn(LOG_PROTOCOL_WARN, LD_APP,
  729. "Relay cell (rend purpose %d) from wrong hop on origin circ",
  730. command);
  731. origin_circ = NULL;
  732. }
  733. } else {
  734. or_circ = TO_OR_CIRCUIT(circ);
  735. }
  736. switch (command) {
  737. case RELAY_COMMAND_ESTABLISH_INTRO:
  738. if (or_circ)
  739. r = hs_intro_received_establish_intro(or_circ,payload,length);
  740. break;
  741. case RELAY_COMMAND_ESTABLISH_RENDEZVOUS:
  742. if (or_circ)
  743. r = rend_mid_establish_rendezvous(or_circ,payload,length);
  744. break;
  745. case RELAY_COMMAND_INTRODUCE1:
  746. if (or_circ)
  747. r = hs_intro_received_introduce1(or_circ,payload,length);
  748. break;
  749. case RELAY_COMMAND_INTRODUCE2:
  750. if (origin_circ)
  751. r = hs_service_receive_introduce2(origin_circ,payload,length);
  752. break;
  753. case RELAY_COMMAND_INTRODUCE_ACK:
  754. if (origin_circ)
  755. r = hs_client_receive_introduce_ack(origin_circ,payload,length);
  756. break;
  757. case RELAY_COMMAND_RENDEZVOUS1:
  758. if (or_circ)
  759. r = rend_mid_rendezvous(or_circ,payload,length);
  760. break;
  761. case RELAY_COMMAND_RENDEZVOUS2:
  762. if (origin_circ)
  763. r = hs_client_receive_rendezvous2(origin_circ,payload,length);
  764. break;
  765. case RELAY_COMMAND_INTRO_ESTABLISHED:
  766. if (origin_circ)
  767. r = hs_service_receive_intro_established(origin_circ,payload,length);
  768. break;
  769. case RELAY_COMMAND_RENDEZVOUS_ESTABLISHED:
  770. if (origin_circ)
  771. r = hs_client_receive_rendezvous_acked(origin_circ,payload,length);
  772. break;
  773. default:
  774. tor_fragile_assert();
  775. }
  776. if (r == 0 && origin_circ) {
  777. /* This was a valid cell. Count it as delivered + overhead. */
  778. circuit_read_valid_data(origin_circ, length);
  779. }
  780. if (r == -2)
  781. log_info(LD_PROTOCOL, "Dropping cell (type %d) for wrong circuit type.",
  782. command);
  783. }
  784. /** Determine the routers that are responsible for <b>id</b> (binary) and
  785. * add pointers to those routers' routerstatus_t to <b>responsible_dirs</b>.
  786. * Return -1 if we're returning an empty smartlist, else return 0.
  787. */
  788. int
  789. hid_serv_get_responsible_directories(smartlist_t *responsible_dirs,
  790. const char *id)
  791. {
  792. int start, found, n_added = 0, i;
  793. networkstatus_t *c = networkstatus_get_latest_consensus();
  794. if (!c || !smartlist_len(c->routerstatus_list)) {
  795. log_warn(LD_REND, "We don't have a consensus, so we can't perform v2 "
  796. "rendezvous operations.");
  797. return -1;
  798. }
  799. tor_assert(id);
  800. start = networkstatus_vote_find_entry_idx(c, id, &found);
  801. if (start == smartlist_len(c->routerstatus_list)) start = 0;
  802. i = start;
  803. do {
  804. routerstatus_t *r = smartlist_get(c->routerstatus_list, i);
  805. if (r->is_hs_dir) {
  806. smartlist_add(responsible_dirs, r);
  807. if (++n_added == REND_NUMBER_OF_CONSECUTIVE_REPLICAS)
  808. return 0;
  809. }
  810. if (++i == smartlist_len(c->routerstatus_list))
  811. i = 0;
  812. } while (i != start);
  813. /* Even though we don't have the desired number of hidden service
  814. * directories, be happy if we got any. */
  815. return smartlist_len(responsible_dirs) ? 0 : -1;
  816. }
  817. /* Length of the 'extended' auth cookie used to encode auth type before
  818. * base64 encoding. */
  819. #define REND_DESC_COOKIE_LEN_EXT (REND_DESC_COOKIE_LEN + 1)
  820. /* Length of the zero-padded auth cookie when base64 encoded. These two
  821. * padding bytes always (A=) are stripped off of the returned cookie. */
  822. #define REND_DESC_COOKIE_LEN_EXT_BASE64 (REND_DESC_COOKIE_LEN_BASE64 + 2)
  823. /** Encode a client authorization descriptor cookie.
  824. * The result of this function is suitable for use in the HidServAuth
  825. * option. The trailing padding characters are removed, and the
  826. * auth type is encoded into the cookie.
  827. *
  828. * Returns a new base64-encoded cookie. This function cannot fail.
  829. * The caller is responsible for freeing the returned value.
  830. */
  831. char *
  832. rend_auth_encode_cookie(const uint8_t *cookie_in, rend_auth_type_t auth_type)
  833. {
  834. uint8_t extended_cookie[REND_DESC_COOKIE_LEN_EXT];
  835. char *cookie_out = tor_malloc_zero(REND_DESC_COOKIE_LEN_EXT_BASE64 + 1);
  836. int re;
  837. tor_assert(cookie_in);
  838. memcpy(extended_cookie, cookie_in, REND_DESC_COOKIE_LEN);
  839. extended_cookie[REND_DESC_COOKIE_LEN] = ((int)auth_type - 1) << 4;
  840. re = base64_encode(cookie_out, REND_DESC_COOKIE_LEN_EXT_BASE64 + 1,
  841. (const char *) extended_cookie, REND_DESC_COOKIE_LEN_EXT,
  842. 0);
  843. tor_assert(re == REND_DESC_COOKIE_LEN_EXT_BASE64);
  844. /* Remove the trailing 'A='. Auth type is encoded in the high bits
  845. * of the last byte, so the last base64 character will always be zero
  846. * (A). This is subtly different behavior from base64_encode_nopad. */
  847. cookie_out[REND_DESC_COOKIE_LEN_BASE64] = '\0';
  848. memwipe(extended_cookie, 0, sizeof(extended_cookie));
  849. return cookie_out;
  850. }
  851. /** Decode a base64-encoded client authorization descriptor cookie.
  852. * The descriptor_cookie can be truncated to REND_DESC_COOKIE_LEN_BASE64
  853. * characters (as given to clients), or may include the two padding
  854. * characters (as stored by the service).
  855. *
  856. * The result is stored in REND_DESC_COOKIE_LEN bytes of cookie_out.
  857. * The rend_auth_type_t decoded from the cookie is stored in the
  858. * optional auth_type_out parameter.
  859. *
  860. * Return 0 on success, or -1 on error. The caller is responsible for
  861. * freeing the returned err_msg.
  862. */
  863. int
  864. rend_auth_decode_cookie(const char *cookie_in, uint8_t *cookie_out,
  865. rend_auth_type_t *auth_type_out, char **err_msg_out)
  866. {
  867. uint8_t descriptor_cookie_decoded[REND_DESC_COOKIE_LEN_EXT + 1] = { 0 };
  868. char descriptor_cookie_base64ext[REND_DESC_COOKIE_LEN_EXT_BASE64 + 1];
  869. const char *descriptor_cookie = cookie_in;
  870. char *err_msg = NULL;
  871. int auth_type_val = 0;
  872. int res = -1;
  873. int decoded_len;
  874. size_t len = strlen(descriptor_cookie);
  875. if (len == REND_DESC_COOKIE_LEN_BASE64) {
  876. /* Add a trailing zero byte to make base64-decoding happy. */
  877. tor_snprintf(descriptor_cookie_base64ext,
  878. sizeof(descriptor_cookie_base64ext),
  879. "%sA=", descriptor_cookie);
  880. descriptor_cookie = descriptor_cookie_base64ext;
  881. } else if (len != REND_DESC_COOKIE_LEN_EXT_BASE64) {
  882. tor_asprintf(&err_msg, "Authorization cookie has wrong length: %s",
  883. escaped(cookie_in));
  884. goto err;
  885. }
  886. decoded_len = base64_decode((char *) descriptor_cookie_decoded,
  887. sizeof(descriptor_cookie_decoded),
  888. descriptor_cookie,
  889. REND_DESC_COOKIE_LEN_EXT_BASE64);
  890. if (decoded_len != REND_DESC_COOKIE_LEN &&
  891. decoded_len != REND_DESC_COOKIE_LEN_EXT) {
  892. tor_asprintf(&err_msg, "Authorization cookie has invalid characters: %s",
  893. escaped(cookie_in));
  894. goto err;
  895. }
  896. if (auth_type_out) {
  897. auth_type_val = (descriptor_cookie_decoded[REND_DESC_COOKIE_LEN] >> 4) + 1;
  898. if (auth_type_val < 1 || auth_type_val > 2) {
  899. tor_asprintf(&err_msg, "Authorization cookie type is unknown: %s",
  900. escaped(cookie_in));
  901. goto err;
  902. }
  903. *auth_type_out = auth_type_val == 1 ? REND_BASIC_AUTH : REND_STEALTH_AUTH;
  904. }
  905. memcpy(cookie_out, descriptor_cookie_decoded, REND_DESC_COOKIE_LEN);
  906. res = 0;
  907. err:
  908. if (err_msg_out) {
  909. *err_msg_out = err_msg;
  910. } else {
  911. tor_free(err_msg);
  912. }
  913. memwipe(descriptor_cookie_decoded, 0, sizeof(descriptor_cookie_decoded));
  914. memwipe(descriptor_cookie_base64ext, 0, sizeof(descriptor_cookie_base64ext));
  915. return res;
  916. }
  917. /* Is this a rend client or server that allows direct (non-anonymous)
  918. * connections?
  919. * Clients must be specifically compiled and configured in this mode.
  920. * Onion services can be configured to start in this mode.
  921. * Prefer rend_client_allow_non_anonymous_connection() or
  922. * rend_service_allow_non_anonymous_connection() whenever possible, so that
  923. * checks are specific to Single Onion Services or Tor2web. */
  924. int
  925. rend_allow_non_anonymous_connection(const or_options_t* options)
  926. {
  927. return (rend_client_allow_non_anonymous_connection(options)
  928. || rend_service_allow_non_anonymous_connection(options));
  929. }
  930. /* Is this a rend client or server in non-anonymous mode?
  931. * Clients must be specifically compiled in this mode.
  932. * Onion services can be configured to start in this mode.
  933. * Prefer rend_client_non_anonymous_mode_enabled() or
  934. * rend_service_non_anonymous_mode_enabled() whenever possible, so that checks
  935. * are specific to Single Onion Services or Tor2web. */
  936. int
  937. rend_non_anonymous_mode_enabled(const or_options_t *options)
  938. {
  939. return (rend_client_non_anonymous_mode_enabled(options)
  940. || rend_service_non_anonymous_mode_enabled(options));
  941. }
  942. /* Make sure that tor only builds one-hop circuits when they would not
  943. * compromise user anonymity.
  944. *
  945. * One-hop circuits are permitted in Tor2web or Single Onion modes.
  946. *
  947. * Tor2web or Single Onion modes are also allowed to make multi-hop circuits.
  948. * For example, single onion HSDir circuits are 3-hop to prevent denial of
  949. * service.
  950. */
  951. void
  952. assert_circ_anonymity_ok(const origin_circuit_t *circ,
  953. const or_options_t *options)
  954. {
  955. tor_assert(options);
  956. tor_assert(circ);
  957. tor_assert(circ->build_state);
  958. if (circ->build_state->onehop_tunnel) {
  959. tor_assert(rend_allow_non_anonymous_connection(options));
  960. }
  961. }
  962. /* Return 1 iff the given <b>digest</b> of a permenanent hidden service key is
  963. * equal to the digest in the origin circuit <b>ocirc</b> of its rend data .
  964. * If the rend data doesn't exist, 0 is returned. This function is agnostic to
  965. * the rend data version. */
  966. int
  967. rend_circuit_pk_digest_eq(const origin_circuit_t *ocirc,
  968. const uint8_t *digest)
  969. {
  970. size_t rend_pk_digest_len;
  971. const uint8_t *rend_pk_digest;
  972. tor_assert(ocirc);
  973. tor_assert(digest);
  974. if (ocirc->rend_data == NULL) {
  975. goto no_match;
  976. }
  977. rend_pk_digest = rend_data_get_pk_digest(ocirc->rend_data,
  978. &rend_pk_digest_len);
  979. if (tor_memeq(rend_pk_digest, digest, rend_pk_digest_len)) {
  980. goto match;
  981. }
  982. no_match:
  983. return 0;
  984. match:
  985. return 1;
  986. }