Debian Codegraph @

proton/session/srp/util.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 """
2 Copyright (c) 2023 Proton AG
3
4 This file is part of Proton.
5
6 Proton is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
10
11 Proton is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with ProtonVPN. If not, see <https://www.gnu.org/licenses/>.
18 """
19 import base64
20 import bcrypt
21 import os
22
23 from proton.session.exceptions import ProtonUnsupportedAuthVersionError
24
25
26 PM_VERSION = 4
27
28 SRP_LEN_BYTES = 256
29 SALT_LEN_BYTES = 10
30
31
32 def bcrypt_b64_encode(s): # The joy of bcrypt
33 bcrypt_base64 = b"./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" # noqa
34 std_base64chars = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" # noqa
35 s = base64.b64encode(s)
36 return s.translate(bytes.maketrans(std_base64chars, bcrypt_base64))
37
38
39 def hash_password_3(hash_class, password, salt, modulus):
40 salt = (salt + b"proton")[:16]
41 salt = bcrypt_b64_encode(salt)[:22]
42 hashed = bcrypt.hashpw(password, b"$2y$10$" + salt)
43 return hash_class(hashed + modulus).digest()
44
45
46 def hash_password(hash_class, password, salt, modulus, version):
47 if version == 4 or version == 3:
48 return hash_password_3(hash_class, password, salt, modulus)
49
50 # If the auth_version is lower then the
51 # supported value 3 (which were dropped in 2018). In such a case, the user
52 # needs to first login via web so that the auth version can be properly updated.
53 #
54 # This usually happens on older accounts that haven't been used in a while or
55 # account that rarely login via the web client.
56 raise ProtonUnsupportedAuthVersionError(
57 "Account auth_version is not supported. "
58 "Login via webclient for it to be updated."
59 )
60
61
62 def bytes_to_long(s):
63 return int.from_bytes(s, 'little')
64
65
66 def long_to_bytes(n, num_bytes):
67 return n.to_bytes(num_bytes, 'little')
68
69
70 def get_random(nbytes):
71 return bytes_to_long(os.urandom(nbytes))
72
73
74 def get_random_of_length(nbytes):
75 offset = (nbytes * 8) - 1
76 return get_random(nbytes) | (1 << offset)
77
78
79 def custom_hash(hash_class, *args, **kwargs):
80 h = hash_class()
81 for s in args:
82 if s is not None:
83 data = long_to_bytes(s, SRP_LEN_BYTES) if isinstance(s, int) else s
84 h.update(data)
85
86 return bytes_to_long(h.digest())