-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathVaultParser.cs
More file actions
411 lines (366 loc) · 19.9 KB
/
VaultParser.cs
File metadata and controls
411 lines (366 loc) · 19.9 KB
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
using System;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Text;
using SecureFolderFS.Core.Cryptography.Cipher;
using SecureFolderFS.Core.Cryptography.Helpers;
using SecureFolderFS.Core.DataModels;
using SecureFolderFS.Shared.Extensions;
namespace SecureFolderFS.Core.VaultAccess
{
public static class VaultParser
{
/// <summary>
/// Computes a unique HMAC thumbprint of <paramref name="configDataModel"/> properties.
/// </summary>
/// <param name="configDataModel">The <see cref="VaultConfigurationDataModel"/> to compute the thumbprint for.</param>
/// <param name="macKey">The key part of HMAC.</param>
/// <param name="mac">The destination to fill the calculated HMAC thumbprint into.</param>
public static void CalculateConfigMac(VaultConfigurationDataModel configDataModel, ReadOnlySpan<byte> macKey, Span<byte> mac)
{
// Initialize HMAC
using var hmacSha256 = new HMACSHA256(macKey.ToArray());
// Update HMAC
hmacSha256.AppendData(BitConverter.GetBytes(configDataModel.Version)); // Version
hmacSha256.AppendData(BitConverter.GetBytes(CryptHelpers.ContentCipherId(configDataModel.ContentCipherId))); // ContentCipherScheme
hmacSha256.AppendData(BitConverter.GetBytes(CryptHelpers.FileNameCipherId(configDataModel.FileNameCipherId))); // FileNameCipherScheme
hmacSha256.AppendData(BitConverter.GetBytes(configDataModel.RecycleBinSize)); // RecycleBinSize
hmacSha256.AppendData(Encoding.UTF8.GetBytes(configDataModel.FileNameEncodingId)); // FileNameEncodingId
hmacSha256.AppendData(Encoding.UTF8.GetBytes(configDataModel.Uid)); // Id
hmacSha256.AppendFinalData(Encoding.UTF8.GetBytes(configDataModel.AuthenticationMethod)); // AuthMethod
// Fill the hash to payload
hmacSha256.GetCurrentHash(mac);
}
public static void V4CalculateConfigMac(V4VaultConfigurationDataModel configDataModel, ReadOnlySpan<byte> macKey, Span<byte> mac)
{
using var hmacSha256 = new HMACSHA256(macKey.ToArray());
hmacSha256.AppendData(BitConverter.GetBytes(configDataModel.Version));
hmacSha256.AppendData(BitConverter.GetBytes(CryptHelpers.ContentCipherId(configDataModel.ContentCipherId)));
hmacSha256.AppendData(BitConverter.GetBytes(CryptHelpers.FileNameCipherId(configDataModel.FileNameCipherId)));
hmacSha256.AppendData(BitConverter.GetBytes(configDataModel.RecycleBinSize));
hmacSha256.AppendData(Encoding.UTF8.GetBytes(configDataModel.FileNameEncodingId));
hmacSha256.AppendData(Encoding.UTF8.GetBytes(configDataModel.Uid));
hmacSha256.AppendData(Encoding.UTF8.GetBytes(configDataModel.AppPlatform?.ServerUrl ?? string.Empty));
hmacSha256.AppendData(Encoding.UTF8.GetBytes(configDataModel.AppPlatform?.VaultResource ?? string.Empty));
hmacSha256.AppendData(Encoding.UTF8.GetBytes(configDataModel.AppPlatform?.Organization ?? string.Empty));
hmacSha256.AppendData(Encoding.UTF8.GetBytes(configDataModel.AppPlatform?.AccessTokenEndpoint ?? string.Empty));
hmacSha256.AppendData(Encoding.UTF8.GetBytes(configDataModel.AppPlatform?.DeviceRegistrationEndpoint ?? string.Empty));
hmacSha256.AppendFinalData(Encoding.UTF8.GetBytes(configDataModel.AuthenticationMethod));
hmacSha256.GetCurrentHash(mac);
}
/// <summary>
/// Derives DEK and MAC keys from provided credentials.
/// </summary>
/// <param name="passkey">The passkey credential that combines password and 'magic'.</param>
/// <param name="keystoreDataModel">The keystore that holds wrapped keys.</param>
/// <returns>A tuple containing the DEK and MAC keys respectively.</returns>
[SkipLocalsInit]
public static (byte[] dekKey, byte[] macKey) V3DeriveKeystore(ReadOnlySpan<byte> passkey, V3VaultKeystoreDataModel keystoreDataModel)
{
var dekKey = new byte[Cryptography.Constants.KeyTraits.DEK_KEY_LENGTH];
var macKey = new byte[Cryptography.Constants.KeyTraits.MAC_KEY_LENGTH];
// Derive KEK
Span<byte> kek = stackalloc byte[Cryptography.Constants.KeyTraits.ARGON2_KEK_LENGTH];
Argon2id.DeriveKey(passkey, keystoreDataModel.Salt, kek);
// Unwrap keys
using var rfc3394 = new Rfc3394KeyWrap();
rfc3394.UnwrapKey(keystoreDataModel.WrappedDekKey, kek, dekKey);
rfc3394.UnwrapKey(keystoreDataModel.WrappedMacKey, kek, macKey);
return (dekKey, macKey);
}
/// <summary>
/// Encrypts cryptographic keys and creates a new instance of <see cref="V3VaultKeystoreDataModel"/>.
/// </summary>
/// <param name="passkey">The passkey credential that combines password and 'magic'.</param>
/// <param name="dekKey">The DEK key.</param>
/// <param name="macKey">The MAC key.</param>
/// <param name="salt">The salt used during KEK derivation.</param>
/// <returns>A new instance of <see cref="V3VaultKeystoreDataModel"/> containing the encrypted cryptographic keys.</returns>
[SkipLocalsInit]
public static V3VaultKeystoreDataModel V3EncryptKeystore(
ReadOnlySpan<byte> passkey,
ReadOnlySpan<byte> dekKey,
ReadOnlySpan<byte> macKey,
byte[] salt)
{
// Derive KEK
Span<byte> kek = stackalloc byte[Cryptography.Constants.KeyTraits.ARGON2_KEK_LENGTH];
Argon2id.DeriveKey(passkey, salt, kek);
// Wrap keys
using var rfc3394 = new Rfc3394KeyWrap();
var wrappedDekKey = rfc3394.WrapKey(dekKey, kek);
var wrappedMacKey = rfc3394.WrapKey(macKey, kek);
// Generate keystore
return new()
{
WrappedDekKey = wrappedDekKey,
WrappedMacKey = wrappedMacKey,
Salt = salt
};
}
/// <summary>
/// Derives DEK and MAC keys from provided credentials for a vault.
/// Decrypts <see cref="V4VaultKeystoreDataModel.EncryptedSoftwareEntropy"/> using the
/// raw passkey, then mixes it into the Argon2id input via HKDF-Extract before
/// deriving the KEK. This raises the quantum security floor to 256 bits regardless
/// of the entropy of the auth factor feeding the passkey.
/// </summary>
/// <param name="passkey">The passkey credential that combines all active auth factor outputs.</param>
/// <param name="keystoreDataModel">The keystore that holds wrapped keys.</param>
/// <returns>A tuple containing the DEK and MAC keys respectively.</returns>
[SkipLocalsInit]
public static (byte[] dekKey, byte[] macKey) V4DeriveKeystore(ReadOnlySpan<byte> passkey, V4VaultKeystoreDataModel keystoreDataModel)
{
ArgumentNullException.ThrowIfNull(keystoreDataModel.Salt);
ArgumentNullException.ThrowIfNull(keystoreDataModel.EncryptedSoftwareEntropy);
ArgumentNullException.ThrowIfNull(keystoreDataModel.SoftwareEntropyNonce);
ArgumentNullException.ThrowIfNull(keystoreDataModel.SoftwareEntropyTag);
var dekKey = new byte[Cryptography.Constants.KeyTraits.DEK_KEY_LENGTH];
var macKey = new byte[Cryptography.Constants.KeyTraits.MAC_KEY_LENGTH];
// Step 1: Decrypt SoftwareEntropy using a key derived from the raw passkey.
// The bootstrap key is derived from the passkey alone (not the augmented key)
// so that recovering SoftwareEntropy always requires all active auth factors.
Span<byte> bootstrapKey = stackalloc byte[32];
HKDF.DeriveKey(
HashAlgorithmName.SHA256,
passkey,
bootstrapKey,
keystoreDataModel.Salt, // Salt ties the bootstrap key to this specific keystore
"SFFSv4-EntropyBootstrap-v1"u8);
Span<byte> softwareEntropy = stackalloc byte[keystoreDataModel.EncryptedSoftwareEntropy.Length];
using (var aes = new AesGcm(bootstrapKey, 16))
{
aes.Decrypt(
keystoreDataModel.SoftwareEntropyNonce,
keystoreDataModel.EncryptedSoftwareEntropy,
keystoreDataModel.SoftwareEntropyTag,
softwareEntropy);
}
try
{
// Step 2: Mix passkey and SoftwareEntropy via HKDF-Extract.
// passkey is IKM; SoftwareEntropy is salt.
// Breaking either alone is insufficient to reproduce the augmented key.
Span<byte> augmentedPasskey = stackalloc byte[32];
HKDF.DeriveKey(
HashAlgorithmName.SHA256,
passkey,
augmentedPasskey,
softwareEntropy,
"SFFSv4-AugmentedPasskey-v1"u8);
// Step 3: Derive KEK from the augmented passkey
Span<byte> kek = stackalloc byte[Cryptography.Constants.KeyTraits.ARGON2_KEK_LENGTH];
Argon2id.DeriveKey(augmentedPasskey, keystoreDataModel.Salt, kek);
// Step 4: Unwrap keys
using var rfc3394 = new Rfc3394KeyWrap();
rfc3394.UnwrapKey(keystoreDataModel.WrappedDekKey, kek, dekKey);
rfc3394.UnwrapKey(keystoreDataModel.WrappedMacKey, kek, macKey);
}
finally
{
CryptographicOperations.ZeroMemory(softwareEntropy);
}
return (dekKey, macKey);
}
/// <summary>
/// Encrypts cryptographic keys and creates a new instance of <see cref="V4VaultKeystoreDataModel"/>.
/// Generates and encrypts a fresh <see cref="V4VaultKeystoreDataModel.EncryptedSoftwareEntropy"/>
/// which is mixed into Argon2id input at unlock time to raise the quantum security floor.
/// </summary>
/// <param name="passkey">The passkey credential that combines all active auth factor outputs.</param>
/// <param name="dekKey">The DEK key.</param>
/// <param name="macKey">The MAC key.</param>
/// <param name="salt">The salt used during KEK derivation.</param>
/// <returns>A new instance of <see cref="V4VaultKeystoreDataModel"/> containing the encrypted cryptographic keys and entropy.</returns>
[SkipLocalsInit]
public static V4VaultKeystoreDataModel V4EncryptKeystore(
ReadOnlySpan<byte> passkey,
ReadOnlySpan<byte> dekKey,
ReadOnlySpan<byte> macKey,
byte[] salt)
{
// Step 1: Generate fresh SoftwareEntropy (256-bit CSPRNG)
Span<byte> softwareEntropy = stackalloc byte[32];
RandomNumberGenerator.Fill(softwareEntropy);
return V4EncryptKeystoreWithEntropy(passkey, dekKey, macKey, salt, softwareEntropy);
}
/// <summary>
/// Re-encrypts cryptographic keys into a new <see cref="V4VaultKeystoreDataModel"/> while
/// preserving the provided <paramref name="existingSoftwareEntropy"/>.
/// This is an optional credential-rotation path when the previous passkey is available.
/// </summary>
/// <param name="passkey">The new passkey credential.</param>
/// <param name="dekKey">The DEK key (unchanged from the existing keystore).</param>
/// <param name="macKey">The MAC key (unchanged from the existing keystore).</param>
/// <param name="salt">A freshly generated salt for the new keystore.</param>
/// <param name="existingSoftwareEntropy">The plaintext SoftwareEntropy recovered from the old keystore.</param>
/// <returns>A new <see cref="V4VaultKeystoreDataModel"/> with re-encrypted keys and entropy.</returns>
[SkipLocalsInit]
public static V4VaultKeystoreDataModel V4ReEncryptKeystore(
ReadOnlySpan<byte> passkey,
ReadOnlySpan<byte> dekKey,
ReadOnlySpan<byte> macKey,
byte[] salt,
ReadOnlySpan<byte> existingSoftwareEntropy)
{
return V4EncryptKeystoreWithEntropy(passkey, dekKey, macKey, salt, existingSoftwareEntropy);
}
/// <summary>
/// Decrypts the <see cref="V4VaultKeystoreDataModel.EncryptedSoftwareEntropy"/> from an existing
/// keystore using the previous passkey.
/// This is only required for preserve-entropy rotation; fresh-entropy rotation uses
/// <see cref="V4EncryptKeystore(ReadOnlySpan{byte}, ReadOnlySpan{byte}, ReadOnlySpan{byte}, byte[])"/>.
/// </summary>
/// <param name="passkey">The current (old) passkey.</param>
/// <param name="keystoreDataModel">The existing V4 keystore.</param>
/// <param name="softwareEntropy">The destination span to fill with the decrypted entropy (must be 32 bytes).</param>
public static void V4DecryptSoftwareEntropy(
ReadOnlySpan<byte> passkey,
V4VaultKeystoreDataModel keystoreDataModel,
Span<byte> softwareEntropy)
{
ArgumentNullException.ThrowIfNull(keystoreDataModel.Salt);
ArgumentNullException.ThrowIfNull(keystoreDataModel.EncryptedSoftwareEntropy);
ArgumentNullException.ThrowIfNull(keystoreDataModel.SoftwareEntropyNonce);
ArgumentNullException.ThrowIfNull(keystoreDataModel.SoftwareEntropyTag);
Span<byte> bootstrapKey = stackalloc byte[32];
HKDF.DeriveKey(
HashAlgorithmName.SHA256,
passkey,
bootstrapKey,
keystoreDataModel.Salt,
"SFFSv4-EntropyBootstrap-v1"u8);
using var aes = new AesGcm(bootstrapKey, 16);
aes.Decrypt(
keystoreDataModel.SoftwareEntropyNonce,
keystoreDataModel.EncryptedSoftwareEntropy,
keystoreDataModel.SoftwareEntropyTag,
softwareEntropy);
}
public static void V4DeriveComplementKey(
ReadOnlySpan<byte> passkey,
string vaultId,
string authenticationMethodId,
Span<byte> complementKey)
{
ArgumentException.ThrowIfNullOrWhiteSpace(vaultId);
ArgumentException.ThrowIfNullOrWhiteSpace(authenticationMethodId);
var salt = Encoding.UTF8.GetBytes(vaultId);
var info = Encoding.UTF8.GetBytes(authenticationMethodId);
HKDF.DeriveKey(
HashAlgorithmName.SHA256,
passkey,
complementKey,
salt,
info);
}
public static VaultShareDataModel V4WrapComplementSecret(
ReadOnlySpan<byte> complementSecret,
ReadOnlySpan<byte> wrappingKeyMaterial,
string vaultId,
string authenticationMethodId)
{
Span<byte> complementWrapKey = stackalloc byte[32];
try
{
V4DeriveComplementKey(wrappingKeyMaterial, vaultId, authenticationMethodId, complementWrapKey);
var nonce = new byte[12];
var tag = new byte[16];
var wrapped = new byte[complementSecret.Length];
RandomNumberGenerator.Fill(nonce);
using (var aes = new AesGcm(complementWrapKey, 16))
aes.Encrypt(nonce, complementSecret, wrapped, tag);
return new()
{
AuthenticationMethodId = authenticationMethodId,
Nonce = nonce,
WrappedComplementSecret = wrapped,
Tag = tag
};
}
finally
{
CryptographicOperations.ZeroMemory(complementWrapKey);
}
}
public static byte[] V4UnwrapComplementSecret(
ReadOnlySpan<byte> wrappingKeyMaterial,
string vaultId,
VaultShareDataModel shareDataModel)
{
ArgumentNullException.ThrowIfNull(shareDataModel.AuthenticationMethodId);
ArgumentNullException.ThrowIfNull(shareDataModel.Nonce);
ArgumentNullException.ThrowIfNull(shareDataModel.WrappedComplementSecret);
ArgumentNullException.ThrowIfNull(shareDataModel.Tag);
Span<byte> complementWrapKey = stackalloc byte[32];
try
{
V4DeriveComplementKey(wrappingKeyMaterial, vaultId, shareDataModel.AuthenticationMethodId, complementWrapKey);
var complementSecret = new byte[shareDataModel.WrappedComplementSecret.Length];
using (var aes = new AesGcm(complementWrapKey, 16))
aes.Decrypt(shareDataModel.Nonce, shareDataModel.WrappedComplementSecret, shareDataModel.Tag, complementSecret);
return complementSecret;
}
finally
{
CryptographicOperations.ZeroMemory(complementWrapKey);
}
}
/// <summary>
/// Shared implementation for both <see cref="V4EncryptKeystore"/> and <see cref="V4ReEncryptKeystore"/>.
/// Encrypts the provided entropy under the passkey and wraps DEK/MAC under the augmented KEK.
/// </summary>
[SkipLocalsInit]
private static V4VaultKeystoreDataModel V4EncryptKeystoreWithEntropy(
ReadOnlySpan<byte> passkey,
ReadOnlySpan<byte> dekKey,
ReadOnlySpan<byte> macKey,
byte[] salt,
ReadOnlySpan<byte> softwareEntropy)
{
// Step 1: Encrypt SoftwareEntropy under a bootstrap key derived from the raw passkey.
// Using the raw passkey (not the augmented one) means decrypting entropy
// always requires all active auth factors — same guarantee at both creation and unlock.
Span<byte> bootstrapKey = stackalloc byte[32];
HKDF.DeriveKey(
HashAlgorithmName.SHA256,
passkey,
bootstrapKey,
salt,
"SFFSv4-EntropyBootstrap-v1"u8);
var entropyNonce = new byte[12];
var entropyTag = new byte[16];
var encryptedEntropy = new byte[softwareEntropy.Length];
RandomNumberGenerator.Fill(entropyNonce);
using (var aes = new AesGcm(bootstrapKey, 16))
{
aes.Encrypt(entropyNonce, softwareEntropy, encryptedEntropy, entropyTag);
}
// Step 2: Augment passkey with SoftwareEntropy via HKDF-Extract before Argon2id.
// This is the same derivation performed at unlock in V4DeriveKeystore.
Span<byte> augmentedPasskey = stackalloc byte[32];
HKDF.DeriveKey(
HashAlgorithmName.SHA256,
passkey,
augmentedPasskey,
softwareEntropy,
"SFFSv4-AugmentedPasskey-v1"u8);
// Step 3: Derive KEK from augmented passkey
Span<byte> kek = stackalloc byte[Cryptography.Constants.KeyTraits.ARGON2_KEK_LENGTH];
Argon2id.DeriveKey(augmentedPasskey, salt, kek);
// Step 4: Wrap keys
using var rfc3394 = new Rfc3394KeyWrap();
var wrappedDekKey = rfc3394.WrapKey(dekKey, kek);
var wrappedMacKey = rfc3394.WrapKey(macKey, kek);
return new()
{
WrappedDekKey = wrappedDekKey,
WrappedMacKey = wrappedMacKey,
Salt = salt,
EncryptedSoftwareEntropy = encryptedEntropy,
SoftwareEntropyNonce = entropyNonce,
SoftwareEntropyTag = entropyTag
};
}
}
}