vote.html 20.2 KB
Newer Older
1
2
3
4
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8" />
Stephane Glondu's avatar
Stephane Glondu committed
5
  <title>Belenios Voting Booth</title>
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  <link rel="stylesheet" type="text/css" href="css/booth.css" />
  <link rel="stylesheet" type="text/css" href="css/forms.css" />
  <script language="javascript" src="js/jscrypto/class.js"></script>
  <script language="javascript" src="js/jscrypto/bigint.dummy.js"></script>
  <script language="javascript" src="js/jscrypto/jsbn.js"></script>
  <script language="javascript" src="js/jscrypto/jsbn2.js"></script>
  <script language="javascript" src="js/jscrypto/sjcl.js"></script>
  <script language="javascript" src="js/underscore-min.js"></script>
  <script language="javascript" src="js/jquery-1.2.2.min.js"></script>
  <script language="javascript" src="js/jquery.query-2.1.5.js"></script>
  <script language="javascript" src="js/jquery-jtemplates.js"></script>
  <script language="javascript" src="js/jquery.json.min.js"></script>

  <script language="javascript">
    // required for jscrypto library
    var JSCRYPTO_HOME = document.location.pathname.replace("vote.html", "js/jscrypto");
  </script>

  <script language="javascript" src="js/jscrypto/class.js"></script>
  <script language="javascript" src="js/jscrypto/bigint.js?d=20111004"></script>
  <!-- this script is a dummy wrapper for bigint when client-side crypto is not possible
  <script language="javascript" src="js/jscrypto/bigint.dummy.js"></script>-->
  <script language="javascript" src="js/jscrypto/random.js"></script>
  <script language="javascript" src="js/jscrypto/elgamal.js?d=20111004"></script>
  <script language="javascript" src="js/jscrypto/sha2.js"></script>
  <script language="javascript" src="js/jscrypto/helios.js?d=20111004"></script>
32
  <script language="javascript" src="js/jscrypto/heliosc-booth.js?d=20130201"></script>
33
34
35
36
</head>
<body>
<div id="wrapper">
<span style="float:right; padding: 7px 15px 5px 10px;">[<a href="javascript:BOOTH.exit();">exit</a>]</span>
Stephane Glondu's avatar
Stephane Glondu committed
37
<div id="banner">Belenios Voting Booth</div>
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<div id="content">

<div id="header">
</div>

<script language="javascript">
// utils
BOOTH = {};

BOOTH.setup_templates = function() {
    if (BOOTH.templates_setup_p)
        return;

    var cache_bust = "?cb=" + new Date().getTime();

    $('#header').setTemplateURL("templates/header.html" + cache_bust);
    $('#election_div').setTemplateURL("templates/election.html" + cache_bust);
    $('#question_div').setTemplateURL("templates/question.html" + cache_bust);
    $('#confirm_div').setTemplateURL("templates/confirm.html" + cache_bust);
    $('#seal_div').setTemplateURL("templates/seal.html" + cache_bust);
    $('#footer').setTemplateURL("templates/footer.html" + cache_bust);

    BOOTH.templates_setup_p = true;
};

// set up the message when navigating away
BOOTH.started_p = false;

window.onbeforeunload = function(evt) {
  if (!BOOTH.started_p)
    return;

  if (typeof evt == 'undefined') {
    evt = window.event;
  }

  var message = "If you leave this page with an in-progress ballot, your ballot will be lost.";

  if (evt) {
    evt.returnValue = message;
  }

  return message;
};

BOOTH.exit = function() {
    if (confirm("Are you sure you want to exit the booth and lose all information about your current ballot?")) {
        BOOTH.started_p = false;
86
        window.location = BOOTH.election_url;
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
    }
};

BOOTH.setup_ballot = function(election) {
  BOOTH.ballot = {};

  // dirty markers for encryption (mostly for async)
  BOOTH.dirty = [];

  // each question starts out with an empty array answer
  // and a dirty bit to make sure we encrypt
  BOOTH.ballot.answers = [];
  $(BOOTH.election.questions).each(function(i,x){
    BOOTH.ballot.answers[i] = [];
    BOOTH.dirty[i] = true;
  });
};

// all ciphertexts to null
BOOTH.reset_ciphertexts = function() {
  _(BOOTH.encrypted_answers).each(function(enc_answer, ea_num) {
    BOOTH.launch_async_encryption_answer(ea_num);
  });
};

BOOTH.log = function(msg) {
  if (typeof(console) != undefined)
    console.log(msg);
};

BOOTH.setup_workers = function(election_raw_json) {
  // async?
  if (!BOOTH.synchronous) {
      // prepare spots for encrypted answers
      // and one worker per question
      BOOTH.encrypted_answers = [];
      BOOTH.answer_timestamps = [];
      BOOTH.workers = [];
      $(BOOTH.election.questions).each(function(q_num, q) {
        BOOTH.encrypted_answers[q_num] = null;
        var new_worker = new window.Worker("boothworker.js");
        new_worker.postMessage({
          'type': 'setup',
          'election' : election_raw_json,
          'question_num' : q_num
        });

        new_worker.onmessage = function(event) {
           // logging
           if (event.data.type == 'log')
             return BOOTH.log(event.data.msg);

           // result of encryption
           if (event.data.type == 'result') {
             // this check ensures that race conditions
             // don't screw up votes.
             if (event.data.id == BOOTH.answer_timestamps[q_num]) {
                BOOTH.encrypted_answers[q_num] = HELIOS.EncryptedAnswer.fromJSONObject(event.data.encrypted_answer, BOOTH.election);
                BOOTH.log("got encrypted answer " + q_num);
             } else {
                BOOTH.log("no way jose");
             }
           }
        };

        BOOTH.workers[q_num] = new_worker;
      });
  }
};

function escape_html(content) {
  return $('<div/>').text(content).html();
}

BOOTH.setup_election = function(raw_json) {
  // IMPORTANT: we use the raw JSON for safer hash computation
  // so that we are using the JSON serialization of the SERVER
  // to compute the hash, not the JSON serialization in JavaScript.
  // the main reason for this is unicode representation: the Python approach
  // appears to be safer.
  BOOTH.election = HELIOS.Election.fromJSONString(raw_json);
168
  BOOTH.election.cast_url = BOOTH.election_url + "cast"
169
170
171
172
173

  // FIXME: we shouldn't need to set both, but right now we are doing so
  // because different code uses each one. Bah. Need fixing.
  BOOTH.election.hash = b64_sha256(raw_json);
  BOOTH.election.election_hash = BOOTH.election.hash
174
  BOOTH.derive_key = heliosc.booth.derive_key(BOOTH.election);
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207

  // async?
  BOOTH.setup_workers(raw_json);

  document.title += ' - ' + BOOTH.election.name;

  // escape election fields
  $(['description', 'name']).each(function(i, field) {
    BOOTH.election[field] = escape_html(BOOTH.election[field]);
  });

  $('#header').processTemplate({'election' : BOOTH.election});
  $('#footer').processTemplate({'election' : BOOTH.election});
  BOOTH.setup_ballot();
};

BOOTH.show = function(el) {
  $('.panel').hide();
  el.show();
  return el;
};

BOOTH.show_election = function() {
  BOOTH.show($('#election_div')).processTemplate({'election' : BOOTH.election});
};

BOOTH.launch_async_encryption_answer = function(question_num) {
   BOOTH.answer_timestamps[question_num] = new Date().getTime();
   BOOTH.encrypted_answers[question_num] = null;
   BOOTH.dirty[question_num] = false;
   BOOTH.workers[question_num].postMessage({
      'type' : 'encrypt',
      'answer' : BOOTH.ballot.answers[question_num],
208
      'zkp' : BOOTH.zkp,
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
      'id' : BOOTH.answer_timestamps[question_num]
   });
};

// check if the current question is ok
BOOTH.validate_question = function(question_num) {
    // check if enough answers are checked
    if (BOOTH.ballot.answers[question_num].length < BOOTH.election.questions[question_num].min) {
        alert('You need to select at least ' + BOOTH.election.questions[question_num].min + ' answer(s).');
        return false;
    }

    // if we need to launch the worker, let's do it
    if (!BOOTH.synchronous) {
       // we need a unique ID for this to ensure that old results
       // don't mess things up. Using timestamp.
       // check if dirty
       if (BOOTH.dirty[question_num]) {
         BOOTH.launch_async_encryption_answer(question_num);
       }
    }
    return true;
};

BOOTH.validate_and_confirm = function(question_num) {
  if (BOOTH.validate_question(question_num)) {
      BOOTH.show_confirm();
  }
};

BOOTH.next = function(question_num) {
    if (BOOTH.validate_question(question_num)) {
        BOOTH.show_question(question_num + 1);
    }
};

BOOTH.previous = function(question_num) {
    if (BOOTH.validate_question(question_num)) {
        BOOTH.show_question(question_num - 1);
    }
};

BOOTH.show_question = function(question_num) {
  BOOTH.started_p = true;

  // the first time we hit the last question, we enable the review all button
  if (question_num == BOOTH.election.questions.length -1)
    BOOTH.all_questions_seen = true;

  BOOTH.show_progress('1');
  BOOTH.show($('#question_div')).processTemplate({'question_num' : question_num,
                      'last_question_num' : BOOTH.election.questions.length - 1,
                      'question' : BOOTH.election.questions[question_num], 'show_reviewall' : BOOTH.all_questions_seen
                });

  // fake clicking through the answers, to trigger the disabling if need be
  // first we remove the answers array
  var answer_array = BOOTH.ballot.answers[question_num];
  BOOTH.ballot.answers[question_num] = [];

  // we should not set the dirty bit here, so we save it away
  var old_dirty = BOOTH.dirty[question_num];
  $(answer_array).each(function(i, ans) {
    BOOTH.click_checkbox_script(question_num, ans, true);
  });
  BOOTH.dirty[question_num] = old_dirty;
};



BOOTH.click_checkbox_script = function(question_num, answer_num) {
  document.forms['answer_form']['answer_'+question_num+'_'+answer_num].click();
};

BOOTH.click_checkbox = function(question_num, answer_num, checked_p) {
  // keep track of dirty answers that need encrypting
  BOOTH.dirty[question_num] = true;

  if (checked_p) {
     // multiple click events shouldn't screw this up
     if ($(BOOTH.ballot.answers[question_num]).index(answer_num) == -1)
        BOOTH.ballot.answers[question_num].push(answer_num);

     $('#answer_label_' + question_num + "_" + answer_num).addClass('selected');
  } else {
     BOOTH.ballot.answers[question_num] = UTILS.array_remove_value(BOOTH.ballot.answers[question_num], answer_num);
     $('#answer_label_' + question_num + "_" + answer_num).removeClass('selected');
  }

  if (BOOTH.election.questions[question_num].max != null && BOOTH.ballot.answers[question_num].length >= BOOTH.election.questions[question_num].max) {
     // disable the other checkboxes
     $('.ballot_answer').each(function(i, checkbox) {
        if (!checkbox.checked)
            checkbox.disabled = true;
     });
     $('#warning_box').html("Maximum number of options selected.<br />To change your selection, please de-select a current selection first.");
  } else {
     // enable the other checkboxes
     $('.ballot_answer').each(function(i, checkbox) {
       checkbox.disabled = false;
     });
     $('#warning_box').html("");
  }
};

BOOTH.show_processing_before = function(str_to_execute) {
    $('#processing_div').html("<h3 align='center'>Processing...</h3>");
    BOOTH.show($('#processing_div'));

    // add a timeout so browsers like Safari actually display the processing message
    setTimeout(str_to_execute, 250);
};

BOOTH.show_encryption_message_before = function(func_to_execute) {
    BOOTH.show($('#encrypting_div'));

    func_to_execute();
};

BOOTH.load_and_setup_election = function(election_url) {
329
    BOOTH.election_url = election_url
330

331
    // the hash will be computed within the setup function call now
332
    $.get(election_url + "election.json", function(raw_json) {
333
        raw_json = raw_json.trim();
334
335
336
337
338
339
340
341
        BOOTH.setup_election(raw_json);
        BOOTH.show_election();
        BOOTH.election_url = election_url;
    });


    if (USE_SJCL) {
      // get more randomness from server
342
      $.getJSON("../get-randomness", {}, function(result) {
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
        sjcl.random.addEntropy(result.randomness);
      });
    }
};

BOOTH.hide_progress = function() {
  $('#progress_div').hide();
};

BOOTH.show_progress = function(step_num) {
    $('#progress_div').show();
    $(['1','2','3','4']).each(function(n, step) {
        if (step == step_num)
            $('#progress_' + step).attr('class', 'selected');
        else
            $('#progress_' + step).attr('class', 'unselected');
    });
};

BOOTH.so_lets_go = function () {
    BOOTH.hide_progress();

    BOOTH.setup_templates();

    // election URL
    var election_url = $.query.get('election_url');
    BOOTH.load_and_setup_election(election_url);
};

BOOTH.nojava = function() {
  // in the case of Chrome, we get here when Java
  // is disabled, instead of detecting the problem earlier.
  // because navigator.javaEnabled() still returns true.
  // $('#election_div').hide();
  // $('#error_div').show();
    USE_SJCL = true;
    sjcl.random.startCollectors();
    BigInt.setup(BOOTH.so_lets_go);
};

BOOTH.ready_p = false;

$(document).ready(function() {
    if (USE_SJCL) {
      sjcl.random.startCollectors();
    }

    // we're asynchronous if we have SJCL and Worker
    BOOTH.synchronous = !(USE_SJCL && window.Worker);

    // we do in the browser only if it's asynchronous
    BigInt.in_browser = !BOOTH.synchronous;

    // set up dummy bigint for fast parsing and serialization
    if (!BigInt.in_browser)
      BigInt = BigIntDummy;

    BigInt.setup(BOOTH.so_lets_go, BOOTH.nojava);
});

BOOTH.show_confirm = function() {
    // process the answers
    var choices = BALLOT.pretty_choices(BOOTH.election, BOOTH.ballot);

    BOOTH.show($('#confirm_div')).processTemplate({'questions' : BOOTH.election.questions, 'choices' : choices});
};

BOOTH.check_encryption_status = function() {
  var progress = BOOTH.progress.progress();
  if (progress == "" || progress == null)
    progress = "0";

  $('#percent_done').html(progress);
};

BOOTH._after_ballot_encryption = function() {
    // if already serialized, use that, otherwise serialize
    BOOTH.encrypted_vote_json = BOOTH.encrypted_ballot_serialized || JSON.stringify(BOOTH.encrypted_ballot.toJSONObject());

    var do_hash = function() {
Stephane Glondu's avatar
Stephane Glondu committed
423
       BOOTH.encrypted_ballot_hash = b64_sha256(BOOTH.encrypted_vote_json); // BOOTH.encrypted_ballot.get_hash();
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
       window.setTimeout(show_cast, 0);
    };

    var show_cast = function() {
      $('#seal_div').processTemplate({'cast_url': BOOTH.election.cast_url,
        'encrypted_vote_json': BOOTH.encrypted_vote_json,
        'encrypted_vote_hash' : BOOTH.encrypted_ballot_hash,
        'election_uuid' : BOOTH.election.uuid,
        'election_hash' : BOOTH.election_hash,
        'election': BOOTH.election});
      BOOTH.show($('#seal_div'));
      BOOTH.show_progress('3');
      BOOTH.encrypted_vote_json = null;
    };

    window.setTimeout(do_hash, 0);
};

BOOTH.total_cycles_waited = 0;

// wait for all workers to be done
BOOTH.wait_for_ciphertexts = function() {
    BOOTH.total_cycles_waited += 1;

    var answers_done = _.reject(BOOTH.encrypted_answers, _.isNull);
    var percentage_done = Math.round((100 * answers_done.length) / BOOTH.encrypted_answers.length);

    if (BOOTH.total_cycles_waited > 250) {
      alert('there appears to be a problem with the encryption process.\nPlease email help@heliosvoting.org and indicate that your encryption process froze at ' + percentage_done + '%');
      return;
    }

    if (percentage_done < 100) {
      setTimeout(BOOTH.wait_for_ciphertexts, 500);
      $('#percent_done').html(percentage_done + '');
      return;
    }

    BOOTH.encrypted_ballot = HELIOS.EncryptedVote.fromEncryptedAnswers(BOOTH.election, BOOTH.encrypted_answers);
463
    BOOTH.encrypted_ballot.doSignature(BOOTH.credential);
464
465
466
467
468
469
470
471

    BOOTH._after_ballot_encryption();
};

BOOTH.seal_ballot_raw = function() {
    if (BOOTH.synchronous) {
      BOOTH.progress = new UTILS.PROGRESS();
      var progress_interval = setInterval("BOOTH.check_encryption_status()", 500);
472
      BOOTH.encrypted_ballot = new HELIOS.EncryptedVote(BOOTH.election, BOOTH.ballot.answers, BOOTH.zkp, BOOTH.progress);
473
      BOOTH.encrypted_ballot.doSignature(BOOTH.credential);
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
      clearInterval(progress_interval);
      BOOTH._after_ballot_encryption();
    } else {
      BOOTH.total_cycles_waited = 0;
      BOOTH.wait_for_ciphertexts();
    }
};

BOOTH.request_ballot_encryption = function() {
    $.post(BOOTH.election_url + "/encrypt-ballot", {'answers_json': $.toJSON(BOOTH.ballot.answers)}, function(result) {
      //BOOTH.encrypted_ballot = HELIOS.EncryptedVote.fromJSONObject($.secureEvalJSON(result), BOOTH.election);
      // rather than deserialize and reserialize, which is inherently slow on browsers
      // that already need to do network requests, just remove the plaintexts

      BOOTH.encrypted_ballot_with_plaintexts_serialized = result;
      var ballot_json_obj = $.secureEvalJSON(BOOTH.encrypted_ballot_with_plaintexts_serialized);
      var answers = ballot_json_obj.answers;
      for (var i=0; i<answers.length; i++) {
         delete answers[i]['answer'];
         delete answers[i]['randomness'];
      }

      BOOTH.encrypted_ballot_serialized = JSON.stringify(ballot_json_obj);

      window.setTimeout(BOOTH._after_ballot_encryption, 0);
    });
};

BOOTH.seal_ballot = function() {
    BOOTH.show_progress('2');

    // if we don't have the ability to do crypto in the browser,
    // we use the server
    if (!BigInt.in_browser) {
      BOOTH.show_encryption_message_before(BOOTH.request_ballot_encryption, true);
    } else {
      BOOTH.show_encryption_message_before(BOOTH.seal_ballot_raw, true);
      $('#percent_done_container').show();
    }
};

BOOTH.cast_ballot = function() {
    // show progress spinner
    $('#loading_div').html('<img src="loading.gif" id="proceed_loading_img" />');
    $('#proceed_button').attr('disabled', 'disabled');

    // at this point, we delete the plaintexts by resetting the ballot
    BOOTH.setup_ballot(BOOTH.election);

    // clear the plaintext from the encrypted
    if (BOOTH.encrypted_ballot)
       BOOTH.encrypted_ballot.clearPlaintexts();

    BOOTH.encrypted_ballot_serialized = null;
    BOOTH.encrypted_ballot_with_plaintexts_serialized = null;

    // we're ready to leave the site
    BOOTH.started_p = false;

    // submit the form
    $('#send_ballot_form').submit();
};

BOOTH.show_receipt = function() {
    UTILS.open_window_with_content("Your smart ballot tracker for " + BOOTH.election.name + ": " + BOOTH.encrypted_ballot_hash);
};

BOOTH.do_done = function() {
  BOOTH.started_p = false;
};

545
546
BOOTH.ask_token = function () {
    try {
547
        var token = window.prompt("Please enter your credential:");
548
        BOOTH.credential = BOOTH.derive_key(token);
549
        BOOTH.zkp = BOOTH.credential.y.toString();
550
551
552
553
554
555
        BOOTH.show_question(0);
    } catch (e) {
        window.alert(e);
    }
};

Stephane Glondu's avatar
Stephane Glondu committed
556
557
558
559
function save_ballot() {
    UTILS.open_window_with_content($('#send_ballot_form')[0].elements[0].value, "application/json");
}

560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
</script>
<div id="page">
  <div id="progress_div" style="display:none; width: 500px; margin:auto;">
      <table width="100%">
          <tr><td id="progress_1">(1) Select</td><td id="progress_2">(2) Encrypt</td><td id="progress_3">(3) Submit</td></tr>
      </table>
  </div>
  <div id="election_div" class="panel">
    <h3>Checking capabilities and loading election booth...</h3>
    <div align="center"><img src="loading.gif" /><br />This may take up to 10 seconds</div>
  </div>

  <div id="error_div" class="panel" style="display: none;">
    <h3>There's a problem</h3>
    <p>
Stephane Glondu's avatar
Stephane Glondu committed
575
      It appears that your browser does not have Java enabled. The booth needs Java to perform encryption within the browser.
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
    </p>
    <p>
      You may be able to install Java by visiting <a target="_new" href="http://java.com">java.com</a>.
    </p>
  </div>

  <div id="question_div" class="panel">
  </div>

  <div id="confirm_div" class="panel">
  </div>

  <div id="processing_div" class="panel" style="display:none;">
      <h3 align="center">Processing....</h3>
  </div>

  <div id="encrypting_div" class="panel" style="display:none;">
Stephane Glondu's avatar
Stephane Glondu committed
593
      <h3 align="center">The booth is now encrypting your ballot<br />
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
          <img src="encrypting.gif" /> <span style="font-size:0.7em; display:none;" id="percent_done_container">(<span id="percent_done">0</span>%)</span></h3>

      <p align="center"><b>This may take up to two minutes.</b>
  </div>

  <div id="seal_div" class="panel">
  </div>

</div>

<br clear="both" />
</div>
<div id="footer">&nbsp;</div>
</div>
<div id="applet_div">
</div>
</body>
</html>