def open_vault():
    p = os.path.dirname(os.path.realpath(__file__))
    # password is in a file inside computer and service
    vault_pass = open(p + '/../pass.txt', 'r',
                      encoding='utf-8').readline().strip()
    vault = pykeepass.PyKeePass(p + '/../vault.kdbx', password=vault_pass)
    return vault
Beispiel #2
0
def open_db(filename, password):
    try:
        with CONSOLE.status("[bold green]Opening DB"):
            db = pykeepass.PyKeePass(filename, password=password)
    except pykeepass.exceptions.CredentialsError:
        abort("Wrong credentials")

    return db
Beispiel #3
0
 def read_keypass_db(self):
     try:
         self.database_instance = pykeepass.PyKeePass(
             filename=self.database_location, password=self.master_password)
     except pykeepass.exceptions.CredentialsError as e:
         print("Incorrect master password, please try again.")
         self.get_master_password()
         self.read_keypass_db()
def get_keepass_file(keepass_db, password, keyfile):
    """
    Create and return the new KEEPASS File.
    """
    # Create keepass file from the keepass base file (keepass empty file)
    keepass = pykeepass.PyKeePass(CONF.KEEPASS_BASEFILE,
                                  password=CONF.KEEPASS_DEFAULT_PASSWORD)

    # Change the password of the file
    keepass.password = password

    # Change the keyfile of the file
    keepass.keyfile = keyfile

    # Save the keepass file into a new keepass file that will be used
    keepass.save(filename=keepass_db)

    # Return the new keepass file
    return pykeepass.PyKeePass(keepass_db, password=password, keyfile=keyfile)
Beispiel #5
0
def copy_entry(entry_name, database_filepath=None):
    """Copy the password corresponding to the given entry to the system
    clipboard.
    The user is prompted to give the correct master password to open the
    database file (default is `~/.database.kdbx` which can be overwritten). The
    function raises a SystemExit if the database file is not found.
    The password is then copied to the system clipboard. A progress bar is
    displayed. After ten seconds, the clipboard is cleared.
    """
    while True:
        password = getpass.getpass()
        try:
            database_filepath = database_filepath or DATABASE_FILEPATH
            kp = pykeepass.PyKeePass(os.path.expanduser(database_filepath),
                                     password=password)
            break
        except FileNotFoundError:
            raise SystemExit("Database file does not exist.")
        except IOError:
            print("Invalid password. Try again.", file=sys.stderr)

    try:
        entry = kp.find_entries_by_title(entry_name, first=True)
        message = "Entry '{}' not found. ".format(entry_name)
    except IndexError:
        entry = None
        message = ""

    if entry is None:
        # print entry titles in database
        print("{}Choose from:".format(message), file=sys.stderr)
        print('\n'.join(
            ("{e.title} ({e.username})".format(e=e) for e in kp.entries)),
              file=sys.stderr)
        raise SystemExit()
    else:
        pyperclip.copy(entry.password)
        print("Password has been copied to clipboard!")

        terminal_width = shutil.get_terminal_size().columns
        time_left = 50  # 50 increments of 0.2s = 10s
        increment = int(terminal_width / time_left)
        residual = terminal_width - time_left * increment
        char = '#'

        try:
            while time_left:
                time.sleep(0.2)
                time_left -= 1
                print(increment * char, end="", flush=True)
            print(residual * char)
        except KeyboardInterrupt:
            pass

        pyperclip.copy("")
Beispiel #6
0
 def get(self, info):
     print("Asking: {0}\n".format(self.kdbx), file=sys.stderr)
     password = self.ask_for_password()
     try:
         kdb = pykeepass.PyKeePass(self.kdbx, password=password)
         url = "{0}".format(info['host'])
         if 'username' not in info:
             entry = kdb.find_entries(url=url, first=True)
         else:
             entry = kdb.find_entries(url=url, username=info['username'], first=True)
         if entry is None:
             sys.exit("No key found for: {0}".format(info['host']))
         return entry
     except ChecksumError:
         print("Wrong password!\n", file=sys.stderr)
Beispiel #7
0
def main(args=None):
    opt = build_parser().parse_args(args)

    with pykeepass.PyKeePass(opt.kdbx,
                             password=getpass.getpass(),
                             keyfile=opt.keyfile) as kdb:
        for entry in kdb.entries:
            if not entry.password:
                continue
            r = check_hash(entry.password)
            if r > 0:
                m = 'Password for %s seen %d times before' % (entry.title, r)
                if opt.show_user:
                    m += ' - %s' % entry.username
                if opt.show_password:
                    m += ' - %s' % entry.password
                print(m)
Beispiel #8
0
 def __init__(self, password, dbpath):
     try:
         if password is None:
             password = getpass4.getpass('Database password:'******'HOME')}/Passwords.kdbx"
         self.database = pykeepass.PyKeePass(dbpath, password=password)
         self.default_group = self.database.root_group
         self.git = None
         self.fb = None
         self.reddit = None
         self.ssh = None
     except CredentialsIntegrityError:
         print("Wrong Password")
         exit()
     except FileNotFoundError:
         print(f'No such File: {dbpath}')
         exit()
Beispiel #9
0
def find_candidates(args, host):
    """Finds candidates that match host"""
    file_path = os.path.expanduser(args.path)

    # TODO find a way to keep the db open, so we don't open (and query
    # password) it every time

    pw = None
    if not args.no_password:
        pw = get_password()

    kf = args.keyfile_path
    if kf:
        kf = os.path.expanduser(kf)

    try:
        kp = pykeepass.PyKeePass(file_path, password=pw, keyfile=kf)
    except Exception as e:
        stderr("There was an error opening the DB: {}".format(str(e)))

    return kp.find_entries(url="{}{}{}".format(".*", host, ".*"), regex=True)
Beispiel #10
0
def main():
    args = parse_args()

    colorama.init()

    if args.debug:
        logging.basicConfig()
        LOGGER.setLevel(logging.DEBUG)
        LOGGER.debug(f"ARGS: {args}")

    kp = pykeepass.PyKeePass(filename=args.file,
                             password=args.password,
                             keyfile=args.keyfile)

    if args.action in ARGPARSE_LIST or not args.action:  # Default to list
        return ls(kp, args)
    elif args.action in ARGPARSE_GET:
        return get(kp, args)
    elif args.action in ARGPARSE_SEARCH:
        return search(kp, args)
    elif args.action in ARGPARSE_SHOW:
        return show(kp, args)
    else:
        LOGGER.error(f"Unknown action: {args.action}")
Beispiel #11
0
def get_credentials():
    db_location = os.path.join(os.path.expanduser("~"), 'credentials/Passwords.kdbx')
    kp = pyk.PyKeePass(db_location, password="******")
    return kp.find_entries(title='openweathermap')[0]
Beispiel #12
0
    hashlib.sha256).digest()

with open('database_base.kdbx', 'wb') as f:
    f.write(header)
    f.write(sha256)
    f.write(cred_check)
    f.write(block_checksum)
    f.write(block_data)
    f.write(empty_block_checksum)
    f.write(empty_block_data)

with open('database_base.kdbx', 'rb') as f:
    data = f.read()

shutil.copy('database_base.kdbx', 'database1.kdbx')
db = pykeepass.PyKeePass("database1.kdbx", password)
db.add_entry(db.root_group, "a" * 20, "a" * 20, "flag{this_is_fake_flag}")
db.save()

shutil.copy('database_base.kdbx', 'database2.kdbx')
db = pykeepass.PyKeePass("database2.kdbx", password)
db.add_entry(db.root_group, "a" * 20, "a" * 20, "flag{this_is_fake_flag}")
db.add_binary(b"\xbb" * 1)
db.save()

# 1. Import empty database with Chacha20
# r = remote('111.186.59.1', 10001)
# r.recvuntil('+')
# suffix = r.recv(16)
# r.recvuntil(' == ')
# digest = r.recv(64).decode()
Beispiel #13
0
    def __init__(self, base, password):

        self.kp = pykeepass.PyKeePass(base, password=password)
Beispiel #14
0
def get_kp():
    password = open('.password').read().lstrip().rstrip()
    return pykeepass.PyKeePass('/share/Passwords.kdbx', password=password)
Beispiel #15
0
def load_agent(args):
    # Load config
    print('[mfa-agent] Loading config:', args.config)
    config = toml.load(args.config)

    if not config.get(DATABASE_GROUP_NAME):
        print(
            f'[mfa-agent] STDERR, Bad config, no {DATABASE_GROUP_NAME} group',
            file=sys.stderr)
        sys.exit(1)

    if not config.get(DATABASE_GROUP_NAME, {}).get(DATABASE_FILE_KEY):
        print(
            f'[mfa-agent] STDERR, No {DATABASE_FILE_KEY} specified in config',
            file=sys.stderr)
        sys.exit(1)

    kdbx_database_file = config[DATABASE_GROUP_NAME][DATABASE_FILE_KEY]
    kdbx_key_file = config[DATABASE_GROUP_NAME][KEY_FILE_KEY]

    print(f'[mfa-agent] Loading database file: {kdbx_database_file}')
    if kdbx_key_file:
        print(f'[mfa-agent] Using keyfile: {kdbx_key_file}')

    # Read in password
    password = getpass.getpass(prompt='[mfa-agent] Enter password: '******'[mfa-agent] STDERR, FATAL ERROR: Could not open database')
        sys.exit(1)

    # Get group(s) from config
    group_names = [
        k for k in config.keys()
        if k != DATABASE_GROUP_NAME and k != DAEMON_GROUP_NAME
    ]

    secrets = {}

    # Load the entries from each group into memory
    for group_name in group_names:
        if 'entries' not in config[group_name]:
            print(
                f'[mfa-agent] STDERR, No entries in group: {group_name}, skipping',
                file=sys.stderr)
            continue

        entry_names = config[group_name]['entries']

        if entry_names == "all":
            group = kp.find_groups(name=group_name, first=True)
            if group:
                entry_names = [i.title for i in group.entries]
            else:
                print(
                    f'[mfa-agent] STDERR, Warning: Could not find group: {group_name}',
                    file=sys.stderr)
                entry_names = []

        for entry_name in entry_names:
            if entry_name.lower() in COMMANDS:
                print(
                    f'[mfa-agent] STDERR, Ignoring entry with reserved name: {entry_name}',
                    file=sys.stderr)
                continue

            entry_path = f'{group_name}/{entry_name}'
            entry = kp.find_entries(path=entry_path,
                                    recursive=True,
                                    first=True)

            if entry:
                secrets[entry_name.lower()] = entry.password
            else:
                print(
                    f'[mfa-agent] STDERR, Could not find entry: {entry_path}',
                    file=sys.stderr)

    # Spawn daemon to listen to socket requests and give codes
    print(f'[mfa-agent] Spawning daemon on socket: {args.socket_path}')
    with daemon.DaemonContext(signal_map={
            signal.SIGTERM: shutdown,
            signal.SIGTSTP: shutdown
    }):
        serve_forever(secrets, args.socket_path)