shared_random.c 41 KB

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