aboutsummaryrefslogtreecommitdiff
path: root/mu4web/password.py
blob: 26bc712f1163f1c72d614b9aeb9e3cd7d4bc0f69 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#!/usr/bin/env python3

"""
Simple password store, backed by a JSON file.

Also contains an entry point for managing the store.
"""

import hashlib
import json
import os
from typing import (
    TypedDict,
)


def gen_salt(length: int = 10) -> str:
    # urandom is stated to be suitable for cryptographic use.
    return bytearray(os.urandom(length)).hex()


# Manual list of entries, to stop someone from executing arbitrary
# code by modyfying password database
hash_methods = {
    'sha256': hashlib.sha256
}


class PasswordEntry(TypedDict):
    hash: str
    salt: str
    # One of the keys of hash_methods
    method: str


class Passwords:
    """
    Simple password store.

    [Parameters]
        fname - Path of json file to load and store from.
    """
    def __init__(self, fname: os.PathLike):
        self.fname = fname
        self.db: dict[str, PasswordEntry]
        try:
            with open(fname) as f:
                self.db = json.load(f)
        except Exception:
            self.db = {}

    def save(self) -> None:
        """Dump current data to disk."""
        try:
            with open(os.fspath(self.fname) + '.tmp', 'w') as f:
                json.dump(self.db, f)
                f.write('\n')
            os.rename(os.fspath(self.fname) + '.tmp', self.fname)
        except Exception as e:
            print(f'Saving password failed {e}')

    def add(self, username: str, password: str) -> None:
        """Add (or modify) entry in store."""
        if cur := self.db.get(username):
            salt = cur['salt']
            hashed = hashlib.sha256((salt + password).encode('UTF-8'))
            self.db[username] = {
                'hash': hashed.hexdigest(),
                'salt': salt,
                'method': 'sha256',
            }
        else:
            salt = gen_salt()
            hashed = hashlib.sha256((salt + password).encode('UTF-8'))
            self.db[username] = {
                'hash': hashed.hexdigest(),
                'salt': salt,
                'method': 'sha256'
            }

    def validate(self, username: str, password: str) -> bool:
        """Check if user exists, and if it has a correct password."""
        # These shall fail when key is missing
        data = self.db.get(username)
        if not data:
            return False
        proc = hash_methods[data['method']]
        digest = proc((data['salt'] + password).encode('UTF-8')).hexdigest()
        return data['hash'] == digest


def main() -> None:
    import argparse
    parser = argparse.ArgumentParser()

    parser.add_argument('--file', default='passwords.json')

    subparsers = parser.add_subparsers(dest='cmd')

    add_parser = subparsers.add_parser('add')
    add_parser.add_argument('username')
    add_parser.add_argument('password')

    val_parser = subparsers.add_parser('validate')
    val_parser.add_argument('username')
    val_parser.add_argument('password')

    args = parser.parse_args()

    passwords = Passwords(args.file)
    if args.cmd == 'add':
        passwords.add(args.username, args.password)
        passwords.save()
    elif args.cmd == 'validate':
        print(passwords.validate(args.username, args.password))
    else:
        parser.print_help()


if __name__ == '__main__':
    main()