rendcommon.c 37 KB

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