rendcommon.c 35 KB

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