-
Notifications
You must be signed in to change notification settings - Fork 33
/
nassh_relay_corp.js
371 lines (337 loc) · 12 KB
/
nassh_relay_corp.js
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
// Copyright 2012 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview Implementation for the [email protected] proxy.
*/
import {lib} from '../../libdot/index.js';
import {localize} from './nassh.js';
import {Relay} from './nassh_relay.js';
import {Stream} from './nassh_stream.js';
import {RelayCorpWsStream,
RelayCorpXhrStream} from './nassh_stream_relay_corp.js';
/**
* Corp Relay implementation.
*/
export class Corp extends Relay {
/** @inheritDoc */
constructor(io, options, location, storage, localPrefs) {
super(io, options, location, storage, localPrefs);
this.proxyHostFallback = options['--proxy-host-fallback'];
this.useSecure = options['--use-ssl'];
this.useWebsocket = !options['--use-xhr'];
this.reportAckLatency = options['--report-ack-latency'];
this.reportConnectAttempts = options['--report-connect-attempts'];
this.relayProtocol = options['--relay-protocol'];
this.relayMethod = options['--relay-method'];
this.relayServer = null;
this.relayServerSocket = null;
this.egressDomain = options['--egress-domain'];
}
/**
* Returns the pattern for the cookie server URL.
*
* @return {string} The fully URI pattern.
*/
cookieServerPattern() {
let template = '%(protocol)://%(host):%(port)/cookie' +
'?ext=%encodeURIComponent(return_to)' +
'&path=html/nassh_google_relay.html';
if (this.relayProtocol === 'v2') {
template += '&version=2&method=js-redirect';
}
if (this.remoteHost) {
template += '&host=%(remote_host)';
}
return template;
}
/** @inheritDoc */
redirect() {
const resumePath = this.location.href.substr(this.location.origin.length);
// Save off our destination in session storage before we leave for the
// proxy page.
this.storage.setItem('googleRelay.resumePath', resumePath);
const uri = lib.f.replaceVars(
this.cookieServerPattern(), {
host: this.proxyHost,
port: this.proxyPort,
protocol: this.useSecure ? 'https' : 'http',
remote_host: this.remoteHost,
// This returns us to nassh_google_relay.html so we can pick the relay
// host out of the reply. From there we continue on to the resumePath.
return_to: this.location.host,
});
// Since the proxy settings are coming from the user, make sure we catch bad
// values (hostnames/etc...) directly.
try {
// eslint-disable-next-line no-new
new URL(uri);
} catch (e) {
this.io_.println(e);
this.io_.println(uri);
return false;
}
this.location.replace(uri);
return true;
}
/** @inheritDoc */
async init() {
if (this.relayMethod === 'direct') {
return this.authenticateDirect();
}
const resumePath = this.location.href.substr(this.location.origin.length);
// This session storage item is created by /html/nassh_google_relay.html
// if we succeed at finding a relay host.
const relayHost = this.storage.getItem('googleRelay.relayHost');
const relayPort = this.storage.getItem('googleRelay.relayPort') ||
this.proxyPort;
if (relayHost) {
const expectedResumePath = this.storage.getItem('googleRelay.resumePath');
if (expectedResumePath === resumePath) {
const pattern = this.relayServerPattern;
this.relayServer = lib.f.replaceVars(pattern, {
host: relayHost,
port: relayPort,
protocol: this.useSecure ? 'https' : 'http',
});
this.relayServerSocket = lib.f.replaceVars(pattern, {
host: relayHost,
port: relayPort,
protocol: this.useSecure ? 'wss' : 'ws',
});
// If we made it this far, we're probably not stuck in a redirect loop.
// Clear the counter used by the relay redirect page.
this.storage.removeItem('googleRelay.redirectCount');
} else {
// If everything is ok, this should be the second time we've been asked
// to do the same init. (The first time would have redirected.) If
// this init specifies a different resumePath, then something is
// probably wrong.
console.warn(`Destination mismatch: ${expectedResumePath} != ` +
`${resumePath}`);
this.relayServer = null;
}
}
this.storage.removeItem('googleRelay.relayHost');
this.storage.removeItem('googleRelay.relayPort');
this.storage.removeItem('googleRelay.resumePath');
if (this.relayServer) {
this.io_.println(localize('FOUND_RELAY', [this.relayServer]));
return true;
}
return false;
}
/** @inheritDoc */
saveState() {
return {
relayServer: this.relayServer,
relayServerSocket: this.relayServerSocket,
};
}
/** @inheritDoc */
loadState(state) {
this.relayServer = state.relayServer;
this.relayServerSocket = state.relayServerSocket;
}
/**
* Return Stream class to use.
*
* @return {function(new:Stream, number, ?)}
*/
getStreamClass() {
return this.useWebsocket ? RelayCorpWsStream : RelayCorpXhrStream;
}
/** @inheritDoc */
openSocket(fd, host, port, streams, onOpen) {
const options = {
io: this.io_,
relayServer: this.relayServer,
relayServerSocket: this.relayServerSocket,
relayUser: this.username,
reportConnectAttempts: this.reportConnectAttempts,
reportAckLatency: this.reportAckLatency,
host: host,
port: port,
resume: this.resumeConnection,
localPrefs: this.localPrefs,
egressDomain: this.egressDomain,
};
return streams.openStream(this.getStreamClass(), fd, options, onOpen);
}
/**
* Authenticates to proxy using fetch with method=direct. Refreshes ticket
* from full cookie if possible, else opens a login popup if required.
*
* @return {!Promise<boolean>} true if authentication succeeded, else false on
* error.
*/
async authenticateDirect() {
const protocol = this.useSecure ? 'https' : 'http';
let endpoint = `${this.proxyHost}:${this.proxyPort}`;
const params = this.remoteHost ? `?host=${this.remoteHost}` : '';
let proxyUrl = `${protocol}://${endpoint}/endpoint${params}`;
// Since the proxy settings are coming from the user, make sure we catch bad
// values (hostnames/etc...) directly.
try {
// eslint-disable-next-line no-new
new URL(proxyUrl);
} catch (e) {
this.io_.println(e);
this.io_.println(proxyUrl);
return false;
}
// Query for endpoint. On failure we might as well continue and attempt
// to connect to /cookie using one of the proxy hosts from the config
// instead of from the /endpoint response.
try {
endpoint = await this.fetchEndpoint(proxyUrl);
} catch (e) {
console.warn('Query endpoint failed', e);
if (this.proxyHostFallback) {
try {
endpoint = `${this.proxyHostFallback}:${this.proxyPort}`;
proxyUrl = `${protocol}://${endpoint}/endpoint${params}`;
endpoint = await this.fetchEndpoint(proxyUrl);
} catch (e) {
console.warn('Fallback query endpoint failed', e);
}
}
}
// Validate cookie. This will fail if ticket or full cookie not set.
proxyUrl = `${protocol}://${endpoint}/cookie?version=2`;
try {
await this.validateCookie(proxyUrl);
return true;
} catch (e) {
console.info(`Refresh ticket and query endpoint again: ${e.message}`);
}
// Refresh ticket and validate ticket again. This will fail if full cookie
// not set.
try {
await this.refreshTicket(proxyUrl);
await this.validateCookie(proxyUrl);
return true;
} catch (e) {
console.info(`Login and query endpoint again: ${e.message}`);
}
// Show a login popup, then validate ticket again.
try {
await this.showLoginPopup(proxyUrl);
await this.validateCookie(proxyUrl);
return true;
} catch (e) {
console.warn('Error in login and query endpoint', e);
return false;
}
}
/**
* Query proxy /endpoint to get relay /cookie host.
*
* @param {string} proxy Proxy url to connect to.
* @return {!Promise<string>}
*/
async fetchEndpoint(proxy) {
const res = await fetch(proxy);
const text = await res.text();
// Skip the XSSI countermeasure.
if (!text.startsWith(")]}'\n")) {
throw Error(`Unknown response: ${text}`);
}
const params = JSON.parse(text.slice(5));
// Expecting format: {endpoint: <host[:port]>}. Port is optional.
// E.g. {"endpoint": "sup-ssh-relay.corp.google.com:8046"}.
const endpoint = params['endpoint'];
if (!endpoint) {
throw new Error(params['error'] || `No endpoint from ${proxy}`);
}
return endpoint;
}
/**
* Query proxy /cookie using 'method=direct'. We must include
* credentials (cookies) and cors in order to read the json response.
* This fetch request will succeed if we already have a valid ticket.
* Otherwise, the proxy server will redirect us to the login server which will
* fail with cors issues. In such a case, we will first attempt
* refreshTicket(), or finally showLoginPopup() and reattempt this function.
*
* @param {string} proxy Proxy url to connect to.
*/
async validateCookie(proxy) {
const url = `${proxy}&method=direct`;
const res = await fetch(url, {credentials: 'include'});
const text = await res.text();
// Skip the XSSI countermeasure.
if (!text.startsWith(")]}'\n")) {
throw Error(`Unknown response: ${text}`);
}
const params = JSON.parse(text.slice(5));
// Expecting format: {endpoint: <host[:port]>}. Port is optional.
// E.g. {"endpoint": "sup-ssh-relay.corp.google.com:8046"}.
const endpoint = params['endpoint'];
if (endpoint) {
this.io_.println(localize('FOUND_RELAY', [endpoint]));
const serverProtocol = this.useSecure ? 'https' : 'http';
const socketProtocol = this.useSecure ? 'wss' : 'ws';
this.relayServer = `${serverProtocol}://${endpoint}/`;
this.relayServerSocket = `${socketProtocol}://${endpoint}/`;
return;
}
throw new Error(params['error'] || `No endpoint from ${proxy}`);
}
/**
* Fetch from proxy in no-cors in order to allow redirects to
* login.corp.google.com where a valid full cookie will be used to issue
* a ticket.
*
* @param {string} proxy Proxy url to connect to.
*/
async refreshTicket(proxy) {
const url = `${proxy}&method=direct`;
await fetch(url, {credentials: 'include', mode: 'no-cors'});
}
/**
* Open a popup window for the proxy with 'method=close'. This will redirect
* to login.corp.google.com where users can reauthenticate (password,gnubby),
* and return back to the proxy with a valid ticket. By using `method=close',
* the proxy will close the popup, and a subsequent call to
* validateCookie() should succeed.
*
* @param {string} proxy Proxy url to connect to.
*/
async showLoginPopup(proxy) {
const url = `${proxy}&method=close&origin=${
encodeURIComponent(globalThis.location.origin)}`;
const width = 1000;
const height = 550;
const left = (screen.width - width) / 2;
const top = (screen.height - height) / 2;
const features =
`titlebar=no,width=${width},height=${height},top=${top},left=${left}`;
const popup = lib.f.openWindow(url, '_blank', features);
if (!popup) {
throw new Error('Could not create login popup');
}
await new Promise((resolve) => {
const listener = () => {
if (popup.closed) {
chrome.windows.onRemoved.removeListener(listener);
resolve();
}
};
chrome.windows.onRemoved.addListener(listener);
});
}
}
/**
* @override
* @type {number}
*/
Corp.prototype.defaultProxyPort = 8022;
/**
* The pattern for XHR relay server's url.
*
* We'll be appending 'proxy', 'read' and 'write' to this as necessary.
*
* @const {string}
*/
Corp.prototype.relayServerPattern = '%(protocol)://%(host):%(port)/';