rendcommon.c 37 KB

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