summaryrefslogtreecommitdiff
path: root/services/crypto/modules/WeaveCrypto.js
blob: d0d5bdb186172682266ca702168ea469c6ee4acf (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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

this.EXPORTED_SYMBOLS = ["WeaveCrypto"];

var {classes: Cc, interfaces: Ci, results: Cr, utils: Cu} = Components;

Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://services-common/async.js");

Cu.importGlobalProperties(['crypto']);

const CRYPT_ALGO        = "AES-CBC";
const CRYPT_ALGO_LENGTH = 256;
const AES_CBC_IV_SIZE   = 16;
const OPERATIONS        = { ENCRYPT: 0, DECRYPT: 1 };
const UTF_LABEL          = "utf-8";

const KEY_DERIVATION_ALGO         = "PBKDF2";
const KEY_DERIVATION_HASHING_ALGO = "SHA-1";
const KEY_DERIVATION_ITERATIONS   = 4096; // PKCS#5 recommends at least 1000.
const DERIVED_KEY_ALGO            = CRYPT_ALGO;

this.WeaveCrypto = function WeaveCrypto() {
    this.init();
};

WeaveCrypto.prototype = {
    prefBranch : null,
    debug      : true,  // services.sync.log.cryptoDebug

    observer : {
        _self : null,

        QueryInterface : XPCOMUtils.generateQI([Ci.nsIObserver,
                                                Ci.nsISupportsWeakReference]),

        observe(subject, topic, data) {
            let self = this._self;
            self.log("Observed " + topic + " topic.");
            if (topic == "nsPref:changed") {
                self.debug = self.prefBranch.getBoolPref("cryptoDebug");
            }
        }
    },

    init() {
        // Preferences. Add observer so we get notified of changes.
        this.prefBranch = Services.prefs.getBranch("services.sync.log.");
        this.prefBranch.addObserver("cryptoDebug", this.observer, false);
        this.observer._self = this;
        this.debug = this.prefBranch.getBoolPref("cryptoDebug", false);
        XPCOMUtils.defineLazyGetter(this, 'encoder', () => new TextEncoder(UTF_LABEL));
        XPCOMUtils.defineLazyGetter(this, 'decoder', () => new TextDecoder(UTF_LABEL, { fatal: true }));
    },

    log(message) {
        if (!this.debug) {
            return;
        }
        dump("WeaveCrypto: " + message + "\n");
        Services.console.logStringMessage("WeaveCrypto: " + message);
    },

    // /!\ Only use this for tests! /!\
    _getCrypto() {
        return crypto;
    },

    encrypt(clearTextUCS2, symmetricKey, iv) {
        this.log("encrypt() called");
        let clearTextBuffer = this.encoder.encode(clearTextUCS2).buffer;
        let encrypted = this._commonCrypt(clearTextBuffer, symmetricKey, iv, OPERATIONS.ENCRYPT);
        return this.encodeBase64(encrypted);
    },

    decrypt(cipherText, symmetricKey, iv) {
        this.log("decrypt() called");
        if (cipherText.length) {
            cipherText = atob(cipherText);
        }
        let cipherTextBuffer = this.byteCompressInts(cipherText);
        let decrypted = this._commonCrypt(cipherTextBuffer, symmetricKey, iv, OPERATIONS.DECRYPT);
        return this.decoder.decode(decrypted);
    },

    /**
     * _commonCrypt
     *
     * @args
     * data: data to encrypt/decrypt (ArrayBuffer)
     * symKeyStr: symmetric key (Base64 String)
     * ivStr: initialization vector (Base64 String)
     * operation: operation to apply (either OPERATIONS.ENCRYPT or OPERATIONS.DECRYPT)
     * @returns
     * the encrypted/decrypted data (ArrayBuffer)
    */
    _commonCrypt(data, symKeyStr, ivStr, operation) {
        this.log("_commonCrypt() called");
        ivStr = atob(ivStr);

        if (operation !== OPERATIONS.ENCRYPT && operation !== OPERATIONS.DECRYPT) {
            throw new Error("Unsupported operation in _commonCrypt.");
        }
        // We never want an IV longer than the block size, which is 16 bytes
        // for AES, neither do we want one smaller; throw in both cases.
        if (ivStr.length !== AES_CBC_IV_SIZE) {
            throw "Invalid IV size; must be " + AES_CBC_IV_SIZE + " bytes.";
        }

        let iv = this.byteCompressInts(ivStr);
        let symKey = this.importSymKey(symKeyStr, operation);
        let cryptMethod = (operation === OPERATIONS.ENCRYPT
                           ? crypto.subtle.encrypt
                           : crypto.subtle.decrypt)
                          .bind(crypto.subtle);
        let algo = { name: CRYPT_ALGO, iv: iv };


        return Async.promiseSpinningly(
            cryptMethod(algo, symKey, data)
            .then(keyBytes => new Uint8Array(keyBytes))
        );
    },


    generateRandomKey() {
        this.log("generateRandomKey() called");
        let algo = {
            name: CRYPT_ALGO,
            length: CRYPT_ALGO_LENGTH
        };
        return Async.promiseSpinningly(
            crypto.subtle.generateKey(algo, true, [])
            .then(key => crypto.subtle.exportKey("raw", key))
            .then(keyBytes => {
                keyBytes = new Uint8Array(keyBytes);
                return this.encodeBase64(keyBytes);
            })
        );
    },

    generateRandomIV() {
      return this.generateRandomBytes(AES_CBC_IV_SIZE);
    },

    generateRandomBytes(byteCount) {
        this.log("generateRandomBytes() called");

        let randBytes = new Uint8Array(byteCount);
        crypto.getRandomValues(randBytes);

        return this.encodeBase64(randBytes);
    },

    //
    // SymKey CryptoKey memoization.
    //

    // Memoize the import of symmetric keys. We do this by using the base64
    // string itself as a key.
    _encryptionSymKeyMemo: {},
    _decryptionSymKeyMemo: {},
    importSymKey(encodedKeyString, operation) {
        let memo;

        // We use two separate memos for thoroughness: operation is an input to
        // key import.
        switch (operation) {
            case OPERATIONS.ENCRYPT:
                memo = this._encryptionSymKeyMemo;
                break;
            case OPERATIONS.DECRYPT:
                memo = this._decryptionSymKeyMemo;
                break;
            default:
                throw "Unsupported operation in importSymKey.";
        }

        if (encodedKeyString in memo)
            return memo[encodedKeyString];

        let symmetricKeyBuffer = this.makeUint8Array(encodedKeyString, true);
        let algo = { name: CRYPT_ALGO };
        let usages = [operation === OPERATIONS.ENCRYPT ? "encrypt" : "decrypt"];

        return Async.promiseSpinningly(
            crypto.subtle.importKey("raw", symmetricKeyBuffer, algo, false, usages)
            .then(symKey => {
                memo[encodedKeyString] = symKey;
                return symKey;
            })
        );
    },


    //
    // Utility functions
    //

    /**
     * Returns an Uint8Array filled with a JS string,
     * which means we only keep utf-16 characters from 0x00 to 0xFF.
     */
    byteCompressInts(str) {
        let arrayBuffer = new Uint8Array(str.length);
        for (let i = 0; i < str.length; i++) {
            arrayBuffer[i] = str.charCodeAt(i) & 0xFF;
        }
        return arrayBuffer;
    },

    expandData(data) {
        let expanded = "";
        for (let i = 0; i < data.length; i++) {
            expanded += String.fromCharCode(data[i]);
        }
        return expanded;
    },

    encodeBase64(data) {
        return btoa(this.expandData(data));
    },

    makeUint8Array(input, isEncoded) {
        if (isEncoded) {
            input = atob(input);
        }
        return this.byteCompressInts(input);
    },

    /**
     * Returns the expanded data string for the derived key.
     */
    deriveKeyFromPassphrase(passphrase, saltStr, keyLength = 32) {
        this.log("deriveKeyFromPassphrase() called.");
        let keyData = this.makeUint8Array(passphrase, false);
        let salt = this.makeUint8Array(saltStr, true);
        let importAlgo = { name: KEY_DERIVATION_ALGO };
        let deriveAlgo = {
            name: KEY_DERIVATION_ALGO,
            salt: salt,
            iterations: KEY_DERIVATION_ITERATIONS,
            hash: { name: KEY_DERIVATION_HASHING_ALGO },
        };
        let derivedKeyType = {
            name: DERIVED_KEY_ALGO,
            length: keyLength * 8,
        };
        return Async.promiseSpinningly(
            crypto.subtle.importKey("raw", keyData, importAlgo, false, ["deriveKey"])
            .then(key => crypto.subtle.deriveKey(deriveAlgo, key, derivedKeyType, true, []))
            .then(derivedKey => crypto.subtle.exportKey("raw", derivedKey))
            .then(keyBytes => {
                keyBytes = new Uint8Array(keyBytes);
                return this.expandData(keyBytes);
            })
        );
    },
};