Debian Codegraph @

vendor/clue/socks-react/README.md

raw
1 # clue/reactphp-socks
2
3 [![CI status](https://github.com/clue/reactphp-socks/actions/workflows/ci.yml/badge.svg)](https://github.com/clue/reactphp-socks/actions)
4 [![installs on Packagist](https://img.shields.io/packagist/dt/clue/socks-react?color=blue&label=installs%20on%20Packagist)](https://packagist.org/packages/clue/socks-react)
5
6 Async SOCKS proxy connector client and server implementation, tunnel any TCP/IP-based
7 protocol through a SOCKS5 or SOCKS4(a) proxy server, built on top of
8 [ReactPHP](https://reactphp.org/).
9
10 The SOCKS proxy protocol family (SOCKS5, SOCKS4 and SOCKS4a) is commonly used to
11 tunnel HTTP(S) traffic through an intermediary ("proxy"), to conceal the origin
12 address (anonymity) or to circumvent address blocking (geoblocking). While many
13 (public) SOCKS proxy servers often limit this to HTTP(S) port `80` and `443`
14 only, this can technically be used to tunnel any TCP/IP-based protocol (HTTP,
15 SMTP, IMAP etc.).
16 This library provides a simple API to create these tunneled connections for you.
17 Because it implements ReactPHP's standard
18 [`ConnectorInterface`](https://github.com/reactphp/socket#connectorinterface),
19 it can simply be used in place of a normal connector.
20 This makes it fairly simple to add SOCKS proxy support to pretty much any
21 existing higher-level protocol implementation.
22 Besides the client side, it also provides a simple SOCKS server implementation
23 which allows you to build your own SOCKS proxy servers with custom business logic.
24
25 * **Async execution of connections** -
26 Send any number of SOCKS requests in parallel and process their
27 responses as soon as results come in.
28 The Promise-based design provides a *sane* interface to working with out of
29 order responses and possible connection errors.
30 * **Standard interfaces** -
31 Allows easy integration with existing higher-level components by implementing
32 ReactPHP's standard
33 [`ConnectorInterface`](https://github.com/reactphp/socket#connectorinterface).
34 * **Lightweight, SOLID design** -
35 Provides a thin abstraction that is [*just good enough*](https://en.wikipedia.org/wiki/Principle_of_good_enough)
36 and does not get in your way.
37 Builds on top of well-tested components and well-established concepts instead of reinventing the wheel.
38 * **Good test coverage** -
39 Comes with an automated tests suite and is regularly tested against actual proxy servers in the wild.
40
41 **Table of contents**
42
43 * [Support us](#support-us)
44 * [Quickstart example](#quickstart-example)
45 * [Usage](#usage)
46 * [Client](#client)
47 * [Plain TCP connections](#plain-tcp-connections)
48 * [Secure TLS connections](#secure-tls-connections)
49 * [HTTP requests](#http-requests)
50 * [Protocol version](#protocol-version)
51 * [DNS resolution](#dns-resolution)
52 * [Authentication](#authentication)
53 * [Proxy chaining](#proxy-chaining)
54 * [Connection timeout](#connection-timeout)
55 * [SOCKS over TLS](#socks-over-tls)
56 * [Unix domain sockets](#unix-domain-sockets)
57 * [Server](#server)
58 * [Server connector](#server-connector)
59 * [Authentication](#server-authentication)
60 * [Proxy chaining](#server-proxy-chaining)
61 * [SOCKS over TLS](#server-socks-over-tls)
62 * [Unix domain sockets](#server-unix-domain-sockets)
63 * [Servers](#servers)
64 * [Using a PHP SOCKS server](#using-a-php-socks-server)
65 * [Using SSH as a SOCKS server](#using-ssh-as-a-socks-server)
66 * [Using the Tor (anonymity network) to tunnel SOCKS connections](#using-the-tor-anonymity-network-to-tunnel-socks-connections)
67 * [Install](#install)
68 * [Tests](#tests)
69 * [License](#license)
70 * [More](#more)
71
72 ## Support us
73
74 I maintain an ecosystem of open-source projects that have been downloaded
75 hundreds of millions of times and are actively maintained and continuously
76 improved. If you find any of these projects useful, please consider
77 [becoming a sponsor on GitHub](https://github.com/sponsors/clue). Your support
78 helps ensure long-term maintenance and continued development. Thank you! πŸš€
79
80 ## Quickstart example
81
82 Once [installed](#install), you can use the following code to send a secure
83 HTTPS request to google.com through a local SOCKS proxy server:
84
85 ```php
86 <?php
87
88 require __DIR__ . '/vendor/autoload.php';
89
90 $proxy = new Clue\React\Socks\Client('127.0.0.1:1080');
91
92 $connector = new React\Socket\Connector(array(
93 'tcp' => $proxy,
94 'dns' => false
95 ));
96
97 $browser = new React\Http\Browser($connector);
98
99 $browser->get('https://google.com/')->then(function (Psr\Http\Message\ResponseInterface $response) {
100 var_dump($response->getHeaders(), (string) $response->getBody());
101 }, function (Exception $e) {
102 echo 'Error: ' . $e->getMessage() . PHP_EOL;
103 });
104 ```
105
106 If you're not already running any other [SOCKS proxy server](#servers),
107 you can use the following code to create a SOCKS
108 proxy server listening for connections on `127.0.0.1:1080`:
109
110 ```php
111 <?php
112
113 require __DIR__ . '/vendor/autoload.php';
114
115 // start a new SOCKS proxy server
116 $socks = new Clue\React\Socks\Server();
117
118 // listen on 127.0.0.1:1080
119 $socket = new React\Socket\SocketServer('127.0.0.1:1080');
120 $socks->listen($socket);
121 ```
122
123 See also the [examples](examples).
124
125 ## Usage
126
127 ### Client
128
129 The `Client` is responsible for communication with your SOCKS server instance.
130
131 Its constructor simply accepts a SOCKS proxy URI with the SOCKS proxy server address:
132
133 ```php
134 $proxy = new Clue\React\Socks\Client('127.0.0.1:1080');
135 ```
136
137 You can omit the port if you're using the default SOCKS port 1080:
138
139 ```php
140 $proxy = new Clue\React\Socks\Client('127.0.0.1');
141 ```
142
143 If you need custom connector settings (DNS resolution, TLS parameters, timeouts,
144 proxy servers etc.), you can explicitly pass a custom instance of the
145 [`ConnectorInterface`](https://github.com/reactphp/socket#connectorinterface):
146
147 ```php
148 $connector = new React\Socket\Connector(array(
149 'dns' => '127.0.0.1',
150 'tcp' => array(
151 'bindto' => '192.168.10.1:0'
152 )
153 ));
154
155 $proxy = new Clue\React\Socks\Client('my-socks-server.local:1080', $connector);
156 ```
157
158 This is one of the two main classes in this package.
159 Because it implements ReactPHP's standard
160 [`ConnectorInterface`](https://github.com/reactphp/socket#connectorinterface),
161 it can simply be used in place of a normal connector.
162 Accordingly, it provides only a single public method, the
163 [`connect()`](https://github.com/reactphp/socket#connect) method.
164 The `connect(string $uri): PromiseInterface<ConnectionInterface, Exception>`
165 method can be used to establish a streaming connection.
166 It returns a [Promise](https://github.com/reactphp/promise) which either
167 fulfills with a [ConnectionInterface](https://github.com/reactphp/socket#connectioninterface)
168 on success or rejects with an `Exception` on error.
169
170 This makes it fairly simple to add SOCKS proxy support to pretty much any
171 higher-level component:
172
173 ```diff
174 - $acme = new AcmeApi($connector);
175 + $proxy = new Clue\React\Socks\Client('127.0.0.1:1080', $connector);
176 + $acme = new AcmeApi($proxy);
177 ```
178
179 #### Plain TCP connections
180
181 SOCKS proxies are most frequently used to issue HTTP(S) requests to your destination.
182 However, this is actually performed on a higher protocol layer and this
183 connector is actually inherently a general-purpose plain TCP/IP connector.
184 As documented above, you can simply invoke its `connect()` method to establish
185 a streaming plain TCP/IP connection and use any higher level protocol like so:
186
187 ```php
188 $proxy = new Clue\React\Socks\Client('127.0.0.1:1080');
189
190 $proxy->connect('tcp://www.google.com:80')->then(function (React\Socket\ConnectionInterface $connection) {
191 echo 'connected to www.google.com:80';
192 $connection->write("GET / HTTP/1.0\r\n\r\n");
193
194 $connection->on('data', function ($chunk) {
195 echo $chunk;
196 });
197 });
198 ```
199
200 You can either use the `Client` directly or you may want to wrap this connector
201 in ReactPHP's [`Connector`](https://github.com/reactphp/socket#connector):
202
203 ```php
204 $proxy = new Clue\React\Socks\Client('127.0.0.1:1080');
205
206 $connector = new React\Socket\Connector(array(
207 'tcp' => $proxy,
208 'dns' => false
209 ));
210
211 $connector->connect('tcp://www.google.com:80')->then(function (React\Socket\ConnectionInterface $connection) {
212 echo 'connected to www.google.com:80';
213 $connection->write("GET / HTTP/1.0\r\n\r\n");
214
215 $connection->on('data', function ($chunk) {
216 echo $chunk;
217 });
218 });
219 ```
220
221 See also the [first example](examples).
222
223 The `tcp://` scheme can also be omitted.
224 Passing any other scheme will reject the promise.
225
226 Pending connection attempts can be cancelled by cancelling its pending promise like so:
227
228 ```php
229 $promise = $connector->connect($uri);
230
231 $promise->cancel();
232 ```
233
234 Calling `cancel()` on a pending promise will cancel the underlying TCP/IP
235 connection to the SOCKS server and/or the SOCKS protocol negotiation and reject
236 the resulting promise.
237
238 #### Secure TLS connections
239
240 This class can also be used if you want to establish a secure TLS connection
241 (formerly known as SSL) between you and your destination, such as when using
242 secure HTTPS to your destination site. You can simply wrap this connector in
243 ReactPHP's [`Connector`](https://github.com/reactphp/socket#connector):
244
245 ```php
246 $proxy = new Clue\React\Socks\Client('127.0.0.1:1080');
247
248 $connector = new React\Socket\Connector(array(
249 'tcp' => $proxy,
250 'dns' => false
251 ));
252
253 $connector->connect('tls://www.google.com:443')->then(function (React\Socket\ConnectionInterface $connection) {
254 // proceed with just the plain text data
255 // everything is encrypted/decrypted automatically
256 echo 'connected to SSL encrypted www.google.com';
257 $connection->write("GET / HTTP/1.0\r\n\r\n");
258
259 $connection->on('data', function ($chunk) {
260 echo $chunk;
261 });
262 });
263 ```
264
265 See also the [second example](examples).
266
267 Pending connection attempts can be cancelled by canceling its pending promise
268 as usual.
269
270 > Note how secure TLS connections are in fact entirely handled outside of
271 this SOCKS client implementation.
272
273 You can optionally pass additional
274 [SSL context options](http://php.net/manual/en/context.ssl.php)
275 to the constructor like this:
276
277 ```php
278 $connector = new React\Socket\Connector(array(
279 'tcp' => $proxy,
280 'tls' => array(
281 'verify_peer' => false,
282 'verify_peer_name' => false
283 ),
284 'dns' => false
285 ));
286 ```
287
288 #### HTTP requests
289
290 This library also allows you to send
291 [HTTP requests through a SOCKS proxy server](https://github.com/reactphp/http#socks-proxy).
292
293 In order to send HTTP requests, you first have to add a dependency for
294 [ReactPHP's async HTTP client](https://github.com/reactphp/http#client-usage).
295 This allows you to send both plain HTTP and TLS-encrypted HTTPS requests like this:
296
297 ```php
298 $proxy = new Clue\React\Socks\Client('127.0.0.1:1080');
299
300 $connector = new React\Socket\Connector(array(
301 'tcp' => $proxy,
302 'dns' => false
303 ));
304
305 $browser = new React\Http\Browser($connector);
306
307 $browser->get('https://example.com/')->then(function (Psr\Http\Message\ResponseInterface $response) {
308 var_dump($response->getHeaders(), (string) $response->getBody());
309 }, function (Exception $e) {
310 echo 'Error: ' . $e->getMessage() . PHP_EOL;
311 });
312 ```
313
314 See also [ReactPHP's HTTP client](https://github.com/reactphp/http#client-usage)
315 and any of the [examples](examples) for more details.
316
317 #### Protocol version
318
319 This library supports the SOCKS5 and SOCKS4(a) protocol versions.
320 It focuses on the most commonly used core feature of connecting to a destination
321 host through the SOCKS proxy server. In this mode, a SOCKS proxy server acts as
322 a generic proxy allowing higher level application protocols to work through it.
323
324 <table>
325 <tr>
326 <th></th>
327 <th>SOCKS5</th>
328 <th>SOCKS4(a)</th>
329 </tr>
330 <tr>
331 <th>Protocol specification</th>
332 <td><a href="https://tools.ietf.org/html/rfc1928">RFC 1928</a></td>
333 <td>
334 <a href="https://ftp.icm.edu.pl/packages/socks/socks4/SOCKS4.protocol">SOCKS4.protocol</a> /
335 <a href="https://ftp.icm.edu.pl/packages/socks/socks4/SOCKS4A.protocol">SOCKS4A.protocol</a>
336 </td>
337 </tr>
338 <tr>
339 <th>Tunnel outgoing TCP/IP connections</th>
340 <td>βœ“</td>
341 <td>βœ“</td>
342 </tr>
343 <tr>
344 <th><a href="#dns-resolution">Remote DNS resolution</a></th>
345 <td>βœ“</td>
346 <td>βœ— / βœ“</td>
347 </tr>
348 <tr>
349 <th>IPv6 addresses</th>
350 <td>βœ“</td>
351 <td>βœ—</td>
352 </tr>
353 <tr>
354 <th><a href="#authentication">Username/Password authentication</a></th>
355 <td>βœ“ (as per <a href="https://tools.ietf.org/html/rfc1929">RFC 1929</a>)</td>
356 <td>βœ—</td>
357 </tr>
358 <tr>
359 <th>Handshake # roundtrips</th>
360 <td>2 (3 with authentication)</td>
361 <td>1</td>
362 </tr>
363 <tr>
364 <th>Handshake traffic<br />+ remote DNS</th>
365 <td><em>variable</em> (+ auth + IPv6)<br />+ hostname - 3</td>
366 <td>17 bytes<br />+ hostname + 1</td>
367 </tr>
368 <tr>
369 <th>Incoming BIND requests</th>
370 <td><em>not implemented</em></td>
371 <td><em>not implemented</em></td>
372 </tr>
373 <tr>
374 <th>UDP datagrams</th>
375 <td><em>not implemented</em></td>
376 <td>βœ—</td>
377 </tr>
378 <tr>
379 <th>GSSAPI authentication</th>
380 <td><em>not implemented</em></td>
381 <td>βœ—</td>
382 </tr>
383 </table>
384
385 By default, the `Client` communicates via SOCKS5 with the SOCKS server.
386 This is done because SOCKS5 is the latest version from the SOCKS protocol family
387 and generally has best support across other vendors.
388 You can also omit the default `socks://` URI scheme. Similarly, the `socks5://`
389 URI scheme acts as an alias for the default `socks://` URI scheme.
390
391 ```php
392 // all three forms are equivalent
393 $proxy = new Clue\React\Socks\Client('127.0.0.1:1080');
394 $proxy = new Clue\React\Socks\Client('socks://127.0.0.1:1080');
395 $proxy = new Clue\React\Socks\Client('socks5://127.0.0.1:1080');
396 ```
397
398 If want to explicitly set the protocol version to SOCKS4(a), you can use the URI
399 scheme `socks4://` as part of the SOCKS URI:
400
401 ```php
402 $proxy = new Clue\React\Socks\Client('socks4://127.0.0.1:1080');
403 ```
404
405 #### DNS resolution
406
407 By default, the `Client` does not perform any DNS resolution at all and simply
408 forwards any hostname you're trying to connect to to the SOCKS server.
409 The remote SOCKS server is thus responsible for looking up any hostnames via DNS
410 (this default mode is thus called *remote DNS resolution*).
411 As seen above, this mode is supported by the SOCKS5 and SOCKS4a protocols, but
412 not the original SOCKS4 protocol, as the protocol lacks a way to communicate hostnames.
413
414 On the other hand, all SOCKS protocol versions support sending destination IP
415 addresses to the SOCKS server.
416 In this mode you either have to stick to using IPs only (which is ofen unfeasable)
417 or perform any DNS lookups locally and only transmit the resolved destination IPs
418 (this mode is thus called *local DNS resolution*).
419
420 The default *remote DNS resolution* is useful if your local `Client` either can
421 not resolve target hostnames because it has no direct access to the internet or
422 if it should not resolve target hostnames because its outgoing DNS traffic might
423 be intercepted (in particular when using the
424 [Tor network](#using-the-tor-anonymity-network-to-tunnel-socks-connections)).
425
426 As noted above, the `Client` defaults to using remote DNS resolution.
427 However, wrapping the `Client` in ReactPHP's
428 [`Connector`](https://github.com/reactphp/socket#connector) actually
429 performs local DNS resolution unless explicitly defined otherwise.
430 Given that remote DNS resolution is assumed to be the preferred mode, all
431 other examples explicitly disable DNS resolution like this:
432
433 ```php
434 $proxy = new Clue\React\Socks\Client('127.0.0.1:1080');
435
436 $connector = new React\Socket\Connector(array(
437 'tcp' => $proxy,
438 'dns' => false
439 ));
440 ```
441
442 If you want to explicitly use *local DNS resolution* (such as when explicitly
443 using SOCKS4), you can use the following code:
444
445 ```php
446 $proxy = new Clue\React\Socks\Client('127.0.0.1:1080');
447
448 // set up Connector which uses Google's public DNS (8.8.8.8)
449 $connector = new React\Socket\Connector(array(
450 'tcp' => $proxy,
451 'dns' => '8.8.8.8'
452 ));
453 ```
454
455 See also the [fourth example](examples).
456
457 Pending connection attempts can be cancelled by cancelling its pending promise
458 as usual.
459
460 > Note how local DNS resolution is in fact entirely handled outside of this
461 SOCKS client implementation.
462
463 #### Authentication
464
465 This library supports username/password authentication for SOCKS5 servers as
466 defined in [RFC 1929](https://tools.ietf.org/html/rfc1929).
467
468 On the client side, simply pass your username and password to use for
469 authentication (see below).
470 For each further connection the client will merely send a flag to the server
471 indicating authentication information is available.
472 Only if the server requests authentication during the initial handshake,
473 the actual authentication credentials will be transmitted to the server.
474
475 Note that the password is transmitted in cleartext to the SOCKS proxy server,
476 so this methods should not be used on a network where you have to worry about eavesdropping.
477
478 You can simply pass the authentication information as part of the SOCKS URI:
479
480 ```php
481 $proxy = new Clue\React\Socks\Client('alice:[email protected]:1080');
482 ```
483
484 Note that both the username and password must be percent-encoded if they contain
485 special characters:
486
487 ```php
488 $user = 'he:llo';
489 $pass = 'p@ss';
490 $url = rawurlencode($user) . ':' . rawurlencode($pass) . '@127.0.0.1:1080';
491
492 $proxy = new Clue\React\Socks\Client($url);
493 ```
494
495 > The authentication details will be transmitted in cleartext to the SOCKS proxy
496 server only if it requires username/password authentication.
497 If the authentication details are missing or not accepted by the remote SOCKS
498 proxy server, it is expected to reject each connection attempt with an
499 exception error code of `SOCKET_EACCES` (13).
500
501 Authentication is only supported by protocol version 5 (SOCKS5),
502 so passing authentication to the `Client` enforces communication with protocol
503 version 5 and complains if you have explicitly set anything else:
504
505 ```php
506 // throws InvalidArgumentException
507 new Clue\React\Socks\Client('socks4://alice:[email protected]:1080');
508 ```
509
510 #### Proxy chaining
511
512 The `Client` is responsible for creating connections to the SOCKS server which
513 then connects to the target host.
514
515 ```
516 Client -> SocksServer -> TargetHost
517 ```
518
519 Sometimes it may be required to establish outgoing connections via another SOCKS
520 server.
521 For example, this can be useful if you want to conceal your origin address.
522
523 ```
524 Client -> MiddlemanSocksServer -> TargetSocksServer -> TargetHost
525 ```
526
527 The `Client` uses any instance of the `ConnectorInterface` to establish
528 outgoing connections.
529 In order to connect through another SOCKS server, you can simply use another
530 SOCKS connector from another SOCKS client like this:
531
532 ```php
533 // https via the proxy chain "MiddlemanSocksServer -> TargetSocksServer -> TargetHost"
534 // please note how the client uses TargetSocksServer (not MiddlemanSocksServer!),
535 // which in turn then uses MiddlemanSocksServer.
536 // this creates a TCP/IP connection to MiddlemanSocksServer, which then connects
537 // to TargetSocksServer, which then connects to the TargetHost
538 $middle = new Clue\React\Socks\Client('127.0.0.1:1080');
539 $target = new Clue\React\Socks\Client('example.com:1080', $middle);
540
541 $connector = new React\Socket\Connector(array(
542 'tcp' => $target,
543 'dns' => false
544 ));
545
546 $connector->connect('tls://www.google.com:443')->then(function (React\Socket\ConnectionInterface $connection) {
547 // …
548 });
549 ```
550
551 See also the [third example](examples).
552
553 Pending connection attempts can be canceled by canceling its pending promise
554 as usual.
555
556 Proxy chaining can happen on the server side and/or the client side:
557
558 * If you ask your client to chain through multiple proxies, then each proxy
559 server does not really know anything about chaining at all.
560 This means that this is a client-only property.
561
562 * If you ask your server to chain through another proxy, then your client does
563 not really know anything about chaining at all.
564 This means that this is a server-only property and not part of this class.
565 For example, you can find this in the below [`Server`](#server-proxy-chaining)
566 class or somewhat similar when you're using the
567 [Tor network](#using-the-tor-anonymity-network-to-tunnel-socks-connections).
568
569 #### Connection timeout
570
571 By default, the `Client` does not implement any timeouts for establishing remote
572 connections.
573 Your underlying operating system may impose limits on pending and/or idle TCP/IP
574 connections, anywhere in a range of a few minutes to several hours.
575
576 Many use cases require more control over the timeout and likely values much
577 smaller, usually in the range of a few seconds only.
578
579 You can use ReactPHP's [`Connector`](https://github.com/reactphp/socket#connector)
580 to decorate any given `ConnectorInterface` instance.
581 It provides the same `connect()` method, but will automatically reject the
582 underlying connection attempt if it takes too long:
583
584 ```php
585 $proxy = new Clue\React\Socks\Client('127.0.0.1:1080');
586
587 $connector = new React\Socket\Connector(array(
588 'tcp' => $proxy,
589 'dns' => false,
590 'timeout' => 3.0
591 ));
592
593 $connector->connect('tcp://google.com:80')->then(function (React\Socket\ConnectionInterface $connection) {
594 // connection succeeded within 3.0 seconds
595 });
596 ```
597
598 See also any of the [examples](examples).
599
600 Pending connection attempts can be cancelled by cancelling its pending promise
601 as usual.
602
603 > Note how connection timeout is in fact entirely handled outside of this
604 SOCKS client implementation.
605
606 #### SOCKS over TLS
607
608 All [SOCKS protocol versions](#protocol-version) support forwarding TCP/IP
609 based connections and higher level protocols.
610 This implies that you can also use [secure TLS connections](#secure-tls-connections)
611 to transfer sensitive data across SOCKS proxy servers.
612 This means that no eavesdropper nor the proxy server will be able to decrypt
613 your data.
614
615 However, the initial SOCKS communication between the client and the proxy is
616 usually via an unencrypted, plain TCP/IP connection.
617 This means that an eavesdropper may be able to see *where* you connect to and
618 may also be able to see your [SOCKS authentication](#authentication) details
619 in cleartext.
620
621 As an alternative, you may establish a secure TLS connection to your SOCKS
622 proxy before starting the initial SOCKS communication.
623 This means that no eavesdroppper will be able to see the destination address
624 you want to connect to or your [SOCKS authentication](#authentication) details.
625
626 You can use the `sockss://` URI scheme or use an explicit
627 [SOCKS protocol version](#protocol-version) like this:
628
629 ```php
630 $proxy = new Clue\React\Socks\Client('sockss://127.0.0.1:1080');
631
632 $proxy = new Clue\React\Socks\Client('socks4s://127.0.0.1:1080');
633 ```
634
635 See also [example 32](examples).
636
637 Similarly, you can also combine this with [authentication](#authentication)
638 like this:
639
640 ```php
641 $proxy = new Clue\React\Socks\Client('sockss://alice:[email protected]:1080');
642 ```
643
644 > Note that for most use cases, [secure TLS connections](#secure-tls-connections)
645 should be used instead. SOCKS over TLS is considered advanced usage and is
646 used very rarely in practice.
647 In particular, the SOCKS server has to accept secure TLS connections, see
648 also [Server SOCKS over TLS](#server-socks-over-tls) for more details.
649 Also, PHP does not support "double encryption" over a single connection.
650 This means that enabling [secure TLS connections](#secure-tls-connections)
651 over a communication channel that has been opened with SOCKS over TLS
652 may not be supported.
653
654 > Note that the SOCKS protocol does not support the notion of TLS. The above
655 works reasonably well because TLS is only used for the connection between
656 client and proxy server and the SOCKS protocol data is otherwise identical.
657 This implies that this may also have only limited support for
658 [proxy chaining](#proxy-chaining) over multiple TLS paths.
659
660 #### Unix domain sockets
661
662 All [SOCKS protocol versions](#protocol-version) support forwarding TCP/IP
663 based connections and higher level protocols.
664 In some advanced cases, it may be useful to let your SOCKS server listen on a
665 Unix domain socket (UDS) path instead of a IP:port combination.
666 For example, this allows you to rely on file system permissions instead of
667 having to rely on explicit [authentication](#authentication).
668
669 You can use the `socks+unix://` URI scheme or use an explicit
670 [SOCKS protocol version](#protocol-version) like this:
671
672 ```php
673 $proxy = new Clue\React\Socks\Client('socks+unix:///tmp/proxy.sock');
674
675 $proxy = new Clue\React\Socks\Client('socks4+unix:///tmp/proxy.sock');
676 ```
677
678 Similarly, you can also combine this with [authentication](#authentication)
679 like this:
680
681 ```php
682 $proxy = new Clue\React\Socks\Client('socks+unix://alice:password@/tmp/proxy.sock');
683 ```
684
685 > Note that Unix domain sockets (UDS) are considered advanced usage and PHP only
686 has limited support for this.
687 In particular, enabling [secure TLS](#secure-tls-connections) may not be
688 supported.
689
690 > Note that the SOCKS protocol does not support the notion of UDS paths. The above
691 works reasonably well because UDS is only used for the connection between
692 client and proxy server and the path will not actually passed over the protocol.
693 This implies that this does also not support [proxy chaining](#proxy-chaining)
694 over multiple UDS paths.
695
696 ### Server
697
698 The `Server` is responsible for accepting incoming communication from SOCKS clients
699 and forwarding the requested connection to the target host.
700 It supports the SOCKS5 and SOCKS4(a) protocol versions by default.
701 You can start listening on an underlying TCP/IP socket server like this:
702
703 ```php
704 $socks = new Clue\React\Socks\Server();
705
706 // listen on 127.0.0.1:1080
707 $socket = new React\Socket\SocketServer('127.0.0.1:1080');
708 $socks->listen($socket);
709 ```
710
711 This class takes an optional `LoopInterface|null $loop` parameter that can be used to
712 pass the event loop instance to use for this object. You can use a `null` value
713 here in order to use the [default loop](https://github.com/reactphp/event-loop#loop).
714 This value SHOULD NOT be given unless you're sure you want to explicitly use a
715 given event loop instance.
716
717 Additionally, the `Server` constructor accepts optional parameters to explicitly
718 configure the [connector](#server-connector) to use and to require
719 [authentication](#server-authentication). For more details, read on...
720
721 #### Server connector
722
723 The `Server` uses an instance of ReactPHP's
724 [`ConnectorInterface`](https://github.com/reactphp/socket#connectorinterface)
725 to establish outgoing connections for each incoming connection request.
726
727 If you need custom connector settings (DNS resolution, TLS parameters, timeouts,
728 proxy servers etc.), you can explicitly pass a custom instance of the
729 [`ConnectorInterface`](https://github.com/reactphp/socket#connectorinterface):
730
731 ```php
732 $connector = new React\Socket\Connector(array(
733 'dns' => '127.0.0.1',
734 'tcp' => array(
735 'bindto' => '192.168.10.1:0'
736 )
737 ));
738
739 $socks = new Clue\React\Socks\Server(null, $connector);
740 ```
741
742 If you want to forward the outgoing connection through another SOCKS proxy, you
743 may also pass a [`Client`](#client) instance as a connector, see also
744 [server proxy chaining](#server-proxy-chaining) for more details.
745
746 Internally, the `Server` uses ReactPHP's normal
747 [`connect()`](https://github.com/reactphp/socket#connect) method, but
748 it also passes the original client IP as the `?source={remote}` parameter.
749 The `source` parameter contains the full remote URI, including the protocol
750 and any authentication details, for example `socks://alice:[email protected]:5678`
751 or `socks4://1.2.3.4:5678` for legacy SOCKS4(a).
752 You can use this parameter for logging purposes or to restrict connection
753 requests for certain clients by providing a custom implementation of the
754 [`ConnectorInterface`](https://github.com/reactphp/socket#connectorinterface).
755
756 #### Server authentication
757
758 By default, the `Server` does not require any authentication from the clients.
759 You can enable authentication support so that clients need to pass a valid
760 username and password before forwarding any connections.
761
762 Setting authentication on the `Server` enforces each further connected client
763 to use protocol version 5 (SOCKS5).
764 If a client tries to use any other protocol version, does not send along
765 authentication details or if authentication details can not be verified,
766 the connection will be rejected.
767
768 If you only want to accept static authentication details, you can simply pass an
769 additional assoc array with your authentication details to the `Server` like this:
770
771 ```php
772 $socks = new Clue\React\Socks\Server(null, null, array(
773 'alice' => 'password',
774 'bob' => 's3cret!1'
775 ));
776 ```
777
778 See also [example #12](examples).
779
780 If you want more control over authentication, you can pass an authenticator
781 function that should return a `bool` value like this synchronous example:
782
783 ```php
784 $socks = new Clue\React\Socks\Server(null, null, function ($username, $password, $remote) {
785 // $remote is a full URI Γ  la socks://alice:[email protected]:1234
786 // or sockss://alice:[email protected]:1234 for SOCKS over TLS
787 // or may be null when remote is unknown (SOCKS over Unix Domain Sockets)
788 // useful for logging or extracting parts, such as the remote IP
789 $ip = parse_url($remote, PHP_URL_HOST);
790
791 return ($username === 'root' && $password === 'secret' && $ip === '127.0.0.1');
792 });
793 ```
794
795 Because your authentication mechanism might take some time to actually check the
796 provided authentication credentials (like querying a remote database or webservice),
797 the server also supports a [Promise](https://github.com/reactphp/promise)-based
798 interface. While this might seem more complex at first, it actually provides a
799 very powerful way of handling a large number of connections concurrently without
800 ever blocking any connections. You can return a [Promise](https://github.com/reactphp/promise)
801 from the authenticator function that will fulfill with a `bool` value like this
802 async example:
803
804 ```php
805 $socks = new Clue\React\Socks\Server(null, null, function ($username, $password) use ($db) {
806 // pseudo-code: query database for given authentication details
807 return $db->query(
808 'SELECT 1 FROM users WHERE name = ? AND password = ?',
809 array($username, $password)
810 )->then(function (QueryResult $result) {
811 // ensure we find exactly one match in the database
812 return count($result->resultRows) === 1;
813 });
814 });
815 ```
816
817 #### Server proxy chaining
818
819 The `Server` is responsible for creating connections to the target host.
820
821 ```
822 Client -> SocksServer -> TargetHost
823 ```
824
825 Sometimes it may be required to establish outgoing connections via another SOCKS
826 server.
827 For example, this can be useful if your target SOCKS server requires
828 authentication, but your client does not support sending authentication
829 information (e.g. like most webbrowser).
830
831 ```
832 Client -> MiddlemanSocksServer -> TargetSocksServer -> TargetHost
833 ```
834
835 The `Server` uses any instance of the `ConnectorInterface` to establish outgoing
836 connections.
837 In order to connect through another SOCKS server, you can simply use the
838 [`Client`](#client) SOCKS connector from above.
839 You can create a SOCKS `Client` instance like this:
840
841 ```php
842 // set next SOCKS server example.com:1080 as target
843 $proxy = new Clue\React\Socks\Client('alice:[email protected]:1080');
844
845 // start a new server which forwards all connections to the other SOCKS server
846 $socks = new Clue\React\Socks\Server(null, $proxy);
847
848 // listen on 127.0.0.1:1080
849 $socket = new React\Socket\SocketServer('127.0.0.1:1080');
850 $socks->listen($socket);
851 ```
852
853 See also [example #21](examples).
854
855 Proxy chaining can happen on the server side and/or the client side:
856
857 * If you ask your client to chain through multiple proxies, then each proxy
858 server does not really know anything about chaining at all.
859 This means that this is a client-only property and not part of this class.
860 For example, you can find this in the above [`Client`](#proxy-chaining) class.
861
862 * If you ask your server to chain through another proxy, then your client does
863 not really know anything about chaining at all.
864 This means that this is a server-only property and can be implemented as above.
865
866 #### Server SOCKS over TLS
867
868 Both SOCKS5 and SOCKS4(a) protocol versions support forwarding TCP/IP based
869 connections and higher level protocols.
870 This implies that you can also use [secure TLS connections](#secure-tls-connections)
871 to transfer sensitive data across SOCKS proxy servers.
872 This means that no eavesdropper nor the proxy server will be able to decrypt
873 your data.
874
875 However, the initial SOCKS communication between the client and the proxy is
876 usually via an unencrypted, plain TCP/IP connection.
877 This means that an eavesdropper may be able to see *where* the client connects
878 to and may also be able to see the [SOCKS authentication](#authentication)
879 details in cleartext.
880
881 As an alternative, you may listen for SOCKS over TLS connections so
882 that the client has to establish a secure TLS connection to your SOCKS
883 proxy before starting the initial SOCKS communication.
884 This means that no eavesdroppper will be able to see the destination address
885 the client wants to connect to or their [SOCKS authentication](#authentication)
886 details.
887
888 You can simply start your listening socket on the `tls://` URI scheme like this:
889
890 ```php
891 $socks = new Clue\React\Socks\Server();
892
893 // listen on tls://127.0.0.1:1080 with the given server certificate
894 $socket = new React\Socket\SocketServer('tls://127.0.0.1:1080', array(
895 'tls' => array(
896 'local_cert' => __DIR__ . '/localhost.pem',
897 )
898 ));
899 $socks->listen($socket);
900 ```
901
902 See also [example 31](examples).
903
904 > Note that for most use cases, [secure TLS connections](#secure-tls-connections)
905 should be used instead. SOCKS over TLS is considered advanced usage and is
906 used very rarely in practice.
907
908 > Note that the SOCKS protocol does not support the notion of TLS. The above
909 works reasonably well because TLS is only used for the connection between
910 client and proxy server and the SOCKS protocol data is otherwise identical.
911 This implies that this does also not support [proxy chaining](#server-proxy-chaining)
912 over multiple TLS paths.
913
914 #### Server Unix domain sockets
915
916 Both SOCKS5 and SOCKS4(a) protocol versions support forwarding TCP/IP based
917 connections and higher level protocols.
918 In some advanced cases, it may be useful to let your SOCKS server listen on a
919 Unix domain socket (UDS) path instead of a IP:port combination.
920 For example, this allows you to rely on file system permissions instead of
921 having to rely on explicit [authentication](#server-authentication).
922
923 You can simply start your listening socket on the `unix://` URI scheme like this:
924
925 ```php
926 $socks = new Clue\React\Socks\Server();
927
928 // listen on /tmp/proxy.sock
929 $socket = new React\Socket\SocketServer('unix:///tmp/proxy.sock');
930 $socks->listen($socket);
931 ```
932
933 > Note that Unix domain sockets (UDS) are considered advanced usage and that
934 the SOCKS protocol does not support the notion of UDS paths. The above
935 works reasonably well because UDS is only used for the connection between
936 client and proxy server and the path will not actually passed over the protocol.
937 This implies that this does also not support [proxy chaining](#server-proxy-chaining)
938 over multiple UDS paths.
939
940 ## Servers
941
942 ### Using a PHP SOCKS server
943
944 * If you're looking for an end-user SOCKS server daemon, you may want to use
945 [LeProxy](https://leproxy.org/) or [clue/psocksd](https://github.com/clue/psocksd).
946 * If you're looking for a SOCKS server implementation, consider using
947 the above [`Server`](#server) class.
948
949 ### Using SSH as a SOCKS server
950
951 If you already have an SSH server set up, you can easily use it as a SOCKS
952 tunnel end point. On your client, simply start your SSH client and use
953 the `-D <port>` option to start a local SOCKS server (quoting the man page:
954 a `local "dynamic" application-level port forwarding`).
955
956 You can start a local SOCKS server by creating a loopback connection to your
957 local system if you already run an SSH daemon:
958
959 ```bash
960 ssh -D 1080 localhost
961 ```
962
963 Alternatively, you can start a local SOCKS server tunneling through a given
964 remote host that runs an SSH daemon:
965
966 ```bash
967 ssh -D 1080 example.com
968 ```
969
970 Now you can simply use this SSH SOCKS server like this:
971
972 ```PHP
973 $proxy = new Clue\React\Socks\Client('127.0.0.1:1080');
974
975 $proxy->connect('tcp://www.google.com:80')->then(function (React\Socket\ConnectionInterface $connection) {
976 $connection->write("GET / HTTP/1.0\r\n\r\n");
977
978 $connection->on('data', function ($chunk) {
979 echo $chunk;
980 });
981 });
982 ```
983
984 Note that the above will allow all users on the local system to connect over
985 your SOCKS server without authentication which may or may not be what you need.
986 As an alternative, recent OpenSSH client versions also support
987 [Unix domain sockets](#unix-domain-sockets) (UDS) paths so that you can rely
988 on Unix file system permissions instead:
989
990 ```bash
991 ssh -D/tmp/proxy.sock example.com
992 ```
993
994 Now you can simply use this SSH SOCKS server like this:
995
996 ```PHP
997 $proxy = new Clue\React\Socks\Client('socks+unix:///tmp/proxy.sock');
998
999 $proxy->connect('tcp://www.google.com:80')->then(function (React\Socket\ConnectionInterface $connection) {
1000 $connection->write("GET / HTTP/1.0\r\n\r\n");
1001
1002 $connection->on('data', function ($chunk) {
1003 echo $chunk;
1004 });
1005 });
1006 ```
1007
1008 > As an alternative to requiring this manual setup, you may also want to look
1009 into using [clue/reactphp-ssh-proxy](https://github.com/clue/reactphp-ssh-proxy)
1010 which automatically creates this SSH tunnel for you. It provides an implementation of the same
1011 [`ConnectorInterface`](https://github.com/reactphp/socket#connectorinterface)
1012 so that supporting either proxy protocol should be fairly trivial.
1013
1014 ### Using the Tor (anonymity network) to tunnel SOCKS connections
1015
1016 The [Tor anonymity network](https://www.torproject.org/) client software is designed
1017 to encrypt your traffic and route it over a network of several nodes to conceal its origin.
1018 It presents a SOCKS5 and SOCKS4(a) interface on TCP port 9050 by default
1019 which allows you to tunnel any traffic through the anonymity network:
1020
1021 ```php
1022 $proxy = new Clue\React\Socks\Client('127.0.0.1:9050');
1023
1024 $proxy->connect('tcp://www.google.com:80')->then(function (React\Socket\ConnectionInterface $connection) {
1025 $connection->write("GET / HTTP/1.0\r\n\r\n");
1026
1027 $connection->on('data', function ($chunk) {
1028 echo $chunk;
1029 });
1030 });
1031 ```
1032
1033 In most common scenarios you probably want to stick to default
1034 [remote DNS resolution](#dns-resolution) and don't want your client to resolve the target hostnames,
1035 because you would leak DNS information to anybody observing your local traffic.
1036 Also, Tor provides hidden services through an `.onion` pseudo top-level domain
1037 which have to be resolved by Tor.
1038
1039 ## Install
1040
1041 The recommended way to install this library is [through Composer](https://getcomposer.org/).
1042 [New to Composer?](https://getcomposer.org/doc/00-intro.md)
1043
1044 This project follows [SemVer](https://semver.org/).
1045 This will install the latest supported version:
1046
1047 ```bash
1048 composer require clue/socks-react:^1.5
1049 ```
1050
1051 See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades.
1052
1053 This project aims to run on any platform and thus does not require any PHP
1054 extensions and supports running on legacy PHP 5.3 through current PHP 8+ and
1055 HHVM.
1056 It's *highly recommended to use the latest supported PHP version* for this project.
1057
1058 ## Tests
1059
1060 To run the test suite, you first need to clone this repo and then install all
1061 dependencies [through Composer](https://getcomposer.org/):
1062
1063 ```bash
1064 composer install
1065 ```
1066
1067 To run the test suite, go to the project root and run:
1068
1069 ```bash
1070 vendor/bin/phpunit
1071 ```
1072
1073 The test suite contains a number of tests that rely on a working internet
1074 connection, alternatively you can also run it like this:
1075
1076 ```bash
1077 vendor/bin/phpunit --exclude-group internet
1078 ```
1079
1080 ## License
1081
1082 This project is released under the permissive [MIT license](LICENSE).
1083
1084 > Do you use this project in a commercial setting? Sponsoring with invoicing is
1085 available, contact me ([@clue](https://github.com/clue)) for details.
1086
1087 ## More
1088
1089 * If you want to learn more about how the
1090 [`ConnectorInterface`](https://github.com/reactphp/socket#connectorinterface)
1091 and its usual implementations look like, refer to the documentation of the
1092 underlying [react/socket component](https://github.com/reactphp/socket).
1093 * If you want to learn more about processing streams of data, refer to the
1094 documentation of the underlying
1095 [react/stream](https://github.com/reactphp/stream) component.
1096 * As an alternative to a SOCKS5 / SOCKS4(a) proxy, you may also want to look into
1097 using an HTTP CONNECT proxy instead.
1098 You may want to use [clue/reactphp-http-proxy](https://github.com/clue/reactphp-http-proxy)
1099 which also provides an implementation of the same
1100 [`ConnectorInterface`](https://github.com/reactphp/socket#connectorinterface)
1101 so that supporting either proxy protocol should be fairly trivial.
1102 * As an alternative to a SOCKS5 / SOCKS4(a) proxy, you may also want to look into
1103 using an SSH proxy (SSH tunnel) instead.
1104 You may want to use [clue/reactphp-ssh-proxy](https://github.com/clue/reactphp-ssh-proxy)
1105 which also provides an implementation of the same
1106 [`ConnectorInterface`](https://github.com/reactphp/socket#connectorinterface)
1107 so that supporting either proxy protocol should be fairly trivial.
1108 * If you're dealing with public proxies, you'll likely have to work with mixed
1109 quality and unreliable proxies. You may want to look into using
1110 [clue/reactphp-connection-manager-extra](https://github.com/clue/reactphp-connection-manager-extra)
1111 which allows retrying unreliable ones, implying connection timeouts,
1112 concurrently working with multiple connectors and more.
1113 * If you're looking for an end-user SOCKS server daemon, you may want to use
1114 [LeProxy](https://leproxy.org/) or [clue/psocksd](https://github.com/clue/psocksd).