Skip to content
Snippets Groups Projects
client.py 40.6 KiB
Newer Older
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
#!/usr/bin/env python3

"""Gestion centralisée des mots de passe avec chiffrement GPG

Copyright (C) 2010-2020 Cr@ns <roots@crans.org>
Authors : Daniel Stan <daniel.stan@crans.org>
          Vincent Le Gallic <legallic@crans.org>
"""
Daniel STAN's avatar
Daniel STAN committed

Daniel STAN's avatar
Daniel STAN committed
import sys
import subprocess
import json
Daniel STAN's avatar
Daniel STAN committed
import tempfile
import os
Daniel STAN's avatar
Daniel STAN committed
import argparse
import re
import datetime
Daniel STAN's avatar
Daniel STAN committed
import copy
import logging
from configparser import ConfigParser
from secrets import token_urlsafe
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
# Import a SSH client
from paramiko.client import SSHClient
from paramiko.ssh_exception import SSHException
# Configuration loading
# On n'a pas encore accès à la config donc on devine le nom
bootstrap_cmd_name = os.path.split(sys.argv[0])[1]
default_config_path = os.path.expanduser("~/.config/" + bootstrap_cmd_name)
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
config_path = os.getenv(
    "CRANSPASSWORDS_CLIENT_CONFIG_DIR", default_config_path)
config = ConfigParser()
if not config.read(config_path + "/clientconfig.ini"):
    # If config could not be imported, display an error if required
    ducktape_display_error = sys.stderr.isatty() and \
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
        not any([opt in sys.argv for opt in ["-q", "--quiet"]]) and \
        __name__ == '__main__'
    if ducktape_display_error:
        # Do not use logger as it has not been initialized yet
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
        print("%s/clientconfig.ini could not be read. Please read README." %
              config_path)
        exit(1)

# Logger local
log = logging.getLogger(bootstrap_cmd_name)
Daniel STAN's avatar
Daniel STAN committed

#: Pattern utilisé pour détecter la ligne contenant le mot de passe dans les fichiers
pass_regexp = re.compile('[\t ]*pass(?:word)?[\t ]*:[\t ]*(.*)\r?\n?$',
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
                         flags=re.IGNORECASE)
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
# GPG Definitions
GPG = 'gpg'

#: Paramètres à fournir à gpg en fonction de l'action désirée
Daniel STAN's avatar
Daniel STAN committed
GPG_ARGS = {
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    'decrypt': ['-d'],
    'encrypt': ['--armor', '-es'],
    'receive-keys': ['--recv-keys'],
    'list-keys': ['--list-keys', '--with-colons', '--fixed-list-mode',
                  '--with-fingerprint', '--with-fingerprint'],  # Ce n'est pas une erreur. Il faut 2 --with-fingerprint pour avoir les fingerprints des subkeys.
}

#: Mapping (lettre de trustlevel) -> (signification, faut-il faire confiance à la clé)
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    "-": ("inconnue (pas de valeur assignée)", False),
    "o": ("inconnue (nouvelle clé)", False),
    "i": ("invalide (self-signature manquante ?)", False),
    "n": ("nulle (il ne faut pas faire confiance à cette clé)", False),
    "m": ("marginale (pas assez de lien de confiance vers cette clé)", False),
    "f": ("entière (clé dans le réseau de confiance)", True),
    "u": ("ultime (c'est probablement ta clé)", True),
    "r": ("révoquée", False),
    "e": ("expirée", False),
    "q": ("non définie", False),
}

def gpg(options, command, args=None):
Daniel STAN's avatar
Daniel STAN committed
    """Lance gpg pour la commande donnée avec les arguments
    donnés. Renvoie son entrée standard et sa sortie standard."""
Daniel STAN's avatar
Daniel STAN committed
    full_command = [GPG]
    full_command.extend(GPG_ARGS[command])
    if args:
        full_command.extend(args)
Daniel STAN's avatar
Daniel STAN committed
    else:
Daniel STAN's avatar
Daniel STAN committed
        full_command.extend(['--debug-level=1'])

    # Run gpg
    log.info("Running `%s`" % " ".join(full_command))
Daniel STAN's avatar
Daniel STAN committed
    proc = subprocess.Popen(full_command,
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
                            stdin=subprocess.PIPE,
                            stdout=subprocess.PIPE,
                            stderr=stderr,
                            close_fds=True)
Daniel STAN's avatar
Daniel STAN committed
        proc.stderr.close()
Daniel STAN's avatar
Daniel STAN committed
    return proc.stdin, proc.stdout

def _parse_timestamp(string, canbenone=False):
    """Interprète ``string`` comme un timestamp depuis l'Epoch."""
    if string == '' and canbenone:
        return None
    return datetime.datetime(*time.localtime(int(string))[:7])

def _parse_pub(data):
    """Interprète une ligne ``pub:``"""
    d = {
        'trustletter': data[1],
        'length': int(data[2]),
        'algorithm': int(data[3]),
        'longid': data[4],
        'signdate': _parse_timestamp(data[5]),
        'expiredate': _parse_timestamp(data[6], canbenone=True),
        'ownertrustletter': data[8],
        'capabilities': data[11],
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    }
def _parse_uid(data):
    """Interprète une ligne ``uid:``"""
    d = {
        'trustletter': data[1],
        'signdate': _parse_timestamp(data[5], canbenone=True),
        'hash': data[7],
        'uid': data[9],
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    }
def _parse_fpr(data):
    """Interprète une ligne ``fpr:``"""
    d = {
        'fpr': data[9],
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    }
def _parse_sub(data):
    """Interprète une ligne ``sub:``"""
    d = {
        'trustletter': data[1],
        'length': int(data[2]),
        'algorithm': int(data[3]),
        'longid': data[4],
        'signdate': _parse_timestamp(data[5]),
        'expiredate': _parse_timestamp(data[6], canbenone=True),
        'capabilities': data[11],
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    }
#: Functions to parse the recognized fields
GPG_PARSERS = {
    'pub': _parse_pub,
    'uid': _parse_uid,
    'fpr': _parse_fpr,
    'sub': _parse_sub,

def parse_keys(gpgout, debug=False):
    """Parse l'output d'un listing de clés gpg."""
    ring = {}
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    # Valeur utilisée pour dire "cet objet n'a pas encore été rencontré pendant le parsing"
    init_value = "initialize"
    current_pub = init_value
    current_sub = init_value
    for line in iter(gpgout.readline, ''):
        # La doc dit que l'output est en UTF-8 «regardless of any --display-charset setting»
        try:
            line = line.decode("utf-8")
        except UnicodeDecodeError:
            try:
                line = line.decode("iso8859-1")
            except UnicodeDecodeError:
                line = line.decode("iso8859-1", "ignore")
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
                log.warning(
                    "gpg is telling shit, it is neither ISO-8859-1 nor UTF-8. Dropping!")
        line = line.split(":")
        field = line[0]
        if field in GPG_PARSERS.keys():
            log.debug("begin loop, met %s :" % (field))
            log.debug("current_pub : %r" % current_pub)
            log.debug("current_sub : %r" % current_sub)
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
            except KeyError:
                log.error("*** FAILED *** Line: %s", line)
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
            if field == "pub":
                # Nouvelle clé
                # On sauvegarde d'abord le dernier sub (si il y en a un) dans son pub parent
                if current_sub != init_value:
                    current_pub["subkeys"].append(current_sub)
                # Ensuite on sauve le pub précédent (si il y en a un) dans le ring
                if current_pub != init_value:
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
                    ring[current_pub["fpr"]] = current_pub
                # On place le nouveau comme pub courant
                current_pub = content
                # Par défaut, il n'a ni subkeys, ni uids
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
                current_pub["subkeys"] = []
                current_pub["uids"] = []
                # On oublié l'éventuel dernier sub rencontré
                current_sub = init_value
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
            elif field == "fpr":
                if current_sub != init_value:
                    # On a lu un sub depuis le dernier pub, donc le fingerprint est celui du dernier sub rencontré
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
                    current_sub["fpr"] = content["fpr"]
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
                    current_pub["fpr"] = content["fpr"]
            elif field == "uid":
                current_pub["uids"].append(content)
            elif field == "sub":
                # Nouvelle sous-clé
                # D'abord on sauvegarde la précédente (si il y en a une) dans son pub parent
                if current_sub != init_value:
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
                    current_pub["subkeys"].append(current_sub)
                # On place la nouvelle comme sub courant
                current_sub = content
            log.debug("current_pub : %r" % current_pub)
            log.debug("current_sub : %r" % current_sub)
            log.debug("parsed object : %r" % content)
    # À la fin, il faut sauvegarder les derniers (sub, pub) rencontrés,
    # parce que leur sauvegarde n'a pas encore été déclenchée
    if current_sub != init_value:
        current_pub["subkeys"].append(current_sub)
    if current_pub != init_value:
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
        ring[current_pub["fpr"]] = current_pub
class simple_memoize(object):
    """ Memoization/Lazy """
    def __init__(self, f):
        self.f = f
        self.val = None

    def __call__(self, *args, **kwargs):
        """Attention ! On peut fournir des paramètres, mais comme on mémorise pour la prochaine fois,
           si on rappelle avec des paramètres différents, on aura quand même la même réponse.
           Pour l'instant, on s'en fiche puisque les paramètres ne changent pas d'un appel au suivant,
           mais il faudra s'en préoccuper si un jour on veut changer le comportement."""
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
        if self.val is None:
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
        # On évite de tout deepcopier. Typiquement, un SSHClient
        # ne devrait pas l'être (comme dans create_ssh_client)
        if type(self.val) in [dict, list]:
            return copy.deepcopy(self.val)
        else:
            return self.val
Daniel STAN's avatar
Daniel STAN committed
######
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
# Remote commands
Daniel STAN's avatar
Daniel STAN committed

me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
@simple_memoize
def create_ssh_client():
    """
    Create a SSH client with paramiko module
    """
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    if "host" not in options.serverdata:
        log.error("Missing parameter `host` in active server configuration")
        exit(1)
    # Create SSH client with system host keys and agent
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    client = SSHClient()
    client.load_system_host_keys()
    try:
        client.connect(str(options.serverdata['host']))
    except SSHException:
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
        log.error(
            "Host key is unknown or you are using a outdated python-paramiko (ssh-ed25519 was implemented in 2017)")
def remote_command(options, command, arg=None, stdin_contents=None):
    """
    Execute remote command and return output
    """
    client = create_ssh_client()

    # Build command
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    if "remote_cmd" not in options.serverdata:
        log.error("Missing parameter `remote_cmd` in active server configuration")
        exit(1)
    remote_cmd = options.serverdata['remote_cmd'] + " " + command
    if arg:
        remote_cmd += " " + arg
Daniel STAN's avatar
Daniel STAN committed

    # Run command and timeout after 10s
    log.info("Running command `%s`" % remote_cmd)
    stdin, stdout, stderr = client.exec_command(remote_cmd, timeout=10)
    # Write
    if stdin_contents is not None:
        log.info("Writing to stdin: %s" % stdin_contents)
        stdin.write(json.dumps(stdin_contents))
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
        stdin.flush()

    # Return code == 0 if success
    ret = stdout.channel.recv_exit_status()
    if ret != 0:
        if stderr.channel.recv_stderr_ready():
            err = stderr.read()
        log.error("Wrong server return code %s, error is %s" % (ret, err))
    # Decode directly read buffer
        answer = json.load(stdout)
    except ValueError:
        log.error("Error while parsing JSON")
        exit(42)

    log.debug("Server returned %s" % answer)
Daniel STAN's avatar
Daniel STAN committed

@simple_memoize
Daniel STAN's avatar
Daniel STAN committed
    """Récupère les clés du serveur distant"""
    return remote_command(options, "listkeys")
Daniel STAN's avatar
Daniel STAN committed

@simple_memoize
Daniel STAN's avatar
Daniel STAN committed
    """Récupère les roles du serveur distant"""
    return remote_command(options, "listroles")
Daniel STAN's avatar
Daniel STAN committed

@simple_memoize
Daniel STAN's avatar
Daniel STAN committed
    """Récupère les fichiers du serveur distant"""
    return remote_command(options, "listfiles")
Daniel STAN's avatar
Daniel STAN committed

@simple_memoize
def restore_all_files(options):
    """Récupère les fichiers du serveur distant"""
    return remote_command(options, "restorefiles")

me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
@simple_memoize
def get_file(options, filename):
    """
    Get the content of one remote file
    """
    return remote_command(options, "getfile", filename)
Daniel STAN's avatar
Daniel STAN committed

    """Dépose les fichiers sur le serveur distant"""
    return remote_command(options, "putfiles", stdin_contents=files)
Daniel STAN's avatar
Daniel STAN committed
def rm_file(filename):
    """Supprime le fichier sur le serveur distant"""
    return remote_command(options, "rmfile", filename)
Daniel STAN's avatar
Daniel STAN committed

@simple_memoize
def get_my_roles(options):
    """Retourne la liste des rôles de l'utilisateur, et également la liste des rôles dont il possède le role-w."""
    allroles = all_roles(options)
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    my_roles = [r for (r, users) in allroles.items()
                if distant_username in users]
    my_roles_w = [r[:-2] for r in my_roles if r.endswith("-w")]
    return (my_roles, my_roles_w)
def gen_password(length=15):
    """
    Generate a random password
    """
    return token_urlsafe(length)
Daniel STAN's avatar
Daniel STAN committed
######
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
# Local commands

Daniel STAN's avatar
Daniel STAN committed

Daniel STAN's avatar
Daniel STAN committed
    """Met à jour les clés existantes"""
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    _, stdout = gpg(options, "receive-keys",
                    [key for _, key in keys.values() if key])
    return stdout.read().decode("utf-8")
Daniel STAN's avatar
Daniel STAN committed

def _check_encryptable(key):
    """Vérifie qu'on peut chiffrer un message pour ``key``.
       C'est-à-dire, que la clé est de confiance (et non expirée).
       Puis qu'on peut chiffrer avec, ou qu'au moins une de ses subkeys est de chiffrement (capability e)
       et est de confiance et n'est pas expirée"""
    # Il faut que la clé soit dans le réseau de confiance…
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    meaning, trustvalue = GPG_TRUSTLEVELS[key["trustletter"]]
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
        return "La confiance en la clé est : %s" % (meaning,)
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    if "e" in key["capabilities"]:
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
        return ""
    # …soit avec une de ses subkeys
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    esubkeys = [sub for sub in key["subkeys"] if "e" in sub["capabilities"]]
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
        return "La clé principale de permet pas de chiffrer et auncune sous-clé de chiffrement."
    if any([GPG_TRUSTLEVELS[sub["trustletter"]][1] for sub in esubkeys]):
        return ""
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
        return "Aucune sous clé de chiffrement n'est de confiance et non expirée."
def check_keys(options, recipients=None, quiet=False):
    """Vérifie les clés, c'est-à-dire, si le mail est présent dans les identités du fingerprint,
       et que la clé est de confiance (et non expirée/révoquée).
        * Si ``recipients`` est fourni, vérifie seulement ces recipients.
          Renvoie la liste de ceux qu'on n'a pas droppés.
         * Si ``options.force=False``, demandera confirmation pour dropper un recipient dont la clé est invalide.
         * Sinon, et si ``options.drop_invalid=True``, droppe les recipients automatiquement.
        * Si rien n'est fourni, vérifie toutes les clés et renvoie juste un booléen disant si tout va bien.
       """
    trusted_recipients = []
        speak = options.verbose and not options.quiet
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
        keys = {u: val for (u, val) in keys.iteritems() if u in recipients}
        print("M : le mail correspond à un uid du fingerprint\nC : confiance OK (inclut la vérification de non expiration).\n")
    _, gpgout = gpg(options, 'list-keys')
    for (recipient, (mail, fpr)) in keys.iteritems():
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
        failed = ""
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
        if fpr is not None:
                print("Checking %s… " % mail, end="")
            # On vérifie qu'on possède la clé…
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
            if key is not None:
                # …qu'elle correspond au mail…
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
                if any(["<%s>" % (mail,) in u["uid"] for u in key["uids"]]):
                        print("M ", end="")
                    # … et qu'on peut raisonnablement chiffrer pour lui
                    failed = _check_encryptable(key)
                    if not failed and speak:
                        print("C ", end="")
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
                    failed = "!! Le fingerprint et le mail ne correspondent pas !"
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
                failed = "Pas (ou trop) de clé avec ce fingerprint."
                print("")
                log.warn("--> Fail on %s:%s\n--> %s" % (mail, fpr, failed))
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
                if recipients is not None:
                    # On cherche à savoir si on droppe ce recipient
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
                    message = "Abandonner le chiffrement pour cette clé ? (Si vous la conservez, il est posible que gpg crashe)"
                    if confirm(options, message, ('drop', fpr, mail)):
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
                        drop = True  # si on a répondu oui à "abandonner ?", on droppe
                    elif options.drop_invalid and options.force:
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
                        drop = True  # ou bien si --drop-invalid avec --force nous autorisent à dropper silencieusement
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
                        drop = False  # Là, on droppe pas
                    if not drop:
                        trusted_recipients.append(recipient)
                        log.warn("Droppe la clé %s:%s" % (fpr, recipient))
            else:
                trusted_recipients.append(recipient)
    if recipients is None:
        return set(keys.keys()).issubset(trusted_recipients)
    else:
        return trusted_recipients
Daniel STAN's avatar
Daniel STAN committed

def get_recipients_of_roles(options, roles):
Vincent Le gallic's avatar
Vincent Le gallic committed
    """Renvoie les destinataires d'une liste de rôles"""
    recipients = set()
    for role in roles:
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
        if role == "whoami":
        for recipient in allroles[role]:
            recipients.add(recipient)
    return recipients

    """Renvoie la liste des "username : mail (fingerprint)" """
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    return ["%s : %s (%s)" % (rec, allkeys[rec][0], allkeys[rec][1])
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
            for rec in get_recipients_of_roles(options, roles) if allkeys[rec][1]]

    """Chiffre le contenu pour les roles donnés"""
    allkeys = all_keys(options)
    recipients = get_recipients_of_roles(options, roles)
    recipients = check_keys(options, recipients=recipients, quiet=True)
Daniel STAN's avatar
Daniel STAN committed
    for recipient in recipients:
        fpr = allkeys[recipient][1]
        if fpr:
            fpr_recipients.append("-r")
            fpr_recipients.append(fpr)
    stdin, stdout = gpg(options, "encrypt", fpr_recipients)
    stdin.write(contents.encode("utf-8"))
Daniel STAN's avatar
Daniel STAN committed
    stdin.close()
    out = stdout.read().decode("utf-8")
Daniel STAN's avatar
Daniel STAN committed
    if out == '':
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
        return [False, "Échec de chiffrement"]
Daniel STAN's avatar
Daniel STAN committed
    else:
        return [True, out]
Daniel STAN's avatar
Daniel STAN committed

def decrypt(options, contents):
Daniel STAN's avatar
Daniel STAN committed
    """Déchiffre le contenu"""
    stdin, stdout = gpg(options, "decrypt")
    stdin.write(contents.encode("utf-8"))
Daniel STAN's avatar
Daniel STAN committed
    stdin.close()
    return stdout.read().decode("utf-8")
Daniel STAN's avatar
Daniel STAN committed

def put_password(options, roles, contents):
Daniel STAN's avatar
Daniel STAN committed
    """Dépose le mot de passe après l'avoir chiffré pour les
    destinataires dans ``roles``."""
    success, enc_pwd_or_error = encrypt(options, roles, contents)
    if success:
        enc_pwd = enc_pwd_or_error
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
        return put_files(options, [{'filename': options.fname, 'roles': roles, 'contents': enc_pwd}])[0]
Daniel STAN's avatar
Daniel STAN committed
    else:
        error = enc_pwd_or_error
        return [False, error]
Daniel STAN's avatar
Daniel STAN committed

######
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
# Interface

def need_filename(f):
    """Décorateur qui ajoutera la fonction à la liste des fonctions qui attendent un filename."""
    NEED_FILENAME.append(f)
    return f

me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
def editor(texte, annotations=""):
    """ Lance $EDITOR sur texte.
    Renvoie le nouveau texte si des modifications ont été apportées, ou None
    """
    # Avoid syntax hilight with ".txt". Would be nice to have some colorscheme
    # for annotations ...
    f = tempfile.NamedTemporaryFile(suffix='.txt')
    if annotations:
        annotations = "# " + annotations.replace("\n", "\n# ")
Daniel STAN's avatar
Daniel STAN committed
        # Usually, there is already an ending newline in a text document
        if texte and texte[-1] != '\n':
Daniel STAN's avatar
Daniel STAN committed
            annotations = '\n' + annotations
        else:
            annotations += '\n'
    f.write((texte + annotations).encode("utf-8"))
Daniel STAN's avatar
Daniel STAN committed
    f.flush()
Daniel STAN's avatar
Daniel STAN committed
    proc = subprocess.Popen([os.getenv('EDITOR', '/usr/bin/editor'), f.name])
    os.waitpid(proc.pid, 0)
Daniel STAN's avatar
Daniel STAN committed
    f.seek(0)
Daniel STAN's avatar
Daniel STAN committed
    ntexte = f.read().decode("utf-8", errors='ignore')
Daniel STAN's avatar
Daniel STAN committed
    f.close()
    ntexte = '\n'.join(
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
        filter(lambda l: not l.startswith('#'), ntexte.split('\n')))
    return ntexte
    """Affiche la liste des fichiers disponibles sur le serveur distant"""
    my_roles, _ = get_my_roles(options)
    files = all_files(options)
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    keys = list(files.keys())
    print("Liste des fichiers disponibles :")
    for fname in keys:
        froles = files[fname]
Daniel STAN's avatar
Daniel STAN committed
        access = set(my_roles).intersection(froles) != set([])
        print((" %s %s (%s)" % ((access and '+' or '-'), fname, ", ".join(froles))))
    print(("""--Mes roles: %s""" % (", ".join(my_roles),)))
def restore_files(options):
    """Restore les fichiers corrompues sur le serveur distant"""
    print("Fichier corrompus :")
    files = restore_all_files(options)
    keys = files.keys()
    keys.sort()
    for fname in keys:
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
        print(" %s (%s)" % (fname, files[fname]))
    """Affiche la liste des roles existants"""
    print("Liste des roles disponibles")
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    allroles = all_roles(options)
    for (role, usernames) in allroles.iteritems():
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
        if role == "whoami":
        if not role.endswith('-w'):
            print(" * %s : %s" % (role, ", ".join(usernames)))
    """Affiche la liste des serveurs disponibles"""
    print("Liste des serveurs disponibles")
    for server in config.keys():
        print(" * " + server)
def saveclipboard(restore=False, old_clipboard=None):
    """Enregistre le contenu du presse-papier. Le rétablit si ``restore=True``"""
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    if restore and old_clipboard is None:
        return
    act = '-in' if restore else '-out'
    proc = subprocess.Popen(['xclip', act, '-selection', 'clipboard'],
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
                            stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=sys.stderr)
    if not restore:
        old_clipboard = proc.stdout.read()
    else:
        input("Appuyez sur Entrée pour récupérer le contenu précédent du presse papier.")
        proc.stdin.write(old_clipboard)
    proc.stdin.close()
    proc.stdout.close()
Daniel STAN's avatar
Daniel STAN committed
def clipboard(texte):
    """Place ``texte`` dans le presse-papier en mémorisant l'ancien contenu."""
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    proc = subprocess.Popen(['xclip', '-selection', 'clipboard'],
                            stdin=subprocess.PIPE, stdout=sys.stdout, stderr=sys.stderr)
    proc.stdin.write(texte.encode("utf-8"))
Daniel STAN's avatar
Daniel STAN committed
    proc.stdin.close()
    """Affiche le contenu d'un fichier"""
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    gotit, value = get_file(options, fname)
    if not gotit:
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
        log.warn(value)  # value contient le message d'erreur
        return
    (sin, sout) = gpg(options, 'decrypt')
    content = passfile['contents']
    # Kludge (broken db ?)
    if type(content) == list:
        log.warn("Eau dans le gaz")
        content = content[-1]

    # Déchiffre le contenu
    sin.write(content.encode("utf-8"))
Daniel STAN's avatar
Daniel STAN committed
    sin.close()
    texte = sout.read().decode("utf-8")

    # Est-ce une clé ssh ?
    is_key = texte.startswith('-----BEGIN RSA PRIVATE KEY-----')
    # Est-ce que le mot de passe a été caché ? (si non, on utilisera less)
    is_hidden = is_key
    # Texte avec mdp caché
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    filtered = ""
    # Ancien contenu du press papier
Daniel STAN's avatar
Daniel STAN committed
    old_clipboard = None

    # Essaie de planquer le mot de passe
    for line in texte.split('\n'):
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
        catch_pass = None
Daniel STAN's avatar
Daniel STAN committed
        # On essaie de trouver le pass pour le cacher dans le clipboard
        # si ce n'est déjà fait et si c'est voulu
        if not is_hidden and options.clipboard:
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
            catch_pass = pass_regexp.match(line)
        if catch_pass is not None:
            is_hidden = True
            # On met le mdp dans le clipboard en mémorisant son ancien contenu
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
            old_clipboard = clipboard(catch_pass.group(1))
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
            line = "[Le mot de passe a été mis dans le presse papier]"
        filtered += line + '\n'

    if is_key:
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
        filtered = "La clé a été mise dans l'agent ssh"
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    shown = "Fichier %s:\n\n%s-----\nVisible par: %s\n" % (
        fname, filtered, ','.join(passfile['roles']))

    if is_key:
        with tempfile.NamedTemporaryFile(suffix='') as key_file:
            # Génère la clé publique correspondante
            key_file.write(texte.encode('utf-8'))
            key_file.flush()
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
            pub = subprocess.check_output(
                ['ssh-keygen', '-y', '-f', key_file.name])
            # Charge en mémoire
            subprocess.check_call(['ssh-add', key_file.name])

        # On attend (hors tmpfile)
        print(shown.encode('utf-8'))
        with tempfile.NamedTemporaryFile(suffix='') as pub_file:
            # On met la clé publique en fichier pour suppression
            pub_file.write(pub)
            pub_file.flush()
            subprocess.check_call(['ssh-add', '-d', pub_file.name])
    else:
        # Le binaire à utiliser
        showbin = "cat" if is_hidden else "less"
        proc = subprocess.Popen([showbin], stdin=subprocess.PIPE)
        out = proc.stdin
        out.write(shown.encode("utf-8"))
        out.close()
        os.waitpid(proc.pid, 0)

Daniel STAN's avatar
Daniel STAN committed
    # Repope ancien pass
    if old_clipboard is not None:
        saveclipboard(restore=True, old_clipboard=old_clipboard)
    """Modifie/Crée un fichier"""
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    gotit, value = get_file(options, fname)
Daniel STAN's avatar
Daniel STAN committed
    nfile = False
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    annotations = ""

    my_roles, _ = get_my_roles(options)
    new_roles = options.roles

    # Cas du nouveau fichier
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    if not gotit and "pas les droits" not in value:
Daniel STAN's avatar
Daniel STAN committed
        nfile = True
            print("Fichier introuvable")
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
        if not confirm(options, "Créer fichier ?"):
Daniel STAN's avatar
Daniel STAN committed
            return
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
        annotations += """Ceci est un fichier initial contenant un mot de passe
aléatoire, pensez à rajouter une ligne "login: ${login}"
Enregistrez le fichier vide pour annuler.\n"""
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
        texte = "pass: %s\n" % gen_password()

        if new_roles is None:
            new_roles = parse_roles(options, cast=True)
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
        passfile = {'roles': new_roles}
    elif not gotit:
        log.warn(value)
Daniel STAN's avatar
Daniel STAN committed
    else:
        (sin, sout) = gpg(options, 'decrypt')
Daniel STAN's avatar
Daniel STAN committed
        contents = passfile['contents']
        # <ducktape> (waddle waddle)
        if isinstance(contents, list):
            contents = contents[-1]
        # </ducktape>
        sin.write(contents.encode("utf-8"))
Daniel STAN's avatar
Daniel STAN committed
        sin.close()
        texte = sout.read().decode("utf-8")
        if new_roles is None:
            new_roles = passfile['roles']

    # On vérifie qu'on a le droit actuellement (plutôt que de se faire jeter
    # plus tard)
    if not any(r + '-w' in my_roles for r in passfile['roles']):
        log.warn("Aucun rôle en écriture pour ce fichier ! Abandon.")
        return

    # On peut vouloir chiffrer un fichier sans avoir la possibilité de le lire
    # dans le futur, mais dans ce cas on préfère demander confirmation
    if not any(r + '-w' in my_roles for r in new_roles):
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
        message = """Vous vous apprêtez à perdre vos droits en écriture""" + \
            """(ROLES ne contient rien parmi : %s) sur ce fichier, continuer ?"""
        message = message % (", ".join(r[:-2] for r in my_roles if '-w' in r),)
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    annotations += """Ce fichier sera chiffré pour les rôles suivants :\n%s\n
C'est-à-dire pour les utilisateurs suivants :\n%s""" % (
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
        ', '.join(new_roles),
        '\n'.join(' %s' %
                  rec for rec in get_dest_of_roles(options, new_roles))
    )
    ntexte = editor(texte, annotations)
    if ((not nfile and ntexte in ['', texte]          # pas nouveau, vidé ou pas modifié
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
         and set(new_roles) == set(passfile['roles']))  # et on n'a même pas touché à ses rôles,
            or (nfile and ntexte == '')):                 # ou alors on a créé un fichier vide.
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
        message = "Pas de modification à enregistrer.\n"
        message += "Si ce n'est pas un nouveau fichier, il a été vidé ou n'a pas été modifié (même pas ses rôles).\n"
        message += "Si c'est un nouveau fichier, vous avez tenté de le créer vide."
            print(message)
Daniel STAN's avatar
Daniel STAN committed
    else:
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
        ntexte = texte if ntexte is None else ntexte
        success, message = put_password(options, new_roles, ntexte)
        print(message)
_remember_dict = {}
def confirm(options, text, remember_key=None):
    """Demande confirmation, sauf si on est mode ``--force``.
    Si ``remember_key`` est fourni, il doit correspondre à un objet hashable
    qui permettra de ne pas poser deux fois les mêmes questions.
    """
    global _remember_dict
    if remember_key in _remember_dict:
        return _remember_dict[remember_key]
Daniel STAN's avatar
Daniel STAN committed
    while True:
        out = input((text + ' (o/n)')).lower()
Daniel STAN's avatar
Daniel STAN committed
        if out == 'o':
Daniel STAN's avatar
Daniel STAN committed
        elif out == 'n':
            res = False
            break
    # Remember the answer
    if remember_key is not None:
        _remember_dict[remember_key] = res
    return res
    """Supprime un fichier"""
    if not confirm(options, 'Êtes-vous sûr de vouloir supprimer %s ?' % (fname,)):
Daniel STAN's avatar
Daniel STAN committed
        return
    message = rm_file(fname)
    print(message)
    """Vérifie les clés et affiche un message en fonction du résultat"""
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    print("Vérification que les clés sont valides (uid correspondant au login) et de confiance.")
    print(check_keys(options) and "Base de clés ok" or "Erreurs dans la base")
    """Met à jour les clés existantes et affiche le résultat"""
    print(update_keys(options))
def recrypt_files(options, strict=False):
       Ici, la signification de ``options.roles`` est :
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
         strict     => on chiffre les fichiers dont *tous* les rôles sont dans la liste
         non strict => on ne veut rechiffrer que les fichiers qui ont au moins un de ces roles.
       """
    rechiffre_roles = options.roles
    _, my_roles_w = get_my_roles(options)
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    if rechiffre_roles is None:
        # Sans précisions, on prend tous les roles qu'on peut

    def is_wanted(fileroles):
        # On drope ce qui ne peut être écrit
        if not set(fileroles).intersection(my_roles_w):
            return False
        if strict:
            return set(fileroles).issubset(rechiffre_roles)
        else:
            return bool(set(fileroles).intersection(rechiffre_roles))

    askfiles = [filename for (filename, fileroles) in allfiles.iteritems()
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
                if is_wanted(fileroles)]
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    files = [get_file(options, f) for f in askfiles]

    # Au cas où on aurait échoué à récupérer ne serait-ce qu'un de ces fichiers,
    # on affiche le message d'erreur correspondant et on abandonne.
    for (success, message) in files:
        if not success:
            log.warn(message)
    # On informe l'utilisateur et on demande confirmation avant de rechiffrer
    # Si il a précisé --force, on ne lui demandera rien.
    filenames = ", ".join(askfiles)
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    message = "Vous vous apprêtez à rechiffrer les fichiers suivants :\n%s" % filenames
    if not confirm(options, message + "\nConfirmer"):
        exit(2)
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    to_put = [{'filename': f['filename'],
               'roles': f['roles'],
               'contents': encrypt(options, f['roles'], decrypt(options, f['contents']))[-1]}
              for [success, f] in files]
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
            print("Rechiffrement de %s" %
                  (", ".join([f['filename'] for f in to_put])))
        results = put_files(options, to_put)
        # On affiche les messages de retour
        if not options.quiet:
            for i in range(len(results)):
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
                print("%s : %s" % (to_put[i]['filename'], results[i][1]))
            print("Aucun fichier n'a besoin d'être rechiffré")
def parse_roles(options, cast=False):
    """Interprête la liste de rôles fournie par l'utilisateur.
       Si il n'en a pas fourni, c'est-à-dire que roles
       vaut None, alors on considère cette valeur comme valide.
       Cependant, si ``cast`` est vraie, cette valeur est remplacée par
       tous les roles en écriture (*-w) de l'utilisateur.
       Renvoie ``False`` si au moins un de ces rôles pose problème.
       poser problème, c'est :
        * être un role-w (il faut utiliser le role sans le w)
        * ne pas exister dans la config du serveur
    """
    if options.roles is None and not cast:
        return options.roles

    strroles = options.roles
    allroles = all_roles(options)
    _, my_roles_w = get_my_roles(options)
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    if strroles is None:
        # L'utilisateur n'a rien donné, on lui donne les rôles (non -w) dont il possède le -w
        return my_roles_w
Daniel STAN's avatar
Daniel STAN committed
    ret = set()
    for role in strroles.split(','):
            log.warn("role %s do not exists" % role)
            exit(1)
Daniel STAN's avatar
Daniel STAN committed
        if role.endswith('-w'):
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
            log.warn("role %s should not be used, rather use %s" %
                     (role, role[:-2]))
            exit(1)
Daniel STAN's avatar
Daniel STAN committed
        ret.add(role)
    return list(ret)
def insult_on_nofilename(options, parser):
    """Insulte (si non quiet) et quitte si aucun nom de fichier n'a été fourni en commandline."""
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    if options.fname is None:
        log.warn("You need to provide a filename with this command")
        exit(1)
Daniel STAN's avatar
Daniel STAN committed
if __name__ == "__main__":
    # Gestion des arguments
    parser = argparse.ArgumentParser(
        description="Gestion de mots de passe partagés grâce à GPG.",
    )
    parser.add_argument(
        '-v', '--verbose',
        action='count',
        default=1,
        help="verbose mode, multiple -v options increase verbosity",
    )
    parser.add_argument(
        '-q', '--quiet',
        action='store_true',
        default=False,
        help="silent mode: hide errors, overrides verbosity"
me5na7qbjqbrp's avatar
me5na7qbjqbrp committed
    parser.add_argument(
        '-s', '--server',