Exemple #1
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)
Exemple #2
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)
Exemple #3
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)
Exemple #4
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)
Exemple #5
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)
Exemple #6
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)
Exemple #7
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
Exemple #8
0
class Rights:
    def __init__(self, elid):
        self.reg = Election().get_sub_reg(elid, ['common', 'rights'])

    def descr(self, code):
        """
        Tagastab tegelase kohta käiva kirjelduse
        """
        if not formatutil.is_isikukood(code):
            raise Exception('Vigane isikukood')

        if self.reg.check([code, 'description']):
            return self.reg.read_string_value([code], 'description').value

        return 'Andmed puuduvad'

    def listall(self):
        """
        Tagastab kõik volitused
        """
        lst = self.reg.list_keys()

        ret = ''
        for ele in lst:
            ret += '\n' + self.listuser(ele)
        return ret.strip()

    def _create_user(self, code):
        """     Loome kasutaja, kui teda veel pole
        """
        if not formatutil.is_isikukood(code):
            raise Exception('Vigane isikukood')

        self.reg.ensure_key([code, 'rights'])

    def add(self, code, right):
        """
        Lisab uue volituse
        """
        new_right = right.upper()
        if not _proper_right(new_right):
            raise Exception('Vigane volitus')

        self._create_user(code)

        if not self.has(code, new_right):
            self.reg.create_value([code, 'rights'], new_right, '')
            return True

        return False

    def adddesc(self, code, desc):
        """
        Lisab kasutajale kirjelduse
        """
        self._create_user(code)
        self.reg.create_value([code], 'description', desc)
        return True

    def remove(self, code, right):
        """
        Võtab kasutajalt volituse
        """

        if not formatutil.is_isikukood(code):
            raise Exception('Vigane isikukood')

        new_right = right.upper()
        if not _proper_right(new_right):
            raise Exception('Vigane volitus')

        if self.has(code, new_right):
            self.reg.delete_value([code, 'rights'], new_right)
            return True

        return False

    def remuser(self, code):
        """
        Eemaldab ühe kasutaja volituste failist
        """
        if not formatutil.is_isikukood(code):
            raise Exception('Vigane isikukood')

        return self.reg.ensure_no_key([code])

    def remall(self):
        """
        Eemaldab kõik volitused
        """
        self.reg.reset_key([''])
        return True

    def has(self, code, right):
        """
        Kas koodil on vastav volitus
        """

        if not formatutil.is_isikukood(code):
            raise Exception('Vigane isikukood')

        new_right = right.upper()
        if not _proper_right(new_right):
            raise Exception('Vigane volitus')

        if not self.reg.check([code, 'rights', new_right]):
            return False
        return True

    def listuser(self, code):
        """
        Ainult konkreetse kasutaja õigused
        """
        if not formatutil.is_isikukood(code):
            raise Exception('Vigane isikukood')

        ret = ''
        if self.reg.check([code]):
            ret += code + ' (%s)' % self.descr(code)
            sub_list = self.reg.list_keys([code, 'rights'])
            if len(sub_list) > 0:
                for _s in sub_list:
                    ret += '\n\t' + G_DESCS[_s]
            else:
                ret += '\n\tVolitused puuduvad'
        return ret.strip()
Exemple #9
0
class HTSBase:
    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]))

    def haaletanud(self, isikukood):
        latest = self.get_latest_vote(isikukood)
        return latest <> None

    def get_revoked_path(self, pc):
        user_key = htscommon.get_user_key(pc)
        return self._reg.path(user_key + ['reason'])

    def get_latest_vote(self, pc):
        user_key = htscommon.get_user_key(pc)
        if self._reg.check(user_key):
            files = self._reg.list_keys(user_key)
            votes = []
            for el in files:
                if htscommon.VALID_VOTE_PATTERN.match(el):
                    votes.append(el)
            votes.sort()
            latest = votes.pop()
            if latest:
                return htscommon.get_votefile_time(latest)

        return None

    def restore_vote(self, revline, operator):
        timest = self.get_latest_vote(revline[0])
        os.unlink(self.get_revoked_path(revline[0]))
        self._revlog.log_info(tegevus='ennistamine',
                              isikukood=revline[0],
                              nimi=revline[1],
                              timestamp=timest,
                              operaator=operator,
                              pohjus=revline[2])

    def revoke_vote(self, revline, operator):
        timest = self.get_latest_vote(revline[0])
        nowstr = time.strftime("%Y%m%d%H%M%S", time.localtime())
        self._reg.create_string_value(\
            htscommon.get_user_key(revline[0]), 'reason', \
            "%s\t%s" % (nowstr, revline[2]))

        self._revlog.log_info(tegevus='tühistamine',
                              testtime=nowstr,
                              isikukood=revline[0],
                              nimi=revline[1],
                              timestamp=timest,
                              operaator=operator,
                              pohjus=revline[2])

    def is_user_revoked(self, pc):
        user_key = htscommon.get_user_key(pc)
        if self._reg.check(user_key + ['reason']):
            line = self._reg.read_string_value(user_key, 'reason').value
            data = line.split('\t')
            return True, data[1], data[0]
        return False, '', ''

    def save_log(self, lines, log):
        fn = self._reg.path(['common', 'log%s' % log])
        lf = htscommon.LoggedFile(fn)
        lf.open('w')
        lf.write(evcommon.VERSION + "\n")
        lf.write(self._elid + "\n")
        lf.write("%s\n" % log)
        for el in lines:
            lf.write(el + '\n')
        lf.close()

    def save_revocation_report(self, report):
        fn = self._reg.path(['hts', 'output', evcommon.REVREPORT_FILE])
        outfile = htscommon.LoggedFile(fn)
        outfile.open('a')
        for el in report:
            outfile.write("\t".join(el) + "\n")

        outfile.close()

    def talletaja(self, ik):
        vl = None
        try:
            vl = inputlists.VotersList('hts', self._reg)
            if not vl.has_voter(ik):
                return None
            ret = vl.get_voter(ik)
            return ret
        finally:
            if vl != None:
                vl.close()
                vl = None
Exemple #10
0
class Rights:

    def __init__(self, elid):
        self.reg = Election().get_sub_reg(elid, ['common', 'rights'])

    def descr(self, code):
        """
        Tagastab tegelase kohta käiva kirjelduse
        """
        if not formatutil.is_isikukood(code):
            raise Exception('Vigane isikukood')

        if self.reg.check([code, 'description']):
            return self.reg.read_string_value([code], 'description').value
        else:
            return 'Andmed puuduvad'

    def listall(self):
        """
        Tagastab kõik volitused
        """
        lst = self.reg.list_keys()

        ret = ''
        for ele in lst:
            ret = ret + '\n' + self.listuser(ele)
        return ret.strip()

    def _create_user(self, code):
        """     Loome kasutaja, kui teda veel pole
        """
        if not formatutil.is_isikukood(code):
            raise Exception('Vigane isikukood')

        self.reg.ensure_key([code, 'rights'])

    def add(self, code, right):
        """
        Lisab uue volituse
        """
        new_right = right.upper()
        if not _proper_right(new_right):
            raise Exception('Vigane volitus')

        self._create_user(code)

        if not self.has(code, new_right):
            self.reg.create_value([code, 'rights'], new_right, '')
            return True

        return False

    def adddesc(self, code, desc):
        """
        Lisab kasutajale kirjelduse
        """
        self._create_user(code)
        self.reg.create_value([code], 'description', desc)
        return True

    def remove(self, code, right):
        """
        Võtab kasutajalt volituse
        """

        if not formatutil.is_isikukood(code):
            raise Exception('Vigane isikukood')

        new_right = right.upper()
        if not _proper_right(new_right):
            raise Exception('Vigane volitus')

        if self.has(code, new_right):
            self.reg.delete_value([code, 'rights'], new_right)
            return True

        return False

    def remuser(self, code):
        """
        Eemaldab ühe kasutaja volituste failist
        """
        if not formatutil.is_isikukood(code):
            raise Exception('Vigane isikukood')

        return self.reg.ensure_no_key([code])

    def remall(self):
        """
        Eemaldab kõik volitused
        """
        self.reg.reset_key([''])
        return True

    def has(self, code, right):
        """
        Kas koodil on vastav volitus
        """

        if not formatutil.is_isikukood(code):
            raise Exception('Vigane isikukood')

        new_right = right.upper()
        if not _proper_right(new_right):
            raise Exception('Vigane volitus')

        if not self.reg.check([code, 'rights', new_right]):
            return False
        return True

    def listuser(self, code):
        """
        Ainult konkreetse kasutaja õigused
        """
        if not formatutil.is_isikukood(code):
            raise Exception('Vigane isikukood')

        ret = ''
        if self.reg.check([code]):
            ret = ret + code
            ret = ret + ' (' + self.descr(code) + ')'
            sub_list = self.reg.list_keys([code, 'rights'])
            if len(sub_list) > 0:
                for _s in sub_list:
                    ret = ret + '\n\t' + G_DESCS[_s]
            else:
                ret = ret + '\n\tVolitused puuduvad'
        return ret.strip()
Exemple #11
0
class HTSBase:

    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]))

    def haaletanud(self, isikukood):
        latest = self.get_latest_vote(isikukood)
        return latest is not None

    def get_revoked_path(self, pc):
        user_key = htscommon.get_user_key(pc)
        return self._reg.path(user_key + ['reason'])

    def get_latest_vote(self, pc):
        user_key = htscommon.get_user_key(pc)
        if self._reg.check(user_key):
            files = self._reg.list_keys(user_key)
            votes = []
            for el in files:
                if htscommon.VALID_VOTE_PATTERN.match(el):
                    votes.append(el)
            votes.sort()
            latest = votes.pop()
            if latest:
                return htscommon.get_votefile_time(latest)

        return None

    def restore_vote(self, revline, operator):
        timest = self.get_latest_vote(revline[0])
        os.unlink(self.get_revoked_path(revline[0]))
        self._revlog.log_info(
            tegevus='ennistamine',
            isikukood=revline[0],
            nimi=revline[1],
            timestamp=timest,
            operaator=operator,
            pohjus=revline[2])

    def revoke_vote(self, revline, operator):
        timest = self.get_latest_vote(revline[0])
        nowstr = time.strftime("%Y%m%d%H%M%S", time.localtime())
        self._reg.create_string_value(
            htscommon.get_user_key(revline[0]), 'reason',
            "%s\t%s" % (nowstr, revline[2]))

        self._revlog.log_info(
            tegevus='tühistamine',
            testtime=nowstr,
            isikukood=revline[0],
            nimi=revline[1],
            timestamp=timest,
            operaator=operator,
            pohjus=revline[2])

    def is_user_revoked(self, pc):
        user_key = htscommon.get_user_key(pc)
        if self._reg.check(user_key + ['reason']):
            line = self._reg.read_string_value(user_key, 'reason').value
            data = line.split('\t')
            return True, data[1], data[0]
        return False, '', ''

    def save_log(self, lines, log):
        fn = self._reg.path(['common', 'log%s' % log])
        lf = htscommon.LoggedFile(fn)
        lf.open('w')
        lf.write(evcommon.VERSION + "\n")
        lf.write(self._elid + "\n")
        lf.write("%s\n" % log)
        for el in lines:
            lf.write(el + '\n')
        lf.close()

    def save_revocation_report(self, report):
        fn = self._reg.path(['hts', 'output', evcommon.REVREPORT_FILE])
        outfile = htscommon.LoggedFile(fn)
        outfile.open('a')
        for el in report:
            outfile.write("\t".join(el) + "\n")

        outfile.close()

    def talletaja(self, ik):
        vl = None
        try:
            vl = inputlists.VotersList('hts', self._reg)
            if not vl.has_voter(ik):
                return None
            ret = vl.get_voter(ik)
            return ret
        finally:
            if vl is not None:
                vl.close()
                vl = None