shared_random.c 44 KB

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