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()
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])
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)
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]
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]])
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)
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 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
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)
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
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)
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]])
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)
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
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)
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
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)
def set_hsm(token_name, priv_key, pkcs11_path): try: Election().set_hsm_token_name(token_name) Election().set_hsm_priv_key(priv_key) Election().set_pkcs11_path(pkcs11_path) Election().config_hsm_done() except: Election().config_hsm_done(False) sys.stderr.write("HSMi konfigureerimine nurjus: %s\n" % exception_msg.trace()) sys.exit(1)
def setup(self): g_config = None e_config = None configfile = open("%s/config" % self.__dir, "r") g_config, e_config = read_config(configfile.readlines()) configfile.close() if Election().is_hes(): Election().set_hts_ip(g_config['*.hts']) Election().set_hts_path("/hts.cgi") Election().set_hts_verify_path("/hts-verify-vote.cgi") Election().config_hth_done() Election().set_mid_conf( g_config["*.mobidurl"], \ g_config["*.mobidservice"], \ g_config["*.mobidauthmsg"], \ g_config["*.mobidsignmsg"]) for el in e_config: init_conf.execute(el, e_config[el]['type'], \ e_config[el]['description']) manage_rights(el, e_config[el]) config_common.config_hes(el, \ "%s/%s" % (self.__dir, e_config[el]['districts']), \ "%s/%s" % (self.__dir, e_config[el]['voters']), \ "%s/%s" % (self.__dir, e_config[el]['choices'])) if Election().is_hts(): Election().set_verification_time(g_config["*.verifytimeout"]) Election().set_verification_count(g_config["*.verifymaxtries"]) for el in e_config: init_conf.execute(el, e_config[el]['type'], \ e_config[el]['description']) manage_rights(el, e_config[el]) config_common.config_hts(el, \ "%s/%s" % (self.__dir, e_config[el]['districts']), \ "%s/%s" % (self.__dir, e_config[el]['voters']), \ "%s/%s" % (self.__dir, e_config[el]['choices'])) if Election().is_hlr(): for el in e_config: init_conf.execute(el, e_config[el]['type'], \ e_config[el]['description']) manage_rights(el, e_config[el]) config_common.config_hlr(el, \ "%s/%s" % (self.__dir, e_config[el]['districts']), \ "%s/%s" % (self.__dir, e_config[el]['choices']))
def main_function(): try: usage() set_bdoc_conf(sys.argv[1]) Election().config_bdoc_done() print "Sertifikaatide konfiguratsiooni laadimine oli edukas." except SystemExit: sys.stderr.write('Konfiguratsiooni laadimine nurjus\n') sys.exit(1) except Exception as ex: Election().config_bdoc_done(False) sys.stderr.write('Konfiguratsiooni laadimine nurjus: %s\n' % str(ex)) sys.exit(1)
def display_verification_conf(): try: def_time = Election().get_verification_time() except: def_time = NOT_DEFINED_STR try: def_count = Election().get_verification_count() except: def_count = NOT_DEFINED_STR print "\t\tTaimaut hääle kontrollimiseks minutites: %s" % def_time print "\t\tLubatud arv kordusi hääle kontrollimiseks: %s" % def_count
def do_get_verification_conf(): try: def_time = Election().get_verification_time() except (IOError, LookupError): def_time = "puudub" try: def_count = Election().get_verification_count() except (IOError, LookupError): def_count = "puudub" print "Taimaut hääle kontrollimiseks minutites: %s" % def_time print "Lubatud arv kordusi hääle kontrollimiseks: %s" % def_count
def create_sub1_hes(sub): sub.create(CHOICE_CONFIGURE_COMMON) sub.add_item(CHOICE_BDOC_CONF, serviceutil.do_bdoc_conf_hes) sub.add_item(CHOICE_INSTALL, serviceutil.do_install) sub.add_item(CHOICE_SET_MID_CONF, serviceutil.do_set_mid_conf) sub.add_item(CHOICE_SET_HES_HTS_CONF, serviceutil.do_set_hts_conf) sub.add_item(CHOICE_SESSION_CONF, serviceutil.do_session_conf) sub.add_item(CHOICE_CONFIG_FILES_HISTORY, serviceutil.do_config_files_history) if Election().is_config_hth_done(): sub.add_item(CHOICE_CHECK_CONSISTENCY, serviceutil.do_check_consistency) 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 Election().is_hes_configured(): if self.state < election.ETAPP_HAALETUS: if autocmd.scheduled(autocmd.COMMAND_START): sub.add_item(CHOICE_UNSCHEDULE_AUTOSTART, serviceutil.do_unschedule_autostart) else: sub.add_item(CHOICE_SCHEDULE_AUTOSTART, serviceutil.do_schedule_autostart) if self.state == election.ETAPP_ENNE_HAALETUST: sub.add_item(CHOICE_START_ELECTION, self.do_change_state) if self.state < election.ETAPP_LUGEMINE: if (autocmd.scheduled(autocmd.COMMAND_PREPARE_STOP) or autocmd.scheduled(autocmd.COMMAND_STOP)): sub.add_item(CHOICE_UNSCHEDULE_AUTOSTOP, serviceutil.do_unschedule_autostop) elif Election().allow_new_voters(): sub.add_item(CHOICE_SCHEDULE_AUTOSTOP, serviceutil.do_schedule_autostop) if self.state == election.ETAPP_HAALETUS: if Election().allow_new_voters(): sub.add_item(CHOICE_PRE_START_COUNTING_HES, serviceutil.do_pre_start_counting_hes) else: sub.add_item(CHOICE_CANCEL_PRE_START_COUNTING_HES, serviceutil.do_cancel_pre_start_counting_hes) sub.add_item(CHOICE_START_COUNTING_HES, self.do_change_state)
def status(self, fo, verify): fo.write('HTS vaheauditi aruanne\n\n') if (not verify): fo.write('NB! Hääli ei verifitseeritud\n\n') fo.write('Käimasolevad hääletused:\n') for el in Election().get_questions(): fo.write('\t%s\n' % el) fo.write('\nAnalüüs hääletuste kaupa:\n\n') for el in Election().get_questions(): _h = htsstatus.HTSStatus(el) _h.calculate(verify) _h.output(fo) fo.write('\n')
def _read_blt(path): '''Parse a .blt file and return the L{Election}. @type path: string @param path: File path. @rtype: L{Election} @return: Returns the L{Election}. ''' f = open(path) # Skip over leading comments while True: line = f.readline() if len(line) == 0: raise Exception('Invalid blt') if len(line) and line[0] != '#': break # Get the number of candidates and seats num_candidates, seats = [int(x) for x in line.split()] root = Node() ranks = 0 # Make sure the root has a child for every candidate for c in xrange(1, num_candidates + 1): root.get_child(c) num_ballots = 0 while True: line = f.readline() m = re.match(r'(\(.*?\) )?1 ([-=0-9 ]*)0', line) if not m: break num_ballots += 1 choices = m.group(2).split() ranks = max(ranks, len(choices)) seen = set() curr = root for c in choices: if c == '-': continue if '=' in c: break c = int(c) if c not in seen: seen.add(c) curr = curr.get_child(c) curr.value += 1 if line != '0\n': raise Exception('Expected 0 after ballots "%s"' % line) names = dict() for c in xrange(1, num_candidates + 1): names[c] = f.readline()[1:-2] description = f.readline()[1:-2] f.close() root.value = num_ballots return Election(names=names, profile=root, ranks=ranks, seats=seats, description=description)
def is_valid_id_cert(): """Verifitseerib hääletaja sertifkaadi vastavust (ahelat) süsteemi laetud sertifikaatidega. @return True kui sertifikaat verifitseerub, vastasel korral False @throws Exception kui viga sertifikaadi lugemisel """ proc = subprocess.Popen(\ ['openssl', 'verify', '-CApath', Election().get_bdoc_ca()],\ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,\ close_fds=True) proc.stdin.write(os.environ[evcommon.HTTP_CERT]) proc.stdin.close() errlst = proc.stderr.readlines() reslst = proc.stdout.readlines() proc.stderr.close() proc.stdout.close() if len(errlst) > 0: err_data = '' if (len(os.environ[evcommon.HTTP_CERT]) > 0): err_data = os.environ[evcommon.HTTP_CERT][:100] raise Exception('Viga autentimissertifikaadi verifitseerimisel: '\ '%s, INPUT: %s' % (errlst, err_data)) if len(reslst) != 1 and reslst[0].strip()[-2:].upper() != "OK": return False, ''.join(reslst) return True, ''
def check_session(self): if not self.__reg.check([evcommon.MIDSPOOL, self.__sessid]): return False start = self.__reg.read_integer_value( [evcommon.MIDSPOOL, self.__sessid], 'start').value length = Election().get_session_length() * 60 return start + length >= int(time.time()) and self.auth_succ()
def __haaletanud(self, ik): lst = Election().get_questions() for el in lst: _h = htsrevoke.HTSRevoke(el) if _h.haaletanud(ik): return True return False
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 verify_vote(self, votedata): import regrights self.user_msg = \ EvMessage().get_str("TEHNILINE_VIGA_HAALE_VERIFITSEERIMISEL", \ evstrings.TEHNILINE_VIGA_HAALE_VERIFITSEERIMISEL) conf = bdocpythonutils.BDocConfig() conf.load(Election().get_bdoc_conf()) self.bdoc = bdocpythonutils.BDocContainer() self.bdoc.load_bytes(votedata) self.bdoc.validateflex() res = self.__check_incoming_vote(conf) if not res.result: self.log_msg = res.error if self.user_msg == '': self.user_msg = EvMessage().\ get_str("TEHNILINE_VIGA_HAALE_VERIFITSEERIMISEL", \ evstrings.TEHNILINE_VIGA_HAALE_VERIFITSEERIMISEL) if not res.ocsp_is_good: self.user_msg = EvMessage().\ get_str("SERTIFIKAAT_ON_TYHISTATUD_VOI_PEATATUD", \ evstrings.SERTIFIKAAT_ON_TYHISTATUD_VOI_PEATATUD) raise HTSStoreException, evcommon.EVOTE_CERT_ERROR raise HTSStoreException, evcommon.EVOTE_ERROR self.signercode = regrights.get_personal_code(res.subject) self.ocsp_time = res.ocsp_time self.signed_vote = self.bdoc.get_bytes()