-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkeychainManager.ts
337 lines (295 loc) · 12.1 KB
/
keychainManager.ts
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
import { Database } from 'better-sqlite3';
import { Entry } from '@napi-rs/keyring';
import os from 'os';
import crypto from 'crypto';
import { decrypt, getDerivateUsingParametersFromEncryptedData } from './decrypt.js';
import { encryptAesCbcHmac256 } from './encrypt.js';
import { sha512 } from './hash.js';
import { EncryptedData } from './types.js';
import { decryptSsoRemoteKey } from './buildSsoRemoteKey.js';
import { CLI_VERSION, cliVersionToString } from '../../cliVersion.js';
import { perform2FAVerification, registerDevice } from '../auth/index.js';
import { DeviceConfiguration, LocalConfiguration } from '../../types.js';
import { askEmailAddress, askMasterPassword } from '../../utils/dialogs.js';
import { get2FAStatusUnauthenticated } from '../../endpoints/get2FAStatusUnauthenticated.js';
import { getDeviceCredentials } from '../../utils/index.js';
import { logger } from '../../logger.js';
const SERVICE = 'dashlane-cli';
export const generateLocalKey = (): Buffer => {
const localKey = crypto.randomBytes(32);
if (!localKey) {
throw new Error('Unable to generate AES local key');
}
return localKey;
};
export const setLocalKey = (login: string, localKey: Buffer, callbackOnError: (errorMessage: string) => void) => {
try {
const entry = new Entry(SERVICE, login);
entry.setPassword(localKey.toString('base64'));
} catch (error) {
let errorMessage = 'unknown error';
if (error instanceof Error) {
errorMessage = error.message;
}
callbackOnError(errorMessage);
}
};
const getLocalKey = (login: string): Buffer | undefined => {
const entry = new Entry(SERVICE, login);
const localKeyEncoded = entry.getPassword();
if (localKeyEncoded) {
return Buffer.from(localKeyEncoded, 'base64');
} else {
return undefined;
}
};
export const deleteLocalKey = (login: string) => {
const entry = new Entry(SERVICE, login);
entry.deletePassword();
};
/**
* Fake transaction used to set derivation parameters to encrypt the local key in the DB using the master password
*/
const getDerivationParametersForLocalKey = (login: string): EncryptedData => {
return {
keyDerivation: {
algo: 'argon2d',
saltLength: 16,
tCost: 3,
mCost: 32768,
parallelism: 2,
},
cipherConfig: {
encryption: 'aes256', // Unused parameter
cipherMode: 'cbchmac', // Unused parameter
ivLength: 0, // Unused parameter
},
cipherData: {
salt: sha512(login).slice(0, 16),
iv: Buffer.from(''), // Unused parameter
hash: Buffer.from(''), // Unused parameter
encryptedPayload: Buffer.from(''), // Unused parameter
},
};
};
const getLocalConfigurationWithoutDB = async (
db: Database,
login: string,
shouldNotSaveMasterPassword: boolean
): Promise<LocalConfiguration> => {
const localKey = generateLocalKey();
// Register the user's device
const deviceCredentials = getDeviceCredentials();
const { deviceAccessKey, deviceSecretKey, serverKey, ssoServerKey, ssoSpKey, remoteKeys } = deviceCredentials
? {
deviceAccessKey: deviceCredentials.accessKey,
deviceSecretKey: deviceCredentials.secretKey,
serverKey: undefined,
ssoServerKey: undefined,
ssoSpKey: undefined,
remoteKeys: [],
}
: await registerDevice({
login,
deviceName: `${os.hostname()} - ${os.platform()}-${os.arch()}`,
});
// Get the authentication type (mainly to identify if the user is with OTP2)
// if non-interactive device, we consider it as email_token, so we don't need to call the API
const { type } = deviceCredentials ? { type: 'email_token' } : await get2FAStatusUnauthenticated({ login });
let masterPassword = '';
const masterPasswordEnv = process.env.DASHLANE_MASTER_PASSWORD;
let serverKeyEncrypted = null;
const isSSO = type === 'sso';
// In case of SSO
if (isSSO) {
masterPassword = decryptSsoRemoteKey({ ssoServerKey, ssoSpKey, remoteKeys });
} else {
masterPassword = masterPasswordEnv ?? (await askMasterPassword());
// In case of OTP2
if (type === 'totp_login' && serverKey) {
serverKeyEncrypted = encryptAesCbcHmac256(localKey, Buffer.from(serverKey));
masterPassword = serverKey + masterPassword;
}
}
const derivate = await getDerivateUsingParametersFromEncryptedData(
masterPassword,
getDerivationParametersForLocalKey(login)
);
const deviceSecretKeyEncrypted = encryptAesCbcHmac256(localKey, Buffer.from(deviceSecretKey, 'hex'));
const masterPasswordEncrypted = encryptAesCbcHmac256(localKey, Buffer.from(masterPassword));
const localKeyEncrypted = encryptAesCbcHmac256(derivate, localKey);
const shouldSaveMasterPassword = !shouldNotSaveMasterPassword || isSSO;
if (shouldSaveMasterPassword) {
setLocalKey(login, localKey, (errorMessage) => {
warnUnreachableKeychainDisabled(errorMessage);
shouldNotSaveMasterPassword = true;
});
}
db.prepare('REPLACE INTO device VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')
.bind(
login,
cliVersionToString(CLI_VERSION),
deviceAccessKey,
deviceSecretKeyEncrypted,
shouldSaveMasterPassword ? masterPasswordEncrypted : null,
shouldSaveMasterPassword ? 0 : 1,
localKeyEncrypted,
1,
'none',
type,
serverKeyEncrypted
)
.run();
return {
login,
masterPassword,
shouldNotSaveMasterPassword,
isSSO,
localKey,
accessKey: deviceAccessKey,
secretKey: deviceSecretKey,
};
};
const getLocalConfigurationWithoutKeychain = async (
db: Database,
login: string,
deviceConfiguration: DeviceConfiguration
): Promise<LocalConfiguration> => {
if (deviceConfiguration.authenticationMode === 'sso') {
throw new Error('SSO is currently not supported without the keychain');
}
/** The master password is a utf-8 string and in case it comes from a remote key with no derivation encoded in base64 */
let masterPassword = '';
let serverKey: string | undefined;
if (deviceConfiguration.authenticationMode === 'totp_login') {
serverKey = await perform2FAVerification({ login, deviceAccessKey: deviceConfiguration.accessKey });
masterPassword = serverKey ?? '';
}
const masterPasswordEnv = process.env.DASHLANE_MASTER_PASSWORD;
masterPassword += masterPasswordEnv ?? (await askMasterPassword());
const derivate = await getDerivateUsingParametersFromEncryptedData(
masterPassword,
getDerivationParametersForLocalKey(login)
);
const localKey = await decrypt(deviceConfiguration.localKeyEncrypted, {
type: 'alreadyComputed',
symmetricKey: derivate,
});
const secretKey = (
await decrypt(deviceConfiguration.secretKeyEncrypted, { type: 'alreadyComputed', symmetricKey: localKey })
).toString('hex');
if (!deviceConfiguration.shouldNotSaveMasterPassword) {
setLocalKey(login, localKey, (errorMessage) => {
logger.warn(`Unable to reach OS keychain because of error: "${errorMessage}". \
Install it or disable its usage via \`dcli configure save-master-password false\`.`);
});
if (!deviceConfiguration.masterPasswordEncrypted) {
// Set encrypted master password in the DB
const masterPasswordEncrypted = encryptAesCbcHmac256(localKey, Buffer.from(masterPassword));
db.prepare('UPDATE device SET masterPasswordEncrypted = ? WHERE login = ?')
.bind(masterPasswordEncrypted, login)
.run();
}
}
return {
login,
masterPassword,
shouldNotSaveMasterPassword: deviceConfiguration.shouldNotSaveMasterPassword,
isSSO: false,
localKey,
accessKey: deviceConfiguration.accessKey,
secretKey,
};
};
export const replaceMasterPassword = async (
db: Database,
localConfiguration: LocalConfiguration,
deviceConfiguration: DeviceConfiguration | null
): Promise<LocalConfiguration> => {
if (deviceConfiguration && deviceConfiguration.authenticationMode === 'sso') {
throw new Error("You can't replace the master password of an SSO account");
}
const { localKey, login, accessKey, secretKey, shouldNotSaveMasterPassword } = localConfiguration;
let newMasterPassword = '';
let serverKey;
let serverKeyEncrypted = null;
if (deviceConfiguration && deviceConfiguration.authenticationMode === 'totp_login') {
serverKey = await perform2FAVerification({ login, deviceAccessKey: deviceConfiguration.accessKey });
newMasterPassword = serverKey ?? '';
serverKeyEncrypted = encryptAesCbcHmac256(localConfiguration.localKey, Buffer.from(serverKey ?? ''));
}
newMasterPassword += await askMasterPassword();
const derivate = await getDerivateUsingParametersFromEncryptedData(
newMasterPassword,
getDerivationParametersForLocalKey(login)
);
const masterPasswordEncrypted = encryptAesCbcHmac256(localConfiguration.localKey, Buffer.from(newMasterPassword));
const localKeyEncrypted = encryptAesCbcHmac256(derivate, localKey);
db.prepare(
'UPDATE device SET localKeyEncrypted = ?, masterPasswordEncrypted = ?, serverKeyEncrypted = ? WHERE login = ?'
)
.bind(
localKeyEncrypted,
shouldNotSaveMasterPassword ? null : masterPasswordEncrypted,
serverKeyEncrypted,
login
)
.run();
return {
login,
masterPassword: newMasterPassword,
shouldNotSaveMasterPassword,
isSSO: false,
localKey,
accessKey,
secretKey,
};
};
export const getLocalConfiguration = async (
db: Database,
deviceConfiguration: DeviceConfiguration | null,
shouldNotSaveMasterPasswordIfNoDeviceKeys = false
): Promise<LocalConfiguration> => {
let login: string;
if (deviceConfiguration) {
login = deviceConfiguration.login;
} else {
login = await askEmailAddress();
}
// If there are no configuration and secrets in the DB
if (!deviceConfiguration) {
return getLocalConfigurationWithoutDB(db, login, shouldNotSaveMasterPasswordIfNoDeviceKeys);
}
let localKey: Buffer | undefined = undefined;
// If the master password is not saved or if the keychain is unreachable, or empty, the local key is retrieved from
// the master password from the DB
if (
deviceConfiguration.shouldNotSaveMasterPassword ||
!deviceConfiguration.masterPasswordEncrypted ||
!(localKey = getLocalKey(login))
) {
return getLocalConfigurationWithoutKeychain(db, login, deviceConfiguration);
}
// Otherwise, the local key can be used to decrypt the device secret key and the master password in the DB
// In case of OTP2, the masterPassword here is already concatenated with the serverKey
const masterPassword = (
await decrypt(deviceConfiguration.masterPasswordEncrypted, { type: 'alreadyComputed', symmetricKey: localKey })
).toString();
const secretKey = (
await decrypt(deviceConfiguration.secretKeyEncrypted, { type: 'alreadyComputed', symmetricKey: localKey })
).toString('hex');
return {
login,
masterPassword,
shouldNotSaveMasterPassword: deviceConfiguration.shouldNotSaveMasterPassword,
isSSO: deviceConfiguration.authenticationMode === 'sso',
localKey,
accessKey: deviceConfiguration.accessKey,
secretKey,
};
};
export const warnUnreachableKeychainDisabled = (errorMessage: string) => {
logger.warn(`Unable to reach OS keychain because of error: "${errorMessage}", so its use has been disabled. \
To retry using it, please execute \`dcli configure save-master-password true\`. \
Until then, you will have to retype your master password each time you run the CLI.`);
};