Beispiel #1
0
    def do_export_all(self):
        """Kõigi valimiste väljund failid CDle
        """
        if Election().count_questions() < 1:
            print "Ei ole midagi eksportida"
            return
        cd_burner = burner.FileListBurner(evcommon.burn_buff())
        try:
            print "Ekspordime kõik. Palun oota.."
            for i in Election().get_questions():
                self.update_files(i)
                file_list = self.file_table.values()
                # Olukord, kus valimiste ID on, aga faile pole
                if len(file_list) == 0:
                    print "Ei ole midagi eksportida"
                    return

                # Kui on, siis ka vastav sha256 fail exporti
                for file_key in self.file_table.keys():
                    sha256f = self.get_sha256_file(file_key)
                    if sha256f:
                        file_list.append(sha256f)
                if not cd_burner.append_files(i, file_list):
                    return
            cd_burner.burn()
        finally:
            cd_burner.delete_files()
Beispiel #2
0
def do_set_mid_conf():

    try:
        def_url = Election().get_mid_url()
    except:
        def_url = 'https://www.openxades.org:8443/DigiDocService'

    try:
        def_name = Election().get_mid_name()
    except:
        def_name = 'Testimine'

    try:
        def_auth_msg, def_sign_msg = Election().get_mid_messages()
    except:
        def_auth_msg = 'E-hääletus, autentimine'
        def_sign_msg = 'E-hääletus, hääle allkirjastamine'

    url = uiutil.ask_string(\
                "Sisesta DigiDocService'i URL", None, None, def_url)

    name = uiutil.ask_string(\
                "Sisesta teenuse nimi", None, None, def_name)

    auth_msg = uiutil.ask_string(\
                "Sisesta sõnum autentimisel", None, None, def_auth_msg)

    sign_msg = uiutil.ask_string(\
                "Sisesta sõnum allkirjastamisel", None, None, def_sign_msg)

    Election().set_mid_conf(url, name, auth_msg, sign_msg)
Beispiel #3
0
    def hts_vote(self, valid_person, vote):
        ik = valid_person[0]
        en = valid_person[1]
        pn = valid_person[2]

        evlog.AppLog().set_person(ik)

        import base64
        decoded_vote = base64.decodestring(vote)

        evlog.log('Hääle talletamine: %s %s' % (en, pn))
        if not Election().can_vote(ik):
            error = HESResult()
            error.pole_valija(ik)
            return self.__return_error(error)

        inspector = VoteChecker(decoded_vote, ik)
        mobid = 'MOBILE_ID_CONTEXT' in os.environ

        if not inspector.check_vote(mobid):
            return self.__return_error(inspector.error)

        params = {}
        params[evcommon.POST_EVOTE] = vote
        params[evcommon.POST_PERSONAL_CODE] = ik
        params[evcommon.POST_VOTERS_FILES_SHA256] = \
            Election().get_voters_files_sha256()
        params[evcommon.POST_SESS_ID] = sessionid.voting()

        hts_connector = HTSConnector(params)
        if not hts_connector.work_strict():
            return self.__return_error(hts_connector.error)

        return hts_connector.answer[1], hts_connector.answer[2]
Beispiel #4
0
    def test_cgp_grey_animal_kingdom(self):
        """Tests CGP Grey example STV election 'Politics in the Animal Kingdom'

        Link: https://www.youtube.com/watch?v=l8XOZJkozfI

        Expected winners: Gorilla, Monkey, Tiger
        """
        # Setup
        tarsier = Candidate('tarsier', name='Tarsier')
        gorilla = Candidate('gorilla', name='Gorilla')
        monkey = Candidate('monkey', name='Monkey')
        tiger = Candidate('tiger', name='Tiger')
        lynx = Candidate('lynx', name='Lynx')

        expected_winners = set([gorilla, monkey, tiger])
        seats = 3
        tiebreak_alphanumeric = 'abcdefghijklmnopqrstuvwxyz'

        num_ballots = 10000
        ballots = (
            ballots_for_candidates([tarsier, gorilla], int(
                .05 * num_ballots)) + ballots_for_candidates(
                    [gorilla, tarsier, monkey], int(.28 * num_ballots)) +
            ballots_for_candidates([monkey], int(.33 * num_ballots)) +
            ballots_for_candidates([tiger], int(.21 * num_ballots)) +
            ballots_for_candidates([lynx, tiger, tarsier, monkey, gorilla],
                                   int(.13 * num_ballots)))

        # Test
        election = Election(seats=seats,
                            ballots=ballots,
                            random_alphanumeric=tiebreak_alphanumeric)
        results = election.compute_results()
        self.assertEqual(expected_winners, results.candidates_elected)
Beispiel #5
0
    def create_actions(self):
        max_votes_per_voter = None
        if Election().get_root_reg().check(['common', 'max_votes_per_voter']):
            max_votes_per_voter = \
                Election().get_root_reg().read_integer_value(\
                    ['common'], 'max_votes_per_voter').value

        for el in self.questions:
            _hts = hts.HTS(el[0])
            voter = _hts.talletaja(self.signercode)
            dsc = ''
            try:
                dsc = Election().get_sub_reg(\
                    el[0]).read_string_value(['common'], 'description').value
            except:
                dsc = el[0]
            if voter == None:
                self.user_msg = EV_ERRORS.POLE_VALIJA
                self.log_msg = "Pole valija %s, %s" % (self.signercode, dsc)
                raise HTSStoreException, evcommon.EVOTE_ERROR
            if max_votes_per_voter:
                if self._count_votes(el[0]) >= max_votes_per_voter:
                    self.user_msg = EV_ERRORS.TEHNILINE_VIGA

                    self.log_msg = self.user_msg
                    raise HTSStoreException, evcommon.EVOTE_ERROR

            self.actions.append([_hts, voter, el[1]])
Beispiel #6
0
def do_rem_rights(elid):
    ik = uiutil.ask_id_num()
    right_str = ""
    if Election().is_hes() or Election().is_hlr():
        right = uiutil.ask_int(
            "Võimalikud volitused:\n " + "\t(1) Valikute nimekirja laadija\n" +
            "\t(2) Valimisjaoskondade nimekirja laadija\n" + "Vali volitus:",
            1, 1, 2)
        if right == 1:
            right_str = "VALIK"
        elif right == 2:
            right_str = "JAOSK"
    elif Election().is_hts():
        right = uiutil.ask_int(
            "Võimalikud volitused:\n " +
            "\t(1) Tühistus- ja ennistusnimekirja laadija\n" +
            "\t(2) Valimisjaoskondade nimekirja laadija\n" + "Vali volitus:",
            1, 1, 2)
        if right == 1:
            right_str = "TYHIS"
        elif right == 2:
            right_str = "JAOSK"
    if not uiutil.ask_yes_no("Kas soovid eemaldada volituse"):
        return
    subprocess.call([SCRIPT_REGRIGHTS, elid, "rem", ik, right_str])
Beispiel #7
0
def check_ocsp():

    log = evlog.Logger()
    log.set_format(evlog.AppLogFormat('OCSPWD'))
    log.set_logs(Election().get_path(evcommon.OCSP_LOG_FILE))

    try:
        _conf = bdocconfig.BDocConfig()
        _conf.load(Election().get_bdoc_conf())
        _ocsp = _conf.get_ocsp_responders()

        for el in _ocsp:
            app = ('openssl ocsp -issuer "%s" -serial 123 -url "%s" -noverify'
                   % (_ocsp[el], el))

            pp = subprocess.Popen(app, shell=True, stdin=subprocess.PIPE,
                                  stdout=subprocess.PIPE, close_fds=True)
            is_ok = 0
            start = time.time()
            while True:
                line = pp.stdout.readline()
                if not line:
                    break
                if line.strip().find('This Update:') != -1:
                    is_ok = 1
            end = time.time()
            if is_ok:
                log.log_info(message='OCSP päringu tegemiseks kulus %5.2f sekundit' % (end - start))
            else:
                log.log_info(message='OCSP ei vasta')
    except:
        log.log_err(message=exception_msg.trace())
def main_function():
    if len(sys.argv) != 3:
        usage()

    el_id = sys.argv[1]
    _if = sys.argv[2]

    if not check_file(_if):
        print "Faili " + _if + " ei eksisteeri"
        sys.exit(1)

    if not ksum.has(_if):
        print "Faili " + ksum.filename(_if) + " ei eksisteeri"
        sys.exit(1)

    if not ksum.check(_if):
        print "Kontrollsumma ei klapi"
        sys.exit(1)

    reg = Election().get_sub_reg(el_id)
    reg.ensure_key(['hlr', 'input'])
    dst = reg.path(['hlr', 'input', 'votes'])
    os.system("cp " + _if + " " + dst)
    os.system("cp " + ksum.filename(_if) + " " + ksum.filename(dst))
    Election().config_hlr_input_elid_done(el_id)
Beispiel #9
0
def do_rem_rights(elid):
    ik = uiutil.ask_id_num()
    right_str = ""
    if Election().is_hes() or Election().is_hlr():
        right = uiutil.ask_int("Võimalikud volitused:\n " + \
            "\t(1) Valikute nimekirja laadija\n" + \
            "\t(2) Valimisjaoskondade nimekirja laadija\n" + \
            "Vali volitus:", 1, 1, 2)
        if right == 1:
            right_str = "VALIK"
        elif right == 2:
            right_str = "JAOSK"
    elif Election().is_hts():
        right = uiutil.ask_int("Võimalikud volitused:\n " + \
                "\t(1) Tühistus- ja ennistusnimekirja laadija\n" +
                "\t(2) Valimisjaoskondade nimekirja laadija\n" + \
                "Vali volitus:", 1, 1, 2)
        if right == 1:
            right_str = "TYHIS"
        elif right == 2:
            right_str = "JAOSK"
    if not uiutil.ask_yes_no("Kas oled kindel"):
        return
    cmd = "%s %s rem %s %s" % (SCRIPT_REGRIGHTS, elid, ik, right_str)
    os.system(cmd)
Beispiel #10
0
    def prepare(self, confer_name):

        if Election().is_hes():
            self.root = 'hes'
        elif Election().is_hlr():
            self.root = 'hlr'
        else:
            raise Exception('Vigane serveritüüp')

        if not ElectionState().can_replace_candidates():
            print 'Selles hääletuse faasis (%s) valikuid muuta ei saa'\
                % ElectionState().str()
            return False

        self.reg = Election().get_sub_reg(self.elid)
        AppLog().set_app(confer_name, self.elid)
        AppLog().log('Valikute nimekirja välja vahetamine: ALGUS')
        self.quest = question.Question(self.elid, self.root, self.reg)

        self._ed = inputlists.Districts()
        self._ed.load(self.root, self.reg)

        self._backup_old_choices()
        print 'Valimised: ' + self.elid
        return True
Beispiel #11
0
        def create_sub1_hts(sub):
            sub.create(CHOICE_CONFIGURE_COMMON)
            sub.add_item(CHOICE_BDOC_CONF, serviceutil.do_bdoc_conf)
            sub.add_item(CHOICE_INSTALL, serviceutil.do_install)
            sub.add_item(CHOICE_CONFIG_FILES_HISTORY,
                         serviceutil.do_config_files_history)

            sub.add_item(CHOICE_VERIFICATION_CONF,
                         serviceutil.do_verification_conf)

            if self.state == election.ETAPP_ENNE_HAALETUST:
                if Election().is_voters_list_disabled():
                    sub.add_item(CHOICE_ENABLE_VOTERS_LIST,
                                 serviceutil.do_enable_voters_list)
                else:
                    sub.add_item(CHOICE_DISABLE_VOTERS_LIST,
                                 serviceutil.do_disable_voters_list)

            if (self.state == election.ETAPP_ENNE_HAALETUST and
                    Election().is_hts_configured()):
                sub.add_item(CHOICE_START_ELECTION, self.do_change_state)

            if self.state == election.ETAPP_HAALETUS:
                sub.add_item(CHOICE_START_REVOCATION, self.do_change_state)

            if self.state == election.ETAPP_TYHISTUS:
                sub.add_item(CHOICE_START_COUNTING, self.do_change_state)
Beispiel #12
0
    def create_actions(self):
        max_votes_per_voter = None
        if Election().get_root_reg().check(['common', 'max_votes_per_voter']):
            max_votes_per_voter = \
                Election().get_root_reg().read_integer_value(\
                    ['common'], 'max_votes_per_voter').value

        for el in self.questions:
            _hts = hts.HTS(el[0])
            voter = _hts.talletaja(self.signercode)
            dsc = ''
            try:
                dsc = Election().get_sub_reg(\
                    el[0]).read_string_value(['common'], 'description').value
            except:
                dsc = el[0]
            if voter == None:
                self.user_msg = EvMessage().get_str("POLE_LUBATUD_HAALETADA", \
                    evstrings.POLE_LUBATUD_HAALETADA) % (self.signercode, dsc)
                self.log_msg = self.user_msg
                raise HTSStoreException, evcommon.EVOTE_ERROR
            if max_votes_per_voter:
                if self._count_votes(el[0]) >= max_votes_per_voter:
                    self.user_msg = EvMessage().get_str(\
            "TEHNILINE_VIGA_MAX_HAALTE_ARV_PER_HAALETAJA_ON_ULETATUD", \
            evstrings.TEHNILINE_VIGA_MAX_HAALTE_ARV_PER_HAALETAJA_ON_ULETATUD)

                    self.log_msg = self.user_msg
                    raise HTSStoreException, evcommon.EVOTE_ERROR

            self.actions.append([_hts, voter, el[1]])
Beispiel #13
0
def result(electionID):
    if 'admin' in session:
        election = Election.getElection({'_id': ObjectId(electionID)})
        if election['date'].date() < datetime.datetime.now().date():
            pass
        elif election['date'].date() == datetime.datetime.now().date() and election['endtime'] < str(datetime.datetime.now().time())[:5]:
            pass
        else:
            flash('Election not yet ended! Wait for Election to end to calculate result', 'warning')
            return redirect(url_for('dashboard'))

        result = {}
        response = Blockchain.get_chain()
        for block in response['chain']:
            IpfsBlock = Blockchain.get_by_hash(block['IpfsHash'])
            for txn_hash in IpfsBlock['data']:
                txn = Blockchain.get_by_hash(txn_hash)
                if txn['electionID'] == electionID:
                    if txn['candidateID'] not in result:
                        result[txn['candidateID']] = 1
                    else:
                        result[txn['candidateID']] += 1
        Election.updateElection({'_id':ObjectId(electionID)}, {'$set':{'result':result}})
        flash('Result calculated and published.', 'info')
        return redirect(url_for('dashboard'))
    else:
        flash('You need to Login first!', 'warning')
        return redirect(url_for('login'))
Beispiel #14
0
def main():
  # Run Experiments
  start = time()
  for cname in sorted(CONTESTS):
    for t in xrange(NTRIALS):
      cattr = CONTESTS[cname]
      c, g, a, params = cattr['c'], cattr['g'], cattr['a'], cattr['p']
      contest = Contest(c, g, a, params)
      e = Election([contest])
      e.run()
      for aname in sorted(AUDITS):
        outcome, nballots = e.audit(AUDITS[aname])[0]  # assumes 1 contest
        if outcome != contest.outcome[0]:
          results[cname][aname]['e'] += 1
        results[cname][aname]['n'] += nballots
  end = time()

  # Report Results
  for cname in sorted(CONTESTS):
    print cname
    for aname in sorted(AUDITS):
      avg_nballots = results[cname][aname]['n'] / float(NTRIALS)
      avg_nerrors = results[cname][aname]['e'] / float(NTRIALS)
      print '\t%s\t%f\t%f' % (aname, avg_nballots, avg_nerrors)
  print 'Runtime: ' + str(end - start)
Beispiel #15
0
def process_args(args):
    """Processes command-line election arguments and runs election.

    Args:
        argparse.Namespace containing election arguments.
    """
    if args.ballots is not None:
        if args.ballots.startswith('http'):
            ballots = ballots_from_url(args.ballots)
        else:
            ballots = ballots_from_file(args.ballots)
    else:
        ballots = ballots_from_input()

    election = Election(
        ballots,
        args.seats,
        can_eliminate_no_confidence=not (args.disallow_nc_elimination),
        can_random_tiebreak=not (args.disallow_random_tiebreak),
        name=args.name,
        random_alphanumeric=args.alphanumeric)

    results = election.compute_results()

    if args.verbose:
        print(results.description())
    else:
        for candidate in results.candidates_elected:
            print(candidate)
Beispiel #16
0
    def do_it(self):

        c_ring, c_dist = self._ed.create(self.root, self.reg)
        Election().copy_config_file(self.elid, self.root, self.jaosk_f,
                                    evcommon.DISTRICT_FILES)
        print 'Paigaldatud %d ringkonda ja %d jaoskonda' % (c_ring, c_dist)

        c_choice = self._ch.create(self.quest.choices_proxy())
        Election().copy_config_file(self.elid, self.root, self.valik_f,
                                    evcommon.CANDIDATE_FILES)
        print 'Paigaldatud %d valikut' % c_choice

        if self.root in ['hes', 'hts']:

            print 'Paigaldan valijate faili võtit'
            Election().copy_voter_public_key_file(self.elid,
                                                  self.voter_public_key_f)
            print 'Võti on paigaldatud'

            c_add, c_del = self._vl.create('Paigaldan valijaid: ')
            print 'Valijad on paigaldatud. '\
                'Teostati %d lisamist ja %d eemaldamist'\
                % (c_add, c_del)
            Election().copy_config_file(self.elid, self.root, self.voter_f,
                                        evcommon.VOTERS_FILES)
            Election().add_voters_file_hash(self.voter_f)

        return True
Beispiel #17
0
    def test_1_candidate_1_seat(self):
        """Tests a 1 candidate election for 1 seat.

        Expected winners: A

        Round 0
            Ballots:
                10 * [A]
            Votes:
                A: 10
            Threshold: (10) / (1+1) + 1 = 6
            Result: A is elected
        """
        # Setup
        expected_winners = set(candidates_for_ids(['A']))
        seats = 1
        tiebreak_alphanumeric = 'abcdefghijklmnopqrstuvwxyz'
        ballots = (ballots_for_ids(['A'], 10))

        # Test
        election = Election(seats=seats,
                            ballots=ballots,
                            random_alphanumeric=tiebreak_alphanumeric)
        results = election.compute_results()
        self.assertEqual(expected_winners, results.candidates_elected)
Beispiel #18
0
    def test_wikipedia_food_selection(self):
        """Tests Wikipedia's example STV election, using choices of food.

        Link: https://en.wikipedia.org/wiki/Single_transferable_vote#Example

        Expected winners: Chocolate, Oranges, Strawberries
        """
        # Setup
        chocolate = Candidate('chocolate', name='Chocolate')
        oranges = Candidate('oranges', name='Oranges')
        pears = Candidate('pears', name='Pears')
        strawberries = Candidate('strawberries', name='Strawberries')
        sweets = Candidate('sweets', name='Sweets')

        expected_winners = set([chocolate, oranges, strawberries])
        seats = 3
        tiebreak_alphanumeric = 'abcdefghijklmnopqrstuvwxyz'

        ballots = (ballots_for_candidates([oranges], 4) +
                   ballots_for_candidates([pears, oranges], 2) +
                   ballots_for_candidates([chocolate, strawberries], 8) +
                   ballots_for_candidates([chocolate, sweets], 4) +
                   ballots_for_candidates([strawberries], 1) +
                   ballots_for_candidates([sweets], 1))

        # Test
        election = Election(seats=seats,
                            ballots=ballots,
                            random_alphanumeric=tiebreak_alphanumeric)
        results = election.compute_results()
        self.assertEqual(expected_winners, results.candidates_elected)
Beispiel #19
0
    def test_nc_halt_early(self):
        """ Tests a 3 candidate election for 3 seats.

        Once No Confidence is elected, the election should end.

        Expected winners: B, NC

        Round 0
            Ballots:
                5 * [A, NC]
                6 * [B, NC]
                4 * [C, NC]
                5 * [NC]
            Votes:
                A: 5
                B: 6
                C: 4
               NC: 5
            Threshold: (6+5+4+5) / (3+1) + 1 = 6
            Result: B is elected

        Round 1
            Ballots:
                5 * [A, NC]
                4 * [C, NC]
                5 * [NC]
            Votes:
                A: 5
                C: 4
               NC: 5
            Threshold: (5+4+5) / (2+1) + 1 = 5.666
            Result: C is eliminated

        Round 2
            Ballots:
                5 * [A, NC]
                9 * [NC]
            Votes:
                A: 5
               NC: 9
            Threshold: (5+9) / (2+1) + 1 = 5.666
            Result: NC is elected
        """
        # Setup
        expected_winners = set(candidates_for_ids(['B', 'NC']))
        seats = 3
        tiebreak_alphanumeric = 'abcdefghijklmnopqrstuvwxyz'

        ballots = (ballots_for_ids(['A', 'NC'], 5) +
                   ballots_for_ids(['B', 'NC'], 6) +
                   ballots_for_ids(['C', 'NC'], 4) +
                   ballots_for_ids(['NC'], 5))

        # Test
        election = Election(seats=seats,
                            ballots=ballots,
                            random_alphanumeric=tiebreak_alphanumeric)
        results = election.compute_results()
        self.assertEqual(expected_winners, results.candidates_elected)
Beispiel #20
0
 def __create_vote_key(self):
     reg = Election().get_root_reg()
     while True:
         vote_id = _generate_vote_id()
         key = htscommon.get_verification_key(vote_id)
         if not reg.check(key):
             reg.create_key(key)
             return vote_id
def process_elid(elid):
    print "%s" % elid
    reg_i = Election().get_sub_reg(elid, [Election().get_server_str()])

    process_district_files(reg_i)
    process_candidate_files(reg_i)
    if not Election().is_hlr():
        process_voters_files(reg_i)
Beispiel #22
0
    def __init__(self, elid):
        self._elid = elid
        self._errmsg = None
        self._reg = Election().get_sub_reg(self._elid)

        self._revlog = evlog.Logger()
        self._revlog.set_format(evlog.RevLogFormat())
        self._revlog.set_logs(self._reg.path(['common', evcommon.REVLOG_FILE]))
Beispiel #23
0
def add_hts_files_to_table(elid, table):
    import os
    reg = Election().get_root_reg()
    if reg.check(['questions', elid, 'hts', 'output']):
        o_files = os.listdir(reg.path(['questions', elid, 'hts', 'output']))
        for of in o_files:
            if of.find("tokend.") == 0 and of.find(".sha1") == -1:
                table.add_file(EvFile(of, of, ['questions', elid, 'hts', 'output']))
Beispiel #24
0
def do_view_election_description(elid):
    el_reg = Election().get_sub_reg(elid)
    try:
        description = el_reg.read_string_value(['common'], 'description').value
    except IOError:
        description = uiutil.NOT_DEFINED_STR
    except LookupError:
        description = uiutil.NOT_DEFINED_STR
    print "Valimiste %s kirjeldus: %s\n" % (elid, description)
Beispiel #25
0
def add_hts_files_to_table(elid, table):
    import os
    reg = Election().get_root_reg()
    if reg.check(['questions', elid, 'hts', 'output']):
        o_files = os.listdir(reg.path(['questions', elid, 'hts', 'output']))
        for of in o_files:
            if of.find("tokend.") == 0 and of.find(".sha1") == -1:
                table.add_file(
                    EvFile(of, of, ['questions', elid, 'hts', 'output']))
Beispiel #26
0
 def calc_probability_hurdle_surpassing(self, party):
     seats = np.zeros(self.__sample_size)
     for idx in range(self.__sample_size):
         election_result = self.values.T[idx]
         election = Election(election_result,
                             drop_other_parties=self.__drop_other_parties)
         seats_by_party = election.calc_seats_by_party()
         seats[idx] = seats_by_party[party.idx]
     return np.count_nonzero(seats) / self.__sample_size
Beispiel #27
0
def do_view_election_description(elid):
    el_reg = Election().get_sub_reg(elid)
    try:
        description = el_reg.read_string_value(['common'], 'description').value
    except IOError:
        description = uiutil.NOT_DEFINED_STR
    except LookupError:
        description = uiutil.NOT_DEFINED_STR
    print "Valimiste %s kirjeldus: %s\n" % (elid, description)
Beispiel #28
0
def do_session_conf():
    try:
        def_length = Election().get_session_length()
    except (IOError, LookupError):
        def_length = 60

    session_length = uiutil.ask_int(
        "Sisesta valimisseansi kehtivusaeg minutites", def_length, 1)

    Election().set_session_length(session_length)
Beispiel #29
0
 def _count_votes(self, elid):
     user_key = htscommon.get_user_key(self.signercode)
     if Election().get_sub_reg(elid).check(user_key):
         keys = Election().get_sub_reg(elid).list_keys(user_key)
         try:
             keys.remove(htscommon.VOTE_VERIFICATION_ID_FILENAME)
         except ValueError:
             pass # No "otp" file
         return len(keys)
     return 0
Beispiel #30
0
 def calc_seats_by(self, coalition: Coalition):
     coalition_seats = np.zeros(self.__sample_size)
     for idx in range(self.__sample_size):
         election_result = self.values.T[idx]
         election = Election(election_result,
                             drop_other_parties=self.__drop_other_parties)
         seats_by_party = election.calc_seats_by_party()
         for party in coalition.parties:
             coalition_seats[idx] += seats_by_party[party.idx]
     return coalition_seats
Beispiel #31
0
 def __init__(self):
     os.environ['MOBILE_ID_CONTEXT'] = '1'
     self.url = Election().get_mid_url()
     self.name = Election().get_mid_name()
     self.auth_msg, self.sign_msg = Election().get_mid_messages()
     loc = DigiDocServiceLocator()
     # self.fp = open('/tmp/debug.out', 'a')
     # kw = { 'tracefile': self.fp }
     kw = {}
     self.srv = loc.getDigiDocService(self.url, **kw)
Beispiel #32
0
 def kooskolaline(self, voters_files_sha1):
     if Election().get_root_reg().check(['common', 'voters_files_sha1']):
         hts_voters_files_sha1 = \
             Election().get_root_reg().read_string_value(
                 ['common'], 'voters_files_sha1').value
     else:
         hts_voters_files_sha1 = ''
     if hts_voters_files_sha1 != voters_files_sha1:
         return False
     return True
Beispiel #33
0
    def test_forward_tiebreak(self):
        """Tests a 3 candidate election for 2 seats.

        In the event of a tie to eliminate a candidate, and no backward
        tiebreak, eliminate the candidate with the fewest next-choice votes.
        Repeat for all subsequent ranks as necessary.

        Expected winners: A, C

        Round 0
            Ballots:
                6 * [A]
                3 * [B, C]
                3 * [C]
            Votes:
                A: 6
                B: 3
                C: 3
            Threshold: (6+3+3) / (2+1) + 1 = 5
            Result: A is elected

        Round 1
            Ballots:
                3 * [B, C]
                3 * [C]
            Votes:
                B: 3
                C: 3
            Threshold: (3+2+1) / (1+1) + 1 = 4
            Result: B is eliminated
            B and C are tied for fewest votes in this and previous rounds.
            B has fewer next-rank votes, so B is eliminated.

        Round 2
            Ballots:
                6 * [C]
            Votes:
                C: 6
            Threshold: (6) / (1+1) + 1 = 4
            Result: C is elected
        """
        # Setup
        expected_winners = set(candidates_for_ids(['A', 'C']))
        seats = 2
        tiebreak_alphanumeric = 'abcdefghijklmnopqrstuvwxyz'

        ballots = (ballots_for_ids(['A'], 6) + ballots_for_ids(['B', 'C'], 3) +
                   ballots_for_ids(['C'], 3))

        # Test
        election = Election(seats=seats,
                            ballots=ballots,
                            random_alphanumeric=tiebreak_alphanumeric)
        results = election.compute_results()
        self.assertEqual(expected_winners, results.candidates_elected)
Beispiel #34
0
    def test_random_tiebreak(self):
        """Tests a 3 candidate election for 2 seats.

        In the event of a tie to eliminate a candidate, and no backward
        tiebreak or forward tiebreak, eliminate a random candidate based on uid.

        Expected winners: A, C

        Round 0
            Ballots:
                6 * [A]
                3 * [B]
                3 * [C]
            Votes:
                A: 6
                B: 3
                C: 3
            Threshold: (6+3+3) / (2+1) + 1 = 5
            Result: A is elected

        Round 1
            Ballots:
                3 * [B]
                3 * [C]
            Votes:
                B: 3
                C: 3
            Threshold: (3+3) / (1+1) + 1 = 4
            Result: B is elected
            B and C are tied for fewest votes in this and all previous rounds,
            as well as future ranks. B's uid ('gwashington') is ordered before
            C's uid ('jadams') in the tiebreak_alphanumeric, so B is eliminated.

        Round 2
            Ballots:
                3 * [C]
            Votes:
                C: 3
            Threshold: (3) / (1+1) + 1 = 2.5
            Result: C is elected
        """
        # Setup
        expected_winners = set(candidates_for_ids(['A', 'C']))
        seats = 2
        tiebreak_alphanumeric = 'abcdefghijklmnopqrstuvwxyz'

        ballots = (ballots_for_ids(['A'], 6) + ballots_for_ids(['B'], 3) +
                   ballots_for_ids(['C'], 3))

        # Test
        election = Election(seats=seats,
                            ballots=ballots,
                            random_alphanumeric=tiebreak_alphanumeric)
        results = election.compute_results()
        self.assertEqual(expected_winners, results.candidates_elected)
Beispiel #35
0
def purge_otp(reg, otp):
    otp_key = htscommon.get_verification_key(otp)

    voter = reg.read_string_value(otp_key, "voter").value.rstrip()
    voter_key = htscommon.get_user_key(voter)
    elids = reg.read_string_value(otp_key, "elids").value.rstrip().split("\t")

    for elid in elids:
        sreg = Election().get_sub_reg(elid)
        if sreg.check(voter_key + [htscommon.VOTE_VERIFICATION_ID_FILENAME]):
            sreg.delete_value(voter_key, htscommon.VOTE_VERIFICATION_ID_FILENAME)
    reg.ensure_no_key(otp_key)
def main_function():

    try:
        election_ids = Election().get_questions()
        if len(election_ids) == 0:
            print "Sätteid pole laaditud"
        else:
            election_ids.sort()
            for el_i in election_ids:
                process_elid(el_i)

    except Exception as ex:
        print 'Viga valijanimekirjade uuenduste ajaloo kuvamisel: ' + str(ex)
        sys.exit(1)
Beispiel #37
0
class EvFile:

    def __init__(self, filename, uiname, regprefix):
        self.__filename = filename
        self.__uiname = uiname
        self.__regprefix = regprefix
        self.__reg = Election().get_root_reg()

    def exists(self):
        return self.__reg.check(self.__regprefix + [self.__filename])

    def path(self):
        return self.__reg.path(self.__regprefix + [self.__filename])

    def name(self):
        return self.__uiname
Beispiel #38
0
    def __init__(self, elid):
        self._elid = elid
        self._errmsg = None
        self._reg = Election().get_sub_reg(self._elid)

        self._revlog = evlog.Logger()
        self._revlog.set_format(evlog.RevLogFormat())
        self._revlog.set_logs(self._reg.path(['common', evcommon.REVLOG_FILE]))
Beispiel #39
0
def main_function():
    if len(sys.argv) != 3:
        usage()

    el_id = sys.argv[1]
    _if = sys.argv[2]

    if not ksum.check(_if, True):
        print "Kontrollsumma ei klapi"
        sys.exit(1)

    reg = Election().get_sub_reg(el_id)
    reg.ensure_key(['hlr', 'input'])
    dst = reg.path(['hlr', 'input', 'votes'])
    shutil.copy(_if, dst)
    ksum.store(dst)
    Election().config_hlr_input_elid_done(el_id)
Beispiel #40
0
    def __load_bdoc(self, elid):
        voter_key = htscommon.get_user_key(self._voter_code)
        sreg = Election().get_sub_reg(elid)
        for votefile in sreg.list_keys(voter_key):
            if htscommon.VALID_VOTE_PATTERN.match(votefile):
                bdoc = bdocpythonutils.BDocContainer()
                bdoc.load(sreg.path(voter_key + [votefile]))
                bdoc.validate(bdocpythonutils.ManifestProfile("TM"))

                self._voter = htscommon.get_votefile_voter(votefile)
                break

        if not bdoc:
            evlog.log_error("No valid BDOC found for voter %s using vote ID %s" % \
                    (self._voter, self._vote_id))
            raise HTSVerifyException, evcommon.VERIFY_ERROR

        return bdoc
Beispiel #41
0
def _revoke_vote_id(voter_code):
    elec = Election()
    otps = set()
    for quest in elec.get_questions():
        reg = elec.get_sub_reg(quest)
        key = htscommon.get_user_key(voter_code)
        if reg.check(key + [htscommon.VOTE_VERIFICATION_ID_FILENAME]):
            otp = reg.read_string_value(key, \
                    htscommon.VOTE_VERIFICATION_ID_FILENAME)
            otps.add(otp.value)
            evlog.log("Revoking vote ID %s" % otp)
            if not _delete_vote_id(otp.value):
                evlog.log_error("No such vote-ID: %s" % otp)
            otp.delete()

    if len(otps) > 1:
        evlog.log_error("The voter %s had multiple vote ID-s: %s" % \
                (voter_code, ", ".join(otps)))
Beispiel #42
0
def do_set_hts_conf():

    reg = Election().get_root_reg()
    if reg.check(['common', 'htsip']):
        try:
            def_ip_port = reg.read_ipaddr_value(\
                                        ['common'], 'htsip').value.split(":")
            def_ip = def_ip_port[0]
            if len(def_ip_port) > 1:
                try:
                    def_port = int(def_ip_port[-1])
                except ValueError:
                    def_port = 80
            else:
                def_port = 80
        except:
            def_ip = None
            def_port = 80
    else:
        def_ip = None
        def_port = 80

    hts_ip = uiutil.ask_string("Sisesta HTSi IP aadress", None, None, def_ip)
    hts_port = uiutil.ask_int("Sisesta HTSi port", def_port, 0, 65535)

    if reg.check(['common', 'htspath']):
        try:
            def_url = reg.read_string_value(['common'], 'htspath').value
        except:
            def_url = None
    else:
        def_url = None
    hts_url = uiutil.ask_string("Sisesta HTSi URL", None, None, def_url)

    try:
        def_verify = Election().get_hts_verify_path()
    except:
        def_verify = None
    hts_verify = uiutil.ask_string("Sisesta HTSi hääle kontrolli URL", \
            None, None, def_verify)

    cmd = "%s set %s:%d %s %s" % (SCRIPT_CONFIG_HTH, hts_ip, hts_port, \
            hts_url, hts_verify)
    os.system(cmd)
Beispiel #43
0
    def __load_bdoc(self, elid):
        voter_key = htscommon.get_user_key(self._voter_code)
        sreg = Election().get_sub_reg(elid)
        vote_files = []
        for vfile in sreg.list_keys(voter_key):
            if htscommon.VALID_VOTE_PATTERN.match(vfile):
                vote_files.append(vfile)

        vote_files.sort()
        latest = vote_files.pop()
        if latest:
            bdoc = htsbase.get_vote(sreg.path(voter_key + [latest]))

        if not bdoc:
            evlog.log_error("No valid BDOC found for voter %s using vote ID %s" % \
                    (self._voter_code, self._vote_id))
            raise HTSVerifyException, evcommon.VERIFY_ERROR

        return bdoc
Beispiel #44
0
    def work(self, check_fn, purge_fn):
        reg = Election().get_root_reg()
        runtime = int(time.time())
        AppLog().log("Purging %ss as of %s: START" % (self._desc,
                time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(runtime))))

        try:
            if not reg.check(self._key):
                return
            for key in reg.list_keys(self._key):
                try:
                    if check_fn(reg, key, runtime):
                        AppLog().log("Purging %s %s" % (self._desc, key))
                        purge_fn(reg, key)
                except:
                    AppLog().log("Error processing %s %s" % (self._desc, key))
                    AppLog().log_exception()
        except:
            AppLog().log_exception()
        finally:
            AppLog().log("Purging %ss: DONE" % self._desc)
Beispiel #45
0
def do_set_hts_conf():

    reg = Election().get_root_reg()
    if reg.check(['common', 'htsip']):
        try:
            def_ip_port = reg.read_ipaddr_value(
                ['common'], 'htsip').value.split(":")
            def_ip = def_ip_port[0]
            if len(def_ip_port) > 1:
                try:
                    def_port = int(def_ip_port[-1])
                except ValueError:
                    def_port = 80
            else:
                def_port = 80
        except:
            def_ip = None
            def_port = 80
    else:
        def_ip = None
        def_port = 80

    hts_ip = uiutil.ask_string("Sisesta HTSi IP aadress", None, None, def_ip)
    hts_port = uiutil.ask_int("Sisesta HTSi port", def_port, 0, 65535)

    try:
        def_url = Election().get_hts_path()
    except:
        def_url = "/hts.cgi"
    hts_url = uiutil.ask_string("Sisesta HTSi URL", None, None, def_url)

    try:
        def_verify = Election().get_hts_verify_path()
    except:
        def_verify = "/hts-verify-vote.cgi"
    hts_verify = uiutil.ask_string(
        "Sisesta HTSi hääle kontrolli URL", None, None, def_verify)

    subprocess.call([SCRIPT_CONFIG_HTH, "%s:%d" %
                     (hts_ip, hts_port), hts_url, hts_verify])
Beispiel #46
0
    def __init__(self, elid, tmpdir):

        self._elid = elid
        evlog.AppLog().set_app('HLR', self._elid)
        self._reg = Election().get_sub_reg(self._elid)
        self._log4 = evlog.Logger('log4')
        self._log5 = evlog.Logger('log5')
        self._log4.set_format(evlog.EvLogFormat())
        self._log5.set_format(evlog.EvLogFormat())
        self._log4.set_logs(self._reg.path(['common', 'log4']))
        self._log5.set_logs(self._reg.path(['common', 'log5']))

        tmpreg = evreg.Registry(root=tmpdir)
        tmpreg.ensure_key([])
        tmpreg.delete_sub_keys([])
        self.output_file = tmpreg.path(['decrypted_votes'])
        self.__cnt = ChoicesCounter()
Beispiel #47
0
def do_set_hsm_conf():

    reg = Election().get_root_reg()

    if reg.check(['common', 'hsm', 'tokenname']):
        try:
            def_tokenname = \
                reg.read_string_value(['common', 'hsm'], 'tokenname').value
        except:
            def_tokenname = "evote"
    else:
        def_tokenname = "evote"

    token_name = uiutil.ask_string(\
                "Sisesta HSM'i partitsiooni nimi", None, None, def_tokenname)

    if reg.check(['common', 'hsm', 'privkeylabel']):
        try:
            def_privkeylabel = \
                reg.read_string_value(['common', 'hsm'], 'privkeylabel').value
        except:
            def_privkeylabel = "evote_key"
    else:
        def_privkeylabel = "evote_key"

    priv_key_label = uiutil.ask_string(\
                    "Sisesta privaatvõtme nimi", None, None, def_privkeylabel)

    if reg.check(['common', 'hsm', 'pkcs11']):
        try:
            def_pkcs11 = \
                reg.read_string_value(['common', 'hsm'], 'pkcs11').value
        except:
            def_pkcs11 = "/usr/lunasa/lib/libCryptoki2_64.so"
    else:
        def_pkcs11 = "/usr/lunasa/lib/libCryptoki2_64.so"

    pkcs11_path = uiutil.ask_file_name(\
                    "Sisesta PKCS11 teegi asukoht", def_pkcs11)

    cmd = "%s set %s %s %s" % \
                (SCRIPT_CONFIG_HSM, token_name, priv_key_label, pkcs11_path)
    os.system(cmd)
Beispiel #48
0
class HTSBase:

    def __init__(self, elid):
        self._elid = elid
        self._errmsg = None
        self._reg = Election().get_sub_reg(self._elid)

        self._log1 = evlog.Logger()
        self._log1.set_format(evlog.EvLogFormat())
        self._log1.set_logs(self._reg.path(['common', 'log1']))

        self._log2 = evlog.Logger()
        self._log2.set_format(evlog.EvLogFormat())
        self._log2.set_logs(self._reg.path(['common', 'log2']))

        self._log3 = evlog.Logger()
        self._log3.set_format(evlog.EvLogFormat())
        self._log3.set_logs(self._reg.path(['common', 'log3']))

        self._revlog = evlog.Logger()
        self._revlog.set_format(evlog.RevLogFormat())
        self._revlog.set_logs(self._reg.path(['common', evcommon.REVLOG_FILE]))

    def _haaletanud_konf(self, isikukood):
        user_key = htscommon.get_user_key(isikukood)
        return self._reg.check(user_key) and \
                len(self._reg.list_keys(user_key)) > 0

    def haaletanud(self, isikukood):
        logi = self._log1.contains(isikukood)
        konf = self._haaletanud_konf(isikukood)
        if logi and konf:
            return True
        if (not logi) and (not konf):
            return False
        self._errmsg = 'Logifail LOG1 ja serveri olek ei ole kooskõlalised'
        raise Exception(self._errmsg)
Beispiel #49
0
def do_change_election_description(elid):
    description = uiutil.ask_string("Sisesta valimiste kirjeldus")
    el_reg = Election().get_sub_reg(elid)
    el_reg.create_string_value(['common'], 'description', description)
Beispiel #50
0
 def __init__(self, sessid):
     if not sessid:
         raise ValueError("Missing sessid")
     self.__key = [evcommon.IDSPOOL, sessid]
     self.__reg = Election().get_root_reg()
Beispiel #51
0
 def __init__(self, filename, uiname, regprefix):
     self.__filename = filename
     self.__uiname = uiname
     self.__regprefix = regprefix
     self.__reg = Election().get_root_reg()
Beispiel #52
0
    def issue_vote_id(self):
        vote_id = self.__create_vote_key()
        rreg = Election().get_root_reg()
        key = htscommon.get_verification_key(vote_id)

        rreg.create_string_value(key, "voter", self.signercode)
        rreg.create_integer_value(key, "timestamp", int(time.time()))
        rreg.create_integer_value(key, "count", \
                Election().get_verification_count())

        # Store the election IDs and include a backreference in the
        # corresponding questions' subregistries.
        elids = ""
        for elid in [quest[0] for quest in self.questions]:
            elids += elid + "\t"

            sreg = Election().get_sub_reg(elid)
            skey = htscommon.get_user_key(self.signercode)
            sreg.ensure_key(skey)
            sreg.create_string_value(skey, \
                    htscommon.VOTE_VERIFICATION_ID_FILENAME, vote_id)

        rreg.create_string_value(key, "elids", elids)
        return vote_id
Beispiel #53
0
class HTSVerify:

    def __init__(self):
        self._rreg = Election().get_root_reg()
        self._vote_id = None
        self._voter_code = None
        self._voter = None

    def __revoke_vote_id(self):
        _revoke_vote_id(self._voter_code)

    def verify_id(self, vote_id):
        # check if valid vote ID
        if not formatutil.is_vote_verification_id(vote_id):
            # We don't know how large vote_id is, so don't write to disk
            evlog.log_error("Malformed vote ID")
            raise HTSVerifyException, evcommon.VERIFY_ERROR

        vote_id = vote_id.lower()
        otp_key = htscommon.get_verification_key(vote_id)

        # check if corresponding OTP exists
        if not self._rreg.check(otp_key):
            evlog.log_error("No such vote ID: %s" % vote_id)
            raise HTSVerifyException, evcommon.VERIFY_ERROR

        self._voter_code = self._rreg.read_string_value(\
                otp_key, "voter").value.rstrip()

        # check if timestamp is OK
        current = int(time.time())
        created = self._rreg.read_integer_value(otp_key, "timestamp").value
        timeout = Election().get_verification_time() * 60
        if created + timeout < current:
            evlog.log("Vote ID %s has expired" % vote_id)
            self.__revoke_vote_id()
            raise HTSVerifyException, evcommon.VERIFY_ERROR

        # check if count is OK
        count = self._rreg.read_integer_value(otp_key, "count").value
        if count <= 0:
            evlog.log_error("Vote ID %s count is zero, but had not been revoked")
            self.__revoke_vote_id()
            raise HTSVerifyException, evcommon.VERIFY_ERROR

        self._vote_id = vote_id

    def __load_bdoc(self, elid):
        voter_key = htscommon.get_user_key(self._voter_code)
        sreg = Election().get_sub_reg(elid)
        for votefile in sreg.list_keys(voter_key):
            if htscommon.VALID_VOTE_PATTERN.match(votefile):
                bdoc = bdocpythonutils.BDocContainer()
                bdoc.load(sreg.path(voter_key + [votefile]))
                bdoc.validate(bdocpythonutils.ManifestProfile("TM"))

                self._voter = htscommon.get_votefile_voter(votefile)
                break

        if not bdoc:
            evlog.log_error("No valid BDOC found for voter %s using vote ID %s" % \
                    (self._voter, self._vote_id))
            raise HTSVerifyException, evcommon.VERIFY_ERROR

        return bdoc

    def __decrease_count(self):
        otp_key = htscommon.get_verification_key(self._vote_id)
        count = self._rreg.read_integer_value(otp_key, "count").value - 1
        if count > 0:
            self._rreg.create_integer_value(otp_key, "count", count)
        else:
            self.__revoke_vote_id()

    def get_response(self):
        import binascii

        # load a random BDOC from the ones available
        otp_key = htscommon.get_verification_key(self._vote_id)
        elids = self._rreg.read_string_value(otp_key, "elids")\
                .value.rstrip().split("\t")
        bdoc = self.__load_bdoc(random.choice(elids))
        evlog.log("Sending BDOC %s with vote ID %s for verification" %\
                (ksum.votehash(bdoc.get_bytes()), self._vote_id))

        # check consistency
        bdoc_set = set([doc.split(".")[0] for doc in bdoc.documents])
        elids_set = set(elids)
        if bdoc_set != elids_set:
            evlog.log_error("Votes in BDOC for vote ID %s are inconsistent " \
                    "with registry: %s, %s" % (self._vote_id, bdoc_set, elids_set))
            raise HTSVerifyException, evcommon.VERIFY_ERROR

        # create question objects
        questions = []
        for elid in elids:
            questions.append(question.Question(\
                    elid, "hts", Election().get_sub_reg(elid)))

        # start assembling the response
        ret = ""

        # append questions
        for quest in questions:
            ret += quest.qname() + ":" + str(quest.get_type()) + "\t"
        ret += "\n"

        # append election IDs and votes
        for votefile in bdoc.documents:
            elid = votefile.split(".")[0]
            ret += elid + "\t" + binascii.b2a_hex(bdoc.documents[votefile]) + "\n"
        ret += "\n"

        # append voter
        ret += self._voter["nimi"] + "\t" + self._voter_code + "\n"

        # append choices list
        for quest in questions:
            ret += quest.choices_to_voter(self._voter)

        self.__decrease_count()
        return ret
Beispiel #54
0
 def __init__(self):
     self._rreg = Election().get_root_reg()
     self._vote_id = None
     self._voter_code = None
     self._voter = None
Beispiel #55
0
class HLR:
    """
    Häältelugemisrakendus
    """

    def __init__(self, elid, tmpdir):

        self._elid = elid
        evlog.AppLog().set_app('HLR', self._elid)
        self._reg = Election().get_sub_reg(self._elid)
        self._log4 = evlog.Logger('log4')
        self._log5 = evlog.Logger('log5')
        self._log4.set_format(evlog.EvLogFormat())
        self._log5.set_format(evlog.EvLogFormat())
        self._log4.set_logs(self._reg.path(['common', 'log4']))
        self._log5.set_logs(self._reg.path(['common', 'log5']))

        tmpreg = evreg.Registry(root=tmpdir)
        tmpreg.ensure_key([])
        tmpreg.delete_sub_keys([])
        self.output_file = tmpreg.path(['decrypted_votes'])
        self.decrypt_prog = DECRYPT_PROGRAM
        self.sign_prog = SIGN_PROGRAM
        self.__cnt = ChoicesCounter()

    def __del__(self):
        try:
            os.remove(self.output_file)
        except:
            pass

    def _decrypt_votes(self, pin):

        input_file = self._reg.path(['hlr', 'input', 'votes'])
        token_name = Election().get_hsm_token_name()
        priv_key_label = Election().get_hsm_priv_key()
        pkcs11lib = Election().get_pkcs11_path()
        args = [input_file, self.output_file, \
            token_name, priv_key_label, pin, pkcs11lib]

        exit_code = 0

        try:
            exit_code = subprocess.call([self.decrypt_prog] + args)
        except OSError, oserr:
            errstr = "Häälte faili '%s' dekrüpteerimine nurjus: %s" % \
                (input_file, oserr)
            evlog.log_error(errstr)
            return False

        if exit_code == 0:
            return True

        if exit_code > 0:
            errstr2 = "Tundmatu viga"
            if exit_code in G_DECRYPT_ERRORS:
                errstr2 = G_DECRYPT_ERRORS[exit_code]

            errstr = \
                "Häälte faili '%s' dekrüpteerimine nurjus: %s (kood %d)" % \
                (input_file, errstr2, exit_code)
            evlog.log_error(errstr)
            return False

        errstr = "Häälte faili '%s' dekrüpteerimine nurjus (signaal %d)" % \
                (input_file, exit_code)
        evlog.log_error(errstr)
        return False
Beispiel #56
0
class MobileIDContext:

    phoneno = None
    lang = None
    challenge = None
    midsess = None
    origvote = None
    votefiles = {}
    __sessid = None
    __reg = None

    def __init__(self, sessid):
        if sessid == None:
            raise Exception('Puuduv sessiooniidentifikaator')
        self.__sessid = sessid
        self.__reg = Election().get_root_reg()
        self.lang = 'EST'

    def sessid(self):
        return self.__sessid

    def kill(self):
        self.__reg.ensure_no_key([evcommon.MIDSPOOL, self.__sessid])

    def set_phone(self, phone):
        self.phoneno = phone

    def set_origvote(self, hv):
        self.origvote = hv

    def get_origvote(self):
        self.origvote = self.__reg.read_value(\
                            [evcommon.MIDSPOOL, self.__sessid], \
                                                    'origvote').value
        return self.origvote

    def add_votefile(self, filename, data):
        self.votefiles[filename] = data

    def get_votefiles(self):
        for key in self.__reg.list_keys([evcommon.MIDSPOOL, self.__sessid, \
                'votefiles']):
            self.votefiles[key] = self.__reg.read_value(\
                    [evcommon.MIDSPOOL, self.__sessid, 'votefiles'], key).value
        return self.votefiles

    def generate_challenge(self):
        self.challenge = binascii.b2a_hex(os.urandom(10))

    def verify_challenge(self, signature):
        return challenge_ok(self.certificate(), self.mychallenge(), \
                            self.ourchallenge(), signature)

    def mychallenge(self):
        return self.__reg.read_value(\
                            [evcommon.MIDSPOOL, self.__sessid], \
                                    'mychallenge').value

    def ourchallenge(self):
        return self.__reg.read_value(\
                            [evcommon.MIDSPOOL, self.__sessid], \
                                    'ourchallenge').value

    def certificate(self):
        return self.__reg.read_value(\
                            [evcommon.MIDSPOOL, self.__sessid], \
                                    'cert').value

    def set_auth_succ(self):
        self.__reg.ensure_key([evcommon.MIDSPOOL, self.__sessid, 'authsucc'])

    def auth_succ(self):
        return self.__reg.check(\
                [evcommon.MIDSPOOL, self.__sessid, 'authsucc'])

    def save_post_auth(self, rsp):

        self.__reg.reset_key([evcommon.MIDSPOOL, self.__sessid])
        self.__reg.create_value([evcommon.MIDSPOOL, self.__sessid], \
                        'cert', rsp._CertificateData)

        self.__reg.create_value([evcommon.MIDSPOOL, self.__sessid], \
                        'phone', self.phoneno)

        self.__reg.create_value([evcommon.MIDSPOOL, self.__sessid], \
                        'midsess', rsp._Sesscode)

        self.__reg.create_value([evcommon.MIDSPOOL, self.__sessid], \
                        'mychallenge', self.challenge)

        self.__reg.create_value([evcommon.MIDSPOOL, self.__sessid], \
                        'ourchallenge', rsp._Challenge)

    def load_pre_sign(self):
        self.phoneno = self.__reg.read_value(\
                [evcommon.MIDSPOOL, self.__sessid], 'phone').value

    def save_post_sign(self, midsess):
        self.__reg.create_value([evcommon.MIDSPOOL, self.__sessid], \
                        'midsess', midsess)

        self.__reg.create_value([evcommon.MIDSPOOL, self.__sessid], \
                        'origvote', self.origvote)

        self.__reg.ensure_key([evcommon.MIDSPOOL, self.__sessid, 'votefiles'])
        for el in self.votefiles:
            self.__reg.create_value(\
                    [evcommon.MIDSPOOL, self.__sessid, 'votefiles'],\
                    el, self.votefiles[el])

    def load_pre_poll(self):
        self.midsess = int(self.__reg.read_value(\
                [evcommon.MIDSPOOL, self.__sessid], 'midsess').value)
Beispiel #57
0
class SessionContext:

    def __init__(self, sessid):
        if not sessid:
            raise ValueError("Missing sessid")
        self.__key = [evcommon.IDSPOOL, sessid]
        self.__reg = Election().get_root_reg()

    def store_session(self, cert):
        self.__reg.ensure_key(self.__key)
        self.__reg.create_value(self.__key, "cert", cert)
        self.__reg.create_integer_value(self.__key, "start", int(time.time()))

    def check_session(self, cert):
        if not self.__reg.check(self.__key):
            return evcommon.EVOTE_ERROR, evmessage.EV_ERRORS.SEANSS_PUUDUB

        start = self.__reg.read_integer_value(self.__key, "start").value
        length = Election().get_session_length() * 60
        if start + length < int(time.time()):
            return evcommon.EVOTE_ERROR, evmessage.EV_ERRORS.SEANSS_PUUDUB

        if self.__reg.read_value(self.__key, "cert").value != cert:
            evlog.log_error('Sertifikaat muutus')
            return evcommon.EVOTE_CERT_ERROR, evmessage.EV_ERRORS.TEHNILINE_VIGA

        return evcommon.EVOTE_OK, None

    def kill(self):
        self.__reg.ensure_no_key(self.__key)
Beispiel #58
0
 def __init__(self, sessid):
     if sessid == None:
         raise Exception('Puuduv sessiooniidentifikaator')
     self.__sessid = sessid
     self.__reg = Election().get_root_reg()
     self.lang = 'EST'