Debian Codegraph @

proton/session/srp/util.py

raw ◀ ▶
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 # bcrypt accepts only first 72 bytes of password
41 if len(password) > 72:
42 password = password[:72]
43 salt = (salt + b"proton")[:16]
44 salt = bcrypt_b64_encode(salt)[:22]
45 hashed = bcrypt.hashpw(password, b"$2y$10$" + salt)
46 return hash_class(hashed + modulus).digest()
47
48 def hash_password(hash_class, password, salt, modulus, version):
49 if version == 4 or version == 3:
50 return hash_password_3(hash_class, password, salt, modulus)
51
52 # If the auth_version is lower then the
53 # supported value 3 (which were dropped in 2018). In such a case, the user
54 # needs to first login via web so that the auth version can be properly updated.
55 #
56 # This usually happens on older accounts that haven't been used in a while or
57 # account that rarely login via the web client.
58 raise ProtonUnsupportedAuthVersionError(
59 "Account auth_version is not supported. "
60 "Login via webclient for it to be updated."
61 )
62
63
64 def bytes_to_long(s):
65 return int.from_bytes(s, 'little')
66
67
68 def long_to_bytes(n, num_bytes):
69 return n.to_bytes(num_bytes, 'little')
70
71
72 def get_random(nbytes):
73 return bytes_to_long(os.urandom(nbytes))
74
75
76 def get_random_of_length(nbytes):
77 offset = (nbytes * 8) - 1
78 return get_random(nbytes) | (1 << offset)
79
80
81 def custom_hash(hash_class, *args, **kwargs):
82 h = hash_class()
83 for s in args:
84 if s is not None:
85 data = long_to_bytes(s, SRP_LEN_BYTES) if isinstance(s, int) else s
86 h.update(data)
87
88 return bytes_to_long(h.digest())