shared_random.c 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291
  1. /* Copyright (c) 2016-2018, 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. * \details
  10. *
  11. * This file implements the dirauth-only commit-and-reveal protocol specified
  12. * by proposal #250. The protocol has two phases (sr_phase_t): the commitment
  13. * phase and the reveal phase (see get_sr_protocol_phase()).
  14. *
  15. * During the protocol, directory authorities keep state in memory (using
  16. * sr_state_t) and in disk (using sr_disk_state_t). The synchronization between
  17. * these two data structures happens in disk_state_update() and
  18. * disk_state_parse().
  19. *
  20. * Here is a rough protocol outline:
  21. *
  22. * 1) In the beginning of the commitment phase, dirauths generate a
  23. * commitment/reveal value for the current protocol run (see
  24. * new_protocol_run() and sr_generate_our_commit()).
  25. *
  26. * 2) During voting, dirauths publish their commits in their votes
  27. * depending on the current phase. Dirauths also include the two
  28. * latest shared random values (SRV) in their votes.
  29. * (see sr_get_string_for_vote())
  30. *
  31. * 3) Upon receiving a commit from a vote, authorities parse it, verify
  32. * it, and attempt to save any new commitment or reveal information in
  33. * their state file (see extract_shared_random_commits() and
  34. * sr_handle_received_commits()). They also parse SRVs from votes to
  35. * decide which SRV should be included in the final consensus (see
  36. * extract_shared_random_srvs()).
  37. *
  38. * 3) After voting is done, we count the SRVs we extracted from the votes,
  39. * to find the one voted by the majority of dirauths which should be
  40. * included in the final consensus (see get_majority_srv_from_votes()).
  41. * If an appropriate SRV is found, it is embedded in the consensus (see
  42. * sr_get_string_for_consensus()).
  43. *
  44. * 4) At the end of the reveal phase, dirauths compute a fresh SRV for the
  45. * day using the active commits (see sr_compute_srv()). This new SRV
  46. * is embedded in the votes as described above.
  47. *
  48. * Some more notes:
  49. *
  50. * - To support rebooting authorities and to avoid double voting, each dirauth
  51. * saves the current state of the protocol on disk so that it can resume
  52. * normally in case of reboot. The disk state (sr_disk_state_t) is managed by
  53. * shared_random_state.c:state_query() and we go to extra lengths to ensure
  54. * that the state is flushed on disk everytime we receive any useful
  55. * information like commits or SRVs.
  56. *
  57. * - When we receive a commit from a vote, we examine it to see if it's useful
  58. * to us and whether it's appropriate to receive it according to the current
  59. * phase of the protocol (see should_keep_commit()). If the commit is useful
  60. * to us, we save it in our disk state using save_commit_to_state(). When we
  61. * receive the reveal information corresponding to a commitment, we verify
  62. * that they indeed match using verify_commit_and_reveal().
  63. *
  64. * - We treat consensuses as the ground truth, so everytime we generate a new
  65. * consensus we update our SR state accordingly even if our local view was
  66. * different (see sr_act_post_consensus()).
  67. *
  68. * - After a consensus has been composed, the SR protocol state gets prepared
  69. * for the next voting session using sr_state_update(). That function takes
  70. * care of housekeeping and also rotates the SRVs and commits in case a new
  71. * protocol run is coming up. We also call sr_state_update() on bootup (in
  72. * sr_state_init()), to prepare the state for the very first voting session.
  73. *
  74. * Terminology:
  75. *
  76. * - "Commitment" is the commitment value of the commit-and-reveal protocol.
  77. *
  78. * - "Reveal" is the reveal value of the commit-and-reveal protocol.
  79. *
  80. * - "Commit" is a struct (sr_commit_t) that contains a commitment value and
  81. * optionally also a corresponding reveal value.
  82. *
  83. * - "SRV" is the Shared Random Value that gets generated as the result of the
  84. * commit-and-reveal protocol.
  85. **/
  86. #define SHARED_RANDOM_PRIVATE
  87. #include "core/or/or.h"
  88. #include "feature/dirauth/shared_random.h"
  89. #include "app/config/config.h"
  90. #include "app/config/confparse.h"
  91. #include "lib/crypt_ops/crypto_rand.h"
  92. #include "lib/crypt_ops/crypto_util.h"
  93. #include "feature/nodelist/networkstatus.h"
  94. #include "feature/relay/router.h"
  95. #include "feature/relay/routerkeys.h"
  96. #include "feature/nodelist/dirlist.h"
  97. #include "feature/hs_common/shared_random_client.h"
  98. #include "feature/dirauth/shared_random_state.h"
  99. #include "feature/dircommon/voting_schedule.h"
  100. #include "feature/dirauth/dirvote.h"
  101. #include "feature/dirauth/authmode.h"
  102. #include "feature/nodelist/authority_cert_st.h"
  103. #include "feature/nodelist/networkstatus_st.h"
  104. /* String prefix of shared random values in votes/consensuses. */
  105. static const char previous_srv_str[] = "shared-rand-previous-value";
  106. static const char current_srv_str[] = "shared-rand-current-value";
  107. static const char commit_ns_str[] = "shared-rand-commit";
  108. static const char sr_flag_ns_str[] = "shared-rand-participate";
  109. /* The value of the consensus param AuthDirNumSRVAgreements found in the
  110. * vote. This is set once the consensus creation subsystem requests the
  111. * SRV(s) that should be put in the consensus. We use this value to decide
  112. * if we keep or not an SRV. */
  113. static int32_t num_srv_agreements_from_vote;
  114. /* Return a heap allocated copy of the SRV <b>orig</b>. */
  115. STATIC sr_srv_t *
  116. srv_dup(const sr_srv_t *orig)
  117. {
  118. sr_srv_t *duplicate = NULL;
  119. if (!orig) {
  120. return NULL;
  121. }
  122. duplicate = tor_malloc_zero(sizeof(sr_srv_t));
  123. duplicate->num_reveals = orig->num_reveals;
  124. memcpy(duplicate->value, orig->value, sizeof(duplicate->value));
  125. return duplicate;
  126. }
  127. /* Allocate a new commit object and initializing it with <b>rsa_identity</b>
  128. * that MUST be provided. The digest algorithm is set to the default one
  129. * that is supported. The rest is uninitialized. This never returns NULL. */
  130. static sr_commit_t *
  131. commit_new(const char *rsa_identity)
  132. {
  133. sr_commit_t *commit;
  134. tor_assert(rsa_identity);
  135. commit = tor_malloc_zero(sizeof(*commit));
  136. commit->alg = SR_DIGEST_ALG;
  137. memcpy(commit->rsa_identity, rsa_identity, sizeof(commit->rsa_identity));
  138. base16_encode(commit->rsa_identity_hex, sizeof(commit->rsa_identity_hex),
  139. commit->rsa_identity, sizeof(commit->rsa_identity));
  140. return commit;
  141. }
  142. /* Issue a log message describing <b>commit</b>. */
  143. static void
  144. commit_log(const sr_commit_t *commit)
  145. {
  146. tor_assert(commit);
  147. log_debug(LD_DIR, "SR: Commit from %s", sr_commit_get_rsa_fpr(commit));
  148. log_debug(LD_DIR, "SR: Commit: [TS: %" PRIu64 "] [Encoded: %s]",
  149. commit->commit_ts, commit->encoded_commit);
  150. log_debug(LD_DIR, "SR: Reveal: [TS: %" PRIu64 "] [Encoded: %s]",
  151. commit->reveal_ts, safe_str(commit->encoded_reveal));
  152. }
  153. /* Make sure that the commitment and reveal information in <b>commit</b>
  154. * match. If they match return 0, return -1 otherwise. This function MUST be
  155. * used everytime we receive a new reveal value. Furthermore, the commit
  156. * object MUST have a reveal value and the hash of the reveal value. */
  157. STATIC int
  158. verify_commit_and_reveal(const sr_commit_t *commit)
  159. {
  160. tor_assert(commit);
  161. log_debug(LD_DIR, "SR: Validating commit from authority %s",
  162. sr_commit_get_rsa_fpr(commit));
  163. /* Check that the timestamps match. */
  164. if (commit->commit_ts != commit->reveal_ts) {
  165. log_warn(LD_BUG, "SR: Commit timestamp %" PRIu64 " doesn't match reveal "
  166. "timestamp %" PRIu64, commit->commit_ts,
  167. commit->reveal_ts);
  168. goto invalid;
  169. }
  170. /* Verify that the hashed_reveal received in the COMMIT message, matches
  171. * the reveal we just received. */
  172. {
  173. /* We first hash the reveal we just received. */
  174. char received_hashed_reveal[sizeof(commit->hashed_reveal)];
  175. /* Only sha3-256 is supported. */
  176. if (commit->alg != SR_DIGEST_ALG) {
  177. goto invalid;
  178. }
  179. /* Use the invariant length since the encoded reveal variable has an
  180. * extra byte for the NUL terminated byte. */
  181. if (crypto_digest256(received_hashed_reveal, commit->encoded_reveal,
  182. SR_REVEAL_BASE64_LEN, commit->alg) < 0) {
  183. /* Unable to digest the reveal blob, this is unlikely. */
  184. goto invalid;
  185. }
  186. /* Now compare that with the hashed_reveal we received in COMMIT. */
  187. if (fast_memneq(received_hashed_reveal, commit->hashed_reveal,
  188. sizeof(received_hashed_reveal))) {
  189. log_warn(LD_BUG, "SR: Received reveal value from authority %s "
  190. "doesn't match the commit value.",
  191. sr_commit_get_rsa_fpr(commit));
  192. goto invalid;
  193. }
  194. }
  195. return 0;
  196. invalid:
  197. return -1;
  198. }
  199. /* Return true iff the commit contains an encoded reveal value. */
  200. STATIC int
  201. commit_has_reveal_value(const sr_commit_t *commit)
  202. {
  203. return !tor_mem_is_zero(commit->encoded_reveal,
  204. sizeof(commit->encoded_reveal));
  205. }
  206. /* Parse the encoded commit. The format is:
  207. * base64-encode( TIMESTAMP || H(REVEAL) )
  208. *
  209. * If successfully decoded and parsed, commit is updated and 0 is returned.
  210. * On error, return -1. */
  211. STATIC int
  212. commit_decode(const char *encoded, sr_commit_t *commit)
  213. {
  214. int decoded_len = 0;
  215. size_t offset = 0;
  216. char b64_decoded[SR_COMMIT_LEN];
  217. tor_assert(encoded);
  218. tor_assert(commit);
  219. if (strlen(encoded) > SR_COMMIT_BASE64_LEN) {
  220. /* This means that if we base64 decode successfully the reveiced commit,
  221. * we'll end up with a bigger decoded commit thus unusable. */
  222. goto error;
  223. }
  224. /* Decode our encoded commit. Let's be careful here since _encoded_ is
  225. * coming from the network in a dirauth vote so we expect nothing more
  226. * than the base64 encoded length of a commit. */
  227. decoded_len = base64_decode(b64_decoded, sizeof(b64_decoded),
  228. encoded, strlen(encoded));
  229. if (decoded_len < 0) {
  230. log_warn(LD_BUG, "SR: Commit from authority %s can't be decoded.",
  231. sr_commit_get_rsa_fpr(commit));
  232. goto error;
  233. }
  234. if (decoded_len != SR_COMMIT_LEN) {
  235. log_warn(LD_BUG, "SR: Commit from authority %s decoded length doesn't "
  236. "match the expected length (%d vs %u).",
  237. sr_commit_get_rsa_fpr(commit), decoded_len,
  238. (unsigned)SR_COMMIT_LEN);
  239. goto error;
  240. }
  241. /* First is the timestamp (8 bytes). */
  242. commit->commit_ts = tor_ntohll(get_uint64(b64_decoded));
  243. offset += sizeof(uint64_t);
  244. /* Next is hashed reveal. */
  245. memcpy(commit->hashed_reveal, b64_decoded + offset,
  246. sizeof(commit->hashed_reveal));
  247. /* Copy the base64 blob to the commit. Useful for voting. */
  248. strlcpy(commit->encoded_commit, encoded, sizeof(commit->encoded_commit));
  249. return 0;
  250. error:
  251. return -1;
  252. }
  253. /* Parse the b64 blob at <b>encoded</b> containing reveal information and
  254. * store the information in-place in <b>commit</b>. Return 0 on success else
  255. * a negative value. */
  256. STATIC int
  257. reveal_decode(const char *encoded, sr_commit_t *commit)
  258. {
  259. int decoded_len = 0;
  260. char b64_decoded[SR_REVEAL_LEN];
  261. tor_assert(encoded);
  262. tor_assert(commit);
  263. if (strlen(encoded) > SR_REVEAL_BASE64_LEN) {
  264. /* This means that if we base64 decode successfully the received reveal
  265. * value, we'll end up with a bigger decoded value thus unusable. */
  266. goto error;
  267. }
  268. /* Decode our encoded reveal. Let's be careful here since _encoded_ is
  269. * coming from the network in a dirauth vote so we expect nothing more
  270. * than the base64 encoded length of our reveal. */
  271. decoded_len = base64_decode(b64_decoded, sizeof(b64_decoded),
  272. encoded, strlen(encoded));
  273. if (decoded_len < 0) {
  274. log_warn(LD_BUG, "SR: Reveal from authority %s can't be decoded.",
  275. sr_commit_get_rsa_fpr(commit));
  276. goto error;
  277. }
  278. if (decoded_len != SR_REVEAL_LEN) {
  279. log_warn(LD_BUG, "SR: Reveal from authority %s decoded length is "
  280. "doesn't match the expected length (%d vs %u)",
  281. sr_commit_get_rsa_fpr(commit), decoded_len,
  282. (unsigned)SR_REVEAL_LEN);
  283. goto error;
  284. }
  285. commit->reveal_ts = tor_ntohll(get_uint64(b64_decoded));
  286. /* Copy the last part, the random value. */
  287. memcpy(commit->random_number, b64_decoded + 8,
  288. sizeof(commit->random_number));
  289. /* Also copy the whole message to use during verification */
  290. strlcpy(commit->encoded_reveal, encoded, sizeof(commit->encoded_reveal));
  291. return 0;
  292. error:
  293. return -1;
  294. }
  295. /* Encode a reveal element using a given commit object to dst which is a
  296. * buffer large enough to put the base64-encoded reveal construction. The
  297. * format is as follow:
  298. * REVEAL = base64-encode( TIMESTAMP || H(RN) )
  299. * Return base64 encoded length on success else a negative value.
  300. */
  301. STATIC int
  302. reveal_encode(const sr_commit_t *commit, char *dst, size_t len)
  303. {
  304. int ret;
  305. size_t offset = 0;
  306. char buf[SR_REVEAL_LEN] = {0};
  307. tor_assert(commit);
  308. tor_assert(dst);
  309. set_uint64(buf, tor_htonll(commit->reveal_ts));
  310. offset += sizeof(uint64_t);
  311. memcpy(buf + offset, commit->random_number,
  312. sizeof(commit->random_number));
  313. /* Let's clean the buffer and then b64 encode it. */
  314. memset(dst, 0, len);
  315. ret = base64_encode(dst, len, buf, sizeof(buf), 0);
  316. /* Wipe this buffer because it contains our random value. */
  317. memwipe(buf, 0, sizeof(buf));
  318. return ret;
  319. }
  320. /* Encode the given commit object to dst which is a buffer large enough to
  321. * put the base64-encoded commit. The format is as follow:
  322. * COMMIT = base64-encode( TIMESTAMP || H(H(RN)) )
  323. * Return base64 encoded length on success else a negative value.
  324. */
  325. STATIC int
  326. commit_encode(const sr_commit_t *commit, char *dst, size_t len)
  327. {
  328. size_t offset = 0;
  329. char buf[SR_COMMIT_LEN] = {0};
  330. tor_assert(commit);
  331. tor_assert(dst);
  332. /* First is the timestamp (8 bytes). */
  333. set_uint64(buf, tor_htonll(commit->commit_ts));
  334. offset += sizeof(uint64_t);
  335. /* and then the hashed reveal. */
  336. memcpy(buf + offset, commit->hashed_reveal,
  337. sizeof(commit->hashed_reveal));
  338. /* Clean the buffer and then b64 encode it. */
  339. memset(dst, 0, len);
  340. return base64_encode(dst, len, buf, sizeof(buf), 0);
  341. }
  342. /* Cleanup both our global state and disk state. */
  343. static void
  344. sr_cleanup(void)
  345. {
  346. sr_state_free_all();
  347. }
  348. /* Using <b>commit</b>, return a newly allocated string containing the commit
  349. * information that should be used during SRV calculation. It's the caller
  350. * responsibility to free the memory. Return NULL if this is not a commit to be
  351. * used for SRV calculation. */
  352. static char *
  353. get_srv_element_from_commit(const sr_commit_t *commit)
  354. {
  355. char *element;
  356. tor_assert(commit);
  357. if (!commit_has_reveal_value(commit)) {
  358. return NULL;
  359. }
  360. tor_asprintf(&element, "%s%s", sr_commit_get_rsa_fpr(commit),
  361. commit->encoded_reveal);
  362. return element;
  363. }
  364. /* Return a srv object that is built with the construction:
  365. * SRV = SHA3-256("shared-random" | INT_8(reveal_num) |
  366. * INT_4(version) | HASHED_REVEALS | previous_SRV)
  367. * This function cannot fail. */
  368. static sr_srv_t *
  369. generate_srv(const char *hashed_reveals, uint64_t reveal_num,
  370. const sr_srv_t *previous_srv)
  371. {
  372. char msg[DIGEST256_LEN + SR_SRV_MSG_LEN] = {0};
  373. size_t offset = 0;
  374. sr_srv_t *srv;
  375. tor_assert(hashed_reveals);
  376. /* Add the invariant token. */
  377. memcpy(msg, SR_SRV_TOKEN, SR_SRV_TOKEN_LEN);
  378. offset += SR_SRV_TOKEN_LEN;
  379. set_uint64(msg + offset, tor_htonll(reveal_num));
  380. offset += sizeof(uint64_t);
  381. set_uint32(msg + offset, htonl(SR_PROTO_VERSION));
  382. offset += sizeof(uint32_t);
  383. memcpy(msg + offset, hashed_reveals, DIGEST256_LEN);
  384. offset += DIGEST256_LEN;
  385. if (previous_srv != NULL) {
  386. memcpy(msg + offset, previous_srv->value, sizeof(previous_srv->value));
  387. }
  388. /* Ok we have our message and key for the HMAC computation, allocate our
  389. * srv object and do the last step. */
  390. srv = tor_malloc_zero(sizeof(*srv));
  391. crypto_digest256((char *) srv->value, msg, sizeof(msg), SR_DIGEST_ALG);
  392. srv->num_reveals = reveal_num;
  393. {
  394. /* Debugging. */
  395. char srv_hash_encoded[SR_SRV_VALUE_BASE64_LEN + 1];
  396. sr_srv_encode(srv_hash_encoded, sizeof(srv_hash_encoded), srv);
  397. log_info(LD_DIR, "SR: Generated SRV: %s", srv_hash_encoded);
  398. }
  399. return srv;
  400. }
  401. /* Compare reveal values and return the result. This should exclusively be
  402. * used by smartlist_sort(). */
  403. static int
  404. compare_reveal_(const void **_a, const void **_b)
  405. {
  406. const sr_commit_t *a = *_a, *b = *_b;
  407. return fast_memcmp(a->hashed_reveal, b->hashed_reveal,
  408. sizeof(a->hashed_reveal));
  409. }
  410. /* Given <b>commit</b> give the line that we should place in our votes.
  411. * It's the responsibility of the caller to free the string. */
  412. static char *
  413. get_vote_line_from_commit(const sr_commit_t *commit, sr_phase_t phase)
  414. {
  415. char *vote_line = NULL;
  416. switch (phase) {
  417. case SR_PHASE_COMMIT:
  418. tor_asprintf(&vote_line, "%s %u %s %s %s\n",
  419. commit_ns_str,
  420. SR_PROTO_VERSION,
  421. crypto_digest_algorithm_get_name(commit->alg),
  422. sr_commit_get_rsa_fpr(commit),
  423. commit->encoded_commit);
  424. break;
  425. case SR_PHASE_REVEAL:
  426. {
  427. /* Send a reveal value for this commit if we have one. */
  428. const char *reveal_str = commit->encoded_reveal;
  429. if (tor_mem_is_zero(commit->encoded_reveal,
  430. sizeof(commit->encoded_reveal))) {
  431. reveal_str = "";
  432. }
  433. tor_asprintf(&vote_line, "%s %u %s %s %s %s\n",
  434. commit_ns_str,
  435. SR_PROTO_VERSION,
  436. crypto_digest_algorithm_get_name(commit->alg),
  437. sr_commit_get_rsa_fpr(commit),
  438. commit->encoded_commit, reveal_str);
  439. break;
  440. }
  441. default:
  442. tor_assert(0);
  443. }
  444. log_debug(LD_DIR, "SR: Commit vote line: %s", vote_line);
  445. return vote_line;
  446. }
  447. /* Return a heap allocated string that contains the given <b>srv</b> string
  448. * representation formatted for a networkstatus document using the
  449. * <b>key</b> as the start of the line. This doesn't return NULL. */
  450. static char *
  451. srv_to_ns_string(const sr_srv_t *srv, const char *key)
  452. {
  453. char *srv_str;
  454. char srv_hash_encoded[SR_SRV_VALUE_BASE64_LEN + 1];
  455. tor_assert(srv);
  456. tor_assert(key);
  457. sr_srv_encode(srv_hash_encoded, sizeof(srv_hash_encoded), srv);
  458. tor_asprintf(&srv_str, "%s %" PRIu64 " %s\n", key,
  459. srv->num_reveals, srv_hash_encoded);
  460. log_debug(LD_DIR, "SR: Consensus SRV line: %s", srv_str);
  461. return srv_str;
  462. }
  463. /* Given the previous SRV and the current SRV, return a heap allocated
  464. * string with their data that could be put in a vote or a consensus. Caller
  465. * must free the returned string. Return NULL if no SRVs were provided. */
  466. static char *
  467. get_ns_str_from_sr_values(const sr_srv_t *prev_srv, const sr_srv_t *cur_srv)
  468. {
  469. smartlist_t *chunks = NULL;
  470. char *srv_str;
  471. if (!prev_srv && !cur_srv) {
  472. return NULL;
  473. }
  474. chunks = smartlist_new();
  475. if (prev_srv) {
  476. char *srv_line = srv_to_ns_string(prev_srv, previous_srv_str);
  477. smartlist_add(chunks, srv_line);
  478. }
  479. if (cur_srv) {
  480. char *srv_line = srv_to_ns_string(cur_srv, current_srv_str);
  481. smartlist_add(chunks, srv_line);
  482. }
  483. /* Join the line(s) here in one string to return. */
  484. srv_str = smartlist_join_strings(chunks, "", 0, NULL);
  485. SMARTLIST_FOREACH(chunks, char *, s, tor_free(s));
  486. smartlist_free(chunks);
  487. return srv_str;
  488. }
  489. /* Return 1 iff the two commits have the same commitment values. This
  490. * function does not care about reveal values. */
  491. STATIC int
  492. commitments_are_the_same(const sr_commit_t *commit_one,
  493. const sr_commit_t *commit_two)
  494. {
  495. tor_assert(commit_one);
  496. tor_assert(commit_two);
  497. if (strcmp(commit_one->encoded_commit, commit_two->encoded_commit)) {
  498. return 0;
  499. }
  500. return 1;
  501. }
  502. /* We just received a commit from the vote of authority with
  503. * <b>identity_digest</b>. Return 1 if this commit is authorititative that
  504. * is, it belongs to the authority that voted it. Else return 0 if not. */
  505. STATIC int
  506. commit_is_authoritative(const sr_commit_t *commit,
  507. const char *voter_key)
  508. {
  509. tor_assert(commit);
  510. tor_assert(voter_key);
  511. return fast_memeq(commit->rsa_identity, voter_key,
  512. sizeof(commit->rsa_identity));
  513. }
  514. /* Decide if the newly received <b>commit</b> should be kept depending on
  515. * the current phase and state of the protocol. The <b>voter_key</b> is the
  516. * RSA identity key fingerprint of the authority's vote from which the
  517. * commit comes from. The <b>phase</b> is the phase we should be validating
  518. * the commit for. Return 1 if the commit should be added to our state or 0
  519. * if not. */
  520. STATIC int
  521. should_keep_commit(const sr_commit_t *commit, const char *voter_key,
  522. sr_phase_t phase)
  523. {
  524. const sr_commit_t *saved_commit;
  525. tor_assert(commit);
  526. tor_assert(voter_key);
  527. log_debug(LD_DIR, "SR: Inspecting commit from %s (voter: %s)?",
  528. sr_commit_get_rsa_fpr(commit),
  529. hex_str(voter_key, DIGEST_LEN));
  530. /* For a commit to be considered, it needs to be authoritative (it should
  531. * be the voter's own commit). */
  532. if (!commit_is_authoritative(commit, voter_key)) {
  533. log_debug(LD_DIR, "SR: Ignoring non-authoritative commit.");
  534. goto ignore;
  535. }
  536. /* Let's make sure, for extra safety, that this fingerprint is known to
  537. * us. Even though this comes from a vote, doesn't hurt to be
  538. * extracareful. */
  539. if (trusteddirserver_get_by_v3_auth_digest(commit->rsa_identity) == NULL) {
  540. log_warn(LD_DIR, "SR: Fingerprint %s is not from a recognized "
  541. "authority. Discarding commit.",
  542. escaped(commit->rsa_identity));
  543. goto ignore;
  544. }
  545. /* Check if the authority that voted for <b>commit</b> has already posted
  546. * a commit before. */
  547. saved_commit = sr_state_get_commit(commit->rsa_identity);
  548. switch (phase) {
  549. case SR_PHASE_COMMIT:
  550. /* Already having a commit for an authority so ignore this one. */
  551. if (saved_commit) {
  552. /* Receiving known commits should happen naturally since commit phase
  553. lasts multiple rounds. However if the commitment value changes
  554. during commit phase, it might be a bug so log more loudly. */
  555. if (!commitments_are_the_same(commit, saved_commit)) {
  556. log_info(LD_DIR,
  557. "SR: Received altered commit from %s in commit phase.",
  558. sr_commit_get_rsa_fpr(commit));
  559. } else {
  560. log_debug(LD_DIR, "SR: Ignoring known commit during commit phase.");
  561. }
  562. goto ignore;
  563. }
  564. /* A commit with a reveal value during commitment phase is very wrong. */
  565. if (commit_has_reveal_value(commit)) {
  566. log_warn(LD_DIR, "SR: Commit from authority %s has a reveal value "
  567. "during COMMIT phase. (voter: %s)",
  568. sr_commit_get_rsa_fpr(commit),
  569. hex_str(voter_key, DIGEST_LEN));
  570. goto ignore;
  571. }
  572. break;
  573. case SR_PHASE_REVEAL:
  574. /* We are now in reveal phase. We keep a commit if and only if:
  575. *
  576. * - We have already seen a commit by this auth, AND
  577. * - the saved commit has the same commitment value as this one, AND
  578. * - the saved commit has no reveal information, AND
  579. * - this commit does have reveal information, AND
  580. * - the reveal & commit information are matching.
  581. *
  582. * If all the above are true, then we are interested in this new commit
  583. * for its reveal information. */
  584. if (!saved_commit) {
  585. log_debug(LD_DIR, "SR: Ignoring commit first seen in reveal phase.");
  586. goto ignore;
  587. }
  588. if (!commitments_are_the_same(commit, saved_commit)) {
  589. log_warn(LD_DIR, "SR: Commit from authority %s is different from "
  590. "previous commit in our state (voter: %s)",
  591. sr_commit_get_rsa_fpr(commit),
  592. hex_str(voter_key, DIGEST_LEN));
  593. goto ignore;
  594. }
  595. if (commit_has_reveal_value(saved_commit)) {
  596. log_debug(LD_DIR, "SR: Ignoring commit with known reveal info.");
  597. goto ignore;
  598. }
  599. if (!commit_has_reveal_value(commit)) {
  600. log_debug(LD_DIR, "SR: Ignoring commit without reveal value.");
  601. goto ignore;
  602. }
  603. if (verify_commit_and_reveal(commit) < 0) {
  604. log_warn(LD_BUG, "SR: Commit from authority %s has an invalid "
  605. "reveal value. (voter: %s)",
  606. sr_commit_get_rsa_fpr(commit),
  607. hex_str(voter_key, DIGEST_LEN));
  608. goto ignore;
  609. }
  610. break;
  611. default:
  612. tor_assert(0);
  613. }
  614. return 1;
  615. ignore:
  616. return 0;
  617. }
  618. /* We are in reveal phase and we found a valid and verified <b>commit</b> in
  619. * a vote that contains reveal values that we could use. Update the commit
  620. * we have in our state. Never call this with an unverified commit. */
  621. STATIC void
  622. save_commit_during_reveal_phase(const sr_commit_t *commit)
  623. {
  624. sr_commit_t *saved_commit;
  625. tor_assert(commit);
  626. /* Get the commit from our state. */
  627. saved_commit = sr_state_get_commit(commit->rsa_identity);
  628. tor_assert(saved_commit);
  629. /* Safety net. They can not be different commitments at this point. */
  630. int same_commits = commitments_are_the_same(commit, saved_commit);
  631. tor_assert(same_commits);
  632. /* Copy reveal information to our saved commit. */
  633. sr_state_copy_reveal_info(saved_commit, commit);
  634. }
  635. /* Save <b>commit</b> to our persistent state. Depending on the current
  636. * phase, different actions are taken. Steals reference of <b>commit</b>.
  637. * The commit object MUST be valid and verified before adding it to the
  638. * state. */
  639. STATIC void
  640. save_commit_to_state(sr_commit_t *commit)
  641. {
  642. sr_phase_t phase = sr_state_get_phase();
  643. ASSERT_COMMIT_VALID(commit);
  644. switch (phase) {
  645. case SR_PHASE_COMMIT:
  646. /* During commit phase, just save any new authoritative commit */
  647. sr_state_add_commit(commit);
  648. break;
  649. case SR_PHASE_REVEAL:
  650. save_commit_during_reveal_phase(commit);
  651. sr_commit_free(commit);
  652. break;
  653. default:
  654. tor_assert(0);
  655. }
  656. }
  657. /* Return 1 if we should we keep an SRV voted by <b>n_agreements</b> auths.
  658. * Return 0 if we should ignore it. */
  659. static int
  660. should_keep_srv(int n_agreements)
  661. {
  662. /* Check if the most popular SRV has reached majority. */
  663. int n_voters = get_n_authorities(V3_DIRINFO);
  664. int votes_required_for_majority = (n_voters / 2) + 1;
  665. /* We need at the very least majority to keep a value. */
  666. if (n_agreements < votes_required_for_majority) {
  667. log_notice(LD_DIR, "SR: SRV didn't reach majority [%d/%d]!",
  668. n_agreements, votes_required_for_majority);
  669. return 0;
  670. }
  671. /* When we just computed a new SRV, we need to have super majority in order
  672. * to keep it. */
  673. if (sr_state_srv_is_fresh()) {
  674. /* Check if we have super majority for this new SRV value. */
  675. if (n_agreements < num_srv_agreements_from_vote) {
  676. log_notice(LD_DIR, "SR: New SRV didn't reach agreement [%d/%d]!",
  677. n_agreements, num_srv_agreements_from_vote);
  678. return 0;
  679. }
  680. }
  681. return 1;
  682. }
  683. /* Helper: compare two DIGEST256_LEN digests. */
  684. static int
  685. compare_srvs_(const void **_a, const void **_b)
  686. {
  687. const sr_srv_t *a = *_a, *b = *_b;
  688. return tor_memcmp(a->value, b->value, sizeof(a->value));
  689. }
  690. /* Return the most frequent member of the sorted list of DIGEST256_LEN
  691. * digests in <b>sl</b> with the count of that most frequent element. */
  692. static sr_srv_t *
  693. smartlist_get_most_frequent_srv(const smartlist_t *sl, int *count_out)
  694. {
  695. return smartlist_get_most_frequent_(sl, compare_srvs_, count_out);
  696. }
  697. /** Compare two SRVs. Used in smartlist sorting. */
  698. static int
  699. compare_srv_(const void **_a, const void **_b)
  700. {
  701. const sr_srv_t *a = *_a, *b = *_b;
  702. return fast_memcmp(a->value, b->value,
  703. sizeof(a->value));
  704. }
  705. /* Using a list of <b>votes</b>, return the SRV object from them that has
  706. * been voted by the majority of dirauths. If <b>current</b> is set, we look
  707. * for the current SRV value else the previous one. The returned pointer is
  708. * an object located inside a vote. NULL is returned if no appropriate value
  709. * could be found. */
  710. STATIC sr_srv_t *
  711. get_majority_srv_from_votes(const smartlist_t *votes, int current)
  712. {
  713. int count = 0;
  714. sr_srv_t *most_frequent_srv = NULL;
  715. sr_srv_t *the_srv = NULL;
  716. smartlist_t *srv_list;
  717. tor_assert(votes);
  718. srv_list = smartlist_new();
  719. /* Walk over votes and register any SRVs found. */
  720. SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
  721. sr_srv_t *srv_tmp = NULL;
  722. if (!v->sr_info.participate) {
  723. /* Ignore vote that do not participate. */
  724. continue;
  725. }
  726. /* Do we want previous or current SRV? */
  727. srv_tmp = current ? v->sr_info.current_srv : v->sr_info.previous_srv;
  728. if (!srv_tmp) {
  729. continue;
  730. }
  731. smartlist_add(srv_list, srv_tmp);
  732. } SMARTLIST_FOREACH_END(v);
  733. smartlist_sort(srv_list, compare_srv_);
  734. most_frequent_srv = smartlist_get_most_frequent_srv(srv_list, &count);
  735. if (!most_frequent_srv) {
  736. goto end;
  737. }
  738. /* Was this SRV voted by enough auths for us to keep it? */
  739. if (!should_keep_srv(count)) {
  740. goto end;
  741. }
  742. /* We found an SRV that we can use! Habemus SRV! */
  743. the_srv = most_frequent_srv;
  744. {
  745. /* Debugging */
  746. char encoded[SR_SRV_VALUE_BASE64_LEN + 1];
  747. sr_srv_encode(encoded, sizeof(encoded), the_srv);
  748. log_debug(LD_DIR, "SR: Chosen SRV by majority: %s (%d votes)", encoded,
  749. count);
  750. }
  751. end:
  752. /* We do not free any sr_srv_t values, we don't have the ownership. */
  753. smartlist_free(srv_list);
  754. return the_srv;
  755. }
  756. /* Free a commit object. */
  757. void
  758. sr_commit_free_(sr_commit_t *commit)
  759. {
  760. if (commit == NULL) {
  761. return;
  762. }
  763. /* Make sure we do not leave OUR random number in memory. */
  764. memwipe(commit->random_number, 0, sizeof(commit->random_number));
  765. tor_free(commit);
  766. }
  767. /* Generate the commitment/reveal value for the protocol run starting at
  768. * <b>timestamp</b>. <b>my_rsa_cert</b> is our authority RSA certificate. */
  769. sr_commit_t *
  770. sr_generate_our_commit(time_t timestamp, const authority_cert_t *my_rsa_cert)
  771. {
  772. sr_commit_t *commit = NULL;
  773. char digest[DIGEST_LEN];
  774. tor_assert(my_rsa_cert);
  775. /* Get our RSA identity fingerprint */
  776. if (crypto_pk_get_digest(my_rsa_cert->identity_key, digest) < 0) {
  777. goto error;
  778. }
  779. /* New commit with our identity key. */
  780. commit = commit_new(digest);
  781. /* Generate the reveal random value */
  782. crypto_strongest_rand(commit->random_number,
  783. sizeof(commit->random_number));
  784. commit->commit_ts = commit->reveal_ts = timestamp;
  785. /* Now get the base64 blob that corresponds to our reveal */
  786. if (reveal_encode(commit, commit->encoded_reveal,
  787. sizeof(commit->encoded_reveal)) < 0) {
  788. log_err(LD_DIR, "SR: Unable to encode our reveal value!");
  789. goto error;
  790. }
  791. /* Now let's create the commitment */
  792. tor_assert(commit->alg == SR_DIGEST_ALG);
  793. /* The invariant length is used here since the encoded reveal variable
  794. * has an extra byte added for the NULL terminated byte. */
  795. if (crypto_digest256(commit->hashed_reveal, commit->encoded_reveal,
  796. SR_REVEAL_BASE64_LEN, commit->alg) < 0) {
  797. goto error;
  798. }
  799. /* Now get the base64 blob that corresponds to our commit. */
  800. if (commit_encode(commit, commit->encoded_commit,
  801. sizeof(commit->encoded_commit)) < 0) {
  802. log_err(LD_DIR, "SR: Unable to encode our commit value!");
  803. goto error;
  804. }
  805. log_debug(LD_DIR, "SR: Generated our commitment:");
  806. commit_log(commit);
  807. /* Our commit better be valid :). */
  808. commit->valid = 1;
  809. return commit;
  810. error:
  811. sr_commit_free(commit);
  812. return NULL;
  813. }
  814. /* Compute the shared random value based on the active commits in our state. */
  815. void
  816. sr_compute_srv(void)
  817. {
  818. uint64_t reveal_num = 0;
  819. char *reveals = NULL;
  820. smartlist_t *chunks, *commits;
  821. digestmap_t *state_commits;
  822. /* Computing a shared random value in the commit phase is very wrong. This
  823. * should only happen at the very end of the reveal phase when a new
  824. * protocol run is about to start. */
  825. if (BUG(sr_state_get_phase() != SR_PHASE_REVEAL))
  826. return;
  827. state_commits = sr_state_get_commits();
  828. commits = smartlist_new();
  829. chunks = smartlist_new();
  830. /* We must make a list of commit ordered by authority fingerprint in
  831. * ascending order as specified by proposal 250. */
  832. DIGESTMAP_FOREACH(state_commits, key, sr_commit_t *, c) {
  833. /* Extra safety net, make sure we have valid commit before using it. */
  834. ASSERT_COMMIT_VALID(c);
  835. /* Let's not use a commit from an authority that we don't know. It's
  836. * possible that an authority could be removed during a protocol run so
  837. * that commit value should never be used in the SRV computation. */
  838. if (trusteddirserver_get_by_v3_auth_digest(c->rsa_identity) == NULL) {
  839. log_warn(LD_DIR, "SR: Fingerprint %s is not from a recognized "
  840. "authority. Discarding commit for the SRV computation.",
  841. sr_commit_get_rsa_fpr(c));
  842. continue;
  843. }
  844. /* We consider this commit valid. */
  845. smartlist_add(commits, c);
  846. } DIGESTMAP_FOREACH_END;
  847. smartlist_sort(commits, compare_reveal_);
  848. /* Now for each commit for that sorted list in ascending order, we'll
  849. * build the element for each authority that needs to go into the srv
  850. * computation. */
  851. SMARTLIST_FOREACH_BEGIN(commits, const sr_commit_t *, c) {
  852. char *element = get_srv_element_from_commit(c);
  853. if (element) {
  854. smartlist_add(chunks, element);
  855. reveal_num++;
  856. }
  857. } SMARTLIST_FOREACH_END(c);
  858. smartlist_free(commits);
  859. {
  860. /* Join all reveal values into one giant string that we'll hash so we
  861. * can generated our shared random value. */
  862. sr_srv_t *current_srv;
  863. char hashed_reveals[DIGEST256_LEN];
  864. reveals = smartlist_join_strings(chunks, "", 0, NULL);
  865. SMARTLIST_FOREACH(chunks, char *, s, tor_free(s));
  866. smartlist_free(chunks);
  867. if (crypto_digest256(hashed_reveals, reveals, strlen(reveals),
  868. SR_DIGEST_ALG) < 0) {
  869. goto end;
  870. }
  871. current_srv = generate_srv(hashed_reveals, reveal_num,
  872. sr_state_get_previous_srv());
  873. sr_state_set_current_srv(current_srv);
  874. /* We have a fresh SRV, flag our state. */
  875. sr_state_set_fresh_srv();
  876. }
  877. end:
  878. tor_free(reveals);
  879. }
  880. /* Parse a commit from a vote or from our disk state and return a newly
  881. * allocated commit object. NULL is returned on error.
  882. *
  883. * The commit's data is in <b>args</b> and the order matters very much:
  884. * version, algname, RSA fingerprint, commit value[, reveal value]
  885. */
  886. sr_commit_t *
  887. sr_parse_commit(const smartlist_t *args)
  888. {
  889. uint32_t version;
  890. char *value, digest[DIGEST_LEN];
  891. digest_algorithm_t alg;
  892. const char *rsa_identity_fpr;
  893. sr_commit_t *commit = NULL;
  894. if (smartlist_len(args) < 4) {
  895. goto error;
  896. }
  897. /* First is the version number of the SR protocol which indicates at which
  898. * version that commit was created. */
  899. value = smartlist_get(args, 0);
  900. version = (uint32_t) tor_parse_ulong(value, 10, 1, UINT32_MAX, NULL, NULL);
  901. if (version > SR_PROTO_VERSION) {
  902. log_info(LD_DIR, "SR: Commit version %" PRIu32 " (%s) is not supported.",
  903. version, escaped(value));
  904. goto error;
  905. }
  906. /* Second is the algorithm. */
  907. value = smartlist_get(args, 1);
  908. alg = crypto_digest_algorithm_parse_name(value);
  909. if (alg != SR_DIGEST_ALG) {
  910. log_warn(LD_BUG, "SR: Commit algorithm %s is not recognized.",
  911. escaped(value));
  912. goto error;
  913. }
  914. /* Third argument is the RSA fingerprint of the auth and turn it into a
  915. * digest value. */
  916. rsa_identity_fpr = smartlist_get(args, 2);
  917. if (base16_decode(digest, DIGEST_LEN, rsa_identity_fpr,
  918. HEX_DIGEST_LEN) < 0) {
  919. log_warn(LD_DIR, "SR: RSA fingerprint %s not decodable",
  920. escaped(rsa_identity_fpr));
  921. goto error;
  922. }
  923. /* Allocate commit since we have a valid identity now. */
  924. commit = commit_new(digest);
  925. /* Fourth argument is the commitment value base64-encoded. */
  926. value = smartlist_get(args, 3);
  927. if (commit_decode(value, commit) < 0) {
  928. goto error;
  929. }
  930. /* (Optional) Fifth argument is the revealed value. */
  931. if (smartlist_len(args) > 4) {
  932. value = smartlist_get(args, 4);
  933. if (reveal_decode(value, commit) < 0) {
  934. goto error;
  935. }
  936. }
  937. return commit;
  938. error:
  939. sr_commit_free(commit);
  940. return NULL;
  941. }
  942. /* Called when we are done parsing a vote by <b>voter_key</b> that might
  943. * contain some useful <b>commits</b>. Find if any of them should be kept
  944. * and update our state accordingly. Once done, the list of commitments will
  945. * be empty. */
  946. void
  947. sr_handle_received_commits(smartlist_t *commits, crypto_pk_t *voter_key)
  948. {
  949. char rsa_identity[DIGEST_LEN];
  950. tor_assert(voter_key);
  951. /* It's possible that the vote has _NO_ commits. */
  952. if (commits == NULL) {
  953. return;
  954. }
  955. /* Get the RSA identity fingerprint of this voter */
  956. if (crypto_pk_get_digest(voter_key, rsa_identity) < 0) {
  957. return;
  958. }
  959. SMARTLIST_FOREACH_BEGIN(commits, sr_commit_t *, commit) {
  960. /* We won't need the commit in this list anymore, kept or not. */
  961. SMARTLIST_DEL_CURRENT(commits, commit);
  962. /* Check if this commit is valid and should be stored in our state. */
  963. if (!should_keep_commit(commit, rsa_identity,
  964. sr_state_get_phase())) {
  965. sr_commit_free(commit);
  966. continue;
  967. }
  968. /* Ok, we have a valid commit now that we are about to put in our state.
  969. * so flag it valid from now on. */
  970. commit->valid = 1;
  971. /* Everything lines up: save this commit to state then! */
  972. save_commit_to_state(commit);
  973. } SMARTLIST_FOREACH_END(commit);
  974. }
  975. /* Return a heap-allocated string containing commits that should be put in
  976. * the votes. It's the responsibility of the caller to free the string.
  977. * This always return a valid string, either empty or with line(s). */
  978. char *
  979. sr_get_string_for_vote(void)
  980. {
  981. char *vote_str = NULL;
  982. digestmap_t *state_commits;
  983. smartlist_t *chunks = smartlist_new();
  984. const or_options_t *options = get_options();
  985. /* Are we participating in the protocol? */
  986. if (!options->AuthDirSharedRandomness) {
  987. goto end;
  988. }
  989. log_debug(LD_DIR, "SR: Preparing our vote info:");
  990. /* First line, put in the vote the participation flag. */
  991. {
  992. char *sr_flag_line;
  993. tor_asprintf(&sr_flag_line, "%s\n", sr_flag_ns_str);
  994. smartlist_add(chunks, sr_flag_line);
  995. }
  996. /* In our vote we include every commitment in our permanent state. */
  997. state_commits = sr_state_get_commits();
  998. smartlist_t *state_commit_vote_lines = smartlist_new();
  999. DIGESTMAP_FOREACH(state_commits, key, const sr_commit_t *, commit) {
  1000. char *line = get_vote_line_from_commit(commit, sr_state_get_phase());
  1001. smartlist_add(state_commit_vote_lines, line);
  1002. } DIGESTMAP_FOREACH_END;
  1003. /* Sort the commit strings by version (string, not numeric), algorithm,
  1004. * and fingerprint. This makes sure the commit lines in votes are in a
  1005. * recognisable, stable order. */
  1006. smartlist_sort_strings(state_commit_vote_lines);
  1007. /* Now add the sorted list of commits to the vote */
  1008. smartlist_add_all(chunks, state_commit_vote_lines);
  1009. smartlist_free(state_commit_vote_lines);
  1010. /* Add the SRV value(s) if any. */
  1011. {
  1012. char *srv_lines = get_ns_str_from_sr_values(sr_state_get_previous_srv(),
  1013. sr_state_get_current_srv());
  1014. if (srv_lines) {
  1015. smartlist_add(chunks, srv_lines);
  1016. }
  1017. }
  1018. end:
  1019. vote_str = smartlist_join_strings(chunks, "", 0, NULL);
  1020. SMARTLIST_FOREACH(chunks, char *, s, tor_free(s));
  1021. smartlist_free(chunks);
  1022. return vote_str;
  1023. }
  1024. /* Return a heap-allocated string that should be put in the consensus and
  1025. * contains the shared randomness values. It's the responsibility of the
  1026. * caller to free the string. NULL is returned if no SRV(s) available.
  1027. *
  1028. * This is called when a consensus (any flavor) is bring created thus it
  1029. * should NEVER change the state nor the state should be changed in between
  1030. * consensus creation.
  1031. *
  1032. * <b>num_srv_agreements</b> is taken from the votes thus the voted value
  1033. * that should be used.
  1034. * */
  1035. char *
  1036. sr_get_string_for_consensus(const smartlist_t *votes,
  1037. int32_t num_srv_agreements)
  1038. {
  1039. char *srv_str;
  1040. const or_options_t *options = get_options();
  1041. tor_assert(votes);
  1042. /* Not participating, avoid returning anything. */
  1043. if (!options->AuthDirSharedRandomness) {
  1044. log_info(LD_DIR, "SR: Support disabled (AuthDirSharedRandomness %d)",
  1045. options->AuthDirSharedRandomness);
  1046. goto end;
  1047. }
  1048. /* Set the global value of AuthDirNumSRVAgreements found in the votes. */
  1049. num_srv_agreements_from_vote = num_srv_agreements;
  1050. /* Check the votes and figure out if SRVs should be included in the final
  1051. * consensus. */
  1052. sr_srv_t *prev_srv = get_majority_srv_from_votes(votes, 0);
  1053. sr_srv_t *cur_srv = get_majority_srv_from_votes(votes, 1);
  1054. srv_str = get_ns_str_from_sr_values(prev_srv, cur_srv);
  1055. if (!srv_str) {
  1056. goto end;
  1057. }
  1058. return srv_str;
  1059. end:
  1060. return NULL;
  1061. }
  1062. /* We just computed a new <b>consensus</b>. Update our state with the SRVs
  1063. * from the consensus (might be NULL as well). Register the SRVs in our SR
  1064. * state and prepare for the upcoming protocol round. */
  1065. void
  1066. sr_act_post_consensus(const networkstatus_t *consensus)
  1067. {
  1068. const or_options_t *options = get_options();
  1069. /* Don't act if our state hasn't been initialized. We can be called during
  1070. * boot time when loading consensus from disk which is prior to the
  1071. * initialization of the SR subsystem. We also should not be doing
  1072. * anything if we are _not_ a directory authority and if we are a bridge
  1073. * authority. */
  1074. if (!sr_state_is_initialized() || !authdir_mode_v3(options) ||
  1075. authdir_mode_bridge(options)) {
  1076. return;
  1077. }
  1078. /* Set the majority voted SRVs in our state even if both are NULL. It
  1079. * doesn't matter this is what the majority has decided. Obviously, we can
  1080. * only do that if we have a consensus. */
  1081. if (consensus) {
  1082. /* Start by freeing the current SRVs since the SRVs we believed during
  1083. * voting do not really matter. Now that all the votes are in, we use the
  1084. * majority's opinion on which are the active SRVs. */
  1085. sr_state_clean_srvs();
  1086. /* Reset the fresh flag of the SRV so we know that from now on we don't
  1087. * have a new SRV to vote for. We just used the one from the consensus
  1088. * decided by the majority. */
  1089. sr_state_unset_fresh_srv();
  1090. /* Set the SR values from the given consensus. */
  1091. sr_state_set_previous_srv(srv_dup(consensus->sr_info.previous_srv));
  1092. sr_state_set_current_srv(srv_dup(consensus->sr_info.current_srv));
  1093. }
  1094. /* Prepare our state so that it's ready for the next voting period. */
  1095. sr_state_update(voting_schedule_get_next_valid_after_time());
  1096. }
  1097. /* Initialize shared random subsystem. This MUST be called early in the boot
  1098. * process of tor. Return 0 on success else -1 on error. */
  1099. int
  1100. sr_init(int save_to_disk)
  1101. {
  1102. return sr_state_init(save_to_disk, 1);
  1103. }
  1104. /* Save our state to disk and cleanup everything. */
  1105. void
  1106. sr_save_and_cleanup(void)
  1107. {
  1108. sr_state_save();
  1109. sr_cleanup();
  1110. }
  1111. #ifdef TOR_UNIT_TESTS
  1112. /* Set the global value of number of SRV agreements so the test can play
  1113. * along by calling specific functions that don't parse the votes prior for
  1114. * the AuthDirNumSRVAgreements value. */
  1115. void
  1116. set_num_srv_agreements(int32_t value)
  1117. {
  1118. num_srv_agreements_from_vote = value;
  1119. }
  1120. #endif /* defined(TOR_UNIT_TESTS) */