shared_random.c 42 KB

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