Coveralls logob
Coveralls logo
  • Home
  • Features
  • Pricing
  • Docs
  • Sign In

tlyu / tor / 2361

18 Dec 2018 - 19:57 coverage decreased (-0.01%) to 60.744%
2361

push

travis-ci

739ebe3feeaa3fc6a86160d22121e5c2?size=18&default=identicontlyu
The big bootstrap phase redefinition

43657 of 71870 relevant lines covered (60.74%)

44782.9 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

85.64
/src/feature/dirauth/shared_random.c
1
/* Copyright (c) 2016-2018, The Tor Project, Inc. */
2
/* See LICENSE for licensing information */
3

4
/**
5
 * \file shared_random.c
6
 *
7
 * \brief Functions and data structure needed to accomplish the shared
8
 *        random protocol as defined in proposal #250.
9
 *
10
 * \details
11
 *
12
 * This file implements the dirauth-only commit-and-reveal protocol specified
13
 * by proposal #250. The protocol has two phases (sr_phase_t): the commitment
14
 * phase and the reveal phase (see get_sr_protocol_phase()).
15
 *
16
 * During the protocol, directory authorities keep state in memory (using
17
 * sr_state_t) and in disk (using sr_disk_state_t). The synchronization between
18
 * these two data structures happens in disk_state_update() and
19
 * disk_state_parse().
20
 *
21
 * Here is a rough protocol outline:
22
 *
23
 *      1) In the beginning of the commitment phase, dirauths generate a
24
 *         commitment/reveal value for the current protocol run (see
25
 *         new_protocol_run() and sr_generate_our_commit()).
26
 *
27
 *      2) During voting, dirauths publish their commits in their votes
28
 *         depending on the current phase.  Dirauths also include the two
29
 *         latest shared random values (SRV) in their votes.
30
 *         (see sr_get_string_for_vote())
31
 *
32
 *      3) Upon receiving a commit from a vote, authorities parse it, verify
33
 *         it, and attempt to save any new commitment or reveal information in
34
 *         their state file (see extract_shared_random_commits() and
35
 *         sr_handle_received_commits()).  They also parse SRVs from votes to
36
 *         decide which SRV should be included in the final consensus (see
37
 *         extract_shared_random_srvs()).
38
 *
39
 *      3) After voting is done, we count the SRVs we extracted from the votes,
40
 *         to find the one voted by the majority of dirauths which should be
41
 *         included in the final consensus (see get_majority_srv_from_votes()).
42
 *         If an appropriate SRV is found, it is embedded in the consensus (see
43
 *         sr_get_string_for_consensus()).
44
 *
45
 *      4) At the end of the reveal phase, dirauths compute a fresh SRV for the
46
 *         day using the active commits (see sr_compute_srv()).  This new SRV
47
 *         is embedded in the votes as described above.
48
 *
49
 * Some more notes:
50
 *
51
 * - To support rebooting authorities and to avoid double voting, each dirauth
52
 *   saves the current state of the protocol on disk so that it can resume
53
 *   normally in case of reboot. The disk state (sr_disk_state_t) is managed by
54
 *   shared_random_state.c:state_query() and we go to extra lengths to ensure
55
 *   that the state is flushed on disk everytime we receive any useful
56
 *   information like commits or SRVs.
57
 *
58
 * - When we receive a commit from a vote, we examine it to see if it's useful
59
 *   to us and whether it's appropriate to receive it according to the current
60
 *   phase of the protocol (see should_keep_commit()). If the commit is useful
61
 *   to us, we save it in our disk state using save_commit_to_state().  When we
62
 *   receive the reveal information corresponding to a commitment, we verify
63
 *   that they indeed match using verify_commit_and_reveal().
64
 *
65
 * - We treat consensuses as the ground truth, so everytime we generate a new
66
 *   consensus we update our SR state accordingly even if our local view was
67
 *   different (see sr_act_post_consensus()).
68
 *
69
 * - After a consensus has been composed, the SR protocol state gets prepared
70
 *   for the next voting session using sr_state_update(). That function takes
71
 *   care of housekeeping and also rotates the SRVs and commits in case a new
72
 *   protocol run is coming up. We also call sr_state_update() on bootup (in
73
 *   sr_state_init()), to prepare the state for the very first voting session.
74
 *
75
 * Terminology:
76
 *
77
 * - "Commitment" is the commitment value of the commit-and-reveal protocol.
78
 *
79
 * - "Reveal" is the reveal value of the commit-and-reveal protocol.
80
 *
81
 * - "Commit" is a struct (sr_commit_t) that contains a commitment value and
82
 *    optionally also a corresponding reveal value.
83
 *
84
 * - "SRV" is the Shared Random Value that gets generated as the result of the
85
 *   commit-and-reveal protocol.
86
 **/
87

88
#define SHARED_RANDOM_PRIVATE
89

90
#include "core/or/or.h"
91
#include "feature/dirauth/shared_random.h"
92
#include "app/config/config.h"
93
#include "app/config/confparse.h"
94
#include "lib/crypt_ops/crypto_rand.h"
95
#include "lib/crypt_ops/crypto_util.h"
96
#include "feature/nodelist/networkstatus.h"
97
#include "feature/relay/router.h"
98
#include "feature/relay/routerkeys.h"
99
#include "feature/nodelist/dirlist.h"
100
#include "feature/hs_common/shared_random_client.h"
101
#include "feature/dirauth/shared_random_state.h"
102
#include "feature/dircommon/voting_schedule.h"
103

104
#include "feature/dirauth/dirvote.h"
105
#include "feature/dirauth/authmode.h"
106

107
#include "feature/nodelist/authority_cert_st.h"
108
#include "feature/nodelist/networkstatus_st.h"
109

110
/* String prefix of shared random values in votes/consensuses. */
111
static const char previous_srv_str[] = "shared-rand-previous-value";
112
static const char current_srv_str[] = "shared-rand-current-value";
113
static const char commit_ns_str[] = "shared-rand-commit";
114
static const char sr_flag_ns_str[] = "shared-rand-participate";
115

116
/* The value of the consensus param AuthDirNumSRVAgreements found in the
117
 * vote. This is set once the consensus creation subsystem requests the
118
 * SRV(s) that should be put in the consensus. We use this value to decide
119
 * if we keep or not an SRV. */
120
static int32_t num_srv_agreements_from_vote;
121

122
/* Return a heap allocated copy of the SRV <b>orig</b>. */
123
STATIC sr_srv_t *
124
srv_dup(const sr_srv_t *orig)
1×
125
{
126
  sr_srv_t *duplicate = NULL;
1×
127

128
  if (!orig) {
1×
129
    return NULL;
130
  }
131

132
  duplicate = tor_malloc_zero(sizeof(sr_srv_t));
1×
133
  duplicate->num_reveals = orig->num_reveals;
1×
134
  memcpy(duplicate->value, orig->value, sizeof(duplicate->value));
1×
135
  return duplicate;
1×
136
}
137

138
/* Allocate a new commit object and initializing it with <b>rsa_identity</b>
139
 * that MUST be provided. The digest algorithm is set to the default one
140
 * that is supported. The rest is uninitialized. This never returns NULL. */
141
static sr_commit_t *
142
commit_new(const char *rsa_identity)
18×
143
{
144
  sr_commit_t *commit;
145

146
  tor_assert(rsa_identity);
18×
147

148
  commit = tor_malloc_zero(sizeof(*commit));
18×
149
  commit->alg = SR_DIGEST_ALG;
18×
150
  memcpy(commit->rsa_identity, rsa_identity, sizeof(commit->rsa_identity));
18×
151
  base16_encode(commit->rsa_identity_hex, sizeof(commit->rsa_identity_hex),
18×
152
                commit->rsa_identity, sizeof(commit->rsa_identity));
153
  return commit;
18×
154
}
155

156
/* Issue a log message describing <b>commit</b>. */
157
static void
158
commit_log(const sr_commit_t *commit)
13×
159
{
160
  tor_assert(commit);
13×
161

162
  log_debug(LD_DIR, "SR: Commit from %s", sr_commit_get_rsa_fpr(commit));
13×
163
  log_debug(LD_DIR, "SR: Commit: [TS: %" PRIu64 "] [Encoded: %s]",
13×
164
            commit->commit_ts, commit->encoded_commit);
165
  log_debug(LD_DIR, "SR: Reveal: [TS: %" PRIu64 "] [Encoded: %s]",
13×
166
            commit->reveal_ts, safe_str(commit->encoded_reveal));
167
}
13×
168

169
/* Make sure that the commitment and reveal information in <b>commit</b>
170
 * match. If they match return 0, return -1 otherwise. This function MUST be
171
 * used everytime we receive a new reveal value. Furthermore, the commit
172
 * object MUST have a reveal value and the hash of the reveal value. */
173
STATIC int
174
verify_commit_and_reveal(const sr_commit_t *commit)
7×
175
{
176
  tor_assert(commit);
7×
177

178
  log_debug(LD_DIR, "SR: Validating commit from authority %s",
7×
179
            sr_commit_get_rsa_fpr(commit));
180

181
  /* Check that the timestamps match. */
182
  if (commit->commit_ts != commit->reveal_ts) {
7×
183
    log_warn(LD_BUG, "SR: Commit timestamp %" PRIu64 " doesn't match reveal "
1×
184
                     "timestamp %" PRIu64, commit->commit_ts,
185
             commit->reveal_ts);
186
    goto invalid;
1×
187
  }
188

189
  /* Verify that the hashed_reveal received in the COMMIT message, matches
190
   * the reveal we just received. */
191
  {
192
    /* We first hash the reveal we just received. */
193
    char received_hashed_reveal[sizeof(commit->hashed_reveal)];
194

195
    /* Only sha3-256 is supported. */
196
    if (commit->alg != SR_DIGEST_ALG) {
6×
197
      goto invalid;
198
    }
199

200
    /* Use the invariant length since the encoded reveal variable has an
201
     * extra byte for the NUL terminated byte. */
202
    if (crypto_digest256(received_hashed_reveal, commit->encoded_reveal,
6×
203
                         SR_REVEAL_BASE64_LEN, commit->alg) < 0) {
204
      /* Unable to digest the reveal blob, this is unlikely. */
205
      goto invalid;
206
    }
207

208
    /* Now compare that with the hashed_reveal we received in COMMIT. */
209
    if (fast_memneq(received_hashed_reveal, commit->hashed_reveal,
6×
210
                    sizeof(received_hashed_reveal))) {
211
      log_warn(LD_BUG, "SR: Received reveal value from authority %s "
2×
212
                       "doesn't match the commit value.",
213
               sr_commit_get_rsa_fpr(commit));
214
      goto invalid;
2×
215
    }
216
  }
217

218
  return 0;
4×
219
 invalid:
220
  return -1;
221
}
222

223
/* Return true iff the commit contains an encoded reveal value. */
224
STATIC int
225
commit_has_reveal_value(const sr_commit_t *commit)
16×
226
{
227
  return !tor_mem_is_zero(commit->encoded_reveal,
16×
228
                          sizeof(commit->encoded_reveal));
229
}
230

231
/* Parse the encoded commit. The format is:
232
 *    base64-encode( TIMESTAMP || H(REVEAL) )
233
 *
234
 * If successfully decoded and parsed, commit is updated and 0 is returned.
235
 * On error, return -1. */
236
STATIC int
237
commit_decode(const char *encoded, sr_commit_t *commit)
7×
238
{
239
  int decoded_len = 0;
7×
240
  size_t offset = 0;
7×
241
  char b64_decoded[SR_COMMIT_LEN];
242

243
  tor_assert(encoded);
7×
244
  tor_assert(commit);
7×
245

246
  if (strlen(encoded) > SR_COMMIT_BASE64_LEN) {
7×
247
    /* This means that if we base64 decode successfully the reveiced commit,
248
     * we'll end up with a bigger decoded commit thus unusable. */
249
    goto error;
250
  }
251

252
  /* Decode our encoded commit. Let's be careful here since _encoded_ is
253
   * coming from the network in a dirauth vote so we expect nothing more
254
   * than the base64 encoded length of a commit. */
255
  decoded_len = base64_decode(b64_decoded, sizeof(b64_decoded),
7×
256
                              encoded, strlen(encoded));
257
  if (decoded_len < 0) {
7×
258
    log_warn(LD_BUG, "SR: Commit from authority %s can't be decoded.",
!
259
             sr_commit_get_rsa_fpr(commit));
260
    goto error;
!
261
  }
262

263
  if (decoded_len != SR_COMMIT_LEN) {
7×
264
    log_warn(LD_BUG, "SR: Commit from authority %s decoded length doesn't "
!
265
                     "match the expected length (%d vs %u).",
266
             sr_commit_get_rsa_fpr(commit), decoded_len,
267
             (unsigned)SR_COMMIT_LEN);
268
    goto error;
!
269
  }
270

271
  /* First is the timestamp (8 bytes). */
272
  commit->commit_ts = tor_ntohll(get_uint64(b64_decoded));
7×
273
  offset += sizeof(uint64_t);
7×
274
  /* Next is hashed reveal. */
275
  memcpy(commit->hashed_reveal, b64_decoded + offset,
7×
276
         sizeof(commit->hashed_reveal));
277
  /* Copy the base64 blob to the commit. Useful for voting. */
278
  strlcpy(commit->encoded_commit, encoded, sizeof(commit->encoded_commit));
7×
279

280
  return 0;
7×
281

282
 error:
283
  return -1;
284
}
285

286
/* Parse the b64 blob at <b>encoded</b> containing reveal information and
287
 * store the information in-place in <b>commit</b>. Return 0 on success else
288
 * a negative value. */
289
STATIC int
290
reveal_decode(const char *encoded, sr_commit_t *commit)
5×
291
{
292
  int decoded_len = 0;
5×
293
  char b64_decoded[SR_REVEAL_LEN];
294

295
  tor_assert(encoded);
5×
296
  tor_assert(commit);
5×
297

298
  if (strlen(encoded) > SR_REVEAL_BASE64_LEN) {
5×
299
    /* This means that if we base64 decode successfully the received reveal
300
     * value, we'll end up with a bigger decoded value thus unusable. */
301
    goto error;
302
  }
303

304
  /* Decode our encoded reveal. Let's be careful here since _encoded_ is
305
   * coming from the network in a dirauth vote so we expect nothing more
306
   * than the base64 encoded length of our reveal. */
307
  decoded_len = base64_decode(b64_decoded, sizeof(b64_decoded),
5×
308
                              encoded, strlen(encoded));
309
  if (decoded_len < 0) {
5×
310
    log_warn(LD_BUG, "SR: Reveal from authority %s can't be decoded.",
!
311
             sr_commit_get_rsa_fpr(commit));
312
    goto error;
!
313
  }
314

315
  if (decoded_len != SR_REVEAL_LEN) {
5×
316
    log_warn(LD_BUG, "SR: Reveal from authority %s decoded length is "
!
317
                     "doesn't match the expected length (%d vs %u)",
318
             sr_commit_get_rsa_fpr(commit), decoded_len,
319
             (unsigned)SR_REVEAL_LEN);
320
    goto error;
!
321
  }
322

323
  commit->reveal_ts = tor_ntohll(get_uint64(b64_decoded));
5×
324
  /* Copy the last part, the random value. */
325
  memcpy(commit->random_number, b64_decoded + 8,
5×
326
         sizeof(commit->random_number));
327
  /* Also copy the whole message to use during verification */
328
  strlcpy(commit->encoded_reveal, encoded, sizeof(commit->encoded_reveal));
5×
329

330
  return 0;
5×
331

332
 error:
333
  return -1;
334
}
335

336
/* Encode a reveal element using a given commit object to dst which is a
337
 * buffer large enough to put the base64-encoded reveal construction. The
338
 * format is as follow:
339
 *     REVEAL = base64-encode( TIMESTAMP || H(RN) )
340
 * Return base64 encoded length on success else a negative value.
341
 */
342
STATIC int
343
reveal_encode(const sr_commit_t *commit, char *dst, size_t len)
14×
344
{
345
  int ret;
346
  size_t offset = 0;
14×
347
  char buf[SR_REVEAL_LEN] = {0};
14×
348

349
  tor_assert(commit);
14×
350
  tor_assert(dst);
14×
351

352
  set_uint64(buf, tor_htonll(commit->reveal_ts));
14×
353
  offset += sizeof(uint64_t);
14×
354
  memcpy(buf + offset, commit->random_number,
14×
355
         sizeof(commit->random_number));
356

357
  /* Let's clean the buffer and then b64 encode it. */
358
  memset(dst, 0, len);
359
  ret = base64_encode(dst, len, buf, sizeof(buf), 0);
14×
360
  /* Wipe this buffer because it contains our random value. */
361
  memwipe(buf, 0, sizeof(buf));
14×
362
  return ret;
14×
363
}
364

365
/* Encode the given commit object to dst which is a buffer large enough to
366
 * put the base64-encoded commit. The format is as follow:
367
 *     COMMIT = base64-encode( TIMESTAMP || H(H(RN)) )
368
 * Return base64 encoded length on success else a negative value.
369
 */
370
STATIC int
371
commit_encode(const sr_commit_t *commit, char *dst, size_t len)
14×
372
{
373
  size_t offset = 0;
14×
374
  char buf[SR_COMMIT_LEN] = {0};
14×
375

376
  tor_assert(commit);
14×
377
  tor_assert(dst);
14×
378

379
  /* First is the timestamp (8 bytes). */
380
  set_uint64(buf, tor_htonll(commit->commit_ts));
14×
381
  offset += sizeof(uint64_t);
14×
382
  /* and then the hashed reveal. */
383
  memcpy(buf + offset, commit->hashed_reveal,
14×
384
         sizeof(commit->hashed_reveal));
385

386
  /* Clean the buffer and then b64 encode it. */
387
  memset(dst, 0, len);
388
  return base64_encode(dst, len, buf, sizeof(buf), 0);
14×
389
}
390

391
/* Cleanup both our global state and disk state. */
392
static void
393
sr_cleanup(void)
!
394
{
395
  sr_state_free_all();
!
396
}
397

398
/* Using <b>commit</b>, return a newly allocated string containing the commit
399
 * information that should be used during SRV calculation. It's the caller
400
 * responsibility to free the memory. Return NULL if this is not a commit to be
401
 * used for SRV calculation. */
402
static char *
403
get_srv_element_from_commit(const sr_commit_t *commit)
4×
404
{
405
  char *element;
406
  tor_assert(commit);
4×
407

408
  if (!commit_has_reveal_value(commit)) {
4×
409
    return NULL;
410
  }
411

412
  tor_asprintf(&element, "%s%s", sr_commit_get_rsa_fpr(commit),
3×
413
               commit->encoded_reveal);
3×
414
  return element;
3×
415
}
416

417
/* Return a srv object that is built with the construction:
418
 *    SRV = SHA3-256("shared-random" | INT_8(reveal_num) |
419
 *                   INT_4(version) | HASHED_REVEALS | previous_SRV)
420
 * This function cannot fail. */
421
static sr_srv_t *
422
generate_srv(const char *hashed_reveals, uint64_t reveal_num,
3×
423
             const sr_srv_t *previous_srv)
424
{
425
  char msg[DIGEST256_LEN + SR_SRV_MSG_LEN] = {0};
3×
426
  size_t offset = 0;
3×
427
  sr_srv_t *srv;
428

429
  tor_assert(hashed_reveals);
3×
430

431
  /* Add the invariant token. */
432
  memcpy(msg, SR_SRV_TOKEN, SR_SRV_TOKEN_LEN);
433
  offset += SR_SRV_TOKEN_LEN;
3×
434
  set_uint64(msg + offset, tor_htonll(reveal_num));
3×
435
  offset += sizeof(uint64_t);
3×
436
  set_uint32(msg + offset, htonl(SR_PROTO_VERSION));
3×
437
  offset += sizeof(uint32_t);
3×
438
  memcpy(msg + offset, hashed_reveals, DIGEST256_LEN);
3×
439
  offset += DIGEST256_LEN;
3×
440
  if (previous_srv != NULL) {
3×
441
    memcpy(msg + offset, previous_srv->value, sizeof(previous_srv->value));
2×
442
  }
443

444
  /* Ok we have our message and key for the HMAC computation, allocate our
445
   * srv object and do the last step. */
446
  srv = tor_malloc_zero(sizeof(*srv));
3×
447
  crypto_digest256((char *) srv->value, msg, sizeof(msg), SR_DIGEST_ALG);
3×
448
  srv->num_reveals = reveal_num;
3×
449

450
  {
451
    /* Debugging. */
452
    char srv_hash_encoded[SR_SRV_VALUE_BASE64_LEN + 1];
453
    sr_srv_encode(srv_hash_encoded, sizeof(srv_hash_encoded), srv);
3×
454
    log_info(LD_DIR, "SR: Generated SRV: %s", srv_hash_encoded);
3×
455
  }
456
  return srv;
3×
457
}
458

459
/* Compare reveal values and return the result. This should exclusively be
460
 * used by smartlist_sort(). */
461
static int
462
compare_reveal_(const void **_a, const void **_b)
4×
463
{
464
  const sr_commit_t *a = *_a, *b = *_b;
4×
465
  return fast_memcmp(a->hashed_reveal, b->hashed_reveal,
4×
466
                     sizeof(a->hashed_reveal));
467
}
468

469
/* Given <b>commit</b> give the line that we should place in our votes.
470
 * It's the responsibility of the caller to free the string. */
471
static char *
472
get_vote_line_from_commit(const sr_commit_t *commit, sr_phase_t phase)
1×
473
{
474
  char *vote_line = NULL;
1×
475

476
  switch (phase) {
1×
477
  case SR_PHASE_COMMIT:
478
    tor_asprintf(&vote_line, "%s %u %s %s %s\n",
!
479
                 commit_ns_str,
480
                 SR_PROTO_VERSION,
481
                 crypto_digest_algorithm_get_name(commit->alg),
482
                 sr_commit_get_rsa_fpr(commit),
483
                 commit->encoded_commit);
!
484
    break;
!
485
  case SR_PHASE_REVEAL:
486
  {
487
    /* Send a reveal value for this commit if we have one. */
488
    const char *reveal_str = commit->encoded_reveal;
1×
489
    if (tor_mem_is_zero(commit->encoded_reveal,
1×
490
                        sizeof(commit->encoded_reveal))) {
491
      reveal_str = "";
!
492
    }
493
    tor_asprintf(&vote_line, "%s %u %s %s %s %s\n",
1×
494
                 commit_ns_str,
495
                 SR_PROTO_VERSION,
496
                 crypto_digest_algorithm_get_name(commit->alg),
497
                 sr_commit_get_rsa_fpr(commit),
498
                 commit->encoded_commit, reveal_str);
1×
499
    break;
1×
500
  }
501
  default:
502
    tor_assert(0);
!
503
  }
504

505
  log_debug(LD_DIR, "SR: Commit vote line: %s", vote_line);
1×
506
  return vote_line;
1×
507
}
508

509
/* Return a heap allocated string that contains the given <b>srv</b> string
510
 * representation formatted for a networkstatus document using the
511
 * <b>key</b> as the start of the line. This doesn't return NULL. */
512
static char *
513
srv_to_ns_string(const sr_srv_t *srv, const char *key)
2×
514
{
515
  char *srv_str;
516
  char srv_hash_encoded[SR_SRV_VALUE_BASE64_LEN + 1];
517
  tor_assert(srv);
2×
518
  tor_assert(key);
2×
519

520
  sr_srv_encode(srv_hash_encoded, sizeof(srv_hash_encoded), srv);
2×
521
  tor_asprintf(&srv_str, "%s %" PRIu64 " %s\n", key,
2×
522
               srv->num_reveals, srv_hash_encoded);
523
  log_debug(LD_DIR, "SR: Consensus SRV line: %s", srv_str);
2×
524
  return srv_str;
2×
525
}
526

527
/* Given the previous SRV and the current SRV, return a heap allocated
528
 * string with their data that could be put in a vote or a consensus. Caller
529
 * must free the returned string.  Return NULL if no SRVs were provided. */
530
static char *
531
get_ns_str_from_sr_values(const sr_srv_t *prev_srv, const sr_srv_t *cur_srv)
52×
532
{
533
  smartlist_t *chunks = NULL;
52×
534
  char *srv_str;
535

536
  if (!prev_srv && !cur_srv) {
52×
537
    return NULL;
538
  }
539

540
  chunks = smartlist_new();
1×
541

542
  if (prev_srv) {
1×
543
    char *srv_line = srv_to_ns_string(prev_srv, previous_srv_str);
1×
544
    smartlist_add(chunks, srv_line);
1×
545
  }
546

547
  if (cur_srv) {
1×
548
    char *srv_line = srv_to_ns_string(cur_srv, current_srv_str);
1×
549
    smartlist_add(chunks, srv_line);
1×
550
  }
551

552
  /* Join the line(s) here in one string to return. */
553
  srv_str = smartlist_join_strings(chunks, "", 0, NULL);
1×
554
  SMARTLIST_FOREACH(chunks, char *, s, tor_free(s));
1×
555
  smartlist_free(chunks);
1×
556

557
  return srv_str;
1×
558
}
559

560
/* Return 1 iff the two commits have the same commitment values. This
561
 * function does not care about reveal values. */
562
STATIC int
563
commitments_are_the_same(const sr_commit_t *commit_one,
8×
564
                         const sr_commit_t *commit_two)
565
{
566
  tor_assert(commit_one);
8×
567
  tor_assert(commit_two);
8×
568

569
  if (strcmp(commit_one->encoded_commit, commit_two->encoded_commit)) {
8×
570
    return 0;
571
  }
572
  return 1;
6×
573
}
574

575
/* We just received a commit from the vote of authority with
576
 * <b>identity_digest</b>. Return 1 if this commit is authorititative that
577
 * is, it belongs to the authority that voted it. Else return 0 if not. */
578
STATIC int
579
commit_is_authoritative(const sr_commit_t *commit,
12×
580
                        const char *voter_key)
581
{
582
  tor_assert(commit);
12×
583
  tor_assert(voter_key);
12×
584

585
  return fast_memeq(commit->rsa_identity, voter_key,
12×
586
                    sizeof(commit->rsa_identity));
587
}
588

589
/* Decide if the newly received <b>commit</b> should be kept depending on
590
 * the current phase and state of the protocol. The <b>voter_key</b> is the
591
 * RSA identity key fingerprint of the authority's vote from which the
592
 * commit comes from. The <b>phase</b> is the phase we should be validating
593
 * the commit for. Return 1 if the commit should be added to our state or 0
594
 * if not. */
595
STATIC int
596
should_keep_commit(const sr_commit_t *commit, const char *voter_key,
10×
597
                   sr_phase_t phase)
598
{
599
  const sr_commit_t *saved_commit;
600

601
  tor_assert(commit);
10×
602
  tor_assert(voter_key);
10×
603

604
  log_debug(LD_DIR, "SR: Inspecting commit from %s (voter: %s)?",
10×
605
            sr_commit_get_rsa_fpr(commit),
606
            hex_str(voter_key, DIGEST_LEN));
607

608
  /* For a commit to be considered, it needs to be authoritative (it should
609
   * be the voter's own commit). */
610
  if (!commit_is_authoritative(commit, voter_key)) {
10×
611
    log_debug(LD_DIR, "SR: Ignoring non-authoritative commit.");
2×
612
    goto ignore;
613
  }
614

615
  /* Let's make sure, for extra safety, that this fingerprint is known to
616
   * us. Even though this comes from a vote, doesn't hurt to be
617
   * extracareful. */
618
  if (trusteddirserver_get_by_v3_auth_digest(commit->rsa_identity) == NULL) {
8×
619
    log_warn(LD_DIR, "SR: Fingerprint %s is not from a recognized "
!
620
                     "authority. Discarding commit.",
621
             escaped(commit->rsa_identity));
622
    goto ignore;
!
623
  }
624

625
  /* Check if the authority that voted for <b>commit</b> has already posted
626
   * a commit before. */
627
  saved_commit = sr_state_get_commit(commit->rsa_identity);
8×
628

629
  switch (phase) {
8×
630
  case SR_PHASE_COMMIT:
631
    /* Already having a commit for an authority so ignore this one. */
632
    if (saved_commit) {
3×
633
      /*  Receiving known commits should happen naturally since commit phase
634
          lasts multiple rounds. However if the commitment value changes
635
          during commit phase, it might be a bug so log more loudly. */
636
      if (!commitments_are_the_same(commit, saved_commit)) {
1×
637
        log_info(LD_DIR,
!
638
                 "SR: Received altered commit from %s in commit phase.",
639
                 sr_commit_get_rsa_fpr(commit));
640
      } else {
641
        log_debug(LD_DIR, "SR: Ignoring known commit during commit phase.");
1×
642
      }
643
      goto ignore;
644
    }
645

646
    /* A commit with a reveal value during commitment phase is very wrong. */
647
    if (commit_has_reveal_value(commit)) {
2×
648
      log_warn(LD_DIR, "SR: Commit from authority %s has a reveal value "
1×
649
                       "during COMMIT phase. (voter: %s)",
650
               sr_commit_get_rsa_fpr(commit),
651
               hex_str(voter_key, DIGEST_LEN));
652
      goto ignore;
1×
653
    }
654
    break;
655
  case SR_PHASE_REVEAL:
656
    /* We are now in reveal phase. We keep a commit if and only if:
657
     *
658
     * - We have already seen a commit by this auth, AND
659
     * - the saved commit has the same commitment value as this one, AND
660
     * - the saved commit has no reveal information, AND
661
     * - this commit does have reveal information, AND
662
     * - the reveal & commit information are matching.
663
     *
664
     * If all the above are true, then we are interested in this new commit
665
     * for its reveal information. */
666

667
    if (!saved_commit) {
5×
668
      log_debug(LD_DIR, "SR: Ignoring commit first seen in reveal phase.");
1×
669
      goto ignore;
670
    }
671

672
    if (!commitments_are_the_same(commit, saved_commit)) {
4×
673
      log_warn(LD_DIR, "SR: Commit from authority %s is different from "
1×
674
                       "previous commit in our state (voter: %s)",
675
               sr_commit_get_rsa_fpr(commit),
676
               hex_str(voter_key, DIGEST_LEN));
677
      goto ignore;
1×
678
    }
679

680
    if (commit_has_reveal_value(saved_commit)) {
3×
681
      log_debug(LD_DIR, "SR: Ignoring commit with known reveal info.");
!
682
      goto ignore;
683
    }
684

685
    if (!commit_has_reveal_value(commit)) {
3×
686
      log_debug(LD_DIR, "SR: Ignoring commit without reveal value.");
1×
687
      goto ignore;
688
    }
689

690
    if (verify_commit_and_reveal(commit) < 0) {
2×
691
      log_warn(LD_BUG, "SR: Commit from authority %s has an invalid "
1×
692
                       "reveal value. (voter: %s)",
693
               sr_commit_get_rsa_fpr(commit),
694
               hex_str(voter_key, DIGEST_LEN));
695
      goto ignore;
1×
696
    }
697
    break;
698
  default:
699
    tor_assert(0);
!
700
  }
701

702
  return 1;
703

704
 ignore:
705
  return 0;
706
}
707

708
/* We are in reveal phase and we found a valid and verified <b>commit</b> in
709
 * a vote that contains reveal values that we could use. Update the commit
710
 * we have in our state. Never call this with an unverified commit. */
711
STATIC void
712
save_commit_during_reveal_phase(const sr_commit_t *commit)
1×
713
{
714
  sr_commit_t *saved_commit;
715

716
  tor_assert(commit);
1×
717

718
  /* Get the commit from our state. */
719
  saved_commit = sr_state_get_commit(commit->rsa_identity);
1×
720
  tor_assert(saved_commit);
1×
721
  /* Safety net. They can not be different commitments at this point. */
722
  int same_commits = commitments_are_the_same(commit, saved_commit);
1×
723
  tor_assert(same_commits);
1×
724

725
  /* Copy reveal information to our saved commit. */
726
  sr_state_copy_reveal_info(saved_commit, commit);
1×
727
}
1×
728

729
/* Save <b>commit</b> to our persistent state. Depending on the current
730
 * phase, different actions are taken. Steals reference of <b>commit</b>.
731
 * The commit object MUST be valid and verified before adding it to the
732
 * state. */
733
STATIC void
734
save_commit_to_state(sr_commit_t *commit)
5×
735
{
736
  sr_phase_t phase = sr_state_get_phase();
5×
737

738
  ASSERT_COMMIT_VALID(commit);
5×
739

740
  switch (phase) {
5×
741
  case SR_PHASE_COMMIT:
742
    /* During commit phase, just save any new authoritative commit */
743
    sr_state_add_commit(commit);
4×
744
    break;
4×
745
  case SR_PHASE_REVEAL:
746
    save_commit_during_reveal_phase(commit);
1×
747
    sr_commit_free(commit);
1×
748
    break;
1×
749
  default:
750
    tor_assert(0);
!
751
  }
752
}
5×
753

754
/* Return 1 if we should we keep an SRV voted by <b>n_agreements</b> auths.
755
 * Return 0 if we should ignore it. */
756
static int
757
should_keep_srv(int n_agreements)
3×
758
{
759
  /* Check if the most popular SRV has reached majority. */
760
  int n_voters = get_n_authorities(V3_DIRINFO);
3×
761
  int votes_required_for_majority = (n_voters / 2) + 1;
3×
762

763
  /* We need at the very least majority to keep a value. */
764
  if (n_agreements < votes_required_for_majority) {
3×
765
    log_notice(LD_DIR, "SR: SRV didn't reach majority [%d/%d]!",
1×
766
               n_agreements, votes_required_for_majority);
767
    return 0;
1×
768
  }
769

770
  /* When we just computed a new SRV, we need to have super majority in order
771
   * to keep it. */
772
  if (sr_state_srv_is_fresh()) {
2×
773
    /* Check if we have super majority for this new SRV value. */
774
    if (n_agreements < num_srv_agreements_from_vote) {
2×
775
      log_notice(LD_DIR, "SR: New SRV didn't reach agreement [%d/%d]!",
1×
776
                 n_agreements, num_srv_agreements_from_vote);
777
      return 0;
1×
778
    }
779
  }
780

781
  return 1;
782
}
783

784
/* Helper: compare two DIGEST256_LEN digests. */
785
static int
786
compare_srvs_(const void **_a, const void **_b)
16×
787
{
788
  const sr_srv_t *a = *_a, *b = *_b;
16×
789
  return tor_memcmp(a->value, b->value, sizeof(a->value));
16×
790
}
791

792
/* Return the most frequent member of the sorted list of DIGEST256_LEN
793
 * digests in <b>sl</b> with the count of that most frequent element. */
794
static sr_srv_t *
795
smartlist_get_most_frequent_srv(const smartlist_t *sl, int *count_out)
51×
796
{
797
  return smartlist_get_most_frequent_(sl, compare_srvs_, count_out);
51×
798
}
799

800
/** Compare two SRVs. Used in smartlist sorting. */
801
static int
802
compare_srv_(const void **_a, const void **_b)
28×
803
{
804
  const sr_srv_t *a = *_a, *b = *_b;
28×
805
  return fast_memcmp(a->value, b->value,
28×
806
                     sizeof(a->value));
807
}
808

809
/* Using a list of <b>votes</b>, return the SRV object from them that has
810
 * been voted by the majority of dirauths. If <b>current</b> is set, we look
811
 * for the current SRV value else the previous one. The returned pointer is
812
 * an object located inside a vote. NULL is returned if no appropriate value
813
 * could be found. */
814
STATIC sr_srv_t *
815
get_majority_srv_from_votes(const smartlist_t *votes, int current)
51×
816
{
817
  int count = 0;
51×
818
  sr_srv_t *most_frequent_srv = NULL;
51×
819
  sr_srv_t *the_srv = NULL;
51×
820
  smartlist_t *srv_list;
821

822
  tor_assert(votes);
51×
823

824
  srv_list = smartlist_new();
51×
825

826
  /* Walk over votes and register any SRVs found. */
827
  SMARTLIST_FOREACH_BEGIN(votes, networkstatus_t *, v) {
214×
828
    sr_srv_t *srv_tmp = NULL;
163×
829

830
    if (!v->sr_info.participate) {
163×
831
      /* Ignore vote that do not participate. */
832
      continue;
!
833
    }
834
    /* Do we want previous or current SRV? */
835
    srv_tmp = current ? v->sr_info.current_srv : v->sr_info.previous_srv;
163×
836
    if (!srv_tmp) {
163×
837
      continue;
144×
838
    }
839

840
    smartlist_add(srv_list, srv_tmp);
19×
841
  } SMARTLIST_FOREACH_END(v);
19×
842

843
  smartlist_sort(srv_list, compare_srv_);
51×
844
  most_frequent_srv = smartlist_get_most_frequent_srv(srv_list, &count);
51×
845
  if (!most_frequent_srv) {
51×
846
    goto end;
847
  }
848

849
  /* Was this SRV voted by enough auths for us to keep it? */
850
  if (!should_keep_srv(count)) {
3×
851
    goto end;
852
  }
853

854
  /* We found an SRV that we can use! Habemus SRV! */
855
  the_srv = most_frequent_srv;
1×
856

857
  {
858
    /* Debugging */
859
    char encoded[SR_SRV_VALUE_BASE64_LEN + 1];
860
    sr_srv_encode(encoded, sizeof(encoded), the_srv);
1×
861
    log_debug(LD_DIR, "SR: Chosen SRV by majority: %s (%d votes)", encoded,
1×
862
              count);
863
  }
864

865
 end:
866
  /* We do not free any sr_srv_t values, we don't have the ownership. */
867
  smartlist_free(srv_list);
51×
868
  return the_srv;
51×
869
}
870

871
/* Free a commit object. */
872
void
873
sr_commit_free_(sr_commit_t *commit)
12×
874
{
875
  if (commit == NULL) {
12×
876
    return;
12×
877
  }
878
  /* Make sure we do not leave OUR random number in memory. */
879
  memwipe(commit->random_number, 0, sizeof(commit->random_number));
12×
880
  tor_free(commit);
12×
881
}
882

883
/* Generate the commitment/reveal value for the protocol run starting at
884
 * <b>timestamp</b>. <b>my_rsa_cert</b> is our authority RSA certificate. */
885
sr_commit_t *
886
sr_generate_our_commit(time_t timestamp, const authority_cert_t *my_rsa_cert)
13×
887
{
888
  sr_commit_t *commit = NULL;
13×
889
  char digest[DIGEST_LEN];
890

891
  tor_assert(my_rsa_cert);
13×
892

893
  /* Get our RSA identity fingerprint */
894
  if (crypto_pk_get_digest(my_rsa_cert->identity_key, digest) < 0) {
13×
895
    goto error;
896
  }
897

898
  /* New commit with our identity key. */
899
  commit = commit_new(digest);
13×
900

901
  /* Generate the reveal random value */
902
  crypto_strongest_rand(commit->random_number,
13×
903
                        sizeof(commit->random_number));
904
  commit->commit_ts = commit->reveal_ts = timestamp;
13×
905

906
  /* Now get the base64 blob that corresponds to our reveal */
907
  if (reveal_encode(commit, commit->encoded_reveal,
13×
908
                    sizeof(commit->encoded_reveal)) < 0) {
909
    log_err(LD_DIR, "SR: Unable to encode our reveal value!");
!
910
    goto error;
!
911
  }
912

913
  /* Now let's create the commitment */
914
  tor_assert(commit->alg == SR_DIGEST_ALG);
13×
915
  /* The invariant length is used here since the encoded reveal variable
916
   * has an extra byte added for the NULL terminated byte. */
917
  if (crypto_digest256(commit->hashed_reveal, commit->encoded_reveal,
13×
918
                       SR_REVEAL_BASE64_LEN, commit->alg) < 0) {
919
    goto error;
920
  }
921

922
  /* Now get the base64 blob that corresponds to our commit. */
923
  if (commit_encode(commit, commit->encoded_commit,
13×
924
                    sizeof(commit->encoded_commit)) < 0) {
925
    log_err(LD_DIR, "SR: Unable to encode our commit value!");
!
926
    goto error;
!
927
  }
928

929
  log_debug(LD_DIR, "SR: Generated our commitment:");
13×
930
  commit_log(commit);
13×
931
  /* Our commit better be valid :). */
932
  commit->valid = 1;
13×
933
  return commit;
13×
934

935
 error:
936
  sr_commit_free(commit);
!
937
  return NULL;
!
938
}
939

940
/* Compute the shared random value based on the active commits in our state. */
941
void
942
sr_compute_srv(void)
3×
943
{
944
  uint64_t reveal_num = 0;
3×
945
  char *reveals = NULL;
3×
946
  smartlist_t *chunks, *commits;
947
  digestmap_t *state_commits;
948

949
  /* Computing a shared random value in the commit phase is very wrong. This
950
   * should only happen at the very end of the reveal phase when a new
951
   * protocol run is about to start. */
952
  if (BUG(sr_state_get_phase() != SR_PHASE_REVEAL))
3×
953
    return;
3×
954
  state_commits = sr_state_get_commits();
3×
955

956
  commits = smartlist_new();
3×
957
  chunks = smartlist_new();
3×
958

959
  /* We must make a list of commit ordered by authority fingerprint in
960
   * ascending order as specified by proposal 250. */
961
  DIGESTMAP_FOREACH(state_commits, key, sr_commit_t *, c) {
8×
962
    /* Extra safety net, make sure we have valid commit before using it. */
963
    ASSERT_COMMIT_VALID(c);
5×
964
    /* Let's not use a commit from an authority that we don't know. It's
965
     * possible that an authority could be removed during a protocol run so
966
     * that commit value should never be used in the SRV computation. */
967
    if (trusteddirserver_get_by_v3_auth_digest(c->rsa_identity) == NULL) {
5×
968
      log_warn(LD_DIR, "SR: Fingerprint %s is not from a recognized "
1×
969
               "authority. Discarding commit for the SRV computation.",
970
               sr_commit_get_rsa_fpr(c));
971
      continue;
1×
972
    }
973
    /* We consider this commit valid. */
974
    smartlist_add(commits, c);
4×
975
  } DIGESTMAP_FOREACH_END;
976
  smartlist_sort(commits, compare_reveal_);
3×
977

978
  /* Now for each commit for that sorted list in ascending order, we'll
979
   * build the element for each authority that needs to go into the srv
980
   * computation. */
981
  SMARTLIST_FOREACH_BEGIN(commits, const sr_commit_t *, c) {
7×
982
    char *element = get_srv_element_from_commit(c);
4×
983
    if (element) {
4×
984
      smartlist_add(chunks, element);
3×
985
      reveal_num++;
3×
986
    }
987
  } SMARTLIST_FOREACH_END(c);
4×
988
  smartlist_free(commits);
3×
989

990
  {
991
    /* Join all reveal values into one giant string that we'll hash so we
992
     * can generated our shared random value. */
993
    sr_srv_t *current_srv;
994
    char hashed_reveals[DIGEST256_LEN];
995
    reveals = smartlist_join_strings(chunks, "", 0, NULL);
3×
996
    SMARTLIST_FOREACH(chunks, char *, s, tor_free(s));
3×
997
    smartlist_free(chunks);
3×
998
    if (crypto_digest256(hashed_reveals, reveals, strlen(reveals),
3×
999
                         SR_DIGEST_ALG) < 0) {
1000
      goto end;
1001
    }
1002
    current_srv = generate_srv(hashed_reveals, reveal_num,
3×
1003
                               sr_state_get_previous_srv());
1004
    sr_state_set_current_srv(current_srv);
3×
1005
    /* We have a fresh SRV, flag our state. */
1006
    sr_state_set_fresh_srv();
3×
1007
  }
1008

1009
 end:
1010
  tor_free(reveals);
3×
1011
}
1012

1013
/* Parse a commit from a vote or from our disk state and return a newly
1014
 * allocated commit object. NULL is returned on error.
1015
 *
1016
 * The commit's data is in <b>args</b> and the order matters very much:
1017
 *  version, algname, RSA fingerprint, commit value[, reveal value]
1018
 */
1019
sr_commit_t *
1020
sr_parse_commit(const smartlist_t *args)
5×
1021
{
1022
  uint32_t version;
1023
  char *value, digest[DIGEST_LEN];
1024
  digest_algorithm_t alg;
1025
  const char *rsa_identity_fpr;
1026
  sr_commit_t *commit = NULL;
5×
1027

1028
  if (smartlist_len(args) < 4) {
5×
1029
    goto error;
1030
  }
1031

1032
  /* First is the version number of the SR protocol which indicates at which
1033
   * version that commit was created. */
1034
  value = smartlist_get(args, 0);
5×
1035
  version = (uint32_t) tor_parse_ulong(value, 10, 1, UINT32_MAX, NULL, NULL);
5×
1036
  if (version > SR_PROTO_VERSION) {
5×
1037
    log_info(LD_DIR, "SR: Commit version %" PRIu32 " (%s) is not supported.",
!
1038
             version, escaped(value));
1039
    goto error;
!
1040
  }
1041

1042
  /* Second is the algorithm. */
1043
  value = smartlist_get(args, 1);
5×
1044
  alg = crypto_digest_algorithm_parse_name(value);
5×
1045
  if (alg != SR_DIGEST_ALG) {
5×
1046
    log_warn(LD_BUG, "SR: Commit algorithm %s is not recognized.",
!
1047
             escaped(value));
1048
    goto error;
!
1049
  }
1050

1051
  /* Third argument is the RSA fingerprint of the auth and turn it into a
1052
   * digest value. */
1053
  rsa_identity_fpr = smartlist_get(args, 2);
5×
1054
  if (base16_decode(digest, DIGEST_LEN, rsa_identity_fpr,
5×
1055
                    HEX_DIGEST_LEN) < 0) {
1056
    log_warn(LD_DIR, "SR: RSA fingerprint %s not decodable",
!
1057
             escaped(rsa_identity_fpr));
1058
    goto error;
!
1059
  }
1060

1061
  /* Allocate commit since we have a valid identity now. */
1062
  commit = commit_new(digest);
5×
1063

1064
  /* Fourth argument is the commitment value base64-encoded. */
1065
  value = smartlist_get(args, 3);
5×
1066
  if (commit_decode(value, commit) < 0) {
5×
1067
    goto error;
1068
  }
1069

1070
  /* (Optional) Fifth argument is the revealed value. */
1071
  if (smartlist_len(args) > 4) {
5×
1072
    value = smartlist_get(args, 4);
3×
1073
    if (reveal_decode(value, commit) < 0) {
3×
1074
      goto error;
1075
    }
1076
  }
1077

1078
  return commit;
5×
1079

1080
 error:
1081
  sr_commit_free(commit);
!
1082
  return NULL;
!
1083
}
1084

1085
/* Called when we are done parsing a vote by <b>voter_key</b> that might
1086
 * contain some useful <b>commits</b>. Find if any of them should be kept
1087
 * and update our state accordingly. Once done, the list of commitments will
1088
 * be empty. */
1089
void
1090
sr_handle_received_commits(smartlist_t *commits, crypto_pk_t *voter_key)
3×
1091
{
1092
  char rsa_identity[DIGEST_LEN];
1093

1094
  tor_assert(voter_key);
3×
1095

1096
  /* It's possible that the vote has _NO_ commits. */
1097
  if (commits == NULL) {
3×
1098
    return;
3×
1099
  }
1100

1101
  /* Get the RSA identity fingerprint of this voter */
1102
  if (crypto_pk_get_digest(voter_key, rsa_identity) < 0) {
!
1103
    return;
1104
  }
1105

1106
  SMARTLIST_FOREACH_BEGIN(commits, sr_commit_t *, commit) {
!
1107
    /* We won't need the commit in this list anymore, kept or not. */
1108
    SMARTLIST_DEL_CURRENT(commits, commit);
!
1109
    /* Check if this commit is valid and should be stored in our state. */
1110
    if (!should_keep_commit(commit, rsa_identity,
!
1111
                            sr_state_get_phase())) {
1112
      sr_commit_free(commit);
!
1113
      continue;
!
1114
    }
1115
    /* Ok, we have a valid commit now that we are about to put in our state.
1116
     * so flag it valid from now on. */
1117
    commit->valid = 1;
!
1118
    /* Everything lines up: save this commit to state then! */
1119
    save_commit_to_state(commit);
!
1120
  } SMARTLIST_FOREACH_END(commit);
!
1121
}
1122

1123
/* Return a heap-allocated string containing commits that should be put in
1124
 * the votes. It's the responsibility of the caller to free the string.
1125
 * This always return a valid string, either empty or with line(s). */
1126
char *
1127
sr_get_string_for_vote(void)
28×
1128
{
1129
  char *vote_str = NULL;
28×
1130
  digestmap_t *state_commits;
1131
  smartlist_t *chunks = smartlist_new();
28×
1132
  const or_options_t *options = get_options();
28×
1133

1134
  /* Are we participating in the protocol? */
1135
  if (!options->AuthDirSharedRandomness) {
28×
1136
    goto end;
1137
  }
1138

1139
  log_debug(LD_DIR, "SR: Preparing our vote info:");
28×
1140

1141
  /* First line, put in the vote the participation flag. */
1142
  {
1143
    char *sr_flag_line;
1144
    tor_asprintf(&sr_flag_line, "%s\n", sr_flag_ns_str);
28×
1145
    smartlist_add(chunks, sr_flag_line);
28×
1146
  }
1147

1148
  /* In our vote we include every commitment in our permanent state. */
1149
  state_commits = sr_state_get_commits();
28×
1150
  smartlist_t *state_commit_vote_lines = smartlist_new();
28×
1151
  DIGESTMAP_FOREACH(state_commits, key, const sr_commit_t *, commit) {
29×
1152
    char *line = get_vote_line_from_commit(commit, sr_state_get_phase());
1×
1153
    smartlist_add(state_commit_vote_lines, line);
1×
1154
  } DIGESTMAP_FOREACH_END;
1155

1156
  /* Sort the commit strings by version (string, not numeric), algorithm,
1157
   * and fingerprint. This makes sure the commit lines in votes are in a
1158
   * recognisable, stable order. */
1159
  smartlist_sort_strings(state_commit_vote_lines);
28×
1160

1161
  /* Now add the sorted list of commits to the vote */
1162
  smartlist_add_all(chunks, state_commit_vote_lines);
28×
1163
  smartlist_free(state_commit_vote_lines);
28×
1164

1165
  /* Add the SRV value(s) if any. */
1166
  {
1167
    char *srv_lines = get_ns_str_from_sr_values(sr_state_get_previous_srv(),
28×
1168
                                                sr_state_get_current_srv());
1169
    if (srv_lines) {
28×
1170
      smartlist_add(chunks, srv_lines);
1×
1171
    }
1172
  }
1173

1174
 end:
1175
  vote_str = smartlist_join_strings(chunks, "", 0, NULL);
28×
1176
  SMARTLIST_FOREACH(chunks, char *, s, tor_free(s));
28×
1177
  smartlist_free(chunks);
28×
1178
  return vote_str;
28×
1179
}
1180

1181
/* Return a heap-allocated string that should be put in the consensus and
1182
 * contains the shared randomness values. It's the responsibility of the
1183
 * caller to free the string. NULL is returned if no SRV(s) available.
1184
 *
1185
 * This is called when a consensus (any flavor) is bring created thus it
1186
 * should NEVER change the state nor the state should be changed in between
1187
 * consensus creation.
1188
 *
1189
 * <b>num_srv_agreements</b> is taken from the votes thus the voted value
1190
 * that should be used.
1191
 * */
1192
char *
1193
sr_get_string_for_consensus(const smartlist_t *votes,
24×
1194
                            int32_t num_srv_agreements)
1195
{
1196
  char *srv_str;
1197
  const or_options_t *options = get_options();
24×
1198

1199
  tor_assert(votes);
24×
1200

1201
  /* Not participating, avoid returning anything. */
1202
  if (!options->AuthDirSharedRandomness) {
24×
1203
    log_info(LD_DIR, "SR: Support disabled (AuthDirSharedRandomness %d)",
!
1204
             options->AuthDirSharedRandomness);
1205
    goto end;
!
1206
  }
1207

1208
  /* Set the global value of AuthDirNumSRVAgreements found in the votes. */
1209
  num_srv_agreements_from_vote = num_srv_agreements;
24×
1210

1211
  /* Check the votes and figure out if SRVs should be included in the final
1212
   * consensus. */
1213
  sr_srv_t *prev_srv = get_majority_srv_from_votes(votes, 0);
24×
1214
  sr_srv_t *cur_srv = get_majority_srv_from_votes(votes, 1);
24×
1215
  srv_str = get_ns_str_from_sr_values(prev_srv, cur_srv);
24×
1216
  if (!srv_str) {
24×
1217
    goto end;
1218
  }
1219

1220
  return srv_str;
!
1221
 end:
1222
  return NULL;
1223
}
1224

1225
/* We just computed a new <b>consensus</b>. Update our state with the SRVs
1226
 * from the consensus (might be NULL as well). Register the SRVs in our SR
1227
 * state and prepare for the upcoming protocol round. */
1228
void
1229
sr_act_post_consensus(const networkstatus_t *consensus)
1×
1230
{
1231
  const or_options_t *options = get_options();
1×
1232

1233
  /* Don't act if our state hasn't been initialized. We can be called during
1234
   * boot time when loading consensus from disk which is prior to the
1235
   * initialization of the SR subsystem. We also should not be doing
1236
   * anything if we are _not_ a directory authority and if we are a bridge
1237
   * authority. */
1238
  if (!sr_state_is_initialized() || !authdir_mode_v3(options) ||
1×
1239
      authdir_mode_bridge(options)) {
!
1240
    return;
1×
1241
  }
1242

1243
  /* Set the majority voted SRVs in our state even if both are NULL. It
1244
   * doesn't matter this is what the majority has decided. Obviously, we can
1245
   * only do that if we have a consensus. */
1246
  if (consensus) {
!
1247
    /* Start by freeing the current SRVs since the SRVs we believed during
1248
     * voting do not really matter. Now that all the votes are in, we use the
1249
     * majority's opinion on which are the active SRVs. */
1250
    sr_state_clean_srvs();
!
1251
    /* Reset the fresh flag of the SRV so we know that from now on we don't
1252
     * have a new SRV to vote for. We just used the one from the consensus
1253
     * decided by the majority. */
1254
    sr_state_unset_fresh_srv();
!
1255
    /* Set the SR values from the given consensus. */
1256
    sr_state_set_previous_srv(srv_dup(consensus->sr_info.previous_srv));
!
1257
    sr_state_set_current_srv(srv_dup(consensus->sr_info.current_srv));
!
1258
  }
1259

1260
  /* Prepare our state so that it's ready for the next voting period. */
1261
  sr_state_update(voting_schedule_get_next_valid_after_time());
!
1262
}
1263

1264
/* Initialize shared random subsystem. This MUST be called early in the boot
1265
 * process of tor. Return 0 on success else -1 on error. */
1266
int
1267
sr_init(int save_to_disk)
6×
1268
{
1269
  return sr_state_init(save_to_disk, 1);
6×
1270
}
1271

1272
/* Save our state to disk and cleanup everything. */
1273
void
1274
sr_save_and_cleanup(void)
!
1275
{
1276
  sr_state_save();
!
1277
  sr_cleanup();
!
1278
}
1279

1280
#ifdef TOR_UNIT_TESTS
1281

1282
/* Set the global value of number of SRV agreements so the test can play
1283
 * along by calling specific functions that don't parse the votes prior for
1284
 * the AuthDirNumSRVAgreements value. */
1285
void
1286
set_num_srv_agreements(int32_t value)
2×
1287
{
1288
  num_srv_agreements_from_vote = value;
2×
1289
}
2×
1290

1291
#endif /* defined(TOR_UNIT_TESTS) */
Troubleshooting · Open an Issue · Sales · Support · ENTERPRISE · CAREERS · STATUS
BLOG · TWITTER · Legal & Privacy · Supported CI Services · What's a CI service? · Automated Testing

© 2021 Coveralls, Inc