Welcome to mirror list, hosted at ThFree Co, Russian Federation.

crypto-worker.ts « runtime « wasm « mono « src - github.com/dotnet/runtime.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 674f1700d22724ab285fbe8c1462c6db3b9ef052 (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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

import { Module } from "./imports";
import { mono_assert } from "./types";

let mono_wasm_crypto: {
    channel: LibraryChannel
    worker: Worker
} | null = null;

export function dotnet_browser_can_use_subtle_crypto_impl(): number {
    return mono_wasm_crypto === null ? 0 : 1;
}

export function dotnet_browser_simple_digest_hash(ver: number, input_buffer: number, input_len: number, output_buffer: number, output_len: number): number {
    mono_assert(!!mono_wasm_crypto, "subtle crypto not initialized");

    const msg = {
        func: "digest",
        type: ver,
        data: Array.from(Module.HEAPU8.subarray(input_buffer, input_buffer + input_len))
    };

    const response = mono_wasm_crypto.channel.send_msg(JSON.stringify(msg));
    const digest = JSON.parse(response);
    if (digest.length > output_len) {
        console.info("call_digest: about to throw!");
        throw "DIGEST HASH: Digest length exceeds output length: " + digest.length + " > " + output_len;
    }

    Module.HEAPU8.set(digest, output_buffer);
    return 1;
}

export function dotnet_browser_sign(hashAlgorithm: number, key_buffer: number, key_len: number, input_buffer: number, input_len: number, output_buffer: number, output_len: number): number {
    mono_assert(!!mono_wasm_crypto, "subtle crypto not initialized");

    const msg = {
        func: "sign",
        type: hashAlgorithm,
        key: Array.from(Module.HEAPU8.subarray(key_buffer, key_buffer + key_len)),
        data: Array.from(Module.HEAPU8.subarray(input_buffer, input_buffer + input_len))
    };

    const response = mono_wasm_crypto.channel.send_msg(JSON.stringify(msg));
    const signResult = JSON.parse(response);
    if (signResult.length > output_len) {
        console.info("dotnet_browser_sign: about to throw!");
        throw "SIGN HASH: Sign length exceeds output length: " + signResult.length + " > " + output_len;
    }

    Module.HEAPU8.set(signResult, output_buffer);
    return 1;
}

const AesBlockSizeBytes = 16; // 128 bits

export function dotnet_browser_encrypt_decrypt(isEncrypting: boolean, key_buffer: number, key_len: number, iv_buffer: number, iv_len: number, input_buffer: number, input_len: number, output_buffer: number, output_len: number): number {
    mono_assert(!!mono_wasm_crypto, "subtle crypto not initialized");

    if (input_len <= 0 || input_len % AesBlockSizeBytes !== 0) {
        throw "ENCRYPT DECRYPT: data was not a full block: " + input_len;
    }

    const msg = {
        func: "encrypt_decrypt",
        isEncrypting: isEncrypting,
        key: Array.from(Module.HEAPU8.subarray(key_buffer, key_buffer + key_len)),
        iv: Array.from(Module.HEAPU8.subarray(iv_buffer, iv_buffer + iv_len)),
        data: Array.from(Module.HEAPU8.subarray(input_buffer, input_buffer + input_len))
    };

    const response = mono_wasm_crypto.channel.send_msg(JSON.stringify(msg));
    const result = JSON.parse(response);

    if (result.length > output_len) {
        console.info("dotnet_browser_encrypt_decrypt: about to throw!");
        throw "ENCRYPT DECRYPT: Encrypt/Decrypt length exceeds output length: " + result.length + " > " + output_len;
    }

    Module.HEAPU8.set(result, output_buffer);
    return result.length;
}

export function init_crypto(): void {
    if (typeof globalThis.crypto !== "undefined" && typeof globalThis.crypto.subtle !== "undefined"
        && typeof SharedArrayBuffer !== "undefined"
        && typeof Worker !== "undefined"
    ) {
        console.debug("MONO_WASM: Initializing Crypto WebWorker");

        const chan = LibraryChannel.create(1024); // 1024 is the buffer size in char units.
        const worker = new Worker("dotnet-crypto-worker.js");
        mono_wasm_crypto = {
            channel: chan,
            worker: worker,
        };
        worker.postMessage({
            comm_buf: chan.get_comm_buffer(),
            msg_buf: chan.get_msg_buffer(),
            msg_char_len: chan.get_msg_len()
        });
        worker.onerror = event => {
            console.warn(`MONO_WASM: Error in Crypto WebWorker. Cryptography digest calls will fallback to managed implementation. Error: ${event.message}`);
            mono_wasm_crypto = null;
        };
    }
}

class LibraryChannel {
    private msg_char_len: number;
    private comm_buf: SharedArrayBuffer;
    private msg_buf: SharedArrayBuffer;
    private comm: Int32Array;
    private msg: Uint16Array;

    // LOCK states
    private get LOCK_UNLOCKED(): number { return 0; }  // 0 means the lock is unlocked
    private get LOCK_OWNED(): number { return 1; } // 1 means the LibraryChannel owns the lock

    // Index constants for the communication buffer.
    private get STATE_IDX(): number { return 0; }
    private get MSG_SIZE_IDX(): number { return 1; }
    private get LOCK_IDX(): number { return 2; }
    private get COMM_LAST_IDX(): number { return this.LOCK_IDX; }

    // Communication states.
    private get STATE_SHUTDOWN(): number { return -1; } // Shutdown
    private get STATE_IDLE(): number { return 0; }
    private get STATE_REQ(): number { return 1; }
    private get STATE_RESP(): number { return 2; }
    private get STATE_REQ_P(): number { return 3; } // Request has multiple parts
    private get STATE_RESP_P(): number { return 4; } // Response has multiple parts
    private get STATE_AWAIT(): number { return 5; } // Awaiting the next part

    private constructor(msg_char_len: number) {
        this.msg_char_len = msg_char_len;

        const int_bytes = 4;
        const comm_byte_len = int_bytes * (this.COMM_LAST_IDX + 1);
        this.comm_buf = new SharedArrayBuffer(comm_byte_len);

        // JavaScript character encoding is UTF-16.
        const char_bytes = 2;
        const msg_byte_len = char_bytes * this.msg_char_len;
        this.msg_buf = new SharedArrayBuffer(msg_byte_len);

        // Create the local arrays to use.
        this.comm = new Int32Array(this.comm_buf);
        this.msg = new Uint16Array(this.msg_buf);
    }

    public get_msg_len(): number { return this.msg_char_len; }
    public get_msg_buffer(): SharedArrayBuffer { return this.msg_buf; }
    public get_comm_buffer(): SharedArrayBuffer { return this.comm_buf; }

    public send_msg(msg: string): string {
        if (Atomics.load(this.comm, this.STATE_IDX) !== this.STATE_IDLE) {
            throw "OWNER: Invalid sync communication channel state. " + Atomics.load(this.comm, this.STATE_IDX);
        }
        this.send_request(msg);
        return this.read_response();
    }

    public shutdown(): void {
        if (Atomics.load(this.comm, this.STATE_IDX) !== this.STATE_IDLE) {
            throw "OWNER: Invalid sync communication channel state. " + Atomics.load(this.comm, this.STATE_IDX);
        }

        // Notify webworker
        Atomics.store(this.comm, this.MSG_SIZE_IDX, 0);
        Atomics.store(this.comm, this.STATE_IDX, this.STATE_SHUTDOWN);
        Atomics.notify(this.comm, this.STATE_IDX);
    }

    private send_request(msg: string): void {
        let state;
        const msg_len = msg.length;
        let msg_written = 0;

        for (; ;) {
            this.acquire_lock();

            // Write the message and return how much was written.
            const wrote = this.write_to_msg(msg, msg_written, msg_len);
            msg_written += wrote;

            // Indicate how much was written to the this.msg buffer.
            Atomics.store(this.comm, this.MSG_SIZE_IDX, wrote);

            // Indicate if this was the whole message or part of it.
            state = msg_written === msg_len ? this.STATE_REQ : this.STATE_REQ_P;

            // Notify webworker
            Atomics.store(this.comm, this.STATE_IDX, state);

            this.release_lock();

            Atomics.notify(this.comm, this.STATE_IDX);

            // The send message is complete.
            if (state === this.STATE_REQ)
                break;

            // Wait for the worker to be ready for the next part.
            //  - Atomics.wait() is not permissible on the main thread.
            do {
                state = Atomics.load(this.comm, this.STATE_IDX);
            } while (state !== this.STATE_AWAIT);
        }
    }

    private write_to_msg(input: string, start: number, input_len: number): number {
        let mi = 0;
        let ii = start;
        while (mi < this.msg_char_len && ii < input_len) {
            this.msg[mi] = input.charCodeAt(ii);
            ii++; // Next character
            mi++; // Next buffer index
        }
        return ii - start;
    }

    private read_response(): string {
        let state;
        let response = "";
        for (; ;) {
            // Wait for webworker response.
            //  - Atomics.wait() is not permissible on the main thread.
            do {
                state = Atomics.load(this.comm, this.STATE_IDX);
            } while (state !== this.STATE_RESP && state !== this.STATE_RESP_P);

            this.acquire_lock();

            const size_to_read = Atomics.load(this.comm, this.MSG_SIZE_IDX);

            // Append the latest part of the message.
            response += this.read_from_msg(0, size_to_read);

            // The response is complete.
            if (state === this.STATE_RESP) {
                this.release_lock();
                break;
            }

            // Reset the size and transition to await state.
            Atomics.store(this.comm, this.MSG_SIZE_IDX, 0);
            Atomics.store(this.comm, this.STATE_IDX, this.STATE_AWAIT);

            this.release_lock();

            Atomics.notify(this.comm, this.STATE_IDX);
        }

        // Reset the communication channel's state and let the
        // webworker know we are done.
        Atomics.store(this.comm, this.STATE_IDX, this.STATE_IDLE);
        Atomics.notify(this.comm, this.STATE_IDX);

        return response;
    }

    private read_from_msg(begin: number, end: number): string {
        const slicedMessage: number[] = [];
        this.msg.slice(begin, end).forEach((value, index) => slicedMessage[index] = value);
        return String.fromCharCode.apply(null, slicedMessage);
    }

    private acquire_lock() {
        while (Atomics.compareExchange(this.comm, this.LOCK_IDX, this.LOCK_UNLOCKED, this.LOCK_OWNED) !== this.LOCK_UNLOCKED) {
            // empty
        }
    }

    private release_lock() {
        const result = Atomics.compareExchange(this.comm, this.LOCK_IDX, this.LOCK_OWNED, this.LOCK_UNLOCKED);
        if (result !== this.LOCK_OWNED) {
            throw "CRYPTO: LibraryChannel tried to release a lock that wasn't acquired: " + result;
        }
    }

    public static create(msg_char_len: number): LibraryChannel {
        if (msg_char_len === undefined) {
            msg_char_len = 1024; // Default size is arbitrary but is in 'char' units (i.e. UTF-16 code points).
        }
        return new LibraryChannel(msg_char_len);
    }
}