shared_random.c 45 KB

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