shared_random.c 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405
  1. /* Copyright (c) 2016-2017, The Tor Project, Inc. */
  2. /* See LICENSE for licensing information */
  3. /**
  4. * \file shared_random.c
  5. *
  6. * \brief Functions and data structure needed to accomplish the shared
  7. * random protocol as defined in proposal #250.
  8. *
  9. * \details
  10. *
  11. * This file implements the dirauth-only commit-and-reveal protocol specified
  12. * by proposal #250. The protocol has two phases (sr_phase_t): the commitment
  13. * phase and the reveal phase (see get_sr_protocol_phase()).
  14. *
  15. * During the protocol, directory authorities keep state in memory (using
  16. * sr_state_t) and in disk (using sr_disk_state_t). The synchronization between
  17. * these two data structures happens in disk_state_update() and
  18. * disk_state_parse().
  19. *
  20. * Here is a rough protocol outline:
  21. *
  22. * 1) In the beginning of the commitment phase, dirauths generate a
  23. * commitment/reveal value for the current protocol run (see
  24. * new_protocol_run() and sr_generate_our_commit()).
  25. *
  26. * 2) During voting, dirauths publish their commits in their votes
  27. * depending on the current phase. Dirauths also include the two
  28. * latest shared random values (SRV) in their votes.
  29. * (see sr_get_string_for_vote())
  30. *
  31. * 3) Upon receiving a commit from a vote, authorities parse it, verify
  32. * it, and attempt to save any new commitment or reveal information in
  33. * their state file (see extract_shared_random_commits() and
  34. * sr_handle_received_commits()). They also parse SRVs from votes to
  35. * decide which SRV should be included in the final consensus (see
  36. * extract_shared_random_srvs()).
  37. *
  38. * 3) After voting is done, we count the SRVs we extracted from the votes,
  39. * to find the one voted by the majority of dirauths which should be
  40. * included in the final consensus (see get_majority_srv_from_votes()).
  41. * If an appropriate SRV is found, it is embedded in the consensus (see
  42. * sr_get_string_for_consensus()).
  43. *
  44. * 4) At the end of the reveal phase, dirauths compute a fresh SRV for the
  45. * day using the active commits (see sr_compute_srv()). This new SRV
  46. * is embedded in the votes as described above.
  47. *
  48. * Some more notes:
  49. *
  50. * - To support rebooting authorities and to avoid double voting, each dirauth
  51. * saves the current state of the protocol on disk so that it can resume
  52. * normally in case of reboot. The disk state (sr_disk_state_t) is managed by
  53. * shared_random_state.c:state_query() and we go to extra lengths to ensure
  54. * that the state is flushed on disk everytime we receive any useful
  55. * information like commits or SRVs.
  56. *
  57. * - When we receive a commit from a vote, we examine it to see if it's useful
  58. * to us and whether it's appropriate to receive it according to the current
  59. * phase of the protocol (see should_keep_commit()). If the commit is useful
  60. * to us, we save it in our disk state using save_commit_to_state(). When we
  61. * receive the reveal information corresponding to a commitment, we verify
  62. * that they indeed match using verify_commit_and_reveal().
  63. *
  64. * - We treat consensuses as the ground truth, so everytime we generate a new
  65. * consensus we update our SR state accordingly even if our local view was
  66. * different (see sr_act_post_consensus()).
  67. *
  68. * - After a consensus has been composed, the SR protocol state gets prepared
  69. * for the next voting session using sr_state_update(). That function takes
  70. * care of housekeeping and also rotates the SRVs and commits in case a new
  71. * protocol run is coming up. We also call sr_state_update() on bootup (in
  72. * sr_state_init()), to prepare the state for the very first voting session.
  73. *
  74. * Terminology:
  75. *
  76. * - "Commitment" is the commitment value of the commit-and-reveal protocol.
  77. *
  78. * - "Reveal" is the reveal value of the commit-and-reveal protocol.
  79. *
  80. * - "Commit" is a struct (sr_commit_t) that contains a commitment value and
  81. * optionally also a corresponding reveal value.
  82. *
  83. * - "SRV" is the Shared Random Value that gets generated as the result of the
  84. * commit-and-reveal protocol.
  85. **/
  86. #define SHARED_RANDOM_PRIVATE
  87. #include "or.h"
  88. #include "shared_random.h"
  89. #include "config.h"
  90. #include "confparse.h"
  91. #include "dirvote.h"
  92. #include "networkstatus.h"
  93. #include "routerkeys.h"
  94. #include "router.h"
  95. #include "routerlist.h"
  96. #include "shared_random_state.h"
  97. #include "util.h"
  98. /* String prefix of shared random values in votes/consensuses. */
  99. static const char previous_srv_str[] = "shared-rand-previous-value";
  100. static const char current_srv_str[] = "shared-rand-current-value";
  101. static const char commit_ns_str[] = "shared-rand-commit";
  102. static const char sr_flag_ns_str[] = "shared-rand-participate";
  103. /* The value of the consensus param AuthDirNumSRVAgreements found in the
  104. * vote. This is set once the consensus creation subsystem requests the
  105. * SRV(s) that should be put in the consensus. We use this value to decide
  106. * if we keep or not an SRV. */
  107. static int32_t num_srv_agreements_from_vote;
  108. /* Return a heap allocated copy of the SRV <b>orig</b>. */
  109. STATIC sr_srv_t *
  110. srv_dup(const sr_srv_t *orig)
  111. {
  112. sr_srv_t *duplicate = NULL;
  113. if (!orig) {
  114. return NULL;
  115. }
  116. duplicate = tor_malloc_zero(sizeof(sr_srv_t));
  117. duplicate->num_reveals = orig->num_reveals;
  118. memcpy(duplicate->value, orig->value, sizeof(duplicate->value));
  119. return duplicate;
  120. }
  121. /* Allocate a new commit object and initializing it with <b>rsa_identity</b>
  122. * that MUST be provided. The digest algorithm is set to the default one
  123. * that is supported. The rest is uninitialized. This never returns NULL. */
  124. static sr_commit_t *
  125. commit_new(const char *rsa_identity)
  126. {
  127. sr_commit_t *commit;
  128. tor_assert(rsa_identity);
  129. commit = tor_malloc_zero(sizeof(*commit));
  130. commit->alg = SR_DIGEST_ALG;
  131. memcpy(commit->rsa_identity, rsa_identity, sizeof(commit->rsa_identity));
  132. base16_encode(commit->rsa_identity_hex, sizeof(commit->rsa_identity_hex),
  133. commit->rsa_identity, sizeof(commit->rsa_identity));
  134. return commit;
  135. }
  136. /* Issue a log message describing <b>commit</b>. */
  137. static void
  138. commit_log(const sr_commit_t *commit)
  139. {
  140. tor_assert(commit);
  141. log_debug(LD_DIR, "SR: Commit from %s", sr_commit_get_rsa_fpr(commit));
  142. log_debug(LD_DIR, "SR: Commit: [TS: %" PRIu64 "] [Encoded: %s]",
  143. commit->commit_ts, commit->encoded_commit);
  144. log_debug(LD_DIR, "SR: Reveal: [TS: %" PRIu64 "] [Encoded: %s]",
  145. commit->reveal_ts, safe_str(commit->encoded_reveal));
  146. }
  147. /* Make sure that the commitment and reveal information in <b>commit</b>
  148. * match. If they match return 0, return -1 otherwise. This function MUST be
  149. * used everytime we receive a new reveal value. Furthermore, the commit
  150. * object MUST have a reveal value and the hash of the reveal value. */
  151. STATIC int
  152. verify_commit_and_reveal(const sr_commit_t *commit)
  153. {
  154. tor_assert(commit);
  155. log_debug(LD_DIR, "SR: Validating commit from authority %s",
  156. sr_commit_get_rsa_fpr(commit));
  157. /* Check that the timestamps match. */
  158. if (commit->commit_ts != commit->reveal_ts) {
  159. log_warn(LD_BUG, "SR: Commit timestamp %" PRIu64 " doesn't match reveal "
  160. "timestamp %" PRIu64, commit->commit_ts,
  161. commit->reveal_ts);
  162. goto invalid;
  163. }
  164. /* Verify that the hashed_reveal received in the COMMIT message, matches
  165. * the reveal we just received. */
  166. {
  167. /* We first hash the reveal we just received. */
  168. char received_hashed_reveal[sizeof(commit->hashed_reveal)];
  169. /* Only sha3-256 is supported. */
  170. if (commit->alg != SR_DIGEST_ALG) {
  171. goto invalid;
  172. }
  173. /* Use the invariant length since the encoded reveal variable has an
  174. * extra byte for the NUL terminated byte. */
  175. if (crypto_digest256(received_hashed_reveal, commit->encoded_reveal,
  176. SR_REVEAL_BASE64_LEN, commit->alg) < 0) {
  177. /* Unable to digest the reveal blob, this is unlikely. */
  178. goto invalid;
  179. }
  180. /* Now compare that with the hashed_reveal we received in COMMIT. */
  181. if (fast_memneq(received_hashed_reveal, commit->hashed_reveal,
  182. sizeof(received_hashed_reveal))) {
  183. log_warn(LD_BUG, "SR: Received reveal value from authority %s "
  184. "doesn't match the commit value.",
  185. sr_commit_get_rsa_fpr(commit));
  186. goto invalid;
  187. }
  188. }
  189. return 0;
  190. invalid:
  191. return -1;
  192. }
  193. /* Return true iff the commit contains an encoded reveal value. */
  194. STATIC int
  195. commit_has_reveal_value(const sr_commit_t *commit)
  196. {
  197. return !tor_mem_is_zero(commit->encoded_reveal,
  198. sizeof(commit->encoded_reveal));
  199. }
  200. /* Parse the encoded commit. The format is:
  201. * base64-encode( TIMESTAMP || H(REVEAL) )
  202. *
  203. * If successfully decoded and parsed, commit is updated and 0 is returned.
  204. * On error, return -1. */
  205. STATIC int
  206. commit_decode(const char *encoded, sr_commit_t *commit)
  207. {
  208. int decoded_len = 0;
  209. size_t offset = 0;
  210. char b64_decoded[SR_COMMIT_LEN];
  211. tor_assert(encoded);
  212. tor_assert(commit);
  213. if (strlen(encoded) > SR_COMMIT_BASE64_LEN) {
  214. /* This means that if we base64 decode successfully the reveiced commit,
  215. * we'll end up with a bigger decoded commit thus unusable. */
  216. goto error;
  217. }
  218. /* Decode our encoded commit. Let's be careful here since _encoded_ is
  219. * coming from the network in a dirauth vote so we expect nothing more
  220. * than the base64 encoded length of a commit. */
  221. decoded_len = base64_decode(b64_decoded, sizeof(b64_decoded),
  222. encoded, strlen(encoded));
  223. if (decoded_len < 0) {
  224. log_warn(LD_BUG, "SR: Commit from authority %s can't be decoded.",
  225. sr_commit_get_rsa_fpr(commit));
  226. goto error;
  227. }
  228. if (decoded_len != SR_COMMIT_LEN) {
  229. log_warn(LD_BUG, "SR: Commit from authority %s decoded length doesn't "
  230. "match the expected length (%d vs %u).",
  231. sr_commit_get_rsa_fpr(commit), decoded_len,
  232. (unsigned)SR_COMMIT_LEN);
  233. goto error;
  234. }
  235. /* First is the timestamp (8 bytes). */
  236. commit->commit_ts = tor_ntohll(get_uint64(b64_decoded));
  237. offset += sizeof(uint64_t);
  238. /* Next is hashed reveal. */
  239. memcpy(commit->hashed_reveal, b64_decoded + offset,
  240. sizeof(commit->hashed_reveal));
  241. /* Copy the base64 blob to the commit. Useful for voting. */
  242. strlcpy(commit->encoded_commit, encoded, sizeof(commit->encoded_commit));
  243. return 0;
  244. error:
  245. return -1;
  246. }
  247. /* Parse the b64 blob at <b>encoded</b> containing reveal information and
  248. * store the information in-place in <b>commit</b>. Return 0 on success else
  249. * a negative value. */
  250. STATIC int
  251. reveal_decode(const char *encoded, sr_commit_t *commit)
  252. {
  253. int decoded_len = 0;
  254. char b64_decoded[SR_REVEAL_LEN];
  255. tor_assert(encoded);
  256. tor_assert(commit);
  257. if (strlen(encoded) > SR_REVEAL_BASE64_LEN) {
  258. /* This means that if we base64 decode successfully the received reveal
  259. * value, we'll end up with a bigger decoded value thus unusable. */
  260. goto error;
  261. }
  262. /* Decode our encoded reveal. Let's be careful here since _encoded_ is
  263. * coming from the network in a dirauth vote so we expect nothing more
  264. * than the base64 encoded length of our reveal. */
  265. decoded_len = base64_decode(b64_decoded, sizeof(b64_decoded),
  266. encoded, strlen(encoded));
  267. if (decoded_len < 0) {
  268. log_warn(LD_BUG, "SR: Reveal from authority %s can't be decoded.",
  269. sr_commit_get_rsa_fpr(commit));
  270. goto error;
  271. }
  272. if (decoded_len != SR_REVEAL_LEN) {
  273. log_warn(LD_BUG, "SR: Reveal from authority %s decoded length is "
  274. "doesn't match the expected length (%d vs %u)",
  275. sr_commit_get_rsa_fpr(commit), decoded_len,
  276. (unsigned)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. /* Convert a given srv object to a string for the control port. This doesn't
  442. * fail and the srv object MUST be valid. */
  443. static char *
  444. srv_to_control_string(const sr_srv_t *srv)
  445. {
  446. char *srv_str;
  447. char srv_hash_encoded[SR_SRV_VALUE_BASE64_LEN + 1];
  448. tor_assert(srv);
  449. sr_srv_encode(srv_hash_encoded, sizeof(srv_hash_encoded), srv);
  450. tor_asprintf(&srv_str, "%s", srv_hash_encoded);
  451. return srv_str;
  452. }
  453. /* Return a heap allocated string that contains the given <b>srv</b> string
  454. * representation formatted for a networkstatus document using the
  455. * <b>key</b> as the start of the line. This doesn't return NULL. */
  456. static char *
  457. srv_to_ns_string(const sr_srv_t *srv, const char *key)
  458. {
  459. char *srv_str;
  460. char srv_hash_encoded[SR_SRV_VALUE_BASE64_LEN + 1];
  461. tor_assert(srv);
  462. tor_assert(key);
  463. sr_srv_encode(srv_hash_encoded, sizeof(srv_hash_encoded), srv);
  464. tor_asprintf(&srv_str, "%s %" PRIu64 " %s\n", key,
  465. srv->num_reveals, srv_hash_encoded);
  466. log_debug(LD_DIR, "SR: Consensus SRV line: %s", srv_str);
  467. return srv_str;
  468. }
  469. /* Given the previous SRV and the current SRV, return a heap allocated
  470. * string with their data that could be put in a vote or a consensus. Caller
  471. * must free the returned string. Return NULL if no SRVs were provided. */
  472. static char *
  473. get_ns_str_from_sr_values(const sr_srv_t *prev_srv, const sr_srv_t *cur_srv)
  474. {
  475. smartlist_t *chunks = NULL;
  476. char *srv_str;
  477. if (!prev_srv && !cur_srv) {
  478. return NULL;
  479. }
  480. chunks = smartlist_new();
  481. if (prev_srv) {
  482. char *srv_line = srv_to_ns_string(prev_srv, previous_srv_str);
  483. smartlist_add(chunks, srv_line);
  484. }
  485. if (cur_srv) {
  486. char *srv_line = srv_to_ns_string(cur_srv, current_srv_str);
  487. smartlist_add(chunks, srv_line);
  488. }
  489. /* Join the line(s) here in one string to return. */
  490. srv_str = smartlist_join_strings(chunks, "", 0, NULL);
  491. SMARTLIST_FOREACH(chunks, char *, s, tor_free(s));
  492. smartlist_free(chunks);
  493. return srv_str;
  494. }
  495. /* Return 1 iff the two commits have the same commitment values. This
  496. * function does not care about reveal values. */
  497. STATIC int
  498. commitments_are_the_same(const sr_commit_t *commit_one,
  499. const sr_commit_t *commit_two)
  500. {
  501. tor_assert(commit_one);
  502. tor_assert(commit_two);
  503. if (strcmp(commit_one->encoded_commit, commit_two->encoded_commit)) {
  504. return 0;
  505. }
  506. return 1;
  507. }
  508. /* We just received a commit from the vote of authority with
  509. * <b>identity_digest</b>. Return 1 if this commit is authorititative that
  510. * is, it belongs to the authority that voted it. Else return 0 if not. */
  511. STATIC int
  512. commit_is_authoritative(const sr_commit_t *commit,
  513. const char *voter_key)
  514. {
  515. tor_assert(commit);
  516. tor_assert(voter_key);
  517. return fast_memeq(commit->rsa_identity, voter_key,
  518. sizeof(commit->rsa_identity));
  519. }
  520. /* Decide if the newly received <b>commit</b> should be kept depending on
  521. * the current phase and state of the protocol. The <b>voter_key</b> is the
  522. * RSA identity key fingerprint of the authority's vote from which the
  523. * commit comes from. The <b>phase</b> is the phase we should be validating
  524. * the commit for. Return 1 if the commit should be added to our state or 0
  525. * if not. */
  526. STATIC int
  527. should_keep_commit(const sr_commit_t *commit, const char *voter_key,
  528. sr_phase_t phase)
  529. {
  530. const sr_commit_t *saved_commit;
  531. tor_assert(commit);
  532. tor_assert(voter_key);
  533. log_debug(LD_DIR, "SR: Inspecting commit from %s (voter: %s)?",
  534. sr_commit_get_rsa_fpr(commit),
  535. hex_str(voter_key, DIGEST_LEN));
  536. /* For a commit to be considered, it needs to be authoritative (it should
  537. * be the voter's own commit). */
  538. if (!commit_is_authoritative(commit, voter_key)) {
  539. log_debug(LD_DIR, "SR: Ignoring non-authoritative commit.");
  540. goto ignore;
  541. }
  542. /* Let's make sure, for extra safety, that this fingerprint is known to
  543. * us. Even though this comes from a vote, doesn't hurt to be
  544. * extracareful. */
  545. if (trusteddirserver_get_by_v3_auth_digest(commit->rsa_identity) == NULL) {
  546. log_warn(LD_DIR, "SR: Fingerprint %s is not from a recognized "
  547. "authority. Discarding commit.",
  548. escaped(commit->rsa_identity));
  549. goto ignore;
  550. }
  551. /* Check if the authority that voted for <b>commit</b> has already posted
  552. * a commit before. */
  553. saved_commit = sr_state_get_commit(commit->rsa_identity);
  554. switch (phase) {
  555. case SR_PHASE_COMMIT:
  556. /* Already having a commit for an authority so ignore this one. */
  557. if (saved_commit) {
  558. /* Receiving known commits should happen naturally since commit phase
  559. lasts multiple rounds. However if the commitment value changes
  560. during commit phase, it might be a bug so log more loudly. */
  561. if (!commitments_are_the_same(commit, saved_commit)) {
  562. log_info(LD_DIR,
  563. "SR: Received altered commit from %s in commit phase.",
  564. sr_commit_get_rsa_fpr(commit));
  565. } else {
  566. log_debug(LD_DIR, "SR: Ignoring known commit during commit phase.");
  567. }
  568. goto ignore;
  569. }
  570. /* A commit with a reveal value during commitment phase is very wrong. */
  571. if (commit_has_reveal_value(commit)) {
  572. log_warn(LD_DIR, "SR: Commit from authority %s has a reveal value "
  573. "during COMMIT phase. (voter: %s)",
  574. sr_commit_get_rsa_fpr(commit),
  575. hex_str(voter_key, DIGEST_LEN));
  576. goto ignore;
  577. }
  578. break;
  579. case SR_PHASE_REVEAL:
  580. /* We are now in reveal phase. We keep a commit if and only if:
  581. *
  582. * - We have already seen a commit by this auth, AND
  583. * - the saved commit has the same commitment value as this one, AND
  584. * - the saved commit has no reveal information, AND
  585. * - this commit does have reveal information, AND
  586. * - the reveal & commit information are matching.
  587. *
  588. * If all the above are true, then we are interested in this new commit
  589. * for its reveal information. */
  590. if (!saved_commit) {
  591. log_debug(LD_DIR, "SR: Ignoring commit first seen in reveal phase.");
  592. goto ignore;
  593. }
  594. if (!commitments_are_the_same(commit, saved_commit)) {
  595. log_warn(LD_DIR, "SR: Commit from authority %s is different from "
  596. "previous commit in our state (voter: %s)",
  597. sr_commit_get_rsa_fpr(commit),
  598. hex_str(voter_key, DIGEST_LEN));
  599. goto ignore;
  600. }
  601. if (commit_has_reveal_value(saved_commit)) {
  602. log_debug(LD_DIR, "SR: Ignoring commit with known reveal info.");
  603. goto ignore;
  604. }
  605. if (!commit_has_reveal_value(commit)) {
  606. log_debug(LD_DIR, "SR: Ignoring commit without reveal value.");
  607. goto ignore;
  608. }
  609. if (verify_commit_and_reveal(commit) < 0) {
  610. log_warn(LD_BUG, "SR: Commit from authority %s has an invalid "
  611. "reveal value. (voter: %s)",
  612. sr_commit_get_rsa_fpr(commit),
  613. hex_str(voter_key, DIGEST_LEN));
  614. goto ignore;
  615. }
  616. break;
  617. default:
  618. tor_assert(0);
  619. }
  620. return 1;
  621. ignore:
  622. return 0;
  623. }
  624. /* We are in reveal phase and we found a valid and verified <b>commit</b> in
  625. * a vote that contains reveal values that we could use. Update the commit
  626. * we have in our state. Never call this with an unverified commit. */
  627. STATIC void
  628. save_commit_during_reveal_phase(const sr_commit_t *commit)
  629. {
  630. sr_commit_t *saved_commit;
  631. tor_assert(commit);
  632. /* Get the commit from our state. */
  633. saved_commit = sr_state_get_commit(commit->rsa_identity);
  634. tor_assert(saved_commit);
  635. /* Safety net. They can not be different commitments at this point. */
  636. int same_commits = commitments_are_the_same(commit, saved_commit);
  637. tor_assert(same_commits);
  638. /* Copy reveal information to our saved commit. */
  639. sr_state_copy_reveal_info(saved_commit, commit);
  640. }
  641. /* Save <b>commit</b> to our persistent state. Depending on the current
  642. * phase, different actions are taken. Steals reference of <b>commit</b>.
  643. * The commit object MUST be valid and verified before adding it to the
  644. * state. */
  645. STATIC void
  646. save_commit_to_state(sr_commit_t *commit)
  647. {
  648. sr_phase_t phase = sr_state_get_phase();
  649. ASSERT_COMMIT_VALID(commit);
  650. switch (phase) {
  651. case SR_PHASE_COMMIT:
  652. /* During commit phase, just save any new authoritative commit */
  653. sr_state_add_commit(commit);
  654. break;
  655. case SR_PHASE_REVEAL:
  656. save_commit_during_reveal_phase(commit);
  657. sr_commit_free(commit);
  658. break;
  659. default:
  660. tor_assert(0);
  661. }
  662. }
  663. /* Return 1 if we should we keep an SRV voted by <b>n_agreements</b> auths.
  664. * Return 0 if we should ignore it. */
  665. static int
  666. should_keep_srv(int n_agreements)
  667. {
  668. /* Check if the most popular SRV has reached majority. */
  669. int n_voters = get_n_authorities(V3_DIRINFO);
  670. int votes_required_for_majority = (n_voters / 2) + 1;
  671. /* We need at the very least majority to keep a value. */
  672. if (n_agreements < votes_required_for_majority) {
  673. log_notice(LD_DIR, "SR: SRV didn't reach majority [%d/%d]!",
  674. n_agreements, votes_required_for_majority);
  675. return 0;
  676. }
  677. /* When we just computed a new SRV, we need to have super majority in order
  678. * to keep it. */
  679. if (sr_state_srv_is_fresh()) {
  680. /* Check if we have super majority for this new SRV value. */
  681. if (n_agreements < num_srv_agreements_from_vote) {
  682. log_notice(LD_DIR, "SR: New SRV didn't reach agreement [%d/%d]!",
  683. n_agreements, num_srv_agreements_from_vote);
  684. return 0;
  685. }
  686. }
  687. return 1;
  688. }
  689. /* Helper: compare two DIGEST256_LEN digests. */
  690. static int
  691. compare_srvs_(const void **_a, const void **_b)
  692. {
  693. const sr_srv_t *a = *_a, *b = *_b;
  694. return tor_memcmp(a->value, b->value, sizeof(a->value));
  695. }
  696. /* Return the most frequent member of the sorted list of DIGEST256_LEN
  697. * digests in <b>sl</b> with the count of that most frequent element. */
  698. static sr_srv_t *
  699. smartlist_get_most_frequent_srv(const smartlist_t *sl, int *count_out)
  700. {
  701. return smartlist_get_most_frequent_(sl, compare_srvs_, count_out);
  702. }
  703. /** Compare two SRVs. Used in smartlist sorting. */
  704. static int
  705. compare_srv_(const void **_a, const void **_b)
  706. {
  707. const sr_srv_t *a = *_a, *b = *_b;
  708. return fast_memcmp(a->value, b->value,
  709. sizeof(a->value));
  710. }
  711. /* Using a list of <b>votes</b>, return the SRV object from them that has
  712. * been voted by the majority of dirauths. If <b>current</b> is set, we look
  713. * for the current SRV value else the previous one. The returned pointer is
  714. * an object located inside a vote. NULL is returned if no appropriate value
  715. * could be found. */
  716. STATIC sr_srv_t *
  717. get_majority_srv_from_votes(const smartlist_t *votes, int current)
  718. {
  719. int count = 0;
  720. sr_srv_t *most_frequent_srv = NULL;
  721. sr_srv_t *the_srv = NULL;
  722. smartlist_t *srv_list;
  723. tor_assert(votes);
  724. srv_list = smartlist_new();
  725. /* Walk over votes and register any SRVs found. */
  726. SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
  727. sr_srv_t *srv_tmp = NULL;
  728. if (!v->sr_info.participate) {
  729. /* Ignore vote that do not participate. */
  730. continue;
  731. }
  732. /* Do we want previous or current SRV? */
  733. srv_tmp = current ? v->sr_info.current_srv : v->sr_info.previous_srv;
  734. if (!srv_tmp) {
  735. continue;
  736. }
  737. smartlist_add(srv_list, srv_tmp);
  738. } SMARTLIST_FOREACH_END(v);
  739. smartlist_sort(srv_list, compare_srv_);
  740. most_frequent_srv = smartlist_get_most_frequent_srv(srv_list, &count);
  741. if (!most_frequent_srv) {
  742. goto end;
  743. }
  744. /* Was this SRV voted by enough auths for us to keep it? */
  745. if (!should_keep_srv(count)) {
  746. goto end;
  747. }
  748. /* We found an SRV that we can use! Habemus SRV! */
  749. the_srv = most_frequent_srv;
  750. {
  751. /* Debugging */
  752. char encoded[SR_SRV_VALUE_BASE64_LEN + 1];
  753. sr_srv_encode(encoded, sizeof(encoded), the_srv);
  754. log_debug(LD_DIR, "SR: Chosen SRV by majority: %s (%d votes)", encoded,
  755. count);
  756. }
  757. end:
  758. /* We do not free any sr_srv_t values, we don't have the ownership. */
  759. smartlist_free(srv_list);
  760. return the_srv;
  761. }
  762. /* Encode the given shared random value and put it in dst. Destination
  763. * buffer must be at least SR_SRV_VALUE_BASE64_LEN plus the NULL byte. */
  764. void
  765. sr_srv_encode(char *dst, size_t dst_len, const sr_srv_t *srv)
  766. {
  767. int ret;
  768. /* Extra byte for the NULL terminated char. */
  769. char buf[SR_SRV_VALUE_BASE64_LEN + 1];
  770. tor_assert(dst);
  771. tor_assert(srv);
  772. tor_assert(dst_len >= sizeof(buf));
  773. ret = base64_encode(buf, sizeof(buf), (const char *) srv->value,
  774. sizeof(srv->value), 0);
  775. /* Always expect the full length without the NULL byte. */
  776. tor_assert(ret == (sizeof(buf) - 1));
  777. tor_assert(ret <= (int) dst_len);
  778. strlcpy(dst, buf, dst_len);
  779. }
  780. /* Free a commit object. */
  781. void
  782. sr_commit_free(sr_commit_t *commit)
  783. {
  784. if (commit == NULL) {
  785. return;
  786. }
  787. /* Make sure we do not leave OUR random number in memory. */
  788. memwipe(commit->random_number, 0, sizeof(commit->random_number));
  789. tor_free(commit);
  790. }
  791. /* Generate the commitment/reveal value for the protocol run starting at
  792. * <b>timestamp</b>. <b>my_rsa_cert</b> is our authority RSA certificate. */
  793. sr_commit_t *
  794. sr_generate_our_commit(time_t timestamp, const authority_cert_t *my_rsa_cert)
  795. {
  796. sr_commit_t *commit = NULL;
  797. char digest[DIGEST_LEN];
  798. tor_assert(my_rsa_cert);
  799. /* Get our RSA identity fingerprint */
  800. if (crypto_pk_get_digest(my_rsa_cert->identity_key, digest) < 0) {
  801. goto error;
  802. }
  803. /* New commit with our identity key. */
  804. commit = commit_new(digest);
  805. /* Generate the reveal random value */
  806. crypto_strongest_rand(commit->random_number,
  807. sizeof(commit->random_number));
  808. commit->commit_ts = commit->reveal_ts = timestamp;
  809. /* Now get the base64 blob that corresponds to our reveal */
  810. if (reveal_encode(commit, commit->encoded_reveal,
  811. sizeof(commit->encoded_reveal)) < 0) {
  812. log_err(LD_DIR, "SR: Unable to encode our reveal value!");
  813. goto error;
  814. }
  815. /* Now let's create the commitment */
  816. tor_assert(commit->alg == SR_DIGEST_ALG);
  817. /* The invariant length is used here since the encoded reveal variable
  818. * has an extra byte added for the NULL terminated byte. */
  819. if (crypto_digest256(commit->hashed_reveal, commit->encoded_reveal,
  820. SR_REVEAL_BASE64_LEN, commit->alg) < 0) {
  821. goto error;
  822. }
  823. /* Now get the base64 blob that corresponds to our commit. */
  824. if (commit_encode(commit, commit->encoded_commit,
  825. sizeof(commit->encoded_commit)) < 0) {
  826. log_err(LD_DIR, "SR: Unable to encode our commit value!");
  827. goto error;
  828. }
  829. log_debug(LD_DIR, "SR: Generated our commitment:");
  830. commit_log(commit);
  831. /* Our commit better be valid :). */
  832. commit->valid = 1;
  833. return commit;
  834. error:
  835. sr_commit_free(commit);
  836. return NULL;
  837. }
  838. /* Compute the shared random value based on the active commits in our state. */
  839. void
  840. sr_compute_srv(void)
  841. {
  842. uint64_t reveal_num = 0;
  843. char *reveals = NULL;
  844. smartlist_t *chunks, *commits;
  845. digestmap_t *state_commits;
  846. /* Computing a shared random value in the commit phase is very wrong. This
  847. * should only happen at the very end of the reveal phase when a new
  848. * protocol run is about to start. */
  849. tor_assert(sr_state_get_phase() == SR_PHASE_REVEAL);
  850. state_commits = sr_state_get_commits();
  851. commits = smartlist_new();
  852. chunks = smartlist_new();
  853. /* We must make a list of commit ordered by authority fingerprint in
  854. * ascending order as specified by proposal 250. */
  855. DIGESTMAP_FOREACH(state_commits, key, sr_commit_t *, c) {
  856. /* Extra safety net, make sure we have valid commit before using it. */
  857. ASSERT_COMMIT_VALID(c);
  858. /* Let's not use a commit from an authority that we don't know. It's
  859. * possible that an authority could be removed during a protocol run so
  860. * that commit value should never be used in the SRV computation. */
  861. if (trusteddirserver_get_by_v3_auth_digest(c->rsa_identity) == NULL) {
  862. log_warn(LD_DIR, "SR: Fingerprint %s is not from a recognized "
  863. "authority. Discarding commit for the SRV computation.",
  864. sr_commit_get_rsa_fpr(c));
  865. continue;
  866. }
  867. /* We consider this commit valid. */
  868. smartlist_add(commits, c);
  869. } DIGESTMAP_FOREACH_END;
  870. smartlist_sort(commits, compare_reveal_);
  871. /* Now for each commit for that sorted list in ascending order, we'll
  872. * build the element for each authority that needs to go into the srv
  873. * computation. */
  874. SMARTLIST_FOREACH_BEGIN(commits, const sr_commit_t *, c) {
  875. char *element = get_srv_element_from_commit(c);
  876. if (element) {
  877. smartlist_add(chunks, element);
  878. reveal_num++;
  879. }
  880. } SMARTLIST_FOREACH_END(c);
  881. smartlist_free(commits);
  882. {
  883. /* Join all reveal values into one giant string that we'll hash so we
  884. * can generated our shared random value. */
  885. sr_srv_t *current_srv;
  886. char hashed_reveals[DIGEST256_LEN];
  887. reveals = smartlist_join_strings(chunks, "", 0, NULL);
  888. SMARTLIST_FOREACH(chunks, char *, s, tor_free(s));
  889. smartlist_free(chunks);
  890. if (crypto_digest256(hashed_reveals, reveals, strlen(reveals),
  891. SR_DIGEST_ALG) < 0) {
  892. goto end;
  893. }
  894. current_srv = generate_srv(hashed_reveals, reveal_num,
  895. sr_state_get_previous_srv());
  896. sr_state_set_current_srv(current_srv);
  897. /* We have a fresh SRV, flag our state. */
  898. sr_state_set_fresh_srv();
  899. }
  900. end:
  901. tor_free(reveals);
  902. }
  903. /* Parse a list of arguments from a SRV value either from a vote, consensus
  904. * or from our disk state and return a newly allocated srv object. NULL is
  905. * returned on error.
  906. *
  907. * The arguments' order:
  908. * num_reveals, value
  909. */
  910. sr_srv_t *
  911. sr_parse_srv(const smartlist_t *args)
  912. {
  913. char *value;
  914. int ok, ret;
  915. uint64_t num_reveals;
  916. sr_srv_t *srv = NULL;
  917. tor_assert(args);
  918. if (smartlist_len(args) < 2) {
  919. goto end;
  920. }
  921. /* First argument is the number of reveal values */
  922. num_reveals = tor_parse_uint64(smartlist_get(args, 0),
  923. 10, 0, UINT64_MAX, &ok, NULL);
  924. if (!ok) {
  925. goto end;
  926. }
  927. /* Second and last argument is the shared random value it self. */
  928. value = smartlist_get(args, 1);
  929. if (strlen(value) != SR_SRV_VALUE_BASE64_LEN) {
  930. goto end;
  931. }
  932. srv = tor_malloc_zero(sizeof(*srv));
  933. srv->num_reveals = num_reveals;
  934. /* We substract one byte from the srclen because the function ignores the
  935. * '=' character in the given buffer. This is broken but it's a documented
  936. * behavior of the implementation. */
  937. ret = base64_decode((char *) srv->value, sizeof(srv->value), value,
  938. SR_SRV_VALUE_BASE64_LEN - 1);
  939. if (ret != sizeof(srv->value)) {
  940. tor_free(srv);
  941. srv = NULL;
  942. goto end;
  943. }
  944. end:
  945. return srv;
  946. }
  947. /* Parse a commit from a vote or from our disk state and return a newly
  948. * allocated commit object. NULL is returned on error.
  949. *
  950. * The commit's data is in <b>args</b> and the order matters very much:
  951. * version, algname, RSA fingerprint, commit value[, reveal value]
  952. */
  953. sr_commit_t *
  954. sr_parse_commit(const smartlist_t *args)
  955. {
  956. uint32_t version;
  957. char *value, digest[DIGEST_LEN];
  958. digest_algorithm_t alg;
  959. const char *rsa_identity_fpr;
  960. sr_commit_t *commit = NULL;
  961. if (smartlist_len(args) < 4) {
  962. goto error;
  963. }
  964. /* First is the version number of the SR protocol which indicates at which
  965. * version that commit was created. */
  966. value = smartlist_get(args, 0);
  967. version = (uint32_t) tor_parse_ulong(value, 10, 1, UINT32_MAX, NULL, NULL);
  968. if (version > SR_PROTO_VERSION) {
  969. log_info(LD_DIR, "SR: Commit version %" PRIu32 " (%s) is not supported.",
  970. version, escaped(value));
  971. goto error;
  972. }
  973. /* Second is the algorithm. */
  974. value = smartlist_get(args, 1);
  975. alg = crypto_digest_algorithm_parse_name(value);
  976. if (alg != SR_DIGEST_ALG) {
  977. log_warn(LD_BUG, "SR: Commit algorithm %s is not recognized.",
  978. escaped(value));
  979. goto error;
  980. }
  981. /* Third argument is the RSA fingerprint of the auth and turn it into a
  982. * digest value. */
  983. rsa_identity_fpr = smartlist_get(args, 2);
  984. if (base16_decode(digest, DIGEST_LEN, rsa_identity_fpr,
  985. HEX_DIGEST_LEN) < 0) {
  986. log_warn(LD_DIR, "SR: RSA fingerprint %s not decodable",
  987. escaped(rsa_identity_fpr));
  988. goto error;
  989. }
  990. /* Allocate commit since we have a valid identity now. */
  991. commit = commit_new(digest);
  992. /* Fourth argument is the commitment value base64-encoded. */
  993. value = smartlist_get(args, 3);
  994. if (commit_decode(value, commit) < 0) {
  995. goto error;
  996. }
  997. /* (Optional) Fifth argument is the revealed value. */
  998. if (smartlist_len(args) > 4) {
  999. value = smartlist_get(args, 4);
  1000. if (reveal_decode(value, commit) < 0) {
  1001. goto error;
  1002. }
  1003. }
  1004. return commit;
  1005. error:
  1006. sr_commit_free(commit);
  1007. return NULL;
  1008. }
  1009. /* Called when we are done parsing a vote by <b>voter_key</b> that might
  1010. * contain some useful <b>commits</b>. Find if any of them should be kept
  1011. * and update our state accordingly. Once done, the list of commitments will
  1012. * be empty. */
  1013. void
  1014. sr_handle_received_commits(smartlist_t *commits, crypto_pk_t *voter_key)
  1015. {
  1016. char rsa_identity[DIGEST_LEN];
  1017. tor_assert(voter_key);
  1018. /* It's possible that the vote has _NO_ commits. */
  1019. if (commits == NULL) {
  1020. return;
  1021. }
  1022. /* Get the RSA identity fingerprint of this voter */
  1023. if (crypto_pk_get_digest(voter_key, rsa_identity) < 0) {
  1024. return;
  1025. }
  1026. SMARTLIST_FOREACH_BEGIN(commits, sr_commit_t *, commit) {
  1027. /* We won't need the commit in this list anymore, kept or not. */
  1028. SMARTLIST_DEL_CURRENT(commits, commit);
  1029. /* Check if this commit is valid and should be stored in our state. */
  1030. if (!should_keep_commit(commit, rsa_identity,
  1031. sr_state_get_phase())) {
  1032. sr_commit_free(commit);
  1033. continue;
  1034. }
  1035. /* Ok, we have a valid commit now that we are about to put in our state.
  1036. * so flag it valid from now on. */
  1037. commit->valid = 1;
  1038. /* Everything lines up: save this commit to state then! */
  1039. save_commit_to_state(commit);
  1040. } SMARTLIST_FOREACH_END(commit);
  1041. }
  1042. /* Return a heap-allocated string containing commits that should be put in
  1043. * the votes. It's the responsibility of the caller to free the string.
  1044. * This always return a valid string, either empty or with line(s). */
  1045. char *
  1046. sr_get_string_for_vote(void)
  1047. {
  1048. char *vote_str = NULL;
  1049. digestmap_t *state_commits;
  1050. smartlist_t *chunks = smartlist_new();
  1051. const or_options_t *options = get_options();
  1052. /* Are we participating in the protocol? */
  1053. if (!options->AuthDirSharedRandomness) {
  1054. goto end;
  1055. }
  1056. log_debug(LD_DIR, "SR: Preparing our vote info:");
  1057. /* First line, put in the vote the participation flag. */
  1058. {
  1059. char *sr_flag_line;
  1060. tor_asprintf(&sr_flag_line, "%s\n", sr_flag_ns_str);
  1061. smartlist_add(chunks, sr_flag_line);
  1062. }
  1063. /* In our vote we include every commitment in our permanent state. */
  1064. state_commits = sr_state_get_commits();
  1065. smartlist_t *state_commit_vote_lines = smartlist_new();
  1066. DIGESTMAP_FOREACH(state_commits, key, const sr_commit_t *, commit) {
  1067. char *line = get_vote_line_from_commit(commit, sr_state_get_phase());
  1068. smartlist_add(state_commit_vote_lines, line);
  1069. } DIGESTMAP_FOREACH_END;
  1070. /* Sort the commit strings by version (string, not numeric), algorithm,
  1071. * and fingerprint. This makes sure the commit lines in votes are in a
  1072. * recognisable, stable order. */
  1073. smartlist_sort_strings(state_commit_vote_lines);
  1074. /* Now add the sorted list of commits to the vote */
  1075. smartlist_add_all(chunks, state_commit_vote_lines);
  1076. smartlist_free(state_commit_vote_lines);
  1077. /* Add the SRV value(s) if any. */
  1078. {
  1079. char *srv_lines = get_ns_str_from_sr_values(sr_state_get_previous_srv(),
  1080. sr_state_get_current_srv());
  1081. if (srv_lines) {
  1082. smartlist_add(chunks, srv_lines);
  1083. }
  1084. }
  1085. end:
  1086. vote_str = smartlist_join_strings(chunks, "", 0, NULL);
  1087. SMARTLIST_FOREACH(chunks, char *, s, tor_free(s));
  1088. smartlist_free(chunks);
  1089. return vote_str;
  1090. }
  1091. /* Return a heap-allocated string that should be put in the consensus and
  1092. * contains the shared randomness values. It's the responsibility of the
  1093. * caller to free the string. NULL is returned if no SRV(s) available.
  1094. *
  1095. * This is called when a consensus (any flavor) is bring created thus it
  1096. * should NEVER change the state nor the state should be changed in between
  1097. * consensus creation.
  1098. *
  1099. * <b>num_srv_agreements</b> is taken from the votes thus the voted value
  1100. * that should be used.
  1101. * */
  1102. char *
  1103. sr_get_string_for_consensus(const smartlist_t *votes,
  1104. int32_t num_srv_agreements)
  1105. {
  1106. char *srv_str;
  1107. const or_options_t *options = get_options();
  1108. tor_assert(votes);
  1109. /* Not participating, avoid returning anything. */
  1110. if (!options->AuthDirSharedRandomness) {
  1111. log_info(LD_DIR, "SR: Support disabled (AuthDirSharedRandomness %d)",
  1112. options->AuthDirSharedRandomness);
  1113. goto end;
  1114. }
  1115. /* Set the global value of AuthDirNumSRVAgreements found in the votes. */
  1116. num_srv_agreements_from_vote = num_srv_agreements;
  1117. /* Check the votes and figure out if SRVs should be included in the final
  1118. * consensus. */
  1119. sr_srv_t *prev_srv = get_majority_srv_from_votes(votes, 0);
  1120. sr_srv_t *cur_srv = get_majority_srv_from_votes(votes, 1);
  1121. srv_str = get_ns_str_from_sr_values(prev_srv, cur_srv);
  1122. if (!srv_str) {
  1123. goto end;
  1124. }
  1125. return srv_str;
  1126. end:
  1127. return NULL;
  1128. }
  1129. /* We just computed a new <b>consensus</b>. Update our state with the SRVs
  1130. * from the consensus (might be NULL as well). Register the SRVs in our SR
  1131. * state and prepare for the upcoming protocol round. */
  1132. void
  1133. sr_act_post_consensus(const networkstatus_t *consensus)
  1134. {
  1135. const or_options_t *options = get_options();
  1136. /* Don't act if our state hasn't been initialized. We can be called during
  1137. * boot time when loading consensus from disk which is prior to the
  1138. * initialization of the SR subsystem. We also should not be doing
  1139. * anything if we are _not_ a directory authority and if we are a bridge
  1140. * authority. */
  1141. if (!sr_state_is_initialized() || !authdir_mode_v3(options) ||
  1142. authdir_mode_bridge(options)) {
  1143. return;
  1144. }
  1145. /* Set the majority voted SRVs in our state even if both are NULL. It
  1146. * doesn't matter this is what the majority has decided. Obviously, we can
  1147. * only do that if we have a consensus. */
  1148. if (consensus) {
  1149. /* Start by freeing the current SRVs since the SRVs we believed during
  1150. * voting do not really matter. Now that all the votes are in, we use the
  1151. * majority's opinion on which are the active SRVs. */
  1152. sr_state_clean_srvs();
  1153. /* Reset the fresh flag of the SRV so we know that from now on we don't
  1154. * have a new SRV to vote for. We just used the one from the consensus
  1155. * decided by the majority. */
  1156. sr_state_unset_fresh_srv();
  1157. /* Set the SR values from the given consensus. */
  1158. sr_state_set_previous_srv(srv_dup(consensus->sr_info.previous_srv));
  1159. sr_state_set_current_srv(srv_dup(consensus->sr_info.current_srv));
  1160. }
  1161. /* Prepare our state so that it's ready for the next voting period. */
  1162. {
  1163. voting_schedule_t *voting_schedule =
  1164. get_voting_schedule(options,time(NULL), LOG_NOTICE);
  1165. time_t interval_starts = voting_schedule->interval_starts;
  1166. sr_state_update(interval_starts);
  1167. voting_schedule_free(voting_schedule);
  1168. }
  1169. }
  1170. /* Initialize shared random subsystem. This MUST be called early in the boot
  1171. * process of tor. Return 0 on success else -1 on error. */
  1172. int
  1173. sr_init(int save_to_disk)
  1174. {
  1175. return sr_state_init(save_to_disk, 1);
  1176. }
  1177. /* Save our state to disk and cleanup everything. */
  1178. void
  1179. sr_save_and_cleanup(void)
  1180. {
  1181. sr_state_save();
  1182. sr_cleanup();
  1183. }
  1184. /* Return the current SRV string representation for the control port. Return a
  1185. * newly allocated string on success containing the value else "" if not found
  1186. * or if we don't have a valid consensus yet. */
  1187. char *
  1188. sr_get_current_for_control(void)
  1189. {
  1190. char *srv_str;
  1191. const networkstatus_t *c = networkstatus_get_latest_consensus();
  1192. if (c && c->sr_info.current_srv) {
  1193. srv_str = srv_to_control_string(c->sr_info.current_srv);
  1194. } else {
  1195. srv_str = tor_strdup("");
  1196. }
  1197. return srv_str;
  1198. }
  1199. /* Return the previous SRV string representation for the control port. Return
  1200. * a newly allocated string on success containing the value else "" if not
  1201. * found or if we don't have a valid consensus yet. */
  1202. char *
  1203. sr_get_previous_for_control(void)
  1204. {
  1205. char *srv_str;
  1206. const networkstatus_t *c = networkstatus_get_latest_consensus();
  1207. if (c && c->sr_info.previous_srv) {
  1208. srv_str = srv_to_control_string(c->sr_info.previous_srv);
  1209. } else {
  1210. srv_str = tor_strdup("");
  1211. }
  1212. return srv_str;
  1213. }
  1214. #ifdef TOR_UNIT_TESTS
  1215. /* Set the global value of number of SRV agreements so the test can play
  1216. * along by calling specific functions that don't parse the votes prior for
  1217. * the AuthDirNumSRVAgreements value. */
  1218. void
  1219. set_num_srv_agreements(int32_t value)
  1220. {
  1221. num_srv_agreements_from_vote = value;
  1222. }
  1223. #endif /* TOR_UNIT_TESTS */