shared_random.c 47 KB

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