python-vaultwarden2 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- python_vaultwarden2-0.1.0.dist-info/METADATA +69 -0
- python_vaultwarden2-0.1.0.dist-info/RECORD +34 -0
- python_vaultwarden2-0.1.0.dist-info/WHEEL +4 -0
- python_vaultwarden2-0.1.0.dist-info/licenses/LICENSE +202 -0
- vaultwarden2/__init__.py +47 -0
- vaultwarden2/_async/__init__.py +1 -0
- vaultwarden2/_async/account.py +379 -0
- vaultwarden2/_async/admin.py +485 -0
- vaultwarden2/_async/auth.py +218 -0
- vaultwarden2/_async/base.py +462 -0
- vaultwarden2/_async/client.py +130 -0
- vaultwarden2/_async/organizations.py +914 -0
- vaultwarden2/_async/vault.py +970 -0
- vaultwarden2/_core.py +1103 -0
- vaultwarden2/_encode.py +422 -0
- vaultwarden2/_json.py +215 -0
- vaultwarden2/_merge.py +529 -0
- vaultwarden2/_offload.py +65 -0
- vaultwarden2/_sync/__init__.py +1 -0
- vaultwarden2/_sync/account.py +381 -0
- vaultwarden2/_sync/admin.py +487 -0
- vaultwarden2/_sync/auth.py +220 -0
- vaultwarden2/_sync/base.py +464 -0
- vaultwarden2/_sync/client.py +132 -0
- vaultwarden2/_sync/organizations.py +914 -0
- vaultwarden2/_sync/vault.py +968 -0
- vaultwarden2/crypto.py +634 -0
- vaultwarden2/dump.py +362 -0
- vaultwarden2/errors.py +123 -0
- vaultwarden2/export.py +128 -0
- vaultwarden2/models.py +842 -0
- vaultwarden2/py.typed +0 -0
- vaultwarden2/search.py +206 -0
- vaultwarden2/totp.py +214 -0
vaultwarden2/_core.py
ADDED
|
@@ -0,0 +1,1103 @@
|
|
|
1
|
+
"""Network-free core shared by the async and sync clients.
|
|
2
|
+
|
|
3
|
+
Request bodies, response parsing, key unlocking and decryption of server data. Nothing here performs I/O.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import logging
|
|
9
|
+
import uuid
|
|
10
|
+
import warnings
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from enum import IntEnum
|
|
13
|
+
from typing import TYPE_CHECKING, Any, TypeVar
|
|
14
|
+
|
|
15
|
+
from vaultwarden2 import crypto
|
|
16
|
+
from vaultwarden2._json import JsonObject
|
|
17
|
+
from vaultwarden2.crypto import KdfParams, KdfType, SymmetricKey
|
|
18
|
+
from vaultwarden2.errors import ApiError, AuthenticationError, CryptoError, RateLimitError, TwoFactorRequiredError, UnsafeWriteError, VaultwardenDataWarning
|
|
19
|
+
from vaultwarden2.models import (
|
|
20
|
+
Attachment,
|
|
21
|
+
Card,
|
|
22
|
+
Cipher,
|
|
23
|
+
CipherType,
|
|
24
|
+
Collection,
|
|
25
|
+
CollectionAccess,
|
|
26
|
+
CustomField,
|
|
27
|
+
FieldType,
|
|
28
|
+
Folder,
|
|
29
|
+
Group,
|
|
30
|
+
Identity,
|
|
31
|
+
Login,
|
|
32
|
+
LoginUri,
|
|
33
|
+
Member,
|
|
34
|
+
MemberStatus,
|
|
35
|
+
Organization,
|
|
36
|
+
OrganizationUserType,
|
|
37
|
+
PasswordHistoryEntry,
|
|
38
|
+
Policy,
|
|
39
|
+
PolicyType,
|
|
40
|
+
Profile,
|
|
41
|
+
RepromptType,
|
|
42
|
+
SshKey,
|
|
43
|
+
UriMatch,
|
|
44
|
+
Vault,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
if TYPE_CHECKING:
|
|
48
|
+
from collections.abc import Callable
|
|
49
|
+
|
|
50
|
+
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey, RSAPublicKey
|
|
51
|
+
|
|
52
|
+
log = logging.getLogger('vaultwarden2')
|
|
53
|
+
|
|
54
|
+
DEVICE_TYPE_SDK = 21
|
|
55
|
+
USER_CLIENT_ID = 'cli'
|
|
56
|
+
INTERACTIVE_SCOPE = 'api offline_access'
|
|
57
|
+
API_KEY_SCOPE = 'api'
|
|
58
|
+
CLIENT_VERSION = '2026.5.0'
|
|
59
|
+
"""Sent as ``Bitwarden-Client-Version``. The header name is part of the protocol. Vaultwarden hides newer features (e.g. SSH key items) from older or unknown clients."""
|
|
60
|
+
TOKEN_REFRESH_MARGIN = 60.0
|
|
61
|
+
"""Seconds before expiry at which the access token is refreshed."""
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
65
|
+
class Device:
|
|
66
|
+
"""How a client identifies itself to the server; shown in the account's device list.
|
|
67
|
+
|
|
68
|
+
Pass the same identifier on every run of a script, so repeated runs count as one device and do not trigger
|
|
69
|
+
"new device" notifications.
|
|
70
|
+
|
|
71
|
+
Attributes:
|
|
72
|
+
identifier: A stable unique id (a random UUID by default).
|
|
73
|
+
name: The name shown in the device list.
|
|
74
|
+
type: The device type number. 21 ("SDK") by default.
|
|
75
|
+
|
|
76
|
+
Example:
|
|
77
|
+
```python
|
|
78
|
+
from vaultwarden2 import Device, VaultwardenClient
|
|
79
|
+
vw = VaultwardenClient(url, device=Device(identifier='2f1c6c3e-...', name='nightly-backup'))
|
|
80
|
+
```
|
|
81
|
+
"""
|
|
82
|
+
|
|
83
|
+
identifier: str = field(default_factory=lambda: str(uuid.uuid4()))
|
|
84
|
+
name: str = 'python-vaultwarden2'
|
|
85
|
+
type: int = DEVICE_TYPE_SDK
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@dataclass(slots=True, kw_only=True)
|
|
89
|
+
class UserKeys:
|
|
90
|
+
"""Unlocked key material of a session. Never shown in ``repr()``.
|
|
91
|
+
|
|
92
|
+
Attributes:
|
|
93
|
+
user_key: The account's user key (encrypts personal items and folders).
|
|
94
|
+
private_key: The account's RSA private key (decrypts shared organization keys), if any.
|
|
95
|
+
org_keys: Organization keys by organization id.
|
|
96
|
+
"""
|
|
97
|
+
|
|
98
|
+
user_key: SymmetricKey
|
|
99
|
+
private_key: RSAPrivateKey | None = None
|
|
100
|
+
org_keys: dict[str, SymmetricKey] = field(default_factory=dict)
|
|
101
|
+
|
|
102
|
+
def __repr__(self) -> str:
|
|
103
|
+
"""Describe the keys without their material.
|
|
104
|
+
|
|
105
|
+
Returns:
|
|
106
|
+
The number of organization keys only.
|
|
107
|
+
"""
|
|
108
|
+
return f'UserKeys(orgs={len(self.org_keys)})'
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
112
|
+
class TokenResponse:
|
|
113
|
+
"""A successful response of the token endpoint.
|
|
114
|
+
|
|
115
|
+
Attributes:
|
|
116
|
+
access_token: The bearer token for API requests.
|
|
117
|
+
refresh_token: The token to renew the session, if issued.
|
|
118
|
+
expires_in: Lifetime of the access token in seconds.
|
|
119
|
+
data: The full response (keys and KDF information).
|
|
120
|
+
"""
|
|
121
|
+
|
|
122
|
+
access_token: str
|
|
123
|
+
refresh_token: str | None
|
|
124
|
+
expires_in: float
|
|
125
|
+
data: JsonObject
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
# ---------------------------------------------------------------- request bodies
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def token_form_password(
|
|
132
|
+
email: str,
|
|
133
|
+
password_hash: str,
|
|
134
|
+
device: Device,
|
|
135
|
+
*,
|
|
136
|
+
two_factor_token: str | None = None,
|
|
137
|
+
two_factor_provider: int | None = None,
|
|
138
|
+
two_factor_remember: bool = False,
|
|
139
|
+
) -> dict[str, str]:
|
|
140
|
+
"""Form body for the password grant.
|
|
141
|
+
|
|
142
|
+
Args:
|
|
143
|
+
email: The account email (normalized).
|
|
144
|
+
password_hash: The authentication hash of the master password.
|
|
145
|
+
device: The client's device identity.
|
|
146
|
+
two_factor_token: A two-step login code, if any.
|
|
147
|
+
two_factor_provider: The provider of the code; the authenticator app by default.
|
|
148
|
+
two_factor_remember: Ask the server to remember the device.
|
|
149
|
+
|
|
150
|
+
Returns:
|
|
151
|
+
The form fields.
|
|
152
|
+
"""
|
|
153
|
+
form = {
|
|
154
|
+
'grant_type': 'password',
|
|
155
|
+
'username': crypto.normalize_email(email),
|
|
156
|
+
'password': password_hash,
|
|
157
|
+
'scope': INTERACTIVE_SCOPE,
|
|
158
|
+
'client_id': USER_CLIENT_ID,
|
|
159
|
+
'deviceIdentifier': device.identifier,
|
|
160
|
+
'deviceName': device.name,
|
|
161
|
+
'deviceType': str(device.type),
|
|
162
|
+
}
|
|
163
|
+
if two_factor_token is not None:
|
|
164
|
+
form['twoFactorToken'] = two_factor_token
|
|
165
|
+
form['twoFactorProvider'] = str(two_factor_provider if two_factor_provider is not None else 0)
|
|
166
|
+
form['twoFactorRemember'] = '1' if two_factor_remember else '0'
|
|
167
|
+
return form
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def token_form_api_key(client_id: str, client_secret: str, device: Device) -> dict[str, str]:
|
|
171
|
+
"""Form body for the personal API key (client credentials) grant.
|
|
172
|
+
|
|
173
|
+
Args:
|
|
174
|
+
client_id: The API key's client id.
|
|
175
|
+
client_secret: The API key's secret.
|
|
176
|
+
device: The client's device identity.
|
|
177
|
+
|
|
178
|
+
Returns:
|
|
179
|
+
The form fields.
|
|
180
|
+
"""
|
|
181
|
+
return {
|
|
182
|
+
'grant_type': 'client_credentials',
|
|
183
|
+
'client_id': client_id,
|
|
184
|
+
'client_secret': client_secret,
|
|
185
|
+
'scope': API_KEY_SCOPE,
|
|
186
|
+
'deviceIdentifier': device.identifier,
|
|
187
|
+
'deviceName': device.name,
|
|
188
|
+
'deviceType': str(device.type),
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def token_form_refresh(refresh_token: str) -> dict[str, str]:
|
|
193
|
+
"""Form body for the refresh grant.
|
|
194
|
+
|
|
195
|
+
Args:
|
|
196
|
+
refresh_token: The refresh token.
|
|
197
|
+
|
|
198
|
+
Returns:
|
|
199
|
+
The form fields.
|
|
200
|
+
"""
|
|
201
|
+
return {'grant_type': 'refresh_token', 'client_id': USER_CLIENT_ID, 'refresh_token': refresh_token}
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def kdf_payload(kdf: KdfParams) -> dict[str, int | None]:
|
|
205
|
+
"""KDF settings in the shape the account endpoints expect.
|
|
206
|
+
|
|
207
|
+
Args:
|
|
208
|
+
kdf: The settings.
|
|
209
|
+
|
|
210
|
+
Returns:
|
|
211
|
+
``kdf``, ``kdfIterations``, ``kdfMemory`` and ``kdfParallelism``.
|
|
212
|
+
"""
|
|
213
|
+
return {'kdf': int(kdf.type), 'kdfIterations': kdf.iterations, 'kdfMemory': kdf.memory, 'kdfParallelism': kdf.parallelism}
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def validate_kdf(kdf: KdfParams) -> None:
|
|
217
|
+
"""Reject KDF settings for a new account or a KDF change before anything is sent.
|
|
218
|
+
|
|
219
|
+
The settings must be accepted by vaultwarden (PBKDF2 at least 100000 iterations; Argon2id memory at most
|
|
220
|
+
1024 MiB, parallelism at most 16) *and* by the login check of this library and the official apps (see
|
|
221
|
+
``check_server_kdf``), so the account can always be logged into again afterwards.
|
|
222
|
+
|
|
223
|
+
Args:
|
|
224
|
+
kdf: The settings to set.
|
|
225
|
+
|
|
226
|
+
Raises:
|
|
227
|
+
CryptoError: The settings are outside these bounds.
|
|
228
|
+
"""
|
|
229
|
+
if kdf.type == KdfType.PBKDF2_SHA256 and kdf.iterations < VAULTWARDEN_PBKDF2_MIN_ITERATIONS:
|
|
230
|
+
raise CryptoError(f'PBKDF2 needs at least {VAULTWARDEN_PBKDF2_MIN_ITERATIONS} iterations')
|
|
231
|
+
try:
|
|
232
|
+
check_server_kdf(kdf)
|
|
233
|
+
except CryptoError as e:
|
|
234
|
+
raise CryptoError(f'KDF settings out of range: {kdf}') from e
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def master_password_data(email: str, password: str, kdf: KdfParams, user_key: SymmetricKey) -> dict[str, Any]:
|
|
238
|
+
"""``authenticationData`` and ``unlockData`` for a new master password, KDF or email: the user key re-wrapped.
|
|
239
|
+
|
|
240
|
+
The result is re-derived and checked before it is returned.
|
|
241
|
+
|
|
242
|
+
Args:
|
|
243
|
+
email: The (new) email address, used as salt.
|
|
244
|
+
password: The (new) master password.
|
|
245
|
+
kdf: The (new) KDF settings.
|
|
246
|
+
user_key: The account's user key (unchanged).
|
|
247
|
+
|
|
248
|
+
Returns:
|
|
249
|
+
The two request parts.
|
|
250
|
+
|
|
251
|
+
Raises:
|
|
252
|
+
UnsafeWriteError: The self-check failed.
|
|
253
|
+
"""
|
|
254
|
+
salt = crypto.normalize_email(email)
|
|
255
|
+
master_key = crypto.make_master_key(password, salt, kdf)
|
|
256
|
+
kdf_json = kdf_payload(kdf)
|
|
257
|
+
data = {
|
|
258
|
+
'authenticationData': {'salt': salt, 'kdf': kdf_json, 'masterPasswordAuthenticationHash': crypto.master_password_hash(master_key, password)},
|
|
259
|
+
'unlockData': {'salt': salt, 'kdf': kdf_json, 'masterKeyWrappedUserKey': str(crypto.encrypt(user_key.to_bytes(), SymmetricKey.stretch(master_key)))},
|
|
260
|
+
}
|
|
261
|
+
_verify_master_password_data(data, password, user_key)
|
|
262
|
+
return data
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _verify_master_password_data(data: dict[str, Any], password: str, user_key: SymmetricKey) -> None:
|
|
266
|
+
"""Re-derive everything from the payload itself: the server must be able to authenticate and unlock with it.
|
|
267
|
+
|
|
268
|
+
Args:
|
|
269
|
+
data: The payload from ``master_password_data``.
|
|
270
|
+
password: The master password.
|
|
271
|
+
user_key: The expected user key.
|
|
272
|
+
|
|
273
|
+
Raises:
|
|
274
|
+
UnsafeWriteError: The hash or the wrapped user key does not match.
|
|
275
|
+
"""
|
|
276
|
+
unlock_info = data['unlockData']
|
|
277
|
+
kdf = parse_kdf(JsonObject(unlock_info['kdf']))
|
|
278
|
+
master_key = crypto.make_master_key(password, unlock_info['salt'], kdf)
|
|
279
|
+
ok = (
|
|
280
|
+
crypto.master_password_hash(master_key, password) == data['authenticationData']['masterPasswordAuthenticationHash']
|
|
281
|
+
and crypto.decrypt_user_key(unlock_info['masterKeyWrappedUserKey'], master_key) == user_key
|
|
282
|
+
)
|
|
283
|
+
if not ok: # pragma: no cover - defensive
|
|
284
|
+
raise UnsafeWriteError('master password payload self-check failed; nothing sent')
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def register_payload(email: str, password: str, kdf: KdfParams, email_verification_token: str, hint: str | None = None) -> dict[str, Any]:
|
|
288
|
+
"""Body for ``/identity/accounts/register/finish``: new user key and RSA key pair, wrapped with the master key.
|
|
289
|
+
|
|
290
|
+
Args:
|
|
291
|
+
email: The new account's email.
|
|
292
|
+
password: The master password.
|
|
293
|
+
kdf: The KDF settings.
|
|
294
|
+
email_verification_token: The token from the verification step.
|
|
295
|
+
hint: The master password hint.
|
|
296
|
+
|
|
297
|
+
Returns:
|
|
298
|
+
The request body.
|
|
299
|
+
|
|
300
|
+
Raises:
|
|
301
|
+
CryptoError: ``kdf`` is outside the supported range (see ``validate_kdf``).
|
|
302
|
+
"""
|
|
303
|
+
validate_kdf(kdf)
|
|
304
|
+
master_key = crypto.make_master_key(password, email, kdf)
|
|
305
|
+
user_key = SymmetricKey.generate()
|
|
306
|
+
public_key, encrypted_private_key = crypto.generate_key_pair(user_key)
|
|
307
|
+
return {
|
|
308
|
+
'email': crypto.normalize_email(email),
|
|
309
|
+
'masterPasswordHash': crypto.master_password_hash(master_key, password),
|
|
310
|
+
'masterPasswordHint': hint,
|
|
311
|
+
'key': str(crypto.encrypt(user_key.to_bytes(), SymmetricKey.stretch(master_key))),
|
|
312
|
+
'keys': {'publicKey': public_key, 'encryptedPrivateKey': encrypted_private_key},
|
|
313
|
+
'emailVerificationToken': email_verification_token,
|
|
314
|
+
**kdf_payload(kdf),
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
# ---------------------------------------------------------------- response parsing
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def error_message(body: Any) -> str:
|
|
322
|
+
"""A human-readable message from an error response.
|
|
323
|
+
|
|
324
|
+
Args:
|
|
325
|
+
body: The decoded response body.
|
|
326
|
+
|
|
327
|
+
Returns:
|
|
328
|
+
The best available message.
|
|
329
|
+
"""
|
|
330
|
+
obj = JsonObject(body)
|
|
331
|
+
model = obj.obj('errorModel')
|
|
332
|
+
for candidate in (model.get_str('message') if model else None, obj.get_str('error_description'), obj.get_str('message'), obj.get_str('error')):
|
|
333
|
+
if candidate:
|
|
334
|
+
return candidate
|
|
335
|
+
return str(body)[:200] if body else 'no details'
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def raise_for_status(status_code: int, body: Any) -> None:
|
|
339
|
+
"""Raise the matching exception for a non-2xx response.
|
|
340
|
+
|
|
341
|
+
Args:
|
|
342
|
+
status_code: The HTTP status.
|
|
343
|
+
body: The decoded response body.
|
|
344
|
+
|
|
345
|
+
Raises:
|
|
346
|
+
AuthenticationError: HTTP 401.
|
|
347
|
+
RateLimitError: HTTP 429.
|
|
348
|
+
ApiError: Any other non-2xx status.
|
|
349
|
+
"""
|
|
350
|
+
if status_code == 401:
|
|
351
|
+
raise AuthenticationError(error_message(body))
|
|
352
|
+
if status_code == 429:
|
|
353
|
+
raise RateLimitError(status_code, error_message(body))
|
|
354
|
+
if not 200 <= status_code < 300:
|
|
355
|
+
raise ApiError(status_code, error_message(body))
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def parse_token_response(status_code: int, body: Any) -> TokenResponse:
|
|
359
|
+
"""Parse a token endpoint response.
|
|
360
|
+
|
|
361
|
+
Args:
|
|
362
|
+
status_code: The HTTP status.
|
|
363
|
+
body: The decoded response body.
|
|
364
|
+
|
|
365
|
+
Returns:
|
|
366
|
+
The tokens and data.
|
|
367
|
+
|
|
368
|
+
Raises:
|
|
369
|
+
TwoFactorRequiredError: The account needs a second factor.
|
|
370
|
+
AuthenticationError: Wrong credentials, or no access token in the response.
|
|
371
|
+
RateLimitError: HTTP 429.
|
|
372
|
+
ApiError: Any other failure.
|
|
373
|
+
"""
|
|
374
|
+
obj = JsonObject(body)
|
|
375
|
+
if status_code != 200:
|
|
376
|
+
if 'TwoFactorProviders' in obj:
|
|
377
|
+
providers = [int(p) for p in obj.strs('TwoFactorProviders') if p.isdigit()]
|
|
378
|
+
if not providers:
|
|
379
|
+
providers = [p for p in (obj.get('TwoFactorProviders') or []) if isinstance(p, int)]
|
|
380
|
+
raise TwoFactorRequiredError(providers)
|
|
381
|
+
if status_code in {400, 401}:
|
|
382
|
+
raise AuthenticationError(error_message(body))
|
|
383
|
+
raise_for_status(status_code, body)
|
|
384
|
+
raise ApiError(status_code, error_message(body))
|
|
385
|
+
access_token = obj.get_str('access_token')
|
|
386
|
+
if not access_token:
|
|
387
|
+
raise AuthenticationError('token response without access_token')
|
|
388
|
+
return TokenResponse(
|
|
389
|
+
access_token=access_token,
|
|
390
|
+
refresh_token=obj.get_str('refresh_token'),
|
|
391
|
+
expires_in=float(obj.get_int('expires_in') or 3600),
|
|
392
|
+
data=obj,
|
|
393
|
+
)
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def parse_kdf(obj: JsonObject) -> KdfParams:
|
|
397
|
+
"""KDF settings from a prelogin or token response, checked against safe bounds.
|
|
398
|
+
|
|
399
|
+
Accepts the flat ``kdf*`` keys and the nested ``Kdf`` object.
|
|
400
|
+
|
|
401
|
+
Args:
|
|
402
|
+
obj: The response object.
|
|
403
|
+
|
|
404
|
+
Returns:
|
|
405
|
+
The settings.
|
|
406
|
+
|
|
407
|
+
Raises:
|
|
408
|
+
AuthenticationError: The response holds no KDF settings.
|
|
409
|
+
CryptoError: Unknown KDF type, or settings outside the safe bounds (see ``check_server_kdf``).
|
|
410
|
+
"""
|
|
411
|
+
nested = obj.obj('Kdf')
|
|
412
|
+
if nested is not None:
|
|
413
|
+
kdf_type, iterations = nested.get_int('KdfType'), nested.get_int('Iterations')
|
|
414
|
+
memory, parallelism = nested.get_int('Memory'), nested.get_int('Parallelism')
|
|
415
|
+
else:
|
|
416
|
+
kdf_type, iterations = obj.get_int('kdf'), obj.get_int('kdfIterations')
|
|
417
|
+
memory, parallelism = obj.get_int('kdfMemory'), obj.get_int('kdfParallelism')
|
|
418
|
+
if kdf_type is None or iterations is None:
|
|
419
|
+
raise AuthenticationError('server did not return KDF parameters')
|
|
420
|
+
try:
|
|
421
|
+
kdf = KdfType(kdf_type)
|
|
422
|
+
except ValueError as e:
|
|
423
|
+
raise CryptoError(f'unsupported KDF type {kdf_type}') from e
|
|
424
|
+
params = KdfParams(type=kdf, iterations=iterations, memory=memory, parallelism=parallelism)
|
|
425
|
+
check_server_kdf(params)
|
|
426
|
+
return params
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
# Minimums as in the official apps' login check (PBKDF2KdfConfig / Argon2KdfConfig.validateKdfConfigForPrelogin
|
|
430
|
+
# in bitwarden/clients): lower values are treated as a downgrade attack.
|
|
431
|
+
PBKDF2_LOGIN_MIN_ITERATIONS = 5_000
|
|
432
|
+
ARGON2_LOGIN_MIN_ITERATIONS = 2
|
|
433
|
+
ARGON2_LOGIN_MIN_MEMORY_MIB = 16
|
|
434
|
+
ARGON2_LOGIN_MIN_PARALLELISM = 1
|
|
435
|
+
# Maximums are this library's own protection against resource exhaustion (the official apps check none at
|
|
436
|
+
# login). They equal the largest values the official apps allow when changing the KDF.
|
|
437
|
+
PBKDF2_MAX_ITERATIONS = 2_000_000
|
|
438
|
+
ARGON2_MAX_ITERATIONS = 10
|
|
439
|
+
ARGON2_MAX_MEMORY_MIB = 1024
|
|
440
|
+
ARGON2_MAX_PARALLELISM = 16
|
|
441
|
+
VAULTWARDEN_PBKDF2_MIN_ITERATIONS = 100_000
|
|
442
|
+
"""vaultwarden refuses to set fewer PBKDF2 iterations (existing legacy accounts may still have fewer)."""
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def check_server_kdf(kdf: KdfParams) -> None:
|
|
446
|
+
"""Refuse KDF settings from the server that are too weak or too expensive, before any key is derived.
|
|
447
|
+
|
|
448
|
+
Too weak: a malicious server could make the login hash cheap to brute-force (downgrade). The minimums are
|
|
449
|
+
those of the official apps: PBKDF2 5000 iterations; Argon2id 2 iterations, 16 MiB, 1 lane. Too expensive:
|
|
450
|
+
it could make the client spend unbounded CPU or memory. The maximums (PBKDF2 2000000; Argon2id 10 iterations,
|
|
451
|
+
1024 MiB, 16 lanes) are this library's own limit; they equal the largest values the official apps allow
|
|
452
|
+
when changing the KDF, so every account set up with them still works.
|
|
453
|
+
|
|
454
|
+
Args:
|
|
455
|
+
kdf: The settings announced by the server.
|
|
456
|
+
|
|
457
|
+
Raises:
|
|
458
|
+
CryptoError: The settings are outside the bounds.
|
|
459
|
+
"""
|
|
460
|
+
if kdf.type == KdfType.PBKDF2_SHA256:
|
|
461
|
+
ok = PBKDF2_LOGIN_MIN_ITERATIONS <= kdf.iterations <= PBKDF2_MAX_ITERATIONS
|
|
462
|
+
else:
|
|
463
|
+
ok = (
|
|
464
|
+
ARGON2_LOGIN_MIN_ITERATIONS <= kdf.iterations <= ARGON2_MAX_ITERATIONS
|
|
465
|
+
and kdf.memory is not None
|
|
466
|
+
and ARGON2_LOGIN_MIN_MEMORY_MIB <= kdf.memory <= ARGON2_MAX_MEMORY_MIB
|
|
467
|
+
and kdf.parallelism is not None
|
|
468
|
+
and ARGON2_LOGIN_MIN_PARALLELISM <= kdf.parallelism <= ARGON2_MAX_PARALLELISM
|
|
469
|
+
)
|
|
470
|
+
if not ok:
|
|
471
|
+
raise CryptoError(f'server sent unsafe KDF settings ({kdf}); refusing to derive keys')
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
def kdf_and_salt_from_token(data: JsonObject) -> tuple[KdfParams, str] | None:
|
|
475
|
+
"""KDF settings and salt from ``UserDecryptionOptions.MasterPasswordUnlock`` of a token response.
|
|
476
|
+
|
|
477
|
+
Args:
|
|
478
|
+
data: The token response.
|
|
479
|
+
|
|
480
|
+
Returns:
|
|
481
|
+
``(kdf, salt)``, or None if the response does not include them.
|
|
482
|
+
"""
|
|
483
|
+
options = data.obj('UserDecryptionOptions')
|
|
484
|
+
unlock_info = options.obj('MasterPasswordUnlock') if options else None
|
|
485
|
+
salt = unlock_info.get_str('Salt') if unlock_info else None
|
|
486
|
+
if unlock_info is None or not salt:
|
|
487
|
+
return None
|
|
488
|
+
return parse_kdf(unlock_info), salt
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
def unlock(master_key: bytes, protected_user_key: str | None, encrypted_private_key: str | None) -> UserKeys:
|
|
492
|
+
"""Unwrap the user key and the RSA private key with the master key.
|
|
493
|
+
|
|
494
|
+
Args:
|
|
495
|
+
master_key: The master key.
|
|
496
|
+
protected_user_key: The protected user key from the server.
|
|
497
|
+
encrypted_private_key: The encrypted private key, if any.
|
|
498
|
+
|
|
499
|
+
Returns:
|
|
500
|
+
The unlocked keys.
|
|
501
|
+
|
|
502
|
+
Raises:
|
|
503
|
+
AuthenticationError: No user key in the response, or it cannot be unwrapped (wrong master password).
|
|
504
|
+
"""
|
|
505
|
+
if not protected_user_key:
|
|
506
|
+
raise AuthenticationError('server did not return the protected user key')
|
|
507
|
+
try:
|
|
508
|
+
user_key = crypto.decrypt_user_key(protected_user_key, master_key)
|
|
509
|
+
except CryptoError as e:
|
|
510
|
+
raise AuthenticationError('could not unlock the vault: wrong master password?') from e
|
|
511
|
+
private_key = crypto.load_private_key(encrypted_private_key, user_key) if encrypted_private_key else None
|
|
512
|
+
return UserKeys(user_key=user_key, private_key=private_key)
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
# ---------------------------------------------------------------- vault decryption
|
|
516
|
+
|
|
517
|
+
E = TypeVar('E', bound=IntEnum)
|
|
518
|
+
|
|
519
|
+
|
|
520
|
+
def _enum(enum_cls: type[E], value: int | None, where: str = '') -> E | int | None:
|
|
521
|
+
"""Convert a number to an enum member; unknown numbers are kept (and logged).
|
|
522
|
+
|
|
523
|
+
Args:
|
|
524
|
+
enum_cls: The enum.
|
|
525
|
+
value: The number, or None.
|
|
526
|
+
where: Location for the log message.
|
|
527
|
+
|
|
528
|
+
Returns:
|
|
529
|
+
The member, the number itself if unknown, or None.
|
|
530
|
+
"""
|
|
531
|
+
if value is None:
|
|
532
|
+
return None
|
|
533
|
+
try:
|
|
534
|
+
return enum_cls(value)
|
|
535
|
+
except ValueError:
|
|
536
|
+
log.warning('%s: unknown %s value %d (kept as is)', where or '?', enum_cls.__name__, value)
|
|
537
|
+
return value
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
def _dec(obj: JsonObject, name: str, key: SymmetricKey) -> str | None:
|
|
541
|
+
"""Decrypt a field; unexpected types are recorded as issues and an empty string stays empty.
|
|
542
|
+
|
|
543
|
+
Args:
|
|
544
|
+
obj: The JSON object holding the field.
|
|
545
|
+
name: The field name.
|
|
546
|
+
key: The key.
|
|
547
|
+
|
|
548
|
+
Returns:
|
|
549
|
+
The plaintext, ``''`` or None.
|
|
550
|
+
"""
|
|
551
|
+
value = obj.get(name)
|
|
552
|
+
if value is None:
|
|
553
|
+
return None
|
|
554
|
+
if not isinstance(value, str):
|
|
555
|
+
obj.issue(name, f'expected an encrypted string, got {type(value).__name__}')
|
|
556
|
+
return None
|
|
557
|
+
if value == '':
|
|
558
|
+
return ''
|
|
559
|
+
return crypto.decrypt_str(value, key)
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
def _dec_any(value: Any, key: SymmetricKey) -> Any:
|
|
563
|
+
"""Recursively decrypt every encrypted string in a JSON value (item types without a model, passkeys).
|
|
564
|
+
|
|
565
|
+
Args:
|
|
566
|
+
value: The JSON value.
|
|
567
|
+
key: The key.
|
|
568
|
+
|
|
569
|
+
Returns:
|
|
570
|
+
The value with every encrypted string decrypted.
|
|
571
|
+
"""
|
|
572
|
+
if crypto.is_enc_string(value):
|
|
573
|
+
return crypto.decrypt_str(value, key)
|
|
574
|
+
if isinstance(value, dict):
|
|
575
|
+
return {k: _dec_any(v, key) for k, v in value.items()}
|
|
576
|
+
if isinstance(value, list):
|
|
577
|
+
return [_dec_any(v, key) for v in value]
|
|
578
|
+
return value
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
def load_org_keys(profile: JsonObject, keys: UserKeys) -> list[str]:
|
|
582
|
+
"""Decrypt the organization keys from a profile into ``keys.org_keys``.
|
|
583
|
+
|
|
584
|
+
Args:
|
|
585
|
+
profile: The profile JSON with its ``organizations``.
|
|
586
|
+
keys: The unlocked keys of the session.
|
|
587
|
+
|
|
588
|
+
Returns:
|
|
589
|
+
The ids of organizations whose key could not be decrypted.
|
|
590
|
+
"""
|
|
591
|
+
failed = []
|
|
592
|
+
for org in profile.objs('organizations'):
|
|
593
|
+
org_id, enc_key = org.get_str('id'), org.get_str('key')
|
|
594
|
+
if not org_id or not enc_key or keys.private_key is None:
|
|
595
|
+
continue
|
|
596
|
+
try:
|
|
597
|
+
keys.org_keys[org_id] = SymmetricKey.from_bytes(crypto.rsa_decrypt(enc_key, keys.private_key))
|
|
598
|
+
except CryptoError:
|
|
599
|
+
failed.append(org_id)
|
|
600
|
+
return failed
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
def cipher_key(obj: JsonObject, keys: UserKeys) -> SymmetricKey:
|
|
604
|
+
"""The key that decrypts an item: its own item key if present, else the organization or user key.
|
|
605
|
+
|
|
606
|
+
Args:
|
|
607
|
+
obj: The item JSON.
|
|
608
|
+
keys: The unlocked keys of the session.
|
|
609
|
+
|
|
610
|
+
Returns:
|
|
611
|
+
The key.
|
|
612
|
+
|
|
613
|
+
Raises:
|
|
614
|
+
CryptoError: The organization key is missing, or the item key cannot be unwrapped.
|
|
615
|
+
"""
|
|
616
|
+
org_id = obj.get_str('organizationId')
|
|
617
|
+
if org_id:
|
|
618
|
+
if org_id not in keys.org_keys:
|
|
619
|
+
raise CryptoError(f'no key for organization {org_id}')
|
|
620
|
+
base = keys.org_keys[org_id]
|
|
621
|
+
else:
|
|
622
|
+
base = keys.user_key
|
|
623
|
+
item_key = obj.get_str('key')
|
|
624
|
+
return SymmetricKey.from_bytes(crypto.decrypt(item_key, base)) if item_key else base
|
|
625
|
+
|
|
626
|
+
|
|
627
|
+
def _login(obj: JsonObject, key: SymmetricKey) -> Login:
|
|
628
|
+
"""Decrypt the login part of an item.
|
|
629
|
+
|
|
630
|
+
Args:
|
|
631
|
+
obj: The ``login`` JSON.
|
|
632
|
+
key: The item key.
|
|
633
|
+
|
|
634
|
+
Returns:
|
|
635
|
+
The login.
|
|
636
|
+
"""
|
|
637
|
+
return Login(
|
|
638
|
+
username=_dec(obj, 'username', key),
|
|
639
|
+
password=_dec(obj, 'password', key),
|
|
640
|
+
totp=_dec(obj, 'totp', key),
|
|
641
|
+
uris=tuple(LoginUri(uri=_dec(u, 'uri', key), match=_enum(UriMatch, u.get_int('match'))) for u in obj.objs('uris')),
|
|
642
|
+
password_revision_date=obj.get_datetime('passwordRevisionDate'),
|
|
643
|
+
fido2_credentials=tuple(_dec_any(c.raw, key) for c in obj.objs('fido2Credentials')),
|
|
644
|
+
)
|
|
645
|
+
|
|
646
|
+
|
|
647
|
+
def _card(obj: JsonObject, key: SymmetricKey) -> Card:
|
|
648
|
+
"""Decrypt the card part of an item.
|
|
649
|
+
|
|
650
|
+
Args:
|
|
651
|
+
obj: The ``card`` JSON.
|
|
652
|
+
key: The item key.
|
|
653
|
+
|
|
654
|
+
Returns:
|
|
655
|
+
The card.
|
|
656
|
+
"""
|
|
657
|
+
return Card(
|
|
658
|
+
cardholder_name=_dec(obj, 'cardholderName', key),
|
|
659
|
+
brand=_dec(obj, 'brand', key),
|
|
660
|
+
number=_dec(obj, 'number', key),
|
|
661
|
+
exp_month=_dec(obj, 'expMonth', key),
|
|
662
|
+
exp_year=_dec(obj, 'expYear', key),
|
|
663
|
+
code=_dec(obj, 'code', key),
|
|
664
|
+
)
|
|
665
|
+
|
|
666
|
+
|
|
667
|
+
IDENTITY_FIELDS = {
|
|
668
|
+
'title': 'title',
|
|
669
|
+
'first_name': 'firstName',
|
|
670
|
+
'middle_name': 'middleName',
|
|
671
|
+
'last_name': 'lastName',
|
|
672
|
+
'address1': 'address1',
|
|
673
|
+
'address2': 'address2',
|
|
674
|
+
'address3': 'address3',
|
|
675
|
+
'city': 'city',
|
|
676
|
+
'state': 'state',
|
|
677
|
+
'postal_code': 'postalCode',
|
|
678
|
+
'country': 'country',
|
|
679
|
+
'company': 'company',
|
|
680
|
+
'email': 'email',
|
|
681
|
+
'phone': 'phone',
|
|
682
|
+
'ssn': 'ssn',
|
|
683
|
+
'username': 'username',
|
|
684
|
+
'passport_number': 'passportNumber',
|
|
685
|
+
'license_number': 'licenseNumber',
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
|
|
689
|
+
def _identity(obj: JsonObject, key: SymmetricKey) -> Identity:
|
|
690
|
+
"""Decrypt the identity part of an item.
|
|
691
|
+
|
|
692
|
+
Args:
|
|
693
|
+
obj: The ``identity`` JSON.
|
|
694
|
+
key: The item key.
|
|
695
|
+
|
|
696
|
+
Returns:
|
|
697
|
+
The identity.
|
|
698
|
+
"""
|
|
699
|
+
return Identity(**{attr: _dec(obj, json_key, key) for attr, json_key in IDENTITY_FIELDS.items()})
|
|
700
|
+
|
|
701
|
+
|
|
702
|
+
def _ssh_key(obj: JsonObject, key: SymmetricKey) -> SshKey:
|
|
703
|
+
"""Decrypt the SSH key part of an item.
|
|
704
|
+
|
|
705
|
+
Args:
|
|
706
|
+
obj: The ``sshKey`` JSON.
|
|
707
|
+
key: The item key.
|
|
708
|
+
|
|
709
|
+
Returns:
|
|
710
|
+
The SSH key.
|
|
711
|
+
"""
|
|
712
|
+
return SshKey(
|
|
713
|
+
private_key=_dec(obj, 'privateKey', key),
|
|
714
|
+
public_key=_dec(obj, 'publicKey', key),
|
|
715
|
+
key_fingerprint=_dec(obj, 'keyFingerprint', key),
|
|
716
|
+
)
|
|
717
|
+
|
|
718
|
+
|
|
719
|
+
def decrypt_cipher(raw: Any, keys: UserKeys) -> Cipher:
|
|
720
|
+
"""Decrypt one item.
|
|
721
|
+
|
|
722
|
+
Parts that are present but cannot be interpreted are listed in ``Cipher.issues`` and logged.
|
|
723
|
+
|
|
724
|
+
Args:
|
|
725
|
+
raw: The item JSON.
|
|
726
|
+
keys: The unlocked keys of the session.
|
|
727
|
+
|
|
728
|
+
Returns:
|
|
729
|
+
The decrypted item.
|
|
730
|
+
|
|
731
|
+
Raises:
|
|
732
|
+
CryptoError: The item has no id or cannot be decrypted.
|
|
733
|
+
"""
|
|
734
|
+
raw_id = raw.get('id') if isinstance(raw, dict) else None
|
|
735
|
+
obj = JsonObject(raw, path=f'cipher {raw_id}')
|
|
736
|
+
cipher_id = obj.get_str('id')
|
|
737
|
+
if not cipher_id:
|
|
738
|
+
raise CryptoError('cipher without id')
|
|
739
|
+
key = cipher_key(obj, keys)
|
|
740
|
+
ctype = _enum(CipherType, obj.get_int('type'), obj.path)
|
|
741
|
+
login = card = identity = ssh_key = None
|
|
742
|
+
secure_note_type = None
|
|
743
|
+
data: dict[str, Any] = {}
|
|
744
|
+
if ctype == CipherType.LOGIN and (sub := obj.obj('login')):
|
|
745
|
+
login = _login(sub, key)
|
|
746
|
+
elif ctype == CipherType.SECURE_NOTE:
|
|
747
|
+
sub = obj.obj('secureNote')
|
|
748
|
+
secure_note_type = sub.get_int('type') if sub else 0
|
|
749
|
+
elif ctype == CipherType.CARD and (sub := obj.obj('card')):
|
|
750
|
+
card = _card(sub, key)
|
|
751
|
+
elif ctype == CipherType.IDENTITY and (sub := obj.obj('identity')):
|
|
752
|
+
identity = _identity(sub, key)
|
|
753
|
+
elif ctype == CipherType.SSH_KEY and (sub := obj.obj('sshKey')):
|
|
754
|
+
ssh_key = _ssh_key(sub, key)
|
|
755
|
+
else:
|
|
756
|
+
# Types without a dedicated model: decrypt whatever type object is present.
|
|
757
|
+
known = {'login', 'securenote', 'card', 'identity', 'sshkey'}
|
|
758
|
+
for name, value in obj.raw.items():
|
|
759
|
+
if isinstance(value, dict) and name.lower() not in known and name.lower() not in {'permissions'}:
|
|
760
|
+
data[name] = _dec_any(value, key)
|
|
761
|
+
return Cipher(
|
|
762
|
+
id=cipher_id,
|
|
763
|
+
type=ctype if ctype is not None else 0,
|
|
764
|
+
name=_dec(obj, 'name', key),
|
|
765
|
+
notes=_dec(obj, 'notes', key),
|
|
766
|
+
organization_id=obj.get_str('organizationId'),
|
|
767
|
+
folder_id=obj.get_str('folderId'),
|
|
768
|
+
favorite=obj.get_bool('favorite'),
|
|
769
|
+
reprompt=_enum(RepromptType, obj.get_int('reprompt')) or RepromptType.NONE,
|
|
770
|
+
login=login,
|
|
771
|
+
secure_note_type=secure_note_type,
|
|
772
|
+
card=card,
|
|
773
|
+
identity=identity,
|
|
774
|
+
ssh_key=ssh_key,
|
|
775
|
+
data=data,
|
|
776
|
+
fields=tuple(
|
|
777
|
+
CustomField(
|
|
778
|
+
name=_dec(f, 'name', key),
|
|
779
|
+
value=_dec(f, 'value', key),
|
|
780
|
+
type=_enum(FieldType, f.get_int('type')) or FieldType.TEXT,
|
|
781
|
+
linked_id=f.get_int('linkedId'),
|
|
782
|
+
)
|
|
783
|
+
for f in obj.objs('fields')
|
|
784
|
+
),
|
|
785
|
+
password_history=tuple(
|
|
786
|
+
PasswordHistoryEntry(password=_dec(p, 'password', key), last_used_date=p.get_datetime('lastUsedDate')) for p in obj.objs('passwordHistory')
|
|
787
|
+
),
|
|
788
|
+
attachments=tuple(
|
|
789
|
+
Attachment(id=a.get_str('id') or '', file_name=_dec(a, 'fileName', key), size=a.get_int('size'), url=a.get_str('url'), key=a.get_str('key'))
|
|
790
|
+
for a in obj.objs('attachments')
|
|
791
|
+
),
|
|
792
|
+
collection_ids=tuple(obj.strs('collectionIds')),
|
|
793
|
+
creation_date=obj.get_datetime('creationDate'),
|
|
794
|
+
revision_date=obj.get_datetime('revisionDate'),
|
|
795
|
+
deleted_date=obj.get_datetime('deletedDate'),
|
|
796
|
+
archived_date=obj.get_datetime('archivedDate'),
|
|
797
|
+
edit=obj.get_bool('edit', default=True),
|
|
798
|
+
view_password=obj.get_bool('viewPassword', default=True),
|
|
799
|
+
issues=_logged(obj.issues),
|
|
800
|
+
raw=obj.raw,
|
|
801
|
+
)
|
|
802
|
+
|
|
803
|
+
|
|
804
|
+
def _logged(issues: list[str]) -> tuple[str, ...]:
|
|
805
|
+
"""Log each issue on the ``vaultwarden2`` logger.
|
|
806
|
+
|
|
807
|
+
Args:
|
|
808
|
+
issues: The recorded issues.
|
|
809
|
+
|
|
810
|
+
Returns:
|
|
811
|
+
The issues as tuple.
|
|
812
|
+
"""
|
|
813
|
+
for issue in issues:
|
|
814
|
+
log.warning('cannot interpret server data: %s', issue)
|
|
815
|
+
return tuple(issues)
|
|
816
|
+
|
|
817
|
+
|
|
818
|
+
def warn_summary(ciphers: list[Cipher] | tuple[Cipher, ...], undecryptable: list[str] | tuple[str, ...] = ()) -> None:
|
|
819
|
+
"""Issue one ``VaultwardenDataWarning`` for a read that met problems (details were logged per item).
|
|
820
|
+
|
|
821
|
+
Args:
|
|
822
|
+
ciphers: The decrypted items.
|
|
823
|
+
undecryptable: Ids of items that could not be decrypted.
|
|
824
|
+
"""
|
|
825
|
+
with_issues = sum(1 for c in ciphers if c.issues)
|
|
826
|
+
if undecryptable or with_issues:
|
|
827
|
+
warnings.warn(
|
|
828
|
+
f'{len(undecryptable)} item(s) could not be decrypted, {with_issues} item(s) have uninterpretable parts '
|
|
829
|
+
"(details on the 'vaultwarden2' logger; such parts are never modified)",
|
|
830
|
+
VaultwardenDataWarning,
|
|
831
|
+
stacklevel=3,
|
|
832
|
+
)
|
|
833
|
+
|
|
834
|
+
|
|
835
|
+
def decrypt_ciphers(raws: list[Any], keys: UserKeys) -> list[Cipher]:
|
|
836
|
+
"""Decrypt many items; warn once if some have uninterpretable parts.
|
|
837
|
+
|
|
838
|
+
Args:
|
|
839
|
+
raws: The item JSON objects.
|
|
840
|
+
keys: The unlocked keys of the session.
|
|
841
|
+
|
|
842
|
+
Returns:
|
|
843
|
+
The decrypted items.
|
|
844
|
+
|
|
845
|
+
Raises:
|
|
846
|
+
CryptoError: An item cannot be decrypted.
|
|
847
|
+
"""
|
|
848
|
+
ciphers = [decrypt_cipher(raw, keys) for raw in raws]
|
|
849
|
+
warn_summary(ciphers)
|
|
850
|
+
return ciphers
|
|
851
|
+
|
|
852
|
+
|
|
853
|
+
def decrypt_folder(raw: Any, keys: UserKeys) -> Folder:
|
|
854
|
+
"""Decrypt a folder.
|
|
855
|
+
|
|
856
|
+
Args:
|
|
857
|
+
raw: The folder JSON.
|
|
858
|
+
keys: The unlocked keys of the session.
|
|
859
|
+
|
|
860
|
+
Returns:
|
|
861
|
+
The folder.
|
|
862
|
+
"""
|
|
863
|
+
obj = JsonObject(raw)
|
|
864
|
+
return Folder(id=obj.get_str('id') or '', name=_dec(obj, 'name', keys.user_key), revision_date=obj.get_datetime('revisionDate'), raw=obj.raw)
|
|
865
|
+
|
|
866
|
+
|
|
867
|
+
def decrypt_collection(raw: Any, keys: UserKeys) -> Collection:
|
|
868
|
+
"""Decrypt a collection.
|
|
869
|
+
|
|
870
|
+
Args:
|
|
871
|
+
raw: The collection JSON.
|
|
872
|
+
keys: The unlocked keys of the session.
|
|
873
|
+
|
|
874
|
+
Returns:
|
|
875
|
+
The collection.
|
|
876
|
+
|
|
877
|
+
Raises:
|
|
878
|
+
CryptoError: The organization key is not available.
|
|
879
|
+
"""
|
|
880
|
+
obj = JsonObject(raw)
|
|
881
|
+
org_id = obj.get_str('organizationId') or ''
|
|
882
|
+
if org_id not in keys.org_keys:
|
|
883
|
+
raise CryptoError(f'no key for organization {org_id}')
|
|
884
|
+
return Collection(
|
|
885
|
+
id=obj.get_str('id') or '',
|
|
886
|
+
organization_id=org_id,
|
|
887
|
+
name=_dec(obj, 'name', keys.org_keys[org_id]),
|
|
888
|
+
external_id=obj.get_str('externalId'),
|
|
889
|
+
read_only=obj.get_bool('readOnly'),
|
|
890
|
+
hide_passwords=obj.get_bool('hidePasswords'),
|
|
891
|
+
manage=obj.get_bool('manage'),
|
|
892
|
+
raw=obj.raw,
|
|
893
|
+
)
|
|
894
|
+
|
|
895
|
+
|
|
896
|
+
def parse_member(raw: Any, organization_id: str) -> Member:
|
|
897
|
+
"""Parse an organization member entry.
|
|
898
|
+
|
|
899
|
+
Args:
|
|
900
|
+
raw: The member JSON.
|
|
901
|
+
organization_id: The organization.
|
|
902
|
+
|
|
903
|
+
Returns:
|
|
904
|
+
The membership.
|
|
905
|
+
"""
|
|
906
|
+
obj = JsonObject(raw)
|
|
907
|
+
return Member(
|
|
908
|
+
id=obj.get_str('id') or '',
|
|
909
|
+
organization_id=organization_id,
|
|
910
|
+
user_id=obj.get_str('userId'),
|
|
911
|
+
email=obj.get_str('email'),
|
|
912
|
+
name=obj.get_str('name'),
|
|
913
|
+
type=_enum(OrganizationUserType, obj.get_int('type')),
|
|
914
|
+
status=_enum(MemberStatus, obj.get_int('status')),
|
|
915
|
+
collections=tuple(
|
|
916
|
+
CollectionAccess(id=c.get_str('id') or '', read_only=c.get_bool('readOnly'), hide_passwords=c.get_bool('hidePasswords'), manage=c.get_bool('manage'))
|
|
917
|
+
for c in obj.objs('collections')
|
|
918
|
+
),
|
|
919
|
+
raw=obj.raw,
|
|
920
|
+
)
|
|
921
|
+
|
|
922
|
+
|
|
923
|
+
def organization_payload(name: str, billing_email: str, collection_name: str, user_public_key: RSAPublicKey) -> tuple[dict[str, Any], SymmetricKey]:
|
|
924
|
+
"""Body for creating an organization, and the new organization key.
|
|
925
|
+
|
|
926
|
+
The organization key is shared with the creator by encrypting it to their public key; the organization's own
|
|
927
|
+
RSA key pair is generated too, its private part wrapped with the organization key.
|
|
928
|
+
|
|
929
|
+
Args:
|
|
930
|
+
name: The organization name.
|
|
931
|
+
billing_email: The billing contact.
|
|
932
|
+
collection_name: The name of the first collection.
|
|
933
|
+
user_public_key: The creator's public key.
|
|
934
|
+
|
|
935
|
+
Returns:
|
|
936
|
+
``(request body, organization key)``.
|
|
937
|
+
"""
|
|
938
|
+
org_key = SymmetricKey.generate()
|
|
939
|
+
org_public, org_private_encrypted = crypto.generate_key_pair(org_key)
|
|
940
|
+
return {
|
|
941
|
+
'name': name,
|
|
942
|
+
'billingEmail': billing_email,
|
|
943
|
+
'collectionName': str(crypto.encrypt(collection_name, org_key)),
|
|
944
|
+
'key': str(crypto.rsa_encrypt(org_key.to_bytes(), user_public_key)),
|
|
945
|
+
'keys': {'publicKey': org_public, 'encryptedPrivateKey': org_private_encrypted},
|
|
946
|
+
'planType': 0,
|
|
947
|
+
}, org_key
|
|
948
|
+
|
|
949
|
+
|
|
950
|
+
def collection_access_payload(access: CollectionAccess) -> dict[str, Any]:
|
|
951
|
+
"""One entry of a collection access list as the server expects it.
|
|
952
|
+
|
|
953
|
+
Args:
|
|
954
|
+
access: The access rights.
|
|
955
|
+
|
|
956
|
+
Returns:
|
|
957
|
+
The JSON entry.
|
|
958
|
+
"""
|
|
959
|
+
return {'id': access.id, 'readOnly': access.read_only, 'hidePasswords': access.hide_passwords, 'manage': access.manage}
|
|
960
|
+
|
|
961
|
+
|
|
962
|
+
def _access(obj: JsonObject) -> CollectionAccess:
|
|
963
|
+
"""Parse a collection access entry.
|
|
964
|
+
|
|
965
|
+
Args:
|
|
966
|
+
obj: The entry JSON.
|
|
967
|
+
|
|
968
|
+
Returns:
|
|
969
|
+
The access rights.
|
|
970
|
+
"""
|
|
971
|
+
return CollectionAccess(
|
|
972
|
+
id=obj.get_str('id') or '', read_only=obj.get_bool('readOnly'), hide_passwords=obj.get_bool('hidePasswords'), manage=obj.get_bool('manage')
|
|
973
|
+
)
|
|
974
|
+
|
|
975
|
+
|
|
976
|
+
def parse_group(raw: Any, organization_id: str) -> Group:
|
|
977
|
+
"""Parse an organization group.
|
|
978
|
+
|
|
979
|
+
Args:
|
|
980
|
+
raw: The group JSON.
|
|
981
|
+
organization_id: The organization.
|
|
982
|
+
|
|
983
|
+
Returns:
|
|
984
|
+
The group.
|
|
985
|
+
"""
|
|
986
|
+
obj = JsonObject(raw)
|
|
987
|
+
return Group(
|
|
988
|
+
id=obj.get_str('id') or '',
|
|
989
|
+
organization_id=organization_id,
|
|
990
|
+
name=obj.get_str('name') or '',
|
|
991
|
+
external_id=obj.get_str('externalId'),
|
|
992
|
+
collections=tuple(_access(c) for c in obj.objs('collections')),
|
|
993
|
+
raw=obj.raw,
|
|
994
|
+
)
|
|
995
|
+
|
|
996
|
+
|
|
997
|
+
def parse_policy(raw: Any) -> Policy:
|
|
998
|
+
"""Parse an organization policy.
|
|
999
|
+
|
|
1000
|
+
Args:
|
|
1001
|
+
raw: The policy JSON.
|
|
1002
|
+
|
|
1003
|
+
Returns:
|
|
1004
|
+
The policy.
|
|
1005
|
+
"""
|
|
1006
|
+
obj = JsonObject(raw)
|
|
1007
|
+
data = obj.get('data')
|
|
1008
|
+
return Policy(type=_enum(PolicyType, obj.get_int('type')) or 0, enabled=obj.get_bool('enabled'), data=data if isinstance(data, dict) else None, raw=obj.raw)
|
|
1009
|
+
|
|
1010
|
+
|
|
1011
|
+
def parse_organization(obj: JsonObject) -> Organization:
|
|
1012
|
+
"""Parse a membership entry of the profile (organization names are not encrypted).
|
|
1013
|
+
|
|
1014
|
+
Args:
|
|
1015
|
+
obj: The organization JSON.
|
|
1016
|
+
|
|
1017
|
+
Returns:
|
|
1018
|
+
The organization.
|
|
1019
|
+
"""
|
|
1020
|
+
return Organization(
|
|
1021
|
+
id=obj.get_str('id') or '',
|
|
1022
|
+
name=obj.get_str('name'),
|
|
1023
|
+
type=_enum(OrganizationUserType, obj.get_int('type')),
|
|
1024
|
+
status=obj.get_int('status'),
|
|
1025
|
+
enabled=obj.get_bool('enabled', default=True),
|
|
1026
|
+
raw=obj.raw,
|
|
1027
|
+
)
|
|
1028
|
+
|
|
1029
|
+
|
|
1030
|
+
def parse_profile(obj: JsonObject) -> Profile:
|
|
1031
|
+
"""Parse the account profile.
|
|
1032
|
+
|
|
1033
|
+
Args:
|
|
1034
|
+
obj: The profile JSON.
|
|
1035
|
+
|
|
1036
|
+
Returns:
|
|
1037
|
+
The profile.
|
|
1038
|
+
"""
|
|
1039
|
+
return Profile(
|
|
1040
|
+
id=obj.get_str('id') or '',
|
|
1041
|
+
email=obj.get_str('email') or '',
|
|
1042
|
+
name=obj.get_str('name'),
|
|
1043
|
+
email_verified=obj.get_bool('emailVerified'),
|
|
1044
|
+
premium=obj.get_bool('premium'),
|
|
1045
|
+
raw=obj.raw,
|
|
1046
|
+
)
|
|
1047
|
+
|
|
1048
|
+
|
|
1049
|
+
T = TypeVar('T')
|
|
1050
|
+
|
|
1051
|
+
|
|
1052
|
+
def _decrypt_each(kind: str, source: list[JsonObject], decrypt: Callable[[Any, UserKeys], T], keys: UserKeys, failed: list[str]) -> list[T]:
|
|
1053
|
+
"""Decrypt a list of objects, logging and collecting the ids of those that fail.
|
|
1054
|
+
|
|
1055
|
+
Args:
|
|
1056
|
+
kind: What the objects are, for log messages.
|
|
1057
|
+
source: The JSON objects.
|
|
1058
|
+
decrypt: The decryption function.
|
|
1059
|
+
keys: The unlocked keys of the session.
|
|
1060
|
+
failed: Receives the ids of objects that could not be decrypted.
|
|
1061
|
+
|
|
1062
|
+
Returns:
|
|
1063
|
+
The decrypted objects.
|
|
1064
|
+
"""
|
|
1065
|
+
result = []
|
|
1066
|
+
for raw in source:
|
|
1067
|
+
try:
|
|
1068
|
+
result.append(decrypt(raw.raw, keys))
|
|
1069
|
+
except CryptoError as e:
|
|
1070
|
+
log.warning('cannot decrypt %s %s: %s', kind, raw.get_str('id') or '?', e)
|
|
1071
|
+
failed.append(raw.get_str('id') or '?')
|
|
1072
|
+
return result
|
|
1073
|
+
|
|
1074
|
+
|
|
1075
|
+
def decrypt_vault(sync_body: Any, keys: UserKeys) -> Vault:
|
|
1076
|
+
"""Decrypt a ``/api/sync`` response.
|
|
1077
|
+
|
|
1078
|
+
Objects that fail to decrypt are logged and listed in ``Vault.undecryptable``; one summary warning is issued.
|
|
1079
|
+
|
|
1080
|
+
Args:
|
|
1081
|
+
sync_body: The sync response.
|
|
1082
|
+
keys: The unlocked keys of the session.
|
|
1083
|
+
|
|
1084
|
+
Returns:
|
|
1085
|
+
The decrypted vault.
|
|
1086
|
+
"""
|
|
1087
|
+
sync = JsonObject(sync_body)
|
|
1088
|
+
profile = sync.obj('profile') or JsonObject({})
|
|
1089
|
+
undecryptable = load_org_keys(profile, keys)
|
|
1090
|
+
for org_id in undecryptable:
|
|
1091
|
+
log.warning('cannot decrypt the key of organization %s', org_id)
|
|
1092
|
+
folders = _decrypt_each('folder', sync.objs('folders'), decrypt_folder, keys, undecryptable)
|
|
1093
|
+
ciphers = _decrypt_each('item', sync.objs('ciphers'), decrypt_cipher, keys, undecryptable)
|
|
1094
|
+
collections = _decrypt_each('collection', sync.objs('collections'), decrypt_collection, keys, undecryptable)
|
|
1095
|
+
warn_summary(ciphers, undecryptable)
|
|
1096
|
+
return Vault(
|
|
1097
|
+
profile=parse_profile(profile),
|
|
1098
|
+
folders=tuple(folders),
|
|
1099
|
+
ciphers=tuple(ciphers),
|
|
1100
|
+
collections=tuple(collections),
|
|
1101
|
+
organizations=tuple(parse_organization(o) for o in profile.objs('organizations')),
|
|
1102
|
+
undecryptable=tuple(undecryptable),
|
|
1103
|
+
)
|