shared_random.c 43 KB

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