summaryrefslogtreecommitdiffstats
path: root/toolkit/components/extensions/test/xpcshell/test_ext_proxy_socks.js
blob: fd0aff709af65b3736e1119b32425c528de8ff50 (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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
"use strict";

/* globals TCPServerSocket */

const CC = Components.Constructor;

const BinaryInputStream = CC(
  "@mozilla.org/binaryinputstream;1",
  "nsIBinaryInputStream",
  "setInputStream"
);

const currentThread =
  Cc["@mozilla.org/thread-manager;1"].getService().currentThread;

// Most of the socks logic here is copied and upgraded to support authentication
// for socks5. The original test is from netwerk/test/unit/test_socks.js

// Socks 4 support was left in place for future tests.

const STATE_WAIT_GREETING = 1;
const STATE_WAIT_SOCKS4_REQUEST = 2;
const STATE_WAIT_SOCKS4_USERNAME = 3;
const STATE_WAIT_SOCKS4_HOSTNAME = 4;
const STATE_WAIT_SOCKS5_GREETING = 5;
const STATE_WAIT_SOCKS5_REQUEST = 6;
const STATE_WAIT_SOCKS5_AUTH = 7;
const STATE_WAIT_INPUT = 8;
const STATE_FINISHED = 9;

/**
 * A basic socks proxy setup that handles a single http response page.  This
 * is used for testing socks auth with webrequest.  We don't bother making
 * sure we buffer ondata, etc., we'll never get anything but tiny chunks here.
 */
class SocksClient {
  constructor(server, socket) {
    this.server = server;
    this.type = "";
    this.username = "";
    this.dest_name = "";
    this.dest_addr = [];
    this.dest_port = [];

    this.inbuf = [];
    this.state = STATE_WAIT_GREETING;
    this.socket = socket;

    socket.onclose = () => {
      this.server.requestCompleted(this);
    };
    socket.ondata = event => {
      let len = event.data.byteLength;

      if (len == 0 && this.state == STATE_FINISHED) {
        this.close();
        this.server.requestCompleted(this);
        return;
      }

      this.inbuf = new Uint8Array(event.data);
      Promise.resolve().then(() => {
        this.callState();
      });
    };
  }

  callState() {
    switch (this.state) {
      case STATE_WAIT_GREETING:
        this.checkSocksGreeting();
        break;
      case STATE_WAIT_SOCKS4_REQUEST:
        this.checkSocks4Request();
        break;
      case STATE_WAIT_SOCKS4_USERNAME:
        this.checkSocks4Username();
        break;
      case STATE_WAIT_SOCKS4_HOSTNAME:
        this.checkSocks4Hostname();
        break;
      case STATE_WAIT_SOCKS5_GREETING:
        this.checkSocks5Greeting();
        break;
      case STATE_WAIT_SOCKS5_REQUEST:
        this.checkSocks5Request();
        break;
      case STATE_WAIT_SOCKS5_AUTH:
        this.checkSocks5Auth();
        break;
      case STATE_WAIT_INPUT:
        this.checkRequest();
        break;
      default:
        do_throw("server: read in invalid state!");
    }
  }

  write(buf) {
    this.socket.send(new Uint8Array(buf).buffer);
  }

  checkSocksGreeting() {
    if (!this.inbuf.length) {
      return;
    }

    if (this.inbuf[0] == 4) {
      this.type = "socks4";
      this.state = STATE_WAIT_SOCKS4_REQUEST;
      this.checkSocks4Request();
    } else if (this.inbuf[0] == 5) {
      this.type = "socks";
      this.state = STATE_WAIT_SOCKS5_GREETING;
      this.checkSocks5Greeting();
    } else {
      do_throw("Unknown socks protocol!");
    }
  }

  checkSocks4Request() {
    if (this.inbuf.length < 8) {
      return;
    }

    this.dest_port = this.inbuf.slice(2, 4);
    this.dest_addr = this.inbuf.slice(4, 8);

    this.inbuf = this.inbuf.slice(8);
    this.state = STATE_WAIT_SOCKS4_USERNAME;
    this.checkSocks4Username();
  }

  readString() {
    let i = this.inbuf.indexOf(0);
    let str = null;

    if (i >= 0) {
      let decoder = new TextDecoder();
      str = decoder.decode(this.inbuf.slice(0, i));
      this.inbuf = this.inbuf.slice(i + 1);
    }

    return str;
  }

  checkSocks4Username() {
    let str = this.readString();

    if (str == null) {
      return;
    }

    this.username = str;
    if (
      this.dest_addr[0] == 0 &&
      this.dest_addr[1] == 0 &&
      this.dest_addr[2] == 0 &&
      this.dest_addr[3] != 0
    ) {
      this.state = STATE_WAIT_SOCKS4_HOSTNAME;
      this.checkSocks4Hostname();
    } else {
      this.sendSocks4Response();
    }
  }

  checkSocks4Hostname() {
    let str = this.readString();

    if (str == null) {
      return;
    }

    this.dest_name = str;
    this.sendSocks4Response();
  }

  sendSocks4Response() {
    this.state = STATE_WAIT_INPUT;
    this.inbuf = [];
    this.write([0, 0x5a, 0, 0, 0, 0, 0, 0]);
  }

  /**
   * checks authentication information.
   *
   * buf[0] socks version
   * buf[1] number of auth methods supported
   * buf[2+nmethods] value for each auth method
   *
   * Response is
   * byte[0] socks version
   * byte[1] desired auth method
   *
   * For whatever reason, Firefox does not present auth method 0x02 however
   * responding with that does cause Firefox to send authentication if
   * the nsIProxyInfo instance has the data.  IUUC Firefox should send
   * supported methods, but I'm no socks expert.
   */
  checkSocks5Greeting() {
    if (this.inbuf.length < 2) {
      return;
    }
    let nmethods = this.inbuf[1];
    if (this.inbuf.length < 2 + nmethods) {
      return;
    }

    // See comment above, keeping for future update.
    // let methods = this.inbuf.slice(2, 2 + nmethods);

    this.inbuf = [];
    if (this.server.password || this.server.username) {
      this.state = STATE_WAIT_SOCKS5_AUTH;
      this.write([5, 2]);
    } else {
      this.state = STATE_WAIT_SOCKS5_REQUEST;
      this.write([5, 0]);
    }
  }

  checkSocks5Auth() {
    equal(this.inbuf[0], 0x01, "subnegotiation version");
    let uname_len = this.inbuf[1];
    let pass_len = this.inbuf[2 + uname_len];
    let unnamebuf = this.inbuf.slice(2, 2 + uname_len);
    let pass_start = 2 + uname_len + 1;
    let pwordbuf = this.inbuf.slice(pass_start, pass_start + pass_len);
    let decoder = new TextDecoder();
    let username = decoder.decode(unnamebuf);
    let password = decoder.decode(pwordbuf);
    this.inbuf = [];
    equal(username, this.server.username, "socks auth username");
    equal(password, this.server.password, "socks auth password");
    if (username == this.server.username && password == this.server.password) {
      this.state = STATE_WAIT_SOCKS5_REQUEST;
      // x00 is success, any other value closes the connection
      this.write([1, 0]);
      return;
    }
    this.state = STATE_FINISHED;
    this.write([1, 1]);
  }

  checkSocks5Request() {
    if (this.inbuf.length < 4) {
      return;
    }

    let atype = this.inbuf[3];
    let len;
    let name = false;

    switch (atype) {
      case 0x01:
        len = 4;
        break;
      case 0x03:
        len = this.inbuf[4];
        name = true;
        break;
      case 0x04:
        len = 16;
        break;
      default:
        do_throw("Unknown address type " + atype);
    }

    if (name) {
      if (this.inbuf.length < 4 + len + 1 + 2) {
        return;
      }

      let buf = this.inbuf.slice(5, 5 + len);
      let decoder = new TextDecoder();
      this.dest_name = decoder.decode(buf);
      len += 1;
    } else {
      if (this.inbuf.length < 4 + len + 2) {
        return;
      }

      this.dest_addr = this.inbuf.slice(4, 4 + len);
    }

    len += 4;
    this.dest_port = this.inbuf.slice(len, len + 2);
    this.inbuf = this.inbuf.slice(len + 2);
    this.sendSocks5Response();
  }

  sendSocks5Response() {
    let buf;
    if (this.dest_addr.length == 16) {
      // send a successful response with the address, [::1]:80
      buf = [5, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 80];
    } else {
      // send a successful response with the address, 127.0.0.1:80
      buf = [5, 0, 0, 1, 127, 0, 0, 1, 0, 80];
    }
    this.state = STATE_WAIT_INPUT;
    this.inbuf = [];
    this.write(buf);
  }

  checkRequest() {
    let decoder = new TextDecoder();
    let request = decoder.decode(this.inbuf);

    if (request == "PING!") {
      this.state = STATE_FINISHED;
      this.socket.send("PONG!");
    } else if (request.startsWith("GET / HTTP/1.1")) {
      this.socket.send(
        "HTTP/1.1 200 OK\r\n" +
          "Content-Length: 2\r\n" +
          "Content-Type: text/html\r\n" +
          "\r\nOK"
      );
      this.state = STATE_FINISHED;
    }
  }

  close() {
    this.socket.close();
  }
}

class SocksTestServer {
  constructor() {
    this.client_connections = new Set();
    this.listener = new TCPServerSocket(-1, { binaryType: "arraybuffer" }, -1);
    this.listener.onconnect = event => {
      let client = new SocksClient(this, event.socket);
      this.client_connections.add(client);
    };
  }

  requestCompleted(client) {
    this.client_connections.delete(client);
  }

  close() {
    for (let client of this.client_connections) {
      client.close();
    }
    this.client_connections = new Set();
    if (this.listener) {
      this.listener.close();
      this.listener = null;
    }
  }

  setUserPass(username, password) {
    this.username = username;
    this.password = password;
  }
}

/**
 * Tests the basic socks logic using a simple socket connection and the
 * protocol proxy service.  Before 902346, TCPSocket has no way to tie proxy
 * data to it, so we go old school here.
 */
class SocksTestClient {
  constructor(socks, dest, resolve, reject) {
    let pps = Cc["@mozilla.org/network/protocol-proxy-service;1"].getService(
      Ci.nsIProtocolProxyService
    );
    let sts = Cc["@mozilla.org/network/socket-transport-service;1"].getService(
      Ci.nsISocketTransportService
    );

    let pi_flags = 0;
    if (socks.dns == "remote") {
      pi_flags = Ci.nsIProxyInfo.TRANSPARENT_PROXY_RESOLVES_HOST;
    }

    let pi = pps.newProxyInfoWithAuth(
      socks.version,
      socks.host,
      socks.port,
      socks.username,
      socks.password,
      "",
      "",
      pi_flags,
      -1,
      null
    );

    this.trans = sts.createTransport([], dest.host, dest.port, pi, null);
    this.input = this.trans.openInputStream(
      Ci.nsITransport.OPEN_BLOCKING,
      0,
      0
    );
    this.output = this.trans.openOutputStream(
      Ci.nsITransport.OPEN_BLOCKING,
      0,
      0
    );
    this.outbuf = String();
    this.resolve = resolve;
    this.reject = reject;

    this.write("PING!");
    this.input.asyncWait(this, 0, 0, currentThread);
  }

  onInputStreamReady(stream) {
    let len = 0;
    try {
      len = stream.available();
    } catch (e) {
      // This will happen on auth failure.
      this.reject(e);
      return;
    }
    let bin = new BinaryInputStream(stream);
    let data = bin.readByteArray(len);
    let decoder = new TextDecoder();
    let result = decoder.decode(data);
    if (result == "PONG!") {
      this.resolve(result);
    } else {
      this.reject();
    }
  }

  write(buf) {
    this.outbuf += buf;
    this.output.asyncWait(this, 0, 0, currentThread);
  }

  onOutputStreamReady(stream) {
    let len = stream.write(this.outbuf, this.outbuf.length);
    if (len != this.outbuf.length) {
      this.outbuf = this.outbuf.substring(len);
      stream.asyncWait(this, 0, 0, currentThread);
    } else {
      this.outbuf = String();
    }
  }

  close() {
    this.output.close();
  }
}

const socksServer = new SocksTestServer();
socksServer.setUserPass("foo", "bar");
registerCleanupFunction(() => {
  socksServer.close();
});

// A simple ping/pong to test the socks server.
add_task(async function test_socks_server() {
  let socks = {
    version: "socks",
    host: "127.0.0.1",
    port: socksServer.listener.localPort,
    username: "foo",
    password: "bar",
    dns: false,
  };
  let dest = {
    host: "localhost",
    port: 8888,
  };

  new Promise((resolve, reject) => {
    new SocksTestClient(socks, dest, resolve, reject);
  })
    .then(result => {
      equal("PONG!", result, "socks test ok");
    })
    .catch(result => {
      ok(false, `socks test failed ${result}`);
    });
});

// Register a proxy to be used by TCPSocket connections later.
function registerProxy(socks) {
  let pps = Cc["@mozilla.org/network/protocol-proxy-service;1"].getService(
    Ci.nsIProtocolProxyService
  );
  let filter = {
    QueryInterface: ChromeUtils.generateQI(["nsIProtocolProxyFilter"]),
    applyFilter(uri, proxyInfo, callback) {
      callback.onProxyFilterResult(
        pps.newProxyInfoWithAuth(
          socks.version,
          socks.host,
          socks.port,
          socks.username,
          socks.password,
          "",
          "",
          socks.dns == "remote"
            ? Ci.nsIProxyInfo.TRANSPARENT_PROXY_RESOLVES_HOST
            : 0,
          -1,
          null
        )
      );
    },
  };
  pps.registerFilter(filter, 0);
  registerCleanupFunction(() => {
    pps.unregisterFilter(filter);
  });
}

// A simple ping/pong to test the socks server with TCPSocket.
add_task(async function test_tcpsocket_proxy() {
  let socks = {
    version: "socks",
    host: "127.0.0.1",
    port: socksServer.listener.localPort,
    username: "foo",
    password: "bar",
    dns: false,
  };
  let dest = {
    host: "localhost",
    port: 8888,
  };

  registerProxy(socks);
  await new Promise((resolve, reject) => {
    let client = new TCPSocket(dest.host, dest.port);
    client.onopen = () => {
      client.send("PING!");
    };
    client.ondata = e => {
      equal("PONG!", e.data, "socks test ok");
      resolve();
    };
    client.onerror = () => reject();
  });
});

add_task(async function test_webRequest_socks_proxy() {
  async function background(port) {
    function checkProxyData(details) {
      browser.test.assertEq("127.0.0.1", details.proxyInfo.host, "proxy host");
      browser.test.assertEq(port, details.proxyInfo.port, "proxy port");
      browser.test.assertEq("socks", details.proxyInfo.type, "proxy type");
      browser.test.assertEq(
        "foo",
        details.proxyInfo.username,
        "proxy username not set"
      );
      browser.test.assertEq(
        undefined,
        details.proxyInfo.password,
        "no proxy password passed to webrequest"
      );
    }
    browser.webRequest.onBeforeRequest.addListener(
      details => {
        checkProxyData(details);
      },
      { urls: ["<all_urls>"] }
    );
    browser.webRequest.onAuthRequired.addListener(
      () => {
        // We should never get onAuthRequired for socks proxy
        browser.test.fail("onAuthRequired");
      },
      { urls: ["<all_urls>"] },
      ["blocking"]
    );
    browser.webRequest.onCompleted.addListener(
      details => {
        checkProxyData(details);
        browser.test.sendMessage("done");
      },
      { urls: ["<all_urls>"] }
    );
    browser.proxy.onRequest.addListener(
      () => {
        return [
          {
            type: "socks",
            host: "127.0.0.1",
            port,
            username: "foo",
            password: "bar",
          },
        ];
      },
      { urls: ["<all_urls>"] }
    );
  }

  let handlingExt = ExtensionTestUtils.loadExtension({
    manifest: {
      permissions: ["proxy", "webRequest", "webRequestBlocking", "<all_urls>"],
    },
    background: `(${background})(${socksServer.listener.localPort})`,
  });

  // proxy.register is deprecated - bug 1443259.
  ExtensionTestUtils.failOnSchemaWarnings(false);
  await handlingExt.startup();
  ExtensionTestUtils.failOnSchemaWarnings(true);

  let contentPage = await ExtensionTestUtils.loadContentPage(
    `http://localhost/`
  );

  await handlingExt.awaitMessage("done");
  await contentPage.close();
  await handlingExt.unload();
});

add_task(async function test_onRequest_tcpsocket_proxy() {
  async function background(port) {
    browser.proxy.onRequest.addListener(
      () => {
        return [
          {
            type: "socks",
            host: "127.0.0.1",
            port,
            username: "foo",
            password: "bar",
          },
        ];
      },
      { urls: ["<all_urls>"] }
    );
  }

  let handlingExt = ExtensionTestUtils.loadExtension({
    manifest: {
      permissions: ["proxy", "webRequest", "webRequestBlocking", "<all_urls>"],
    },
    background: `(${background})(${socksServer.listener.localPort})`,
  });

  await handlingExt.startup();

  await new Promise((resolve, reject) => {
    let client = new TCPSocket("localhost", 8888);
    client.onopen = () => {
      client.send("PING!");
    };
    client.ondata = e => {
      equal("PONG!", e.data, "socks test ok");
      resolve();
    };
    client.onerror = () => reject();
  });

  await handlingExt.unload();
});