shared_random.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. /* Copyright (c) 2016, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /**
  4. * \file shared_random.c
  5. *
  6. * \brief Functions and data structure needed to accomplish the shared
  7. * random protocol as defined in proposal #250.
  8. **/
  9. #define SHARED_RANDOM_PRIVATE
  10. #include "or.h"
  11. #include "shared_random.h"
  12. #include "config.h"
  13. #include "confparse.h"
  14. #include "networkstatus.h"
  15. #include "routerkeys.h"
  16. #include "router.h"
  17. #include "routerlist.h"
  18. #include "shared_random_state.h"
  19. /* Allocate a new commit object and initializing it with <b>identity</b>
  20. * that MUST be provided. The digest algorithm is set to the default one
  21. * that is supported. The rest is uninitialized. This never returns NULL. */
  22. static sr_commit_t *
  23. commit_new(const char *rsa_identity_fpr)
  24. {
  25. sr_commit_t *commit;
  26. tor_assert(rsa_identity_fpr);
  27. commit = tor_malloc_zero(sizeof(*commit));
  28. commit->alg = SR_DIGEST_ALG;
  29. strlcpy(commit->rsa_identity_fpr, rsa_identity_fpr,
  30. sizeof(commit->rsa_identity_fpr));
  31. return commit;
  32. }
  33. /* Issue a log message describing <b>commit</b>. */
  34. static void
  35. commit_log(const sr_commit_t *commit)
  36. {
  37. tor_assert(commit);
  38. log_debug(LD_DIR, "SR: Commit from %s", commit->rsa_identity_fpr);
  39. if (commit->commit_ts >= 0) {
  40. log_debug(LD_DIR, "SR: Commit: [TS: %ld] [Encoded: %s]",
  41. commit->commit_ts, commit->encoded_commit);
  42. }
  43. if (commit->reveal_ts >= 0) {
  44. log_debug(LD_DIR, "SR: Reveal: [TS: %ld] [Encoded: %s]",
  45. commit->reveal_ts, safe_str(commit->encoded_reveal));
  46. } else {
  47. log_debug(LD_DIR, "SR: Reveal: UNKNOWN");
  48. }
  49. }
  50. /* Return true iff the commit contains an encoded reveal value. */
  51. STATIC int
  52. commit_has_reveal_value(const sr_commit_t *commit)
  53. {
  54. return !tor_mem_is_zero(commit->encoded_reveal,
  55. sizeof(commit->encoded_reveal));
  56. }
  57. /* Parse the encoded commit. The format is:
  58. * base64-encode( TIMESTAMP || H(REVEAL) )
  59. *
  60. * If successfully decoded and parsed, commit is updated and 0 is returned.
  61. * On error, return -1. */
  62. STATIC int
  63. commit_decode(const char *encoded, sr_commit_t *commit)
  64. {
  65. int decoded_len = 0;
  66. size_t offset = 0;
  67. /* XXX: Needs two extra bytes for the base64 decode calculation matches
  68. * the binary length once decoded. #17868. */
  69. char b64_decoded[SR_COMMIT_LEN + 2];
  70. tor_assert(encoded);
  71. tor_assert(commit);
  72. if (strlen(encoded) > SR_COMMIT_BASE64_LEN) {
  73. /* This means that if we base64 decode successfully the reveiced commit,
  74. * we'll end up with a bigger decoded commit thus unusable. */
  75. goto error;
  76. }
  77. /* Decode our encoded commit. Let's be careful here since _encoded_ is
  78. * coming from the network in a dirauth vote so we expect nothing more
  79. * than the base64 encoded length of a commit. */
  80. decoded_len = base64_decode(b64_decoded, sizeof(b64_decoded),
  81. encoded, strlen(encoded));
  82. if (decoded_len < 0) {
  83. log_warn(LD_BUG, "SR: Commit from authority %s can't be decoded.",
  84. commit->rsa_identity_fpr);
  85. goto error;
  86. }
  87. if (decoded_len != SR_COMMIT_LEN) {
  88. log_warn(LD_BUG, "SR: Commit from authority %s decoded length doesn't "
  89. "match the expected length (%d vs %d).",
  90. commit->rsa_identity_fpr, decoded_len, SR_COMMIT_LEN);
  91. goto error;
  92. }
  93. /* First is the timestamp (8 bytes). */
  94. commit->commit_ts = (time_t) tor_ntohll(get_uint64(b64_decoded));
  95. offset += sizeof(uint64_t);
  96. /* Next is hashed reveal. */
  97. memcpy(commit->hashed_reveal, b64_decoded + offset,
  98. sizeof(commit->hashed_reveal));
  99. /* Copy the base64 blob to the commit. Useful for voting. */
  100. strlcpy(commit->encoded_commit, encoded, sizeof(commit->encoded_commit));
  101. return 0;
  102. error:
  103. return -1;
  104. }
  105. /* Parse the b64 blob at <b>encoded</b> containing reveal information and
  106. * store the information in-place in <b>commit</b>. Return 0 on success else
  107. * a negative value. */
  108. STATIC int
  109. reveal_decode(const char *encoded, sr_commit_t *commit)
  110. {
  111. int decoded_len = 0;
  112. /* XXX: Needs two extra bytes for the base64 decode calculation matches
  113. * the binary length once decoded. #17868. */
  114. char b64_decoded[SR_REVEAL_LEN + 2];
  115. tor_assert(encoded);
  116. tor_assert(commit);
  117. if (strlen(encoded) > SR_REVEAL_BASE64_LEN) {
  118. /* This means that if we base64 decode successfully the received reveal
  119. * value, we'll end up with a bigger decoded value thus unusable. */
  120. goto error;
  121. }
  122. /* Decode our encoded reveal. Let's be careful here since _encoded_ is
  123. * coming from the network in a dirauth vote so we expect nothing more
  124. * than the base64 encoded length of our reveal. */
  125. decoded_len = base64_decode(b64_decoded, sizeof(b64_decoded),
  126. encoded, strlen(encoded));
  127. if (decoded_len < 0) {
  128. log_warn(LD_BUG, "SR: Reveal from authority %s can't be decoded.",
  129. commit->rsa_identity_fpr);
  130. goto error;
  131. }
  132. if (decoded_len != SR_REVEAL_LEN) {
  133. log_warn(LD_BUG, "SR: Reveal from authority %s decoded length is "
  134. "doesn't match the expected length (%d vs %d)",
  135. commit->rsa_identity_fpr, decoded_len, SR_REVEAL_LEN);
  136. goto error;
  137. }
  138. commit->reveal_ts = (time_t) tor_ntohll(get_uint64(b64_decoded));
  139. /* Copy the last part, the random value. */
  140. memcpy(commit->random_number, b64_decoded + 8,
  141. sizeof(commit->random_number));
  142. /* Also copy the whole message to use during verification */
  143. strlcpy(commit->encoded_reveal, encoded, sizeof(commit->encoded_reveal));
  144. return 0;
  145. error:
  146. return -1;
  147. }
  148. /* Encode a reveal element using a given commit object to dst which is a
  149. * buffer large enough to put the base64-encoded reveal construction. The
  150. * format is as follow:
  151. * REVEAL = base64-encode( TIMESTAMP || H(RN) )
  152. * Return base64 encoded length on success else a negative value.
  153. */
  154. STATIC int
  155. reveal_encode(const sr_commit_t *commit, char *dst, size_t len)
  156. {
  157. int ret;
  158. size_t offset = 0;
  159. char buf[SR_REVEAL_LEN] = {0};
  160. tor_assert(commit);
  161. tor_assert(dst);
  162. set_uint64(buf, tor_htonll(commit->reveal_ts));
  163. offset += sizeof(uint64_t);
  164. memcpy(buf + offset, commit->random_number,
  165. sizeof(commit->random_number));
  166. /* Let's clean the buffer and then b64 encode it. */
  167. memset(dst, 0, len);
  168. ret = base64_encode(dst, len, buf, sizeof(buf), 0);
  169. /* Wipe this buffer because it contains our random value. */
  170. memwipe(buf, 0, sizeof(buf));
  171. return ret;
  172. }
  173. /* Encode the given commit object to dst which is a buffer large enough to
  174. * put the base64-encoded commit. The format is as follow:
  175. * COMMIT = base64-encode( TIMESTAMP || H(H(RN)) )
  176. * Return base64 encoded length on success else a negative value.
  177. */
  178. STATIC int
  179. commit_encode(const sr_commit_t *commit, char *dst, size_t len)
  180. {
  181. size_t offset = 0;
  182. char buf[SR_COMMIT_LEN] = {0};
  183. tor_assert(commit);
  184. tor_assert(dst);
  185. /* First is the timestamp (8 bytes). */
  186. set_uint64(buf, tor_htonll((uint64_t) commit->commit_ts));
  187. offset += sizeof(uint64_t);
  188. /* and then the hashed reveal. */
  189. memcpy(buf + offset, commit->hashed_reveal,
  190. sizeof(commit->hashed_reveal));
  191. /* Clean the buffer and then b64 encode it. */
  192. memset(dst, 0, len);
  193. return base64_encode(dst, len, buf, sizeof(buf), 0);
  194. }
  195. /* Cleanup both our global state and disk state. */
  196. static void
  197. sr_cleanup(void)
  198. {
  199. sr_state_free();
  200. }
  201. /* Using <b>commit</b>, return a newly allocated string containing the commit
  202. * information that should be used during SRV calculation. It's the caller
  203. * responsibility to free the memory. Return NULL if this is not a commit to be
  204. * used for SRV calculation. */
  205. static char *
  206. get_srv_element_from_commit(const sr_commit_t *commit)
  207. {
  208. char *element;
  209. tor_assert(commit);
  210. if (!commit_has_reveal_value(commit)) {
  211. return NULL;
  212. }
  213. tor_asprintf(&element, "%s%s", commit->rsa_identity_fpr,
  214. commit->encoded_reveal);
  215. return element;
  216. }
  217. /* Return a srv object that is built with the construction:
  218. * SRV = SHA3-256("shared-random" | INT_8(reveal_num) |
  219. * INT_8(version) | HASHED_REVEALS | previous_SRV)
  220. * This function cannot fail. */
  221. static sr_srv_t *
  222. generate_srv(const char *hashed_reveals, uint8_t reveal_num,
  223. const sr_srv_t *previous_srv)
  224. {
  225. char msg[DIGEST256_LEN + SR_SRV_MSG_LEN] = {0};
  226. size_t offset = 0;
  227. sr_srv_t *srv;
  228. tor_assert(hashed_reveals);
  229. /* Add the invariant token. */
  230. memcpy(msg, SR_SRV_TOKEN, SR_SRV_TOKEN_LEN);
  231. offset += SR_SRV_TOKEN_LEN;
  232. set_uint8(msg + offset, reveal_num);
  233. offset += 1;
  234. set_uint8(msg + offset, SR_PROTO_VERSION);
  235. offset += 1;
  236. memcpy(msg + offset, hashed_reveals, DIGEST256_LEN);
  237. offset += DIGEST256_LEN;
  238. if (previous_srv != NULL) {
  239. memcpy(msg + offset, previous_srv->value, sizeof(previous_srv->value));
  240. }
  241. /* Ok we have our message and key for the HMAC computation, allocate our
  242. * srv object and do the last step. */
  243. srv = tor_malloc_zero(sizeof(*srv));
  244. crypto_digest256((char *) srv->value, msg, sizeof(msg), SR_DIGEST_ALG);
  245. srv->num_reveals = reveal_num;
  246. {
  247. /* Debugging. */
  248. char srv_hash_encoded[SR_SRV_VALUE_BASE64_LEN + 1];
  249. sr_srv_encode(srv_hash_encoded, srv);
  250. log_debug(LD_DIR, "SR: Generated SRV: %s", srv_hash_encoded);
  251. }
  252. return srv;
  253. }
  254. /* Compare reveal values and return the result. This should exclusively be
  255. * used by smartlist_sort(). */
  256. static int
  257. compare_reveal_(const void **_a, const void **_b)
  258. {
  259. const sr_commit_t *a = *_a, *b = *_b;
  260. return fast_memcmp(a->hashed_reveal, b->hashed_reveal,
  261. sizeof(a->hashed_reveal));
  262. }
  263. /* Encode the given shared random value and put it in dst. Destination
  264. * buffer must be at least SR_SRV_VALUE_BASE64_LEN plus the NULL byte. */
  265. void
  266. sr_srv_encode(char *dst, const sr_srv_t *srv)
  267. {
  268. int ret;
  269. /* Extra byte for the NULL terminated char. */
  270. char buf[SR_SRV_VALUE_BASE64_LEN + 1];
  271. tor_assert(dst);
  272. tor_assert(srv);
  273. ret = base64_encode(buf, sizeof(buf), (const char *) srv->value,
  274. sizeof(srv->value), 0);
  275. /* Always expect the full length without the NULL byte. */
  276. tor_assert(ret == (sizeof(buf) - 1));
  277. strlcpy(dst, buf, sizeof(buf));
  278. }
  279. /* Free a commit object. */
  280. void
  281. sr_commit_free(sr_commit_t *commit)
  282. {
  283. if (commit == NULL) {
  284. return;
  285. }
  286. /* Make sure we do not leave OUR random number in memory. */
  287. memwipe(commit->random_number, 0, sizeof(commit->random_number));
  288. tor_free(commit);
  289. }
  290. /* Generate the commitment/reveal value for the protocol run starting at
  291. * <b>timestamp</b>. <b>my_rsa_cert</b> is our authority RSA certificate. */
  292. sr_commit_t *
  293. sr_generate_our_commit(time_t timestamp, const authority_cert_t *my_rsa_cert)
  294. {
  295. sr_commit_t *commit = NULL;
  296. char fingerprint[FINGERPRINT_LEN+1];
  297. tor_assert(my_rsa_cert);
  298. /* Get our RSA identity fingerprint */
  299. if (crypto_pk_get_fingerprint(my_rsa_cert->identity_key,
  300. fingerprint, 0) < 0) {
  301. goto error;
  302. }
  303. /* New commit with our identity key. */
  304. commit = commit_new(fingerprint);
  305. /* Generate the reveal random value */
  306. crypto_strongest_rand(commit->random_number,
  307. sizeof(commit->random_number));
  308. commit->commit_ts = commit->reveal_ts = timestamp;
  309. /* Now get the base64 blob that corresponds to our reveal */
  310. if (reveal_encode(commit, commit->encoded_reveal,
  311. sizeof(commit->encoded_reveal)) < 0) {
  312. log_err(LD_DIR, "SR: Unable to encode our reveal value!");
  313. goto error;
  314. }
  315. /* Now let's create the commitment */
  316. tor_assert(commit->alg == SR_DIGEST_ALG);
  317. /* The invariant length is used here since the encoded reveal variable
  318. * has an extra byte added for the NULL terminated byte. */
  319. if (crypto_digest256(commit->hashed_reveal, commit->encoded_reveal,
  320. SR_REVEAL_BASE64_LEN, commit->alg)) {
  321. goto error;
  322. }
  323. /* Now get the base64 blob that corresponds to our commit. */
  324. if (commit_encode(commit, commit->encoded_commit,
  325. sizeof(commit->encoded_commit)) < 0) {
  326. log_err(LD_DIR, "SR: Unable to encode our commit value!");
  327. goto error;
  328. }
  329. log_debug(LD_DIR, "SR: Generated our commitment:");
  330. commit_log(commit);
  331. return commit;
  332. error:
  333. sr_commit_free(commit);
  334. return NULL;
  335. }
  336. /* Compute the shared random value based on the active commits in our state. */
  337. void
  338. sr_compute_srv(void)
  339. {
  340. size_t reveal_num = 0;
  341. char *reveals = NULL;
  342. smartlist_t *chunks, *commits;
  343. digestmap_t *state_commits;
  344. /* Computing a shared random value in the commit phase is very wrong. This
  345. * should only happen at the very end of the reveal phase when a new
  346. * protocol run is about to start. */
  347. tor_assert(sr_state_get_phase() == SR_PHASE_REVEAL);
  348. state_commits = sr_state_get_commits();
  349. commits = smartlist_new();
  350. chunks = smartlist_new();
  351. /* We must make a list of commit ordered by authority fingerprint in
  352. * ascending order as specified by proposal 250. */
  353. DIGESTMAP_FOREACH(state_commits, key, sr_commit_t *, c) {
  354. smartlist_add(commits, c);
  355. } DIGESTMAP_FOREACH_END;
  356. smartlist_sort(commits, compare_reveal_);
  357. /* Now for each commit for that sorted list in ascending order, we'll
  358. * build the element for each authority that needs to go into the srv
  359. * computation. */
  360. SMARTLIST_FOREACH_BEGIN(commits, const sr_commit_t *, c) {
  361. char *element = get_srv_element_from_commit(c);
  362. if (element) {
  363. smartlist_add(chunks, element);
  364. reveal_num++;
  365. }
  366. } SMARTLIST_FOREACH_END(c);
  367. smartlist_free(commits);
  368. {
  369. /* Join all reveal values into one giant string that we'll hash so we
  370. * can generated our shared random value. */
  371. sr_srv_t *current_srv;
  372. char hashed_reveals[DIGEST256_LEN];
  373. reveals = smartlist_join_strings(chunks, "", 0, NULL);
  374. SMARTLIST_FOREACH(chunks, char *, s, tor_free(s));
  375. smartlist_free(chunks);
  376. if (crypto_digest256(hashed_reveals, reveals, strlen(reveals),
  377. SR_DIGEST_ALG)) {
  378. goto end;
  379. }
  380. tor_assert(reveal_num < UINT8_MAX);
  381. current_srv = generate_srv(hashed_reveals, (uint8_t) reveal_num,
  382. sr_state_get_previous_srv());
  383. sr_state_set_current_srv(current_srv);
  384. /* We have a fresh SRV, flag our state. */
  385. sr_state_set_fresh_srv();
  386. }
  387. end:
  388. tor_free(reveals);
  389. }
  390. /* Parse a list of arguments from a SRV value either from a vote, consensus
  391. * or from our disk state and return a newly allocated srv object. NULL is
  392. * returned on error.
  393. *
  394. * The arguments' order:
  395. * num_reveals, value
  396. */
  397. sr_srv_t *
  398. sr_parse_srv(const smartlist_t *args)
  399. {
  400. char *value;
  401. int num_reveals, ok, ret;
  402. sr_srv_t *srv = NULL;
  403. tor_assert(args);
  404. if (smartlist_len(args) < 2) {
  405. goto end;
  406. }
  407. /* First argument is the number of reveal values */
  408. num_reveals = (int)tor_parse_long(smartlist_get(args, 0),
  409. 10, 0, INT32_MAX, &ok, NULL);
  410. if (!ok) {
  411. goto end;
  412. }
  413. /* Second and last argument is the shared random value it self. */
  414. value = smartlist_get(args, 1);
  415. if (strlen(value) != SR_SRV_VALUE_BASE64_LEN) {
  416. goto end;
  417. }
  418. srv = tor_malloc_zero(sizeof(*srv));
  419. srv->num_reveals = num_reveals;
  420. /* We substract one byte from the srclen because the function ignores the
  421. * '=' character in the given buffer. This is broken but it's a documented
  422. * behavior of the implementation. */
  423. ret = base64_decode((char *) srv->value, sizeof(srv->value), value,
  424. SR_SRV_VALUE_BASE64_LEN - 1);
  425. if (ret != sizeof(srv->value)) {
  426. tor_free(srv);
  427. srv = NULL;
  428. goto end;
  429. }
  430. end:
  431. return srv;
  432. }
  433. /* Parse a commit from a vote or from our disk state and return a newly
  434. * allocated commit object. NULL is returned on error.
  435. *
  436. * The commit's data is in <b>args</b> and the order matters very much:
  437. * algname, RSA fingerprint, commit value[, reveal value]
  438. */
  439. sr_commit_t *
  440. sr_parse_commit(const smartlist_t *args)
  441. {
  442. char *value;
  443. digest_algorithm_t alg;
  444. const char *rsa_identity_fpr;
  445. sr_commit_t *commit = NULL;
  446. if (smartlist_len(args) < 3) {
  447. goto error;
  448. }
  449. /* First argument is the algorithm. */
  450. value = smartlist_get(args, 0);
  451. alg = crypto_digest_algorithm_parse_name(value);
  452. if (alg != SR_DIGEST_ALG) {
  453. log_warn(LD_BUG, "SR: Commit algorithm %s is not recognized.",
  454. escaped(value));
  455. goto error;
  456. }
  457. /* Second argument is the RSA fingerprint of the auth */
  458. rsa_identity_fpr = smartlist_get(args, 1);
  459. if (base16_decode(digest, DIGEST_LEN, rsa_identity_fpr,
  460. HEX_DIGEST_LEN) < 0) {
  461. log_warn(LD_DIR, "SR: RSA fingerprint '%s' not decodable",
  462. rsa_identity_fpr);
  463. goto error;
  464. }
  465. /* Let's make sure, for extra safety, that this fingerprint is known to
  466. * us. Even though this comes from a vote, doesn't hurt to be
  467. * extracareful. */
  468. if (trusteddirserver_get_by_v3_auth_digest(digest) == NULL) {
  469. log_warn(LD_DIR, "SR: Fingerprint %s is not from a recognized "
  470. "authority. Discarding commit.",
  471. rsa_identity_fpr);
  472. goto error;
  473. }
  474. /* Allocate commit since we have a valid identity now. */
  475. commit = commit_new(rsa_identity_fpr);
  476. /* Third argument is the commitment value base64-encoded. */
  477. value = smartlist_get(args, 2);
  478. if (commit_decode(value, commit) < 0) {
  479. goto error;
  480. }
  481. /* (Optional) Fourth argument is the revealed value. */
  482. if (smartlist_len(args) > 3) {
  483. value = smartlist_get(args, 3);
  484. if (reveal_decode(value, commit) < 0) {
  485. goto error;
  486. }
  487. }
  488. return commit;
  489. error:
  490. sr_commit_free(commit);
  491. return NULL;
  492. }
  493. /* Initialize shared random subsystem. This MUST be called early in the boot
  494. * process of tor. Return 0 on success else -1 on error. */
  495. int
  496. sr_init(int save_to_disk)
  497. {
  498. return sr_state_init(save_to_disk, 1);
  499. }
  500. /* Save our state to disk and cleanup everything. */
  501. void
  502. sr_save_and_cleanup(void)
  503. {
  504. sr_state_save();
  505. sr_cleanup();
  506. }