web_site.ml 51.4 KB
Newer Older
Stephane Glondu's avatar
Stephane Glondu committed
1 2 3
(**************************************************************************)
(*                                BELENIOS                                *)
(*                                                                        *)
Stephane Glondu's avatar
Stephane Glondu committed
4
(*  Copyright © 2012-2014 Inria                                           *)
Stephane Glondu's avatar
Stephane Glondu committed
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
(*                                                                        *)
(*  This program is free software: you can redistribute it and/or modify  *)
(*  it under the terms of the GNU Affero General Public License as        *)
(*  published by the Free Software Foundation, either version 3 of the    *)
(*  License, or (at your option) any later version, with the additional   *)
(*  exemption that compiling, linking, and/or using OpenSSL is allowed.   *)
(*                                                                        *)
(*  This program is distributed in the hope that it will be useful, but   *)
(*  WITHOUT ANY WARRANTY; without even the implied warranty of            *)
(*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU     *)
(*  Affero General Public License for more details.                       *)
(*                                                                        *)
(*  You should have received a copy of the GNU Affero General Public      *)
(*  License along with this program.  If not, see                         *)
(*  <http://www.gnu.org/licenses/>.                                       *)
(**************************************************************************)

22
open Lwt
23
open Platform
24
open Serializable_j
25
open Signatures
26
open Common
Stephane Glondu's avatar
Stephane Glondu committed
27
open Web_serializable_j
28
open Web_common
29
open Web_signatures
30
open Web_services
Stephane Glondu's avatar
Stephane Glondu committed
31

32
let source_file = ref "belenios.tar.gz"
Stephane Glondu's avatar
Stephane Glondu committed
33

34 35
let ( / ) = Filename.concat

Stephane Glondu's avatar
Stephane Glondu committed
36
module PString = String
Stephane Glondu's avatar
Stephane Glondu committed
37

Stephane Glondu's avatar
Stephane Glondu committed
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
open Eliom_service
open Eliom_registration

module LwtRandom = MakeLwtRandom (struct let rng = make_rng () end)

(* Table with elections in setup mode. *)
let election_stable = Ocsipersist.open_table "site_setup"

(* Table with tokens given to trustees. *)
let election_pktokens = Ocsipersist.open_table "site_pktokens"

(* Table with tokens given to credential authorities. *)
let election_credtokens = Ocsipersist.open_table "site_credtokens"

module T = Web_templates

54 55
let web_election_data (raw_election, web_params) =
  let params = Group.election_params_of_string raw_election in
Stephane Glondu's avatar
Stephane Glondu committed
56
  let module D = struct
Stephane Glondu's avatar
Stephane Glondu committed
57
    include (val params : ELECTION_DATA)
58
    include (val web_params : WEB_PARAMS)
Stephane Glondu's avatar
Stephane Glondu committed
59
  end in
60 61
  (module D : WEB_ELECTION_DATA)

Stephane Glondu's avatar
Stephane Glondu committed
62
let raw_find_election uuid =
63 64 65 66 67 68 69 70 71 72 73
  lwt raw_election = Web_persist.get_raw_election uuid in
  lwt metadata = Web_persist.get_election_metadata uuid in
  match raw_election, metadata with
  | Some raw_election, Some metadata ->
     let module P = struct
       let dir = !spool_dir / uuid
       let metadata = metadata
     end in
     let web_params = (module P : WEB_PARAMS) in
     return (web_election_data (raw_election, web_params))
  | _, _ -> Lwt.fail Not_found
Stephane Glondu's avatar
Stephane Glondu committed
74

Stephane Glondu's avatar
Stephane Glondu committed
75 76 77 78 79 80 81 82 83 84 85
module WCacheTypes = struct
  type key = string
  type value = (module WEB_ELECTION_DATA)
end

module WCache = Ocsigen_cache.Make (WCacheTypes)

let find_election =
  let cache = new WCache.cache raw_find_election 100 in
  fun x -> cache#find x

Stephane Glondu's avatar
Stephane Glondu committed
86
let dump_passwords dir table =
Stephane Glondu's avatar
Stephane Glondu committed
87 88 89 90 91 92
  Lwt_io.(with_file Output (dir / "passwords.csv") (fun oc ->
    Ocsipersist.iter_step (fun voter (salt, hashed) ->
      write_line oc (voter ^ "," ^ salt ^ "," ^ hashed)
    ) table
  ))

93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
let finalize_election uuid se =
  let uuid_s = Uuidm.to_string uuid in
  (* voters *)
  let () =
    if se.se_voters = [] then failwith "no voters"
  in
  (* passwords *)
  let () =
    match se.se_metadata.e_auth_config with
    | Some [{auth_system = "password"; _}] ->
       if not @@ List.for_all (fun v -> v.sv_password <> None) se.se_voters then
         failwith "some passwords are missing"
    | _ -> ()
  in
  (* credentials *)
  let () =
    if not se.se_public_creds_received then
      failwith "public credentials are missing"
  in
  (* trustees *)
  let group = Group.of_string se.se_group in
  let module G = (val group : GROUP) in
  let module KG = Election.MakeSimpleDistKeyGen (G) (LwtRandom) in
116
  lwt trustees, public_keys, private_key =
117 118 119
    match se.se_public_keys with
    | [] ->
       lwt private_key, public_key = KG.generate_and_prove () in
120
       return (None, [public_key], Some private_key)
121
    | _ :: _ ->
122 123 124
       return (
         Some (List.map (fun {st_id; _} -> st_id) se.se_public_keys),
         (List.map
125 126 127
            (fun {st_public_key; _} ->
              if st_public_key = "" then failwith "some public keys are missing";
              trustee_public_key_of_string G.read st_public_key
128 129
            ) se.se_public_keys),
         None)
130 131 132
  in
  let y = KG.combine (Array.of_list public_keys) in
  (* election parameters *)
133
  let metadata = { se.se_metadata with e_trustees = trustees } in
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
  let template = se.se_questions in
  let params = {
    e_description = template.t_description;
    e_name = template.t_name;
    e_public_key = {wpk_group = G.group; wpk_y = y};
    e_questions = template.t_questions;
    e_uuid = uuid;
    e_short_name = template.t_short_name;
  } in
  let raw_election = string_of_params (write_wrapped_pubkey G.write_group G.write) params in
  (* write election files to disk *)
  let dir = !spool_dir / uuid_s in
  let create_file fname what xs =
    Lwt_io.with_file
      ~flags:(Unix.([O_WRONLY; O_NONBLOCK; O_CREAT; O_TRUNC]))
      ~perm:0o600 ~mode:Lwt_io.Output (dir / fname)
      (fun oc ->
        Lwt_list.iter_s
          (fun v ->
            Lwt_io.write oc (what v) >>
              Lwt_io.write oc "\n") xs)
  in
  Lwt_unix.mkdir dir 0o700 >>
  create_file "public_keys.jsons" (string_of_trustee_public_key G.write) public_keys >>
  create_file "voters.txt" (fun x -> x.sv_id) se.se_voters >>
159
  create_file "metadata.json" string_of_metadata [metadata] >>
160 161 162
  create_file "election.json" (fun x -> x) [raw_election] >>
  (* construct Web_election instance *)
  let module X = struct
163
    let metadata = metadata
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
    let dir = dir
  end in
  let web_params = (module X : WEB_PARAMS) in
  let election = web_election_data (raw_election, web_params) in
  let module W = Web_election.Make ((val election)) (LwtRandom) in
  (* set up authentication *)
  lwt () =
    match W.D.metadata.e_auth_config with
    | None -> return ()
    | Some xs ->
       let auth_config =
         List.map (fun {auth_system; auth_instance; auth_config} ->
           auth_instance, (auth_system, List.map snd auth_config)
         ) xs
       in
       Web_persist.set_auth_config uuid_s auth_config
  in
  (* inject credentials *)
  lwt () =
    let fname = !spool_dir / uuid_s ^ ".public_creds.txt" in
    Lwt_io.lines_of_file fname |>
    Lwt_stream.iter_s W.B.inject_cred >>
    W.B.update_files () >>
    Lwt_unix.unlink fname
  in
  (* create file with private key, if any *)
  lwt () =
    match private_key with
    | None -> return_unit
    | Some x -> create_file "private_key.json" string_of_number [x]
  in
  (* clean up setup database *)
  Ocsipersist.remove election_credtokens se.se_public_creds >>
  Lwt_list.iter_s
198 199
    (fun {st_token; _} ->
      Ocsipersist.remove election_pktokens st_token)
200 201 202
    se.se_public_keys >>
  Ocsipersist.remove election_stable uuid_s >>
  (* inject passwords *)
203
  (match metadata.e_auth_config with
204 205 206 207 208 209 210 211 212 213 214 215 216
  | Some [{auth_system = "password"; _}] ->
     let table = "password_" ^ underscorize uuid_s in
     let table = Ocsipersist.open_table table in
     Lwt_list.iter_s
       (fun v ->
         let _, login = split_identity v.sv_id in
         match v.sv_password with
         | Some x -> Ocsipersist.add table login x
         | None -> return_unit
       ) se.se_voters >>
       dump_passwords W.D.dir table
  | _ -> return_unit) >>
  (* finish *)
Stephane Glondu's avatar
Stephane Glondu committed
217
  Web_persist.set_election_state uuid_s `Open >>
218
  Web_persist.set_election_date uuid_s (now ())
Stephane Glondu's avatar
Stephane Glondu committed
219

Stephane Glondu's avatar
Stephane Glondu committed
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
let cleanup_table ?uuid_s table =
  let table = Ocsipersist.open_table table in
  match uuid_s with
  | None ->
     lwt indexes = Ocsipersist.fold_step (fun k _ accu ->
       return (k :: accu)) table []
     in
     Lwt_list.iter_s (Ocsipersist.remove table) indexes
  | Some u -> Ocsipersist.remove table u

let cleanup_file f =
  try_lwt Lwt_unix.unlink f
  with _ -> return_unit

let archive_election uuid_s =
  let uuid_u = underscorize uuid_s in
  lwt () = cleanup_table ~uuid_s "election_states" in
  lwt () = cleanup_table ~uuid_s "election_pds" in
  lwt () = cleanup_table ~uuid_s "auth_configs" in
  lwt () = cleanup_table ("password_" ^ uuid_u) in
  lwt () = cleanup_table ("records_" ^ uuid_u) in
  lwt () = cleanup_table ("creds_" ^ uuid_u) in
  lwt () = cleanup_table ("ballots_" ^ uuid_u) in
  lwt () = cleanup_file (!spool_dir / uuid_s / "private_key.json") in
  return_unit

Stephane Glondu's avatar
Stephane Glondu committed
246 247
let () = Any.register ~service:home
  (fun () () ->
Stephane Glondu's avatar
Stephane Glondu committed
248
    Eliom_reference.unset Web_auth_state.cont >>
249
    T.home () >>= Html5.send
Stephane Glondu's avatar
Stephane Glondu committed
250 251
  )

252
let get_finalized_elections_by_owner u =
Stephane Glondu's avatar
Stephane Glondu committed
253
  lwt elections, tallied, archived =
254 255 256 257 258
    Web_persist.get_elections_by_owner u >>=
    Lwt_list.fold_left_s (fun accu uuid_s ->
        lwt w = find_election uuid_s in
        lwt state = Web_persist.get_election_state uuid_s in
        lwt date = Web_persist.get_election_date uuid_s in
Stephane Glondu's avatar
Stephane Glondu committed
259
        let elections, tallied, archived = accu in
260
        match state with
Stephane Glondu's avatar
Stephane Glondu committed
261 262 263 264
        | `Tallied _ -> return (elections, (date, w) :: tallied, archived)
        | `Archived -> return (elections, tallied, (date, w) :: archived)
        | _ -> return ((date, w) :: elections, tallied, archived)
    ) ([], [], [])
265 266 267 268 269
  in
  let sort l =
    List.sort (fun (x, _) (y, _) -> datetime_compare x y) l |>
    List.map (fun (_, x) -> x)
  in
Stephane Glondu's avatar
Stephane Glondu committed
270
  return (sort elections, sort tallied, sort archived)
271

Stephane Glondu's avatar
Stephane Glondu committed
272 273
let () = Html5.register ~service:admin
  (fun () () ->
Stephane Glondu's avatar
Stephane Glondu committed
274 275 276
    let cont () = Redirection.send admin in
    Eliom_reference.set Web_auth_state.cont [cont] >>
    lwt site_user = Web_auth_state.get_site_user () in
Stephane Glondu's avatar
Stephane Glondu committed
277
    lwt elections =
278
      match site_user with
279
      | None -> return None
Stephane Glondu's avatar
Stephane Glondu committed
280
      | Some u ->
Stephane Glondu's avatar
Stephane Glondu committed
281
         lwt elections, tallied, archived = get_finalized_elections_by_owner u in
282
         lwt setup_elections =
283 284
           Ocsipersist.fold_step (fun k v accu ->
             if v.se_owner = u
285
             then return ((uuid_of_string k, v.se_questions.t_name) :: accu)
286 287
             else return accu
           ) election_stable []
288
         in
Stephane Glondu's avatar
Stephane Glondu committed
289
         return @@ Some (elections, tallied, archived, setup_elections)
Stephane Glondu's avatar
Stephane Glondu committed
290
    in
291
    T.admin ~elections ()
Stephane Glondu's avatar
Stephane Glondu committed
292 293 294 295 296 297 298 299
  )

let () = File.register
  ~service:source_code
  ~content_type:"application/x-gzip"
  (fun () () -> return !source_file)

let do_get_randomness =
300
  let prng = Lazy.from_fun (Lwt_preemptive.detach (fun () ->
Stephane Glondu's avatar
Stephane Glondu committed
301 302 303 304 305 306 307
    pseudo_rng (random_string secure_rng 16)
  )) in
  let mutex = Lwt_mutex.create () in
  fun () ->
    Lwt_mutex.with_lock mutex (fun () ->
      lwt prng = Lazy.force prng in
      return (random_string prng 32)
308 309
    )

Stephane Glondu's avatar
Stephane Glondu committed
310 311 312 313 314 315 316 317 318 319 320
let () = String.register
  ~service:get_randomness
  (fun () () ->
    lwt r = do_get_randomness () in
    b64_encode_compact r |>
    (fun x -> string_of_randomness { randomness=x }) |>
    (fun x -> return (x, "application/json"))
  )

let generate_uuid = Uuidm.v4_gen (Random.State.make_self_init ())

Stephane Glondu's avatar
Stephane Glondu committed
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
let create_new_election owner cred auth =
  let e_cred_authority = match cred with
    | `Automatic -> Some "server"
    | `Manual -> None
  in
  let e_auth_config = match auth with
    | `Password -> Some [{auth_system = "password"; auth_instance = "password"; auth_config = []}]
    | `Dummy -> Some [{auth_system = "dummy"; auth_instance = "dummy"; auth_config = []}]
    | `CAS server -> Some [{auth_system = "cas"; auth_instance = "cas"; auth_config = ["server", server]}]
  in
  let uuid = generate_uuid () in
  let uuid_s = Uuidm.to_string uuid in
  lwt token = generate_token () in
  let se_metadata = {
    e_owner = Some owner;
    e_auth_config;
    e_cred_authority;
338
    e_trustees = None;
Stephane Glondu's avatar
Stephane Glondu committed
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
  } in
  let question = {
    q_answers = [| "Answer 1"; "Answer 2"; "Blank" |];
    q_min = 1;
    q_max = 1;
    q_question = "Question 1?";
  } in
  let se_questions = {
    t_description = "Description of the election.";
    t_name = "Name of the election";
    t_questions = [| question |];
    t_short_name = "short_name";
  } in
  let se = {
    se_owner = owner;
    se_group = "{\"g\":\"14887492224963187634282421537186040801304008017743492304481737382571933937568724473847106029915040150784031882206090286938661464458896494215273989547889201144857352611058572236578734319505128042602372864570426550855201448111746579871811249114781674309062693442442368697449970648232621880001709535143047913661432883287150003429802392229361583608686643243349727791976247247948618930423866180410558458272606627111270040091203073580238905303994472202930783207472394578498507764703191288249547659899997131166130259700604433891232298182348403175947450284433411265966789131024573629546048637848902243503970966798589660808533\",\"p\":\"16328632084933010002384055033805457329601614771185955389739167309086214800406465799038583634953752941675645562182498120750264980492381375579367675648771293800310370964745767014243638518442553823973482995267304044326777047662957480269391322789378384619428596446446984694306187644767462460965622580087564339212631775817895958409016676398975671266179637898557687317076177218843233150695157881061257053019133078545928983562221396313169622475509818442661047018436264806901023966236718367204710755935899013750306107738002364137917426595737403871114187750804346564731250609196846638183903982387884578266136503697493474682071\",\"q\":\"61329566248342901292543872769978950870633559608669337131139375508370458778917\"}";
    se_voters = [];
    se_questions;
    se_public_keys = [];
    se_metadata;
    se_public_creds = token;
360
    se_public_creds_received = false;
Stephane Glondu's avatar
Stephane Glondu committed
361 362 363 364 365 366 367 368
  } in
  lwt () = Ocsipersist.add election_stable uuid_s se in
  lwt () = Ocsipersist.add election_credtokens token uuid_s in
  return (preapply election_setup uuid)

let () = Html5.register ~service:election_setup_pre
  (fun () () -> T.election_setup_pre ())

Stephane Glondu's avatar
Stephane Glondu committed
369
let () = Redirection.register ~service:election_setup_new
Stephane Glondu's avatar
Stephane Glondu committed
370
  (fun () (credmgmt, (auth, cas_server)) ->
Stephane Glondu's avatar
Stephane Glondu committed
371
   match_lwt Web_auth_state.get_site_user () with
Stephane Glondu's avatar
Stephane Glondu committed
372
   | Some u ->
Stephane Glondu's avatar
Stephane Glondu committed
373 374 375 376 377 378 379 380 381 382 383 384 385
      lwt credmgmt = match credmgmt with
        | Some "auto" -> return `Automatic
        | Some "manual" -> return `Manual
        | _ -> fail_http 400
      in
      lwt auth = match auth with
        | Some "password" -> return `Password
        | Some "dummy" -> return `Dummy
        | Some "cas" -> return @@ `CAS cas_server
        | _ -> fail_http 400
      in
      create_new_election u credmgmt auth
   | None -> forbidden ())
Stephane Glondu's avatar
Stephane Glondu committed
386

387 388 389 390 391 392 393 394 395 396
let generic_setup_page f uuid () =
  match_lwt Web_auth_state.get_site_user () with
  | Some u ->
     let uuid_s = Uuidm.to_string uuid in
     lwt se = Ocsipersist.find election_stable uuid_s in
     if se.se_owner = u
     then f uuid se ()
     else forbidden ()
  | None -> forbidden ()

Stephane Glondu's avatar
Stephane Glondu committed
397
let () = Html5.register ~service:election_setup
398
  (generic_setup_page T.election_setup)
Stephane Glondu's avatar
Stephane Glondu committed
399

400
let () = Html5.register ~service:election_setup_trustees
401 402 403 404
  (generic_setup_page T.election_setup_trustees)

let () = Html5.register ~service:election_setup_credential_authority
  (generic_setup_page T.election_setup_credential_authority)
405

Stephane Glondu's avatar
Stephane Glondu committed
406 407
let election_setup_mutex = Lwt_mutex.create ()

408
let handle_setup f uuid x =
Stephane Glondu's avatar
Stephane Glondu committed
409
  match_lwt Web_auth_state.get_site_user () with
Stephane Glondu's avatar
Stephane Glondu committed
410 411 412 413 414 415
  | Some u ->
     let uuid_s = Uuidm.to_string uuid in
     Lwt_mutex.with_lock election_setup_mutex (fun () ->
       lwt se = Ocsipersist.find election_stable uuid_s in
       if se.se_owner = u then (
         try_lwt
416
           lwt cont = f se x u uuid in
Stephane Glondu's avatar
Stephane Glondu committed
417
           Ocsipersist.add election_stable uuid_s se >>
418
           cont ()
Stephane Glondu's avatar
Stephane Glondu committed
419
         with e ->
420
           T.generic_page ~title:"Error" (Printexc.to_string e) () >>= Html5.send
Stephane Glondu's avatar
Stephane Glondu committed
421 422 423
       ) else forbidden ()
     )
  | None -> forbidden ()
424

425 426
let redir_preapply s u () = Redirection.send (preapply s u)

427 428 429 430
let () =
  Any.register
    ~service:election_setup_description
    (handle_setup
431
       (fun se (name, description) _ uuid ->
432 433 434
         se.se_questions <- {se.se_questions with
           t_name = name;
           t_description = description;
435 436
         };
         return (redir_preapply election_setup uuid)))
437

Stephane Glondu's avatar
Stephane Glondu committed
438 439 440 441
let () =
  Any.register
    ~service:election_setup_group
    (handle_setup
442
       (fun se x _ uuid ->
Stephane Glondu's avatar
Stephane Glondu committed
443 444
        let _group = Group.of_string x in
        (* we keep it as a string since it contains a type *)
445 446
        se.se_group <- x;
        return (redir_preapply election_setup uuid)))
447

Stephane Glondu's avatar
Stephane Glondu committed
448 449 450 451
let () =
  Any.register
    ~service:election_setup_metadata
    (handle_setup
452
       (fun se x u uuid ->
Stephane Glondu's avatar
Stephane Glondu committed
453 454
        let metadata = metadata_of_string x in
        if metadata.e_owner <> Some u then failwith "wrong owner";
455 456
        se.se_metadata <- metadata;
        return (redir_preapply election_setup uuid)))
457

458 459 460 461
let () =
  Any.register
    ~service:election_setup_auth
    (handle_setup
462 463
       (fun se auth_system _ uuid ->
         (match auth_system with
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
         | Some (("dummy" | "password") as auth_system) ->
            se.se_metadata <- {
              se.se_metadata with
                e_auth_config = Some [{
                  auth_system;
                  auth_instance = auth_system;
                  auth_config = []
                }]
            }
         | Some "cas" ->
            se.se_metadata <- {
              se.se_metadata with
                e_auth_config = Some [{
                  auth_system = "cas";
                  auth_instance = "cas";
                  auth_config = ["server", ""];
                }]
            }
         | Some x -> failwith ("unknown authentication system: "^x)
483 484
         | None -> failwith "no authentication system was given");
         return (redir_preapply election_setup uuid)))
485 486 487 488 489

let () =
  Any.register
    ~service:election_setup_auth_cas
    (handle_setup
490
       (fun se server _ uuid ->
491 492 493 494 495 496 497
         se.se_metadata <- {
           se.se_metadata with
             e_auth_config = Some [{
               auth_system = "cas";
               auth_instance = "cas";
               auth_config = ["server", server];
             }]
498 499
         };
         return (redir_preapply election_setup uuid)))
500

501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
let template_password = format_of_string
  "You are listed as a voter for the election

  %s

You will find below your login and password.  To cast a vote, you will
also need a credential, sent in a separate email.  Be careful,
passwords and credentials look similar but play different roles.  You
will be asked to enter your credential before entering the voting
booth.  Login and passwords are required once your ballot is ready to
be cast.

Username: %s
Password: %s
Page of the election: %s

Note that you are allowed to vote several times.  Only the last vote
counts.

-- 
Belenios"

523
let generate_password title url id =
524
  let email, login = split_identity id in
525 526 527
  lwt salt = generate_token () in
  lwt password = generate_token () in
  let hashed = sha256_hex (salt ^ password) in
528
  let body = Printf.sprintf template_password title login password url in
529
  let subject = "Your password for election " ^ title in
530 531
  send_email "noreply@belenios.org" email subject body >>
  return (salt, hashed)
532

533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
let handle_password se uuid ~force voters =
  let title = se.se_questions.t_name in
  let url = Eliom_uri.make_string_uri ~absolute:true ~service:election_home
    (uuid, ()) |> rewrite_prefix
  in
  Lwt_list.iter_s (fun id ->
    match id.sv_password with
    | Some _ when not force -> return_unit
    | None | Some _ ->
       lwt x = generate_password title url id.sv_id in
       return (id.sv_password <- Some x)
  ) voters >>
  return (fun () ->
    T.generic_page ~title:"Success"
      "Passwords have been generated and mailed!" () >>= Html5.send)

549 550 551 552 553
let () =
  Any.register
    ~service:election_setup_auth_genpwd
    (handle_setup
       (fun se () _ uuid ->
554
         handle_password se uuid ~force:false se.se_voters))
555

556 557 558
let () =
  Any.register
    ~service:election_regenpwd
Stephane Glondu's avatar
Stephane Glondu committed
559
    (fun (uuid, ()) () ->
560 561 562 563 564 565
      T.regenpwd uuid () >>= Html5.send)

let () =
  Any.register
    ~service:election_regenpwd_post
    (fun (uuid, ()) user ->
566
      let uuid_s = Uuidm.to_string uuid in
567 568
      lwt w = find_election uuid_s in
      let module W = (val w) in
569 570 571 572 573 574 575 576 577 578 579 580
      lwt site_user = Web_auth_state.get_site_user () in
      match site_user with
      | Some u when W.metadata.e_owner = Some u ->
         let table = "password_" ^ underscorize uuid_s in
         let table = Ocsipersist.open_table table in
         let title = W.election.e_params.e_name in
         let url = Eliom_uri.make_string_uri
           ~absolute:true ~service:election_home
           (uuid, ()) |> rewrite_prefix
         in
         begin try_lwt
           lwt _ = Ocsipersist.find table user in
581 582
           lwt x = generate_password title url user in
           Ocsipersist.add table user x >>
Stephane Glondu's avatar
Stephane Glondu committed
583
           dump_passwords W.dir table >>
584 585 586 587 588 589 590 591 592 593 594
           T.generic_page ~title:"Success"
             ("A new password has been mailed to " ^ user ^ ".") ()
           >>= Html5.send
         with Not_found ->
           T.generic_page ~title:"Error"
             (user ^ " is not a registered user for this election.") ()
           >>= Html5.send
         end
      | _ -> forbidden ()
    )

Stephane Glondu's avatar
Stephane Glondu committed
595 596 597 598
let () =
  Html5.register
    ~service:election_setup_questions
    (fun uuid () ->
Stephane Glondu's avatar
Stephane Glondu committed
599
     match_lwt Web_auth_state.get_site_user () with
600 601
     | Some u ->
        let uuid_s = Uuidm.to_string uuid in
Stephane Glondu's avatar
Stephane Glondu committed
602 603
        lwt se = Ocsipersist.find election_stable uuid_s in
        if se.se_owner = u
604
        then T.election_setup_questions uuid se ()
Stephane Glondu's avatar
Stephane Glondu committed
605 606
        else forbidden ()
     | None -> forbidden ()
607 608
    )

Stephane Glondu's avatar
Stephane Glondu committed
609 610 611 612
let () =
  Any.register
    ~service:election_setup_questions_post
    (handle_setup
613 614 615
       (fun se x _ uuid ->
        se.se_questions <- template_of_string x;
         return (redir_preapply election_setup_questions uuid)))
Stephane Glondu's avatar
Stephane Glondu committed
616

Stephane Glondu's avatar
Stephane Glondu committed
617 618 619 620
let () =
  Html5.register
    ~service:election_setup_voters
    (fun uuid () ->
Stephane Glondu's avatar
Stephane Glondu committed
621
      match_lwt Web_auth_state.get_site_user () with
Stephane Glondu's avatar
Stephane Glondu committed
622 623 624 625
      | Some u ->
         let uuid_s = Uuidm.to_string uuid in
         lwt se = Ocsipersist.find election_stable uuid_s in
         if se.se_owner = u
626
         then T.election_setup_voters uuid se ()
Stephane Glondu's avatar
Stephane Glondu committed
627 628 629 630 631
         else forbidden ()
      | None -> forbidden ()
    )

(* see http://www.regular-expressions.info/email.html *)
Stephane Glondu's avatar
Stephane Glondu committed
632
let identity_rex = Pcre.regexp
Stephane Glondu's avatar
Stephane Glondu committed
633
  ~flags:[`CASELESS]
634
  "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,7}(,[A-Z0-9._%+-]+)?$"
Stephane Glondu's avatar
Stephane Glondu committed
635

Stephane Glondu's avatar
Stephane Glondu committed
636 637
let is_identity x =
  try ignore (Pcre.pcre_exec ~rex:identity_rex x); true
Stephane Glondu's avatar
Stephane Glondu committed
638 639
  with Not_found -> false

640 641 642 643 644 645 646 647
let email_rex = Pcre.regexp
  ~flags:[`CASELESS]
  "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,7}$"

let is_email x =
  try ignore (Pcre.pcre_exec ~rex:email_rex x); true
  with Not_found -> false

648 649
module SSet = Set.Make (PString)

650
let merge_voters a b f =
651 652 653 654 655 656 657
  let existing = List.fold_left (fun accu sv ->
    SSet.add sv.sv_id accu
  ) SSet.empty a in
  let _, res = List.fold_left (fun (existing, accu) sv_id ->
    if SSet.mem sv_id existing then
      (existing, accu)
    else
658
      (SSet.add sv_id existing, {sv_id; sv_password = f sv_id} :: accu)
659 660 661
  ) (existing, List.rev a) b in
  List.rev res

Stephane Glondu's avatar
Stephane Glondu committed
662 663
let () =
  Any.register
664
    ~service:election_setup_voters_add
Stephane Glondu's avatar
Stephane Glondu committed
665
    (handle_setup
666
       (fun se x _ uuid ->
667
         if se.se_public_creds_received then forbidden () else (
Stephane Glondu's avatar
Stephane Glondu committed
668 669 670
         let xs = Pcre.split x in
         let () =
           try
Stephane Glondu's avatar
Stephane Glondu committed
671 672
             let bad = List.find (fun x -> not (is_identity x)) xs in
             Printf.ksprintf failwith "%S is not a valid identity" bad
Stephane Glondu's avatar
Stephane Glondu committed
673 674
           with Not_found -> ()
         in
675
         se.se_voters <- merge_voters se.se_voters xs (fun _ -> None);
676
         return (redir_preapply election_setup_voters uuid))))
677 678 679 680 681 682

let () =
  Any.register
    ~service:election_setup_voters_remove
    (handle_setup
       (fun se voter _ uuid ->
683
         if se.se_public_creds_received then forbidden () else (
684 685 686
         se.se_voters <- List.filter (fun v ->
           v.sv_id <> voter
         ) se.se_voters;
687
         return (redir_preapply election_setup_voters uuid))))
Stephane Glondu's avatar
Stephane Glondu committed
688

689 690 691 692 693 694 695
let () =
  Any.register ~service:election_setup_voters_passwd
    (handle_setup
       (fun se voter _ uuid ->
         let voter = List.filter (fun v -> v.sv_id = voter) se.se_voters in
         handle_password se uuid ~force:true voter))

Stephane Glondu's avatar
Stephane Glondu committed
696
let () =
697
  Any.register
Stephane Glondu's avatar
Stephane Glondu committed
698
    ~service:election_setup_trustee_add
699 700
    (fun uuid st_id ->
     if is_email st_id then
Stephane Glondu's avatar
Stephane Glondu committed
701
     match_lwt Web_auth_state.get_site_user () with
702 703
     | Some u ->
        let uuid_s = Uuidm.to_string uuid in
Stephane Glondu's avatar
Stephane Glondu committed
704 705 706 707
        Lwt_mutex.with_lock election_setup_mutex (fun () ->
          lwt se = Ocsipersist.find election_stable uuid_s in
          if se.se_owner = u
          then (
708
            lwt st_token = generate_token () in
709 710
            let trustee = {st_id; st_token; st_public_key = ""} in
            se.se_public_keys <- se.se_public_keys @ [trustee];
Stephane Glondu's avatar
Stephane Glondu committed
711
            Ocsipersist.add election_stable uuid_s se >>
712
            Ocsipersist.add election_pktokens st_token uuid_s
Stephane Glondu's avatar
Stephane Glondu committed
713 714
          ) else forbidden ()
        ) >>
715
        Redirection.send (preapply election_setup_trustees uuid)
716
     | None -> forbidden ()
717 718 719
     else
       let msg = st_id ^ " is not a valid e-mail address!" in
       T.generic_page ~title:"Error" msg () >>= Html5.send
720 721 722 723 724
    )

let () =
  Redirection.register
    ~service:election_setup_trustee_del
725
    (fun uuid index ->
Stephane Glondu's avatar
Stephane Glondu committed
726
     match_lwt Web_auth_state.get_site_user () with
727 728 729 730 731 732
     | Some u ->
        let uuid_s = Uuidm.to_string uuid in
        Lwt_mutex.with_lock election_setup_mutex (fun () ->
          lwt se = Ocsipersist.find election_stable uuid_s in
          if se.se_owner = u
          then (
733 734 735 736 737 738 739 740 741 742 743
            let trustees, old =
              se.se_public_keys |>
              List.mapi (fun i x -> i, x) |>
              List.partition (fun (i, _) -> i <> index) |>
              (fun (x, y) -> List.map snd x, List.map snd y)
            in
            se.se_public_keys <- trustees;
            Ocsipersist.add election_stable uuid_s se >>
            Lwt_list.iter_s (fun {st_token; _} ->
              Ocsipersist.remove election_pktokens st_token
            ) old
744 745
          ) else forbidden ()
        ) >>
746
        return (preapply election_setup_trustees uuid)
747 748 749
     | None -> forbidden ()
    )

Stephane Glondu's avatar
Stephane Glondu committed
750 751 752 753 754 755 756 757
let () =
  Html5.register
    ~service:election_setup_credentials
    (fun token () ->
     lwt uuid = Ocsipersist.find election_credtokens token in
     lwt se = Ocsipersist.find election_stable uuid in
     T.election_setup_credentials token uuid se ()
    )
758

Stephane Glondu's avatar
Stephane Glondu committed
759 760 761 762 763 764 765 766
let () =
  File.register
    ~service:election_setup_credentials_download
    ~content_type:"text/plain"
    (fun token () ->
     lwt uuid = Ocsipersist.find election_credtokens token in
     return (!spool_dir / uuid ^ ".public_creds.txt")
    )
767

Stephane Glondu's avatar
Stephane Glondu committed
768 769 770
let wrap_handler f =
  try_lwt f ()
  with
771
  | e -> T.generic_page ~title:"Error" (Printexc.to_string e) () >>= Html5.send
Stephane Glondu's avatar
Stephane Glondu committed
772 773 774 775

let handle_credentials_post token creds =
  lwt uuid = Ocsipersist.find election_credtokens token in
  lwt se = Ocsipersist.find election_stable uuid in
776
  if se.se_public_creds_received then forbidden () else
Stephane Glondu's avatar
Stephane Glondu committed
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
  let module G = (val Group.of_string se.se_group : GROUP) in
  let fname = !spool_dir / uuid ^ ".public_creds.txt" in
  Lwt_mutex.with_lock
    election_setup_mutex
    (fun () ->
     Lwt_io.with_file
       ~flags:(Unix.([O_WRONLY; O_NONBLOCK; O_CREAT; O_TRUNC]))
       ~perm:0o600 ~mode:Lwt_io.Output fname
       (fun oc -> Lwt_io.write_chars oc creds)
    ) >>
  lwt () =
    let i = ref 1 in
    Lwt_stream.iter
      (fun x ->
       try
         let x = G.of_string x in
         if not (G.check x) then raise Exit;
         incr i
       with _ ->
         Printf.ksprintf failwith "invalid credential at line %d" !i)
      (Lwt_io.lines_of_file fname)
  in
799
  let () = se.se_metadata <- {se.se_metadata with e_cred_authority = None} in
800 801
  let () = se.se_public_creds_received <- true in
  Ocsipersist.add election_stable uuid se >>
802 803
  T.generic_page ~title:"Success"
    "Credentials have been received and checked!" () >>= Html5.send
Stephane Glondu's avatar
Stephane Glondu committed
804 805 806 807 808 809 810

let () =
  Any.register
    ~service:election_setup_credentials_post
    (fun token creds ->
     let s = Lwt_stream.of_string creds in
     wrap_handler (fun () -> handle_credentials_post token s))
811

Stephane Glondu's avatar
Stephane Glondu committed
812 813 814 815 816 817 818
let () =
  Any.register
    ~service:election_setup_credentials_post_file
    (fun token creds ->
     let s = Lwt_io.chars_of_file creds.Ocsigen_extensions.tmp_filename in
     wrap_handler (fun () -> handle_credentials_post token s))

819 820 821 822 823 824
module Credgen = struct
  module String = PString

  (* FIXME: duplicate of Tool_credgen *)

  let get_random_char =
825
    let prng = Lazy.from_fun (Lwt_preemptive.detach (fun () ->
826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
      pseudo_rng (random_string secure_rng 16)
    )) in
    let mutex = Lwt_mutex.create () in
    fun () ->
      Lwt_mutex.with_lock mutex (fun () ->
        lwt prng = Lazy.force prng in
        let s = random_string prng 1 in
        return @@ s.[0]
      )

  (* Beware: the following must be changed in accordance with the booth! *)
  let digits = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
  let token_length = 14
  let n58 = Z.of_int 58
  let n53 = Z.of_int 53

  let generate_raw_token () =
843
    let res = Bytes.create token_length in
844 845 846 847
    let rec loop i accu =
      if i < token_length then (
        lwt digit = get_random_char () in
        let digit = int_of_char digit mod 58 in
848
        Bytes.set res i digits.[digit];
849
        loop (i+1) Z.(n58 * accu + of_int digit)
850
      ) else return (Bytes.to_string res, accu)
851 852 853 854 855 856 857 858 859 860 861
    in loop 0 Z.zero

  let add_checksum (raw, value) =
    let checksum = 53 - Z.(to_int (value mod n53)) in
    return (raw ^ String.make 1 digits.[checksum])

  let generate () =
    generate_raw_token () >>= add_checksum

end

862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
let template_credential = format_of_string
  "You are listed as a voter for the election

  %s

You will find below your login and credential.  To cast a vote, you will
also need a password, sent in a separate email.  Be careful,
passwords and credentials look similar but play different roles.  You
will be asked to enter your credential before entering the voting
booth.  Login and passwords are required once your ballot is ready to
be cast.

Username: %s
Credential: %s
Page of the election: %s

Note that you are allowed to vote several times.  Only the last vote
counts.

-- 
Belenios"

884 885 886
let () =
  Any.register
    ~service:election_setup_credentials_server
887
    (handle_setup (fun se () _ uuid ->
888
      if se.se_public_creds_received then forbidden () else
889 890 891
      let () = se.se_metadata <- {se.se_metadata with
        e_cred_authority = Some "server"
      } in
892
      let uuid_s = Uuidm.to_string uuid in
893 894 895 896 897
      let title = se.se_questions.t_name in
      let url = Eliom_uri.make_string_uri
        ~absolute:true ~service:election_home
        (uuid, ()) |> rewrite_prefix
      in
898 899 900
      let module S = Set.Make (PString) in
      let module G = (val Group.of_string se.se_group : GROUP) in
      lwt creds =
901 902
        Lwt_list.fold_left_s (fun accu v ->
          let email, login = split_identity v.sv_id in
903 904 905 906 907 908 909
          lwt cred = Credgen.generate () in
          let priv_cred = derive_cred uuid cred in
          let pub_cred =
            let x = Z.(of_string_base 16 priv_cred mod G.q) in
            let y = G.(g **~ x) in
            G.to_string y
          in
910
          let body = Printf.sprintf template_credential title login cred url in
911
          let subject = "Your credential for election " ^ title in
912
          lwt () = send_email "noreply@belenios.org" email subject body in
913 914 915 916 917
          return @@ S.add pub_cred accu
        ) S.empty se.se_voters
      in
      let creds = S.elements creds in
      let fname = !spool_dir / uuid_s ^ ".public_creds.txt" in
918
      lwt () =
919 920 921 922
          Lwt_io.with_file
            ~flags:(Unix.([O_WRONLY; O_NONBLOCK; O_CREAT; O_TRUNC]))
            ~perm:0o600 ~mode:Lwt_io.Output fname
            (fun oc ->
923
              Lwt_list.iter_s (Lwt_io.write_line oc) creds)
924
      in
925
      se.se_public_creds_received <- true;
926 927 928
      return (fun () ->
        T.generic_page ~title:"Success"
          "Credentials have been generated and mailed!" () >>= Html5.send)))
929

Stephane Glondu's avatar
Stephane Glondu committed
930 931 932 933 934 935
let () =
  Html5.register
    ~service:election_setup_trustee
    (fun token () ->
     lwt uuid = Ocsipersist.find election_pktokens token in
     lwt se = Ocsipersist.find election_stable uuid in
Stephane Glondu's avatar
Stephane Glondu committed
936
     T.election_setup_trustee token se ()
Stephane Glondu's avatar
Stephane Glondu committed
937 938 939 940 941 942 943 944 945 946 947 948 949
    )

let () =
  Any.register
    ~service:election_setup_trustee_post
    (fun token public_key ->
     wrap_handler
       (fun () ->
        lwt uuid = Ocsipersist.find election_pktokens token in
        Lwt_mutex.with_lock
          election_setup_mutex
          (fun () ->
           lwt se = Ocsipersist.find election_stable uuid in
950
           let t = List.find (fun x -> token = x.st_token) se.se_public_keys in
Stephane Glondu's avatar
Stephane Glondu committed
951 952 953 954 955
           let module G = (val Group.of_string se.se_group : GROUP) in
           let pk = trustee_public_key_of_string G.read public_key in
           let module KG = Election.MakeSimpleDistKeyGen (G) (LwtRandom) in
           if not (KG.check pk) then failwith "invalid public key";
           (* we keep pk as a string because of G.t *)
956
           t.st_public_key <- public_key;
Stephane Glondu's avatar
Stephane Glondu committed
957
           Ocsipersist.add election_stable uuid se
958 959 960
          ) >> T.generic_page ~title:"Success"
            "Your key has been received and checked!"
            () >>= Html5.send
Stephane Glondu's avatar
Stephane Glondu committed
961 962 963 964 965 966 967
       )
    )

let () =
  Any.register
    ~service:election_setup_create
    (fun uuid () ->
Stephane Glondu's avatar
Stephane Glondu committed
968
     match_lwt Web_auth_state.get_site_user () with
Stephane Glondu's avatar
Stephane Glondu committed
969 970 971
     | None -> forbidden ()
     | Some u ->
        begin try_lwt
972 973 974
          let uuid_s = Uuidm.to_string uuid in
          Lwt_mutex.with_lock election_setup_mutex (fun () ->
            lwt se = Ocsipersist.find election_stable uuid_s in
Stephane Glondu's avatar
Stephane Glondu committed
975
            if se.se_owner <> u then forbidden () else
976 977
            finalize_election uuid se >>
            Redirection.send (preapply election_admin (uuid, ()))
Stephane Glondu's avatar
Stephane Glondu committed
978 979
          )
        with e ->
980
          T.new_election_failure (`Exception e) () >>= Html5.send
Stephane Glondu's avatar
Stephane Glondu committed
981 982
        end
    )
983

984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
let () =
  Html5.register
    ~service:election_setup_import
    (fun uuid () ->
      lwt site_user = Web_auth_state.get_site_user () in
      match site_user with
      | None -> forbidden ()
      | Some u ->
         lwt se = Ocsipersist.find election_stable (Uuidm.to_string uuid) in
         lwt elections = get_finalized_elections_by_owner u in
         T.election_setup_import uuid se elections ())

let () =
  Any.register
    ~service:election_setup_import_post
    (handle_setup
       (fun se from _ uuid ->
         let from_s = Uuidm.to_string from in
         lwt voters = Web_persist.get_voters from_s in
1003 1004 1005 1006 1007 1008 1009 1010 1011
         lwt passwords = Web_persist.get_passwords from_s in
         let get_password =
           match passwords with
           | None -> fun _ -> None
           | Some p -> fun sv_id ->
             let _, login = split_identity sv_id in
             try Some (SMap.find login p)
             with Not_found -> None
         in
1012 1013 1014
         match voters with
         | Some voters ->
            if se.se_public_creds_received then forbidden () else (
1015
              se.se_voters <- merge_voters se.se_voters voters get_password;
1016 1017 1018 1019 1020 1021 1022 1023 1024
              return (redir_preapply election_setup_voters uuid))
         | None ->
            return (fun () -> T.generic_page ~title:"Error"
              (Printf.sprintf
                 "Could not retrieve voter list from election %s"
                 from_s)
              () >>= Html5.send)))


Stephane Glondu's avatar
Stephane Glondu committed
1025 1026 1027 1028
let () =
  Any.register
    ~service:election_home
    (fun (uuid, ()) () ->
1029
      let uuid_s = Uuidm.to_string uuid in
1030 1031 1032
      try_lwt
        lwt w = find_election uuid_s in
        let module W = (val w) in
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
        Eliom_reference.unset Web_services.ballot >>
        let cont () =
          Redirection.send
            (Eliom_service.preapply
               election_home (W.election.e_params.e_uuid, ()))
        in
        Eliom_reference.set Web_auth_state.cont [cont] >>
        match_lwt Eliom_reference.get Web_services.cast_confirmed with
        | Some result ->
           Eliom_reference.unset Web_services.cast_confirmed >>
           T.cast_confirmed (module W) ~result () >>= Html5.send
        | None ->
           lwt state = Web_persist.get_election_state uuid_s in
           T.election_home (module W) state () >>= Html5.send
      with Not_found ->
Stephane Glondu's avatar
Stephane Glondu committed
1048
        T.generic_page ~title:"Sorry, this election is not yet open"
1049 1050
          "This election does not exist yet. Please come back later." ()
          >>= Html5.send)
1051

Stephane Glondu's avatar
Stephane Glondu committed
1052 1053 1054 1055 1056
let () =
  Any.register
    ~service:election_admin
    (fun (uuid, ()) () ->
     let uuid_s = Uuidm.to_string uuid in
1057
     lwt w = find_election uuid_s in
Stephane Glondu's avatar
Stephane Glondu committed
1058
     lwt site_user = Web_auth_state.get_site_user () in
1059
     let module W = (val w) in
1060 1061
     match site_user with
     | Some u when W.metadata.e_owner = Some u ->