shared_random.c 44 KB

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