summaryrefslogtreecommitdiffstats
path: root/security/manager/ssl/tests/unit/test_oskeystore.js
blob: 028c308faf8f684997f7a06c22eb8b1b64eff0ab (plain)
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
412
413
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */
// Any copyright is dedicated to the Public Domain.
// http://creativecommons.org/publicdomain/zero/1.0/
"use strict";

// Tests the methods and attributes for interfacing with nsIOSKeyStore.

// Ensure that the appropriate initialization has happened.
do_get_profile();

const LABELS = ["mylabel1", "mylabel2", "mylabel3"];

async function delete_all_secrets() {
  let keystore = Cc["@mozilla.org/security/oskeystore;1"].getService(
    Ci.nsIOSKeyStore
  );
  for (let label of LABELS) {
    if (await keystore.asyncSecretAvailable(label)) {
      await keystore.asyncDeleteSecret(label);
      ok(
        !(await keystore.asyncSecretAvailable(label)),
        label + " should be deleted now."
      );
    }
  }
}

// Test that Firefox handles locking and unlocking of the OSKeyStore properly.
// Does so by mocking out the actual dialog and "filling in" the
// password. Also tests that providing an incorrect password will fail (well,
// technically the user will just get prompted again, but if they then cancel
// the dialog the overall operation will fail).

var gMockPrompter = {
  passwordToTry: null,
  numPrompts: 0,

  // This intentionally does not use arrow function syntax to avoid an issue
  // where in the context of the arrow function, |this != gMockPrompter| due to
  // how objects get wrapped when going across xpcom boundaries.
  promptPassword(dialogTitle, text, password, checkMsg, checkValue) {
    this.numPrompts++;
    equal(
      text,
      "Please enter your Primary Password.",
      "password prompt text should be as expected"
    );
    equal(checkMsg, null, "checkMsg should be null");
    ok(this.passwordToTry, "passwordToTry should be non-null");
    if (this.passwordToTry == "DontTryThisPassword") {
      // Cancel the prompt in this case.
      return false;
    }
    password.value = this.passwordToTry;
    return true;
  },

  QueryInterface: ChromeUtils.generateQI(["nsIPrompt"]),
};

// Mock nsIWindowWatcher. PSM calls getNewPrompter on this to get an nsIPrompt
// to call promptPassword. We return the mock one, above.
var gWindowWatcher = {
  getNewPrompter: () => gMockPrompter,
  QueryInterface: ChromeUtils.generateQI(["nsIWindowWatcher"]),
};

async function encrypt_decrypt_test() {
  let keystore = Cc["@mozilla.org/security/oskeystore;1"].getService(
    Ci.nsIOSKeyStore
  );
  ok(
    !(await keystore.asyncSecretAvailable(LABELS[0])),
    "The secret should not be available yet."
  );

  let recoveryPhrase = await keystore.asyncGenerateSecret(LABELS[0]);
  ok(recoveryPhrase, "A recovery phrase should've been created.");
  let recoveryPhrase2 = await keystore.asyncGenerateSecret(LABELS[1]);
  ok(recoveryPhrase2, "A recovery phrase should've been created.");

  let text = new Uint8Array([0x01, 0x00, 0x01]);
  let ciphertext = "";
  try {
    ciphertext = await keystore.asyncEncryptBytes(LABELS[0], text);
    ok(ciphertext, "We should have a ciphertext now.");
  } catch (e) {
    ok(false, "Error encrypting " + e);
  }

  // Decrypting should give us the plaintext bytes again.
  try {
    let plaintext = await keystore.asyncDecryptBytes(LABELS[0], ciphertext);
    ok(
      plaintext.toString() == text.toString(),
      "Decrypted plaintext should be the same as text."
    );
  } catch (e) {
    ok(false, "Error decrypting ciphertext " + e);
  }

  // Decrypting with a wrong key should throw an error.
  try {
    await keystore.asyncDecryptBytes(LABELS[1], ciphertext);
    ok(false, "Decrypting with the wrong key should fail.");
  } catch (e) {
    ok(true, "Decrypting with the wrong key should fail " + e);
  }
}

add_task(async function () {
  let keystore = Cc["@mozilla.org/security/oskeystore;1"].getService(
    Ci.nsIOSKeyStore
  );
  let windowWatcherCID;
  if (keystore.isNSSKeyStore) {
    windowWatcherCID = MockRegistrar.register(
      "@mozilla.org/embedcomp/window-watcher;1",
      gWindowWatcher
    );
    registerCleanupFunction(() => {
      MockRegistrar.unregister(windowWatcherCID);
    });
  }

  await delete_all_secrets();
  await encrypt_decrypt_test();
  await delete_all_secrets();

  if (
    AppConstants.platform == "macosx" ||
    AppConstants.platform == "win" ||
    AppConstants.platform == "linux"
  ) {
    ok(
      !keystore.isNSSKeyStore,
      "OS X, Windows, and Linux should use the non-NSS implementation"
    );
  }

  if (keystore.isNSSKeyStore) {
    // If we use the NSS key store implementation test that everything works
    // when a master password is set.
    // Set an initial password.
    let tokenDB = Cc["@mozilla.org/security/pk11tokendb;1"].getService(
      Ci.nsIPK11TokenDB
    );
    let token = tokenDB.getInternalKeyToken();
    token.initPassword("hunter2");

    // Lock the key store. This should be equivalent to token.logoutSimple()
    await keystore.asyncLock();

    // Set the correct password so that the test operations should succeed.
    gMockPrompter.passwordToTry = "hunter2";
    await encrypt_decrypt_test();
    ok(
      gMockPrompter.numPrompts == 1,
      "There should've been one password prompt."
    );
    await delete_all_secrets();
  }

  // Check lock/unlock behaviour.
  // Unfortunately we can only test this automatically for the NSS key store.
  // Uncomment the outer keystore.isNSSKeyStore to test other key stores manually.
  if (keystore.isNSSKeyStore) {
    await delete_all_secrets();
    await encrypt_decrypt_test();
    await keystore.asyncLock();
    info("Keystore should be locked. Cancel the login request.");
    try {
      if (keystore.isNSSKeyStore) {
        gMockPrompter.passwordToTry = "DontTryThisPassword";
      }
      await keystore.asyncUnlock();
      ok(false, "Unlock should've rejected.");
    } catch (e) {
      ok(
        e.result == Cr.NS_ERROR_FAILURE || e.result == Cr.NS_ERROR_ABORT,
        "Rejected login prompt."
      );
    }
    // clean up
    if (keystore.isNSSKeyStore) {
      gMockPrompter.passwordToTry = "hunter2";
    }
    await delete_all_secrets();
  }
});

// Test that if we kick off a background operation and then call a synchronous function on the
// keystore, we don't deadlock.
add_task(async function () {
  await delete_all_secrets();

  let keystore = Cc["@mozilla.org/security/oskeystore;1"].getService(
    Ci.nsIOSKeyStore
  );
  let recoveryPhrase = await keystore.asyncGenerateSecret(LABELS[0]);
  ok(recoveryPhrase, "A recovery phrase should've been created.");

  try {
    let text = new Uint8Array(8192);
    let promise = keystore.asyncEncryptBytes(LABELS[0], text);
    /* eslint-disable no-unused-expressions */
    keystore.isNSSKeyStore; // we don't care what this is - we just need to access it
    /* eslint-enable no-unused-expressions */
    let ciphertext = await promise;
    ok(ciphertext, "We should have a ciphertext now.");
  } catch (e) {
    ok(false, "Error encrypting " + e);
  }

  await delete_all_secrets();
});

// Test that using a recovery phrase works.
add_task(async function () {
  await delete_all_secrets();

  let keystore = Cc["@mozilla.org/security/oskeystore;1"].getService(
    Ci.nsIOSKeyStore
  );

  let recoveryPhrase = await keystore.asyncGenerateSecret(LABELS[0]);
  ok(recoveryPhrase, "A recovery phrase should've been created.");

  let text = new Uint8Array([0x01, 0x00, 0x01]);
  let ciphertext = await keystore.asyncEncryptBytes(LABELS[0], text);
  ok(ciphertext, "We should have a ciphertext now.");

  await keystore.asyncDeleteSecret(LABELS[0]);
  // Decrypting should fail after deleting the secret.
  await keystore
    .asyncDecryptBytes(LABELS[0], ciphertext)
    .then(() =>
      ok(false, "decrypting didn't throw as expected after deleting the secret")
    )
    .catch(() =>
      ok(true, "decrypting threw as expected after deleting the secret")
    );

  await keystore.asyncRecoverSecret(LABELS[0], recoveryPhrase);
  let plaintext = await keystore.asyncDecryptBytes(LABELS[0], ciphertext);
  ok(
    plaintext.toString() == text.toString(),
    "Decrypted plaintext should be the same as text."
  );

  await delete_all_secrets();
});

// Test that trying to use a non-base64 recovery phrase fails.
add_task(async function () {
  await delete_all_secrets();

  let keystore = Cc["@mozilla.org/security/oskeystore;1"].getService(
    Ci.nsIOSKeyStore
  );
  await keystore
    .asyncRecoverSecret(LABELS[0], "@##$^&*()#$^&*(@#%&*_")
    .then(() =>
      ok(false, "base64-decoding non-base64 should have failed but didn't")
    )
    .catch(() => ok(true, "base64-decoding non-base64 failed as expected"));

  ok(
    !(await keystore.asyncSecretAvailable(LABELS[0])),
    "we didn't recover a secret, so the secret shouldn't be available"
  );
  let recoveryPhrase = await keystore.asyncGenerateSecret(LABELS[0]);
  ok(
    recoveryPhrase && !!recoveryPhrase.length,
    "we should be able to re-use that label to generate a new secret"
  );
  await delete_all_secrets();
});

// Test that re-using a label overwrites any previously-stored secret.
add_task(async function () {
  await delete_all_secrets();

  let keystore = Cc["@mozilla.org/security/oskeystore;1"].getService(
    Ci.nsIOSKeyStore
  );

  let recoveryPhrase = await keystore.asyncGenerateSecret(LABELS[0]);
  ok(recoveryPhrase, "A recovery phrase should've been created.");

  let text = new Uint8Array([0x66, 0x6f, 0x6f, 0x66]);
  let ciphertext = await keystore.asyncEncryptBytes(LABELS[0], text);
  ok(ciphertext, "We should have a ciphertext now.");

  let newRecoveryPhrase = await keystore.asyncGenerateSecret(LABELS[0]);
  ok(newRecoveryPhrase, "A new recovery phrase should've been created.");

  // The new secret replaced the old one so we shouldn't be able to decrypt the ciphertext now.
  await keystore
    .asyncDecryptBytes(LABELS[0], ciphertext)
    .then(() =>
      ok(false, "decrypting without the original key should have failed")
    )
    .catch(() =>
      ok(true, "decrypting without the original key failed as expected")
    );

  await keystore.asyncRecoverSecret(LABELS[0], recoveryPhrase);
  let plaintext = await keystore.asyncDecryptBytes(LABELS[0], ciphertext);
  ok(
    plaintext.toString() == text.toString(),
    "Decrypted plaintext should be the same as text (once we have the original key again)."
  );

  await delete_all_secrets();
});

// Test that re-using a label (this time using a recovery phrase) overwrites any previously-stored
// secret.
add_task(async function () {
  await delete_all_secrets();

  let keystore = Cc["@mozilla.org/security/oskeystore;1"].getService(
    Ci.nsIOSKeyStore
  );

  let recoveryPhrase = await keystore.asyncGenerateSecret(LABELS[0]);
  ok(recoveryPhrase, "A recovery phrase should've been created.");

  let newRecoveryPhrase = await keystore.asyncGenerateSecret(LABELS[0]);
  ok(newRecoveryPhrase, "A new recovery phrase should've been created.");

  let text = new Uint8Array([0x66, 0x6f, 0x6f, 0x66]);
  let ciphertext = await keystore.asyncEncryptBytes(LABELS[0], text);
  ok(ciphertext, "We should have a ciphertext now.");

  await keystore.asyncRecoverSecret(LABELS[0], recoveryPhrase);

  // We recovered the old secret, so decrypting ciphertext that had been encrypted with the newer
  // key should fail.
  await keystore
    .asyncDecryptBytes(LABELS[0], ciphertext)
    .then(() => ok(false, "decrypting without the new key should have failed"))
    .catch(() => ok(true, "decrypting without the new key failed as expected"));

  await keystore.asyncRecoverSecret(LABELS[0], newRecoveryPhrase);
  let plaintext = await keystore.asyncDecryptBytes(LABELS[0], ciphertext);
  ok(
    plaintext.toString() == text.toString(),
    "Decrypted plaintext should be the same as text (once we have the new key again)."
  );

  await delete_all_secrets();
});

// Test that trying to use recovery phrases that are the wrong size fails.
add_task(async function () {
  await delete_all_secrets();

  let keystore = Cc["@mozilla.org/security/oskeystore;1"].getService(
    Ci.nsIOSKeyStore
  );

  await keystore
    .asyncRecoverSecret(LABELS[0], "")
    .then(() => ok(false, "'recovering' with an empty key should have failed"))
    .catch(() => ok(true, "'recovering' with an empty key failed as expected"));
  ok(
    !(await keystore.asyncSecretAvailable(LABELS[0])),
    "we didn't recover a secret, so the secret shouldn't be available"
  );

  await keystore
    .asyncRecoverSecret(LABELS[0], "AAAAAA")
    .then(() =>
      ok(false, "recovering with a key that is too short should have failed")
    )
    .catch(() =>
      ok(true, "recovering with a key that is too short failed as expected")
    );
  ok(
    !(await keystore.asyncSecretAvailable(LABELS[0])),
    "we didn't recover a secret, so the secret shouldn't be available"
  );

  await keystore
    .asyncRecoverSecret(
      LABELS[0],
      "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
    )
    .then(() =>
      ok(false, "recovering with a key that is too long should have failed")
    )
    .catch(() =>
      ok(true, "recovering with a key that is too long failed as expected")
    );
  ok(
    !(await keystore.asyncSecretAvailable(LABELS[0])),
    "we didn't recover a secret, so the secret shouldn't be available"
  );

  let recoveryPhrase = await keystore.asyncGenerateSecret(LABELS[0]);
  ok(
    recoveryPhrase && !!recoveryPhrase.length,
    "we should be able to use that label to generate a new secret"
  );
  ok(
    await keystore.asyncSecretAvailable(LABELS[0]),
    "the generated secret should now be available"
  );

  await delete_all_secrets();
});