source: node_modules/socks/README.md@ 81bc7da

finki-main main
Last change on this file since 81bc7da was 81bc7da, checked in by Klimentina Efremova <klimentina08642@…>, 3 months ago

Initial commit

  • Property mode set to 100644
File size: 22.8 KB
Line 
1# socks [![Build Status](https://travis-ci.org/JoshGlazebrook/socks.svg?branch=master)](https://travis-ci.org/JoshGlazebrook/socks) [![Coverage Status](https://coveralls.io/repos/github/JoshGlazebrook/socks/badge.svg?branch=master)](https://coveralls.io/github/JoshGlazebrook/socks?branch=v2)
2
3Fully featured SOCKS proxy client supporting SOCKSv4, SOCKSv4a, and SOCKSv5. Includes Bind and Associate functionality.
4
5> Looking for Node.js agent? Check [node-socks-proxy-agent](https://github.com/TooTallNate/node-socks-proxy-agent).
6
7### Features
8
9* Supports SOCKS v4, v4a, v5, and v5h protocols.
10* Supports the CONNECT, BIND, and ASSOCIATE commands.
11* Supports callbacks, promises, and events for proxy connection creation async flow control.
12* Supports proxy chaining (CONNECT only).
13* Supports user/password authentication.
14* Supports custom authentication.
15* Built in UDP frame creation & parse functions.
16* Created with TypeScript, type definitions are provided.
17
18### Requirements
19
20* Node.js v10.0+ (Please use [v1](https://github.com/JoshGlazebrook/socks/tree/82d83923ad960693d8b774cafe17443ded7ed584) for older versions of Node.js)
21
22### Looking for v1?
23* Docs for v1 are available [here](https://github.com/JoshGlazebrook/socks/tree/82d83923ad960693d8b774cafe17443ded7ed584)
24
25## Installation
26
27`yarn add socks`
28
29or
30
31`npm install --save socks`
32
33## Usage
34
35```typescript
36// TypeScript
37import { SocksClient, SocksClientOptions, SocksClientChainOptions } from 'socks';
38
39// ES6 JavaScript
40import { SocksClient } from 'socks';
41
42// Legacy JavaScript
43const SocksClient = require('socks').SocksClient;
44```
45
46## Quick Start Example
47
48Connect to github.com (192.30.253.113) on port 80, using a SOCKS proxy.
49
50```javascript
51const options = {
52 proxy: {
53 host: '159.203.75.200', // ipv4 or ipv6 or hostname
54 port: 1080,
55 type: 5 // Proxy version (4 or 5)
56 },
57
58 command: 'connect', // SOCKS command (createConnection factory function only supports the connect command)
59
60 destination: {
61 host: '192.30.253.113', // github.com (hostname lookups are supported with SOCKS v4a and 5)
62 port: 80
63 }
64};
65
66// Async/Await
67try {
68 const info = await SocksClient.createConnection(options);
69
70 console.log(info.socket);
71 // <Socket ...> (this is a raw net.Socket that is established to the destination host through the given proxy server)
72} catch (err) {
73 // Handle errors
74}
75
76// Promises
77SocksClient.createConnection(options)
78.then(info => {
79 console.log(info.socket);
80 // <Socket ...> (this is a raw net.Socket that is established to the destination host through the given proxy server)
81})
82.catch(err => {
83 // Handle errors
84});
85
86// Callbacks
87SocksClient.createConnection(options, (err, info) => {
88 if (!err) {
89 console.log(info.socket);
90 // <Socket ...> (this is a raw net.Socket that is established to the destination host through the given proxy server)
91 } else {
92 // Handle errors
93 }
94});
95```
96
97## Chaining Proxies
98
99**Note:** Chaining is only supported when using the SOCKS connect command, and chaining can only be done through the special factory chaining function.
100
101This example makes a proxy chain through two SOCKS proxies to ip-api.com. Once the connection to the destination is established it sends an HTTP request to get a JSON response that returns ip info for the requesting ip.
102
103```javascript
104const options = {
105 destination: {
106 host: 'ip-api.com', // host names are supported with SOCKS v4a and SOCKS v5.
107 port: 80
108 },
109 command: 'connect', // Only the connect command is supported when chaining proxies.
110 proxies: [ // The chain order is the order in the proxies array, meaning the last proxy will establish a connection to the destination.
111 {
112 host: '159.203.75.235', // ipv4, ipv6, or hostname
113 port: 1081,
114 type: 5
115 },
116 {
117 host: '104.131.124.203', // ipv4, ipv6, or hostname
118 port: 1081,
119 type: 5
120 }
121 ]
122}
123
124// Async/Await
125try {
126 const info = await SocksClient.createConnectionChain(options);
127
128 console.log(info.socket);
129 // <Socket ...> (this is a raw net.Socket that is established to the destination host through the given proxy servers)
130
131 console.log(info.socket.remoteAddress) // The remote address of the returned socket is the first proxy in the chain.
132 // 159.203.75.235
133
134 info.socket.write('GET /json HTTP/1.1\nHost: ip-api.com\n\n');
135 info.socket.on('data', (data) => {
136 console.log(data.toString()); // ip-api.com sees that the last proxy in the chain (104.131.124.203) is connected to it.
137 /*
138 HTTP/1.1 200 OK
139 Access-Control-Allow-Origin: *
140 Content-Type: application/json; charset=utf-8
141 Date: Sun, 24 Dec 2017 03:47:51 GMT
142 Content-Length: 300
143
144 {
145 "as":"AS14061 Digital Ocean, Inc.",
146 "city":"Clifton",
147 "country":"United States",
148 "countryCode":"US",
149 "isp":"Digital Ocean",
150 "lat":40.8326,
151 "lon":-74.1307,
152 "org":"Digital Ocean",
153 "query":"104.131.124.203",
154 "region":"NJ",
155 "regionName":"New Jersey",
156 "status":"success",
157 "timezone":"America/New_York",
158 "zip":"07014"
159 }
160 */
161 });
162} catch (err) {
163 // Handle errors
164}
165
166// Promises
167SocksClient.createConnectionChain(options)
168.then(info => {
169 console.log(info.socket);
170 // <Socket ...> (this is a raw net.Socket that is established to the destination host through the given proxy server)
171
172 console.log(info.socket.remoteAddress) // The remote address of the returned socket is the first proxy in the chain.
173 // 159.203.75.235
174
175 info.socket.write('GET /json HTTP/1.1\nHost: ip-api.com\n\n');
176 info.socket.on('data', (data) => {
177 console.log(data.toString()); // ip-api.com sees that the last proxy in the chain (104.131.124.203) is connected to it.
178 /*
179 HTTP/1.1 200 OK
180 Access-Control-Allow-Origin: *
181 Content-Type: application/json; charset=utf-8
182 Date: Sun, 24 Dec 2017 03:47:51 GMT
183 Content-Length: 300
184
185 {
186 "as":"AS14061 Digital Ocean, Inc.",
187 "city":"Clifton",
188 "country":"United States",
189 "countryCode":"US",
190 "isp":"Digital Ocean",
191 "lat":40.8326,
192 "lon":-74.1307,
193 "org":"Digital Ocean",
194 "query":"104.131.124.203",
195 "region":"NJ",
196 "regionName":"New Jersey",
197 "status":"success",
198 "timezone":"America/New_York",
199 "zip":"07014"
200 }
201 */
202 });
203})
204.catch(err => {
205 // Handle errors
206});
207
208// Callbacks
209SocksClient.createConnectionChain(options, (err, info) => {
210 if (!err) {
211 console.log(info.socket);
212 // <Socket ...> (this is a raw net.Socket that is established to the destination host through the given proxy server)
213
214 console.log(info.socket.remoteAddress) // The remote address of the returned socket is the first proxy in the chain.
215 // 159.203.75.235
216
217 info.socket.write('GET /json HTTP/1.1\nHost: ip-api.com\n\n');
218 info.socket.on('data', (data) => {
219 console.log(data.toString()); // ip-api.com sees that the last proxy in the chain (104.131.124.203) is connected to it.
220 /*
221 HTTP/1.1 200 OK
222 Access-Control-Allow-Origin: *
223 Content-Type: application/json; charset=utf-8
224 Date: Sun, 24 Dec 2017 03:47:51 GMT
225 Content-Length: 300
226
227 {
228 "as":"AS14061 Digital Ocean, Inc.",
229 "city":"Clifton",
230 "country":"United States",
231 "countryCode":"US",
232 "isp":"Digital Ocean",
233 "lat":40.8326,
234 "lon":-74.1307,
235 "org":"Digital Ocean",
236 "query":"104.131.124.203",
237 "region":"NJ",
238 "regionName":"New Jersey",
239 "status":"success",
240 "timezone":"America/New_York",
241 "zip":"07014"
242 }
243 */
244 });
245 } else {
246 // Handle errors
247 }
248});
249```
250
251## Bind Example (TCP Relay)
252
253When the bind command is sent to a SOCKS v4/v5 proxy server, the proxy server starts listening on a new TCP port and the proxy relays then remote host information back to the client. When another remote client connects to the proxy server on this port the SOCKS proxy sends a notification that an incoming connection has been accepted to the initial client and a full duplex stream is now established to the initial client and the client that connected to that special port.
254
255```javascript
256const options = {
257 proxy: {
258 host: '159.203.75.235', // ipv4, ipv6, or hostname
259 port: 1081,
260 type: 5
261 },
262
263 command: 'bind',
264
265 // When using BIND, the destination should be the remote client that is expected to connect to the SOCKS proxy. Using 0.0.0.0 makes the Proxy accept any incoming connection on that port.
266 destination: {
267 host: '0.0.0.0',
268 port: 0
269 }
270};
271
272// Creates a new SocksClient instance.
273const client = new SocksClient(options);
274
275// When the SOCKS proxy has bound a new port and started listening, this event is fired.
276client.on('bound', info => {
277 console.log(info.remoteHost);
278 /*
279 {
280 host: "159.203.75.235",
281 port: 57362
282 }
283 */
284});
285
286// When a client connects to the newly bound port on the SOCKS proxy, this event is fired.
287client.on('established', info => {
288 // info.remoteHost is the remote address of the client that connected to the SOCKS proxy.
289 console.log(info.remoteHost);
290 /*
291 host: 67.171.34.23,
292 port: 49823
293 */
294
295 console.log(info.socket);
296 // <Socket ...> (This is a raw net.Socket that is a connection between the initial client and the remote client that connected to the proxy)
297
298 // Handle received data...
299 info.socket.on('data', data => {
300 console.log('recv', data);
301 });
302});
303
304// An error occurred trying to establish this SOCKS connection.
305client.on('error', err => {
306 console.error(err);
307});
308
309// Start connection to proxy
310client.connect();
311```
312
313## Associate Example (UDP Relay)
314
315When the associate command is sent to a SOCKS v5 proxy server, it sets up a UDP relay that allows the client to send UDP packets to a remote host through the proxy server, and also receive UDP packet responses back through the proxy server.
316
317```javascript
318const options = {
319 proxy: {
320 host: '159.203.75.235', // ipv4, ipv6, or hostname
321 port: 1081,
322 type: 5
323 },
324
325 command: 'associate',
326
327 // When using associate, the destination should be the remote client that is expected to send UDP packets to the proxy server to be forwarded. This should be your local ip, or optionally the wildcard address (0.0.0.0) UDP Client <-> Proxy <-> UDP Client
328 destination: {
329 host: '0.0.0.0',
330 port: 0
331 }
332};
333
334// Create a local UDP socket for sending packets to the proxy.
335const udpSocket = dgram.createSocket('udp4');
336udpSocket.bind();
337
338// Listen for incoming UDP packets from the proxy server.
339udpSocket.on('message', (message, rinfo) => {
340 console.log(SocksClient.parseUDPFrame(message));
341 /*
342 { frameNumber: 0,
343 remoteHost: { host: '165.227.108.231', port: 4444 }, // The remote host that replied with a UDP packet
344 data: <Buffer 74 65 73 74 0a> // The data
345 }
346 */
347});
348
349let client = new SocksClient(options);
350
351// When the UDP relay is established, this event is fired and includes the UDP relay port to send data to on the proxy server.
352client.on('established', info => {
353 console.log(info.remoteHost);
354 /*
355 {
356 host: '159.203.75.235',
357 port: 44711
358 }
359 */
360
361 // Send 'hello' to 165.227.108.231:4444
362 const packet = SocksClient.createUDPFrame({
363 remoteHost: { host: '165.227.108.231', port: 4444 },
364 data: Buffer.from('hello')
365 });
366 udpSocket.send(packet, info.remoteHost.port, info.remoteHost.host);
367});
368
369// Start connection
370client.connect();
371```
372
373**Note:** The associate TCP connection to the proxy must remain open for the UDP relay to work.
374
375## Additional Examples
376
377[Documentation](docs/index.md)
378
379
380## Migrating from v1
381
382Looking for a guide to migrate from v1? Look [here](docs/migratingFromV1.md)
383
384## Api Reference:
385
386**Note:** socks includes full TypeScript definitions. These can even be used without using TypeScript as most IDEs (such as VS Code) will use these type definition files for auto completion intellisense even in JavaScript files.
387
388* Class: SocksClient
389 * [new SocksClient(options[, callback])](#new-socksclientoptions)
390 * [Class Method: SocksClient.createConnection(options[, callback])](#class-method-socksclientcreateconnectionoptions-callback)
391 * [Class Method: SocksClient.createConnectionChain(options[, callback])](#class-method-socksclientcreateconnectionchainoptions-callback)
392 * [Class Method: SocksClient.createUDPFrame(options)](#class-method-socksclientcreateudpframedetails)
393 * [Class Method: SocksClient.parseUDPFrame(data)](#class-method-socksclientparseudpframedata)
394 * [Event: 'error'](#event-error)
395 * [Event: 'bound'](#event-bound)
396 * [Event: 'established'](#event-established)
397 * [client.connect()](#clientconnect)
398 * [client.socksClientOptions](#clientconnect)
399
400### SocksClient
401
402SocksClient establishes SOCKS proxy connections to remote destination hosts. These proxy connections are fully transparent to the server and once established act as full duplex streams. SOCKS v4, v4a, v5, and v5h are supported, as well as the connect, bind, and associate commands.
403
404SocksClient supports creating connections using callbacks, promises, and async/await flow control using two static factory functions createConnection and createConnectionChain. It also internally extends EventEmitter which results in allowing event handling based async flow control.
405
406**SOCKS Compatibility Table**
407
408Note: When using 4a please specify type: 4, and when using 5h please specify type 5.
409
410| Socks Version | TCP | UDP | IPv4 | IPv6 | Hostname |
411| --- | :---: | :---: | :---: | :---: | :---: |
412| SOCKS v4 | ✅ | ❌ | ✅ | ❌ | ❌ |
413| SOCKS v4a | ✅ | ❌ | ✅ | ❌ | ✅ |
414| SOCKS v5 (includes v5h) | ✅ | ✅ | ✅ | ✅ | ✅ |
415
416### new SocksClient(options)
417
418* ```options``` {SocksClientOptions} - An object describing the SOCKS proxy to use, the command to send and establish, and the destination host to connect to.
419
420### SocksClientOptions
421
422```typescript
423{
424 proxy: {
425 host: '159.203.75.200', // ipv4, ipv6, or hostname
426 port: 1080,
427 type: 5, // Proxy version (4 or 5). For v4a use 4, for v5h use 5.
428
429 // Optional fields
430 userId: 'some username', // Used for SOCKS4 userId auth, and SOCKS5 user/pass auth in conjunction with password.
431 password: 'some password', // Used in conjunction with userId for user/pass auth for SOCKS5 proxies.
432 custom_auth_method: 0x80, // If using a custom auth method, specify the type here. If this is set, ALL other custom_auth_*** options must be set as well.
433 custom_auth_request_handler: async () =>. {
434 // This will be called when it's time to send the custom auth handshake. You must return a Buffer containing the data to send as your authentication.
435 return Buffer.from([0x01,0x02,0x03]);
436 },
437 // This is the expected size (bytes) of the custom auth response from the proxy server.
438 custom_auth_response_size: 2,
439 // This is called when the auth response is received. The received packet is passed in as a Buffer, and you must return a boolean indicating the response from the server said your custom auth was successful or failed.
440 custom_auth_response_handler: async (data) => {
441 return data[1] === 0x00;
442 }
443 },
444
445 command: 'connect', // connect, bind, associate
446
447 destination: {
448 host: '192.30.253.113', // ipv4, ipv6, hostname. Hostnames work with v4a and v5.
449 port: 80
450 },
451
452 // Optional fields
453 timeout: 30000, // How long to wait to establish a proxy connection. (defaults to 30 seconds)
454
455 set_tcp_nodelay: true // If true, will turn on the underlying sockets TCP_NODELAY option.
456}
457```
458
459### Class Method: SocksClient.createConnection(options[, callback])
460* ```options``` { SocksClientOptions } - An object describing the SOCKS proxy to use, the command to send and establish, and the destination host to connect to.
461* ```callback``` { Function } - Optional callback function that is called when the proxy connection is established, or an error occurs.
462* ```returns``` { Promise } - A Promise is returned that is resolved when the proxy connection is established, or rejected when an error occurs.
463
464Creates a new proxy connection through the given proxy to the given destination host. This factory function supports callbacks and promises for async flow control.
465
466**Note:** If a callback function is provided, the promise will always resolve regardless of an error occurring. Please be sure to exclusively use either promises or callbacks when using this factory function.
467
468```typescript
469const options = {
470 proxy: {
471 host: '159.203.75.200', // ipv4, ipv6, or hostname
472 port: 1080,
473 type: 5 // Proxy version (4 or 5)
474 },
475
476 command: 'connect', // connect, bind, associate
477
478 destination: {
479 host: '192.30.253.113', // ipv4, ipv6, or hostname
480 port: 80
481 }
482}
483
484// Await/Async (uses a Promise)
485try {
486 const info = await SocksClient.createConnection(options);
487 console.log(info);
488 /*
489 {
490 socket: <Socket ...>, // Raw net.Socket
491 }
492 */
493 / <Socket ...> (this is a raw net.Socket that is established to the destination host through the given proxy server)
494
495} catch (err) {
496 // Handle error...
497}
498
499// Promise
500SocksClient.createConnection(options)
501.then(info => {
502 console.log(info);
503 /*
504 {
505 socket: <Socket ...>, // Raw net.Socket
506 }
507 */
508})
509.catch(err => {
510 // Handle error...
511});
512
513// Callback
514SocksClient.createConnection(options, (err, info) => {
515 if (!err) {
516 console.log(info);
517 /*
518 {
519 socket: <Socket ...>, // Raw net.Socket
520 }
521 */
522 } else {
523 // Handle error...
524 }
525});
526```
527
528### Class Method: SocksClient.createConnectionChain(options[, callback])
529* ```options``` { SocksClientChainOptions } - An object describing a list of SOCKS proxies to use, the command to send and establish, and the destination host to connect to.
530* ```callback``` { Function } - Optional callback function that is called when the proxy connection chain is established, or an error occurs.
531* ```returns``` { Promise } - A Promise is returned that is resolved when the proxy connection chain is established, or rejected when an error occurs.
532
533Creates a new proxy connection chain through a list of at least two SOCKS proxies to the given destination host. This factory method supports callbacks and promises for async flow control.
534
535**Note:** If a callback function is provided, the promise will always resolve regardless of an error occurring. Please be sure to exclusively use either promises or callbacks when using this factory function.
536
537**Note:** At least two proxies must be provided for the chain to be established.
538
539```typescript
540const options = {
541 proxies: [ // The chain order is the order in the proxies array, meaning the last proxy will establish a connection to the destination.
542 {
543 host: '159.203.75.235', // ipv4, ipv6, or hostname
544 port: 1081,
545 type: 5
546 },
547 {
548 host: '104.131.124.203', // ipv4, ipv6, or hostname
549 port: 1081,
550 type: 5
551 }
552 ]
553
554 command: 'connect', // Only connect is supported in chaining mode.
555
556 destination: {
557 host: '192.30.253.113', // ipv4, ipv6, hostname
558 port: 80
559 }
560}
561```
562
563### Class Method: SocksClient.createUDPFrame(details)
564* ```details``` { SocksUDPFrameDetails } - An object containing the remote host, frame number, and frame data to use when creating a SOCKS UDP frame packet.
565* ```returns``` { Buffer } - A Buffer containing all of the UDP frame data.
566
567Creates a SOCKS UDP frame relay packet that is sent and received via a SOCKS proxy when using the associate command for UDP packet forwarding.
568
569**SocksUDPFrameDetails**
570
571```typescript
572{
573 frameNumber: 0, // The frame number (used for breaking up larger packets)
574
575 remoteHost: { // The remote host to have the proxy send data to, or the remote host that send this data.
576 host: '1.2.3.4',
577 port: 1234
578 },
579
580 data: <Buffer 01 02 03 04...> // A Buffer instance of data to include in the packet (actual data sent to the remote host)
581}
582interface SocksUDPFrameDetails {
583 // The frame number of the packet.
584 frameNumber?: number;
585
586 // The remote host.
587 remoteHost: SocksRemoteHost;
588
589 // The packet data.
590 data: Buffer;
591}
592```
593
594### Class Method: SocksClient.parseUDPFrame(data)
595* ```data``` { Buffer } - A Buffer instance containing SOCKS UDP frame data to parse.
596* ```returns``` { SocksUDPFrameDetails } - An object containing the remote host, frame number, and frame data of the SOCKS UDP frame.
597
598```typescript
599const frame = SocksClient.parseUDPFrame(data);
600console.log(frame);
601/*
602{
603 frameNumber: 0,
604 remoteHost: {
605 host: '1.2.3.4',
606 port: 1234
607 },
608 data: <Buffer 01 02 03 04 ...>
609}
610*/
611```
612
613Parses a Buffer instance and returns the parsed SocksUDPFrameDetails object.
614
615## Event: 'error'
616* ```err``` { SocksClientError } - An Error object containing an error message and the original SocksClientOptions.
617
618This event is emitted if an error occurs when trying to establish the proxy connection.
619
620## Event: 'bound'
621* ```info``` { SocksClientBoundEvent } An object containing a Socket and SocksRemoteHost info.
622
623This event is emitted when using the BIND command on a remote SOCKS proxy server. This event indicates the proxy server is now listening for incoming connections on a specified port.
624
625**SocksClientBoundEvent**
626```typescript
627{
628 socket: net.Socket, // The underlying raw Socket
629 remoteHost: {
630 host: '1.2.3.4', // The remote host that is listening (usually the proxy itself)
631 port: 4444 // The remote port the proxy is listening on for incoming connections (when using BIND).
632 }
633}
634```
635
636## Event: 'established'
637* ```info``` { SocksClientEstablishedEvent } An object containing a Socket and SocksRemoteHost info.
638
639This event is emitted when the following conditions are met:
6401. When using the CONNECT command, and a proxy connection has been established to the remote host.
6412. When using the BIND command, and an incoming connection has been accepted by the proxy and a TCP relay has been established.
6423. When using the ASSOCIATE command, and a UDP relay has been established.
643
644When using BIND, 'bound' is first emitted to indicate the SOCKS server is waiting for an incoming connection, and provides the remote port the SOCKS server is listening on.
645
646When using ASSOCIATE, 'established' is emitted with the remote UDP port the SOCKS server is accepting UDP frame packets on.
647
648**SocksClientEstablishedEvent**
649```typescript
650{
651 socket: net.Socket, // The underlying raw Socket
652 remoteHost: {
653 host: '1.2.3.4', // The remote host that is listening (usually the proxy itself)
654 port: 52738 // The remote port the proxy is listening on for incoming connections (when using BIND).
655 }
656}
657```
658
659## client.connect()
660
661Starts connecting to the remote SOCKS proxy server to establish a proxy connection to the destination host.
662
663## client.socksClientOptions
664* ```returns``` { SocksClientOptions } The options that were passed to the SocksClient.
665
666Gets the options that were passed to the SocksClient when it was created.
667
668
669**SocksClientError**
670```typescript
671{ // Subclassed from Error.
672 message: 'An error has occurred',
673 options: {
674 // SocksClientOptions
675 }
676}
677```
678
679# Further Reading:
680
681Please read the SOCKS 5 specifications for more information on how to use BIND and Associate.
682http://www.ietf.org/rfc/rfc1928.txt
683
684# License
685
686This work is licensed under the [MIT license](http://en.wikipedia.org/wiki/MIT_License).
Note: See TracBrowser for help on using the repository browser.