-
Notifications
You must be signed in to change notification settings - Fork 629
/
_tls_wrap.ts
417 lines (357 loc) · 11.5 KB
/
_tls_wrap.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
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
414
415
416
417
// Copyright 2018-2022 the Deno authors. All rights reserved. MIT license.
// Copyright Joyent and Node contributors. All rights reserved. MIT license.
// deno-lint-ignore-file no-explicit-any
import {
ObjectAssign,
StringPrototypeReplace,
} from "./internal/primordials.mjs";
import assert from "./internal/assert.mjs";
import * as net from "./net.ts";
import { createSecureContext } from "./_tls_common.ts";
import { kStreamBaseField } from "./internal_binding/stream_wrap.ts";
import { connResetException } from "./internal/errors.ts";
import { emitWarning } from "./process.ts";
import { debuglog } from "./internal/util/debuglog.ts";
import { constants as TCPConstants, TCP } from "./internal_binding/tcp_wrap.ts";
import {
constants as PipeConstants,
Pipe,
} from "./internal_binding/pipe_wrap.ts";
import { EventEmitter } from "./events.ts";
import { kEmptyObject } from "./internal/util.mjs";
const kConnectOptions = Symbol("connect-options");
const kIsVerified = Symbol("verified");
const kPendingSession = Symbol("pendingSession");
const kRes = Symbol("res");
let _debug = debuglog("tls", (fn) => {
_debug = fn;
});
function onConnectEnd(this: any) {
// NOTE: This logic is shared with _http_client.js
if (!this._hadError) {
const options = this[kConnectOptions];
this._hadError = true;
const error: any = connResetException(
"Client network socket disconnected " +
"before secure TLS connection was " +
"established",
);
error.path = options.path;
error.host = options.host;
error.port = options.port;
error.localAddress = options.localAddress;
this.destroy(error);
}
}
export class TLSSocket extends net.Socket {
_tlsOptions: any;
_secureEstablished: boolean;
_securePending: boolean;
_newSessionPending: boolean;
_controlReleased: boolean;
secureConnecting: boolean;
_SNICallback: any;
servername: string | null;
alpnProtocol: any;
authorized: boolean;
authorizationError: any;
[kRes]: any;
[kIsVerified]: boolean;
[kPendingSession]: any;
[kConnectOptions]: any;
ssl: any;
_start: any;
constructor(socket: any, opts: any = kEmptyObject) {
const tlsOptions = { ...opts };
let hostname = tlsOptions?.secureContext?.servername;
hostname = opts.host;
tlsOptions.hostname = hostname;
const _cert = tlsOptions?.secureContext?.cert;
const _key = tlsOptions?.secureContext?.key;
let caCerts = tlsOptions?.secureContext?.ca;
if (typeof caCerts === "string") caCerts = [caCerts];
tlsOptions.caCerts = caCerts;
super({
handle: _wrapHandle(tlsOptions, socket),
...opts,
manualStart: true, // This prevents premature reading from TLS handle
});
if (socket) {
this._parent = socket;
}
this._tlsOptions = tlsOptions;
this._secureEstablished = false;
this._securePending = false;
this._newSessionPending = false;
this._controlReleased = false;
this.secureConnecting = true;
this._SNICallback = null;
this.servername = null;
this.alpnProtocol = null;
this.authorized = false;
this.authorizationError = null;
this[kRes] = null;
this[kIsVerified] = false;
this[kPendingSession] = null;
this.ssl = new class {
verifyError() {
return null; // Never fails, rejectUnauthorized is always true in Deno.
}
}();
// deno-lint-ignore no-this-alias
const tlssock = this;
/** Wraps the given socket and adds the tls capability to the underlying
* handle */
function _wrapHandle(tlsOptions: any, wrap: net.Socket | undefined) {
let handle: any;
if (wrap) {
handle = wrap._handle;
}
const options = tlsOptions;
if (!handle) {
handle = options.pipe
? new Pipe(PipeConstants.SOCKET)
: new TCP(TCPConstants.SOCKET);
}
// Patches `afterConnect` hook to replace TCP conn with TLS conn
const afterConnect = handle.afterConnect;
handle.afterConnect = async (req: any, status: number) => {
try {
const conn = await Deno.startTls(handle[kStreamBaseField], options);
tlssock.emit("secure");
tlssock.removeListener("end", onConnectEnd);
handle[kStreamBaseField] = conn;
} catch {
// TODO(kt3k): Handle this
}
return afterConnect.call(handle, req, status);
};
(handle as any).verifyError = function () {
return null; // Never fails, rejectUnauthorized is always true in Deno.
};
// Pretends `handle` is `tls_wrap.wrap(handle, ...)` to make some npm modules happy
// An example usage of `_parentWrap` in npm module:
// https://github.com/szmarczak/http2-wrapper/blob/51eeaf59ff9344fb192b092241bfda8506983620/source/utils/js-stream-socket.js#L6
handle._parent = handle;
handle._parentWrap = wrap;
return handle;
}
}
_tlsError(err: Error) {
this.emit("_tlsError", err);
if (this._controlReleased) {
return err;
}
return null;
}
_releaseControl() {
if (this._controlReleased) {
return false;
}
this._controlReleased = true;
this.removeListener("error", this._tlsError);
return true;
}
getEphemeralKeyInfo() {
return {};
}
isSessionReused() {
return false;
}
setSession(_session: any) {
// TODO(kt3k): implement this
}
setServername(_servername: any) {
// TODO(kt3k): implement this
}
getPeerCertificate(_detailed: boolean) {
// TODO(kt3k): implement this
return {
subject: "localhost",
subjectaltname: "IP Address:127.0.0.1, IP Address:::1",
};
}
}
function normalizeConnectArgs(listArgs: any) {
const args = net._normalizeArgs(listArgs);
const options = args[0];
const cb = args[1];
// If args[0] was options, then normalize dealt with it.
// If args[0] is port, or args[0], args[1] is host, port, we need to
// find the options and merge them in, normalize's options has only
// the host/port/path args that it knows about, not the tls options.
// This means that options.host overrides a host arg.
if (listArgs[1] !== null && typeof listArgs[1] === "object") {
ObjectAssign(options, listArgs[1]);
} else if (listArgs[2] !== null && typeof listArgs[2] === "object") {
ObjectAssign(options, listArgs[2]);
}
return cb ? [options, cb] : [options];
}
let ipServernameWarned = false;
export function Server(options: any, listener: any) {
return new ServerImpl(options, listener);
}
export class ServerImpl extends EventEmitter {
listener?: Deno.TlsListener;
#closed = false;
constructor(public options: any, listener: any) {
super();
if (listener) {
this.on("secureConnection", listener);
}
}
listen(port: any, callback: any): this {
const { key, cert } = this.options;
// TODO(kt3k): Get this from optional 2nd argument.
const hostname = "localhost";
this.listener = Deno.listenTls({ port, hostname, cert, key });
callback?.();
this.#listen(this.listener);
return this;
}
async #listen(listener: Deno.TlsListener) {
while (!this.#closed) {
try {
// Creates TCP handle and socket directly from Deno.TlsConn.
// This works as TLS socket. We don't use TLSSocket class for doing
// this because Deno.startTls only supports client side tcp connection.
const handle = new TCP(TCPConstants.SOCKET, await listener.accept());
const socket = new net.Socket({ handle });
this.emit("secureConnection", socket);
} catch (e) {
if (e instanceof Deno.errors.BadResource) {
this.#closed = true;
}
// swallow
}
}
}
close(cb?: (err?: Error) => void): this {
if (this.listener) {
this.listener.close();
}
cb?.();
return this;
}
}
Server.prototype = ServerImpl.prototype;
export function createServer(options: any, listener: any) {
return new ServerImpl(options, listener);
}
export function connect(...args: any[]) {
args = normalizeConnectArgs(args);
let options = args[0];
const cb = args[1];
const allowUnauthorized = getAllowUnauthorized();
options = {
rejectUnauthorized: !allowUnauthorized,
ciphers: DEFAULT_CIPHERS,
checkServerIdentity,
minDHSize: 1024,
...options,
};
if (!options.keepAlive) {
options.singleUse = true;
}
assert(typeof options.checkServerIdentity === "function");
assert(
typeof options.minDHSize === "number",
"options.minDHSize is not a number: " + options.minDHSize,
);
assert(
options.minDHSize > 0,
"options.minDHSize is not a positive number: " +
options.minDHSize,
);
const context = options.secureContext || createSecureContext(options);
const tlssock = new TLSSocket(options.socket, {
allowHalfOpen: options.allowHalfOpen,
pipe: !!options.path,
secureContext: context,
isServer: false,
requestCert: true,
rejectUnauthorized: options.rejectUnauthorized !== false,
session: options.session,
ALPNProtocols: options.ALPNProtocols,
requestOCSP: options.requestOCSP,
enableTrace: options.enableTrace,
pskCallback: options.pskCallback,
highWaterMark: options.highWaterMark,
onread: options.onread,
signal: options.signal,
...options, // Caveat emptor: Node does not do this.
});
// rejectUnauthorized property can be explicitly defined as `undefined`
// causing the assignment to default value (`true`) fail. Before assigning
// it to the tlssock connection options, explicitly check if it is false
// and update rejectUnauthorized property. The property gets used by TLSSocket
// connection handler to allow or reject connection if unauthorized
options.rejectUnauthorized = options.rejectUnauthorized !== false;
tlssock[kConnectOptions] = options;
if (cb) {
tlssock.once("secureConnect", cb);
}
if (!options.socket) {
// If user provided the socket, it's their responsibility to manage its
// connectivity. If we created one internally, we connect it.
if (options.timeout) {
tlssock.setTimeout(options.timeout);
}
tlssock.connect(options, tlssock._start);
}
tlssock._releaseControl();
if (options.session) {
tlssock.setSession(options.session);
}
if (options.servername) {
if (!ipServernameWarned && net.isIP(options.servername)) {
emitWarning(
"Setting the TLS ServerName to an IP address is not permitted by " +
"RFC 6066. This will be ignored in a future version.",
"DeprecationWarning",
"DEP0123",
);
ipServernameWarned = true;
}
tlssock.setServername(options.servername);
}
if (options.socket) {
tlssock._start();
}
tlssock.prependListener("end", onConnectEnd);
return tlssock;
}
function getAllowUnauthorized() {
return false;
}
// TODO(kt3k): Implement this when Deno provides APIs for getting peer
// certificates.
export function checkServerIdentity(_hostname: string, _cert: any) {
}
function unfqdn(host: string): string {
return StringPrototypeReplace(host, /[.]$/, "");
}
// Order matters. Mirrors ALL_CIPHER_SUITES from rustls/src/suites.rs but
// using openssl cipher names instead. Mutable in Node but not (yet) in Deno.
export const DEFAULT_CIPHERS = [
// TLSv1.3 suites
"AES256-GCM-SHA384",
"AES128-GCM-SHA256",
"TLS_CHACHA20_POLY1305_SHA256",
// TLSv1.2 suites
"ECDHE-ECDSA-AES256-GCM-SHA384",
"ECDHE-ECDSA-AES128-GCM-SHA256",
"ECDHE-ECDSA-CHACHA20-POLY1305",
"ECDHE-RSA-AES256-GCM-SHA384",
"ECDHE-RSA-AES128-GCM-SHA256",
"ECDHE-RSA-CHACHA20-POLY1305",
].join(":");
export default {
TLSSocket,
connect,
createServer,
checkServerIdentity,
DEFAULT_CIPHERS,
unfqdn,
};