Debian Codegraph @

vendor/clue/socks-react/src/Server.php

raw
1 <?php
2
3 namespace Clue\React\Socks;
4
5 use React\Socket\ServerInterface;
6 use React\Promise\PromiseInterface;
7 use React\Socket\ConnectorInterface;
8 use React\Socket\Connector;
9 use React\Socket\ConnectionInterface;
10 use React\EventLoop\LoopInterface;
11 use \UnexpectedValueException;
12 use \InvalidArgumentException;
13 use \Exception;
14 use React\Promise\Timer\TimeoutException;
15
16 final class Server
17 {
18 // the following error codes are only used for SOCKS5 only
19 /** @internal */
20 const ERROR_GENERAL = 0x01;
21 /** @internal */
22 const ERROR_NOT_ALLOWED_BY_RULESET = 0x02;
23 /** @internal */
24 const ERROR_NETWORK_UNREACHABLE = 0x03;
25 /** @internal */
26 const ERROR_HOST_UNREACHABLE = 0x04;
27 /** @internal */
28 const ERROR_CONNECTION_REFUSED = 0x05;
29 /** @internal */
30 const ERROR_TTL = 0x06;
31 /** @internal */
32 const ERROR_COMMAND_UNSUPPORTED = 0x07;
33 /** @internal */
34 const ERROR_ADDRESS_UNSUPPORTED = 0x08;
35
36 private $loop;
37
38 private $connector;
39
40 /**
41 * @var null|callable
42 */
43 private $auth;
44
45 /**
46 * @param LoopInterface $loop
47 * @param null|ConnectorInterface $connector
48 * @param null|array|callable $auth
49 */
50 public function __construct(LoopInterface $loop, ConnectorInterface $connector = null, $auth = null)
51 {
52 if ($connector === null) {
53 $connector = new Connector($loop);
54 }
55
56 if (\is_array($auth)) {
57 // wrap authentication array in authentication callback
58 $this->auth = function ($username, $password) use ($auth) {
59 return \React\Promise\resolve(
60 isset($auth[$username]) && (string)$auth[$username] === $password
61 );
62 };
63 } elseif (\is_callable($auth)) {
64 // wrap authentication callback in order to cast its return value to a promise
65 $this->auth = function($username, $password, $remote) use ($auth) {
66 return \React\Promise\resolve(
67 \call_user_func($auth, $username, $password, $remote)
68 );
69 };
70 } elseif ($auth !== null) {
71 throw new \InvalidArgumentException('Invalid authenticator given');
72 }
73
74 $this->loop = $loop;
75 $this->connector = $connector;
76 }
77
78 /**
79 * @param ServerInterface $socket
80 * @return void
81 */
82 public function listen(ServerInterface $socket)
83 {
84 $that = $this;
85 $socket->on('connection', function ($connection) use ($that) {
86 $that->onConnection($connection);
87 });
88 }
89
90 /** @internal */
91 public function onConnection(ConnectionInterface $connection)
92 {
93 $that = $this;
94 $handling = $this->handleSocks($connection)->then(null, function () use ($connection, $that) {
95 // SOCKS failed => close connection
96 $that->endConnection($connection);
97 });
98
99 $connection->on('close', function () use ($handling) {
100 $handling->cancel();
101 });
102 }
103
104 /**
105 * [internal] gracefully shutdown connection by flushing all remaining data and closing stream
106 *
107 * @internal
108 */
109 public function endConnection(ConnectionInterface $stream)
110 {
111 $tid = true;
112 $loop = $this->loop;
113
114 // cancel below timer in case connection is closed in time
115 $stream->once('close', function () use (&$tid, $loop) {
116 // close event called before the timer was set up, so everything is okay
117 if ($tid === true) {
118 // make sure to not start a useless timer
119 $tid = false;
120 } else {
121 $loop->cancelTimer($tid);
122 }
123 });
124
125 // shut down connection by pausing input data, flushing outgoing buffer and then exit
126 $stream->pause();
127 $stream->end();
128
129 // check if connection is not already closed
130 if ($tid === true) {
131 // fall back to forcefully close connection in 3 seconds if buffer can not be flushed
132 $tid = $loop->addTimer(3.0, array($stream,'close'));
133 }
134 }
135
136 private function handleSocks(ConnectionInterface $stream)
137 {
138 $reader = new StreamReader();
139 $stream->on('data', array($reader, 'write'));
140
141 $that = $this;
142 $auth = $this->auth;
143
144 return $reader->readByte()->then(function ($version) use ($stream, $that, $auth, $reader){
145 if ($version === 0x04) {
146 if ($auth !== null) {
147 throw new UnexpectedValueException('SOCKS4 not allowed because authentication is required');
148 }
149 return $that->handleSocks4($stream, $reader);
150 } else if ($version === 0x05) {
151 return $that->handleSocks5($stream, $auth, $reader);
152 }
153 throw new UnexpectedValueException('Unexpected/unknown version number');
154 });
155 }
156
157 /** @internal */
158 public function handleSocks4(ConnectionInterface $stream, StreamReader $reader)
159 {
160 $remote = $stream->getRemoteAddress();
161 if ($remote !== null) {
162 // remove transport scheme and prefix socks4:// instead
163 $secure = strpos($remote, 'tls://') === 0;
164 if (($pos = strpos($remote, '://')) !== false) {
165 $remote = substr($remote, $pos + 3);
166 }
167 $remote = 'socks4' . ($secure ? 's' : '') . '://' . $remote;
168 }
169
170 $that = $this;
171 return $reader->readByteAssert(0x01)->then(function () use ($reader) {
172 return $reader->readBinary(array(
173 'port' => 'n',
174 'ipLong' => 'N',
175 'null' => 'C'
176 ));
177 })->then(function ($data) use ($reader, $remote) {
178 if ($data['null'] !== 0x00) {
179 throw new Exception('Not a null byte');
180 }
181 if ($data['ipLong'] === 0) {
182 throw new Exception('Invalid IP');
183 }
184 if ($data['port'] === 0) {
185 throw new Exception('Invalid port');
186 }
187 if ($data['ipLong'] < 256) {
188 // invalid IP => probably a SOCKS4a request which appends the hostname
189 return $reader->readStringNull()->then(function ($string) use ($data, $remote){
190 return array($string, $data['port'], $remote);
191 });
192 } else {
193 $ip = long2ip($data['ipLong']);
194 return array($ip, $data['port'], $remote);
195 }
196 })->then(function ($target) use ($stream, $that) {
197 return $that->connectTarget($stream, $target)->then(function (ConnectionInterface $remote) use ($stream){
198 $stream->write(pack('C8', 0x00, 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00));
199
200 return $remote;
201 }, function($error) use ($stream){
202 $stream->end(pack('C8', 0x00, 0x5b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00));
203
204 throw $error;
205 });
206 }, function($error) {
207 throw new UnexpectedValueException('SOCKS4 protocol error',0,$error);
208 });
209 }
210
211 /** @internal */
212 public function handleSocks5(ConnectionInterface $stream, $auth, StreamReader $reader)
213 {
214 $remote = $stream->getRemoteAddress();
215 if ($remote !== null) {
216 // remove transport scheme and prefix socks5:// instead
217 $secure = strpos($remote, 'tls://') === 0;
218 if (($pos = strpos($remote, '://')) !== false) {
219 $remote = substr($remote, $pos + 3);
220 }
221 $remote = 'socks' . ($secure ? 's' : '') . '://' . $remote;
222 }
223
224 $that = $this;
225 return $reader->readByte()->then(function ($num) use ($reader) {
226 // $num different authentication mechanisms offered
227 return $reader->readLength($num);
228 })->then(function ($methods) use ($reader, $stream, $auth, &$remote) {
229 if ($auth === null && strpos($methods,"\x00") !== false) {
230 // accept "no authentication"
231 $stream->write(pack('C2', 0x05, 0x00));
232
233 return 0x00;
234 } else if ($auth !== null && strpos($methods,"\x02") !== false) {
235 // username/password authentication (RFC 1929) sub negotiation
236 $stream->write(pack('C2', 0x05, 0x02));
237 return $reader->readByteAssert(0x01)->then(function () use ($reader) {
238 return $reader->readByte();
239 })->then(function ($length) use ($reader) {
240 return $reader->readLength($length);
241 })->then(function ($username) use ($reader, $auth, $stream, &$remote) {
242 return $reader->readByte()->then(function ($length) use ($reader) {
243 return $reader->readLength($length);
244 })->then(function ($password) use ($username, $auth, $stream, &$remote) {
245 // username and password given => authenticate
246
247 // prefix username/password to remote URI
248 if ($remote !== null) {
249 $remote = str_replace('://', '://' . rawurlencode($username) . ':' . rawurlencode($password) . '@', $remote);
250 }
251
252 return $auth($username, $password, $remote)->then(function ($authenticated) use ($stream) {
253 if ($authenticated) {
254 // accept auth
255 $stream->write(pack('C2', 0x01, 0x00));
256 } else {
257 // reject auth => send any code but 0x00
258 $stream->end(pack('C2', 0x01, 0xFF));
259 throw new UnexpectedValueException('Authentication denied');
260 }
261 }, function ($e) use ($stream) {
262 // reject failed authentication => send any code but 0x00
263 $stream->end(pack('C2', 0x01, 0xFF));
264 throw new UnexpectedValueException('Authentication error', 0, $e);
265 });
266 });
267 });
268 } else {
269 // reject all offered authentication methods
270 $stream->write(pack('C2', 0x05, 0xFF));
271 throw new UnexpectedValueException('No acceptable authentication mechanism found');
272 }
273 })->then(function ($method) use ($reader) {
274 return $reader->readBinary(array(
275 'version' => 'C',
276 'command' => 'C',
277 'null' => 'C',
278 'type' => 'C'
279 ));
280 })->then(function ($data) use ($reader) {
281 if ($data['version'] !== 0x05) {
282 throw new UnexpectedValueException('Invalid SOCKS version');
283 }
284 if ($data['command'] !== 0x01) {
285 throw new UnexpectedValueException('Only CONNECT requests supported', Server::ERROR_COMMAND_UNSUPPORTED);
286 }
287 // if ($data['null'] !== 0x00) {
288 // throw new UnexpectedValueException('Reserved byte has to be NULL');
289 // }
290 if ($data['type'] === 0x03) {
291 // target hostname string
292 return $reader->readByte()->then(function ($len) use ($reader) {
293 return $reader->readLength($len);
294 });
295 } else if ($data['type'] === 0x01) {
296 // target IPv4
297 return $reader->readLength(4)->then(function ($addr) {
298 return inet_ntop($addr);
299 });
300 } else if ($data['type'] === 0x04) {
301 // target IPv6
302 return $reader->readLength(16)->then(function ($addr) {
303 return inet_ntop($addr);
304 });
305 } else {
306 throw new UnexpectedValueException('Invalid address type', Server::ERROR_ADDRESS_UNSUPPORTED);
307 }
308 })->then(function ($host) use ($reader, &$remote) {
309 return $reader->readBinary(array('port'=>'n'))->then(function ($data) use ($host, &$remote) {
310 return array($host, $data['port'], $remote);
311 });
312 })->then(function ($target) use ($that, $stream) {
313 return $that->connectTarget($stream, $target);
314 }, function($error) use ($stream) {
315 throw new UnexpectedValueException('SOCKS5 protocol error', $error->getCode(), $error);
316 })->then(function (ConnectionInterface $remote) use ($stream) {
317 $stream->write(pack('C4Nn', 0x05, 0x00, 0x00, 0x01, 0, 0));
318
319 return $remote;
320 }, function(Exception $error) use ($stream){
321 $stream->write(pack('C4Nn', 0x05, $error->getCode() === 0 ? Server::ERROR_GENERAL : $error->getCode(), 0x00, 0x01, 0, 0));
322
323 throw $error;
324 });
325 }
326
327 /** @internal */
328 public function connectTarget(ConnectionInterface $stream, array $target)
329 {
330 $uri = $target[0];
331 if (strpos($uri, ':') !== false) {
332 $uri = '[' . $uri . ']';
333 }
334 $uri .= ':' . $target[1];
335
336 // validate URI so a string hostname can not pass excessive URI parts
337 $parts = parse_url('tcp://' . $uri);
338 if (!$parts || !isset($parts['scheme'], $parts['host'], $parts['port']) || count($parts) !== 3) {
339 return \React\Promise\reject(new InvalidArgumentException('Invalid target URI given'));
340 }
341
342 if (isset($target[2])) {
343 $uri .= '?source=' . rawurlencode($target[2]);
344 }
345
346 $that = $this;
347 $connecting = $this->connector->connect($uri);
348
349 $stream->on('close', function () use ($connecting) {
350 $connecting->cancel();
351 });
352
353 return $connecting->then(function (ConnectionInterface $remote) use ($stream, $that) {
354 $stream->pipe($remote, array('end'=>false));
355 $remote->pipe($stream, array('end'=>false));
356
357 // remote end closes connection => stop reading from local end, try to flush buffer to local and disconnect local
358 $remote->on('end', function() use ($stream, $that) {
359 $that->endConnection($stream);
360 });
361
362 // local end closes connection => stop reading from remote end, try to flush buffer to remote and disconnect remote
363 $stream->on('end', function() use ($remote, $that) {
364 $that->endConnection($remote);
365 });
366
367 // set bigger buffer size of 100k to improve performance
368 $stream->bufferSize = $remote->bufferSize = 100 * 1024 * 1024;
369
370 return $remote;
371 }, function(Exception $error) {
372 // default to general/unknown error
373 $code = Server::ERROR_GENERAL;
374
375 // map common socket error conditions to limited list of SOCKS error codes
376 if ((defined('SOCKET_EACCES') && $error->getCode() === SOCKET_EACCES) || $error->getCode() === 13) {
377 $code = Server::ERROR_NOT_ALLOWED_BY_RULESET;
378 } elseif ((defined('SOCKET_EHOSTUNREACH') && $error->getCode() === SOCKET_EHOSTUNREACH) || $error->getCode() === 113) {
379 $code = Server::ERROR_HOST_UNREACHABLE;
380 } elseif ((defined('SOCKET_ENETUNREACH') && $error->getCode() === SOCKET_ENETUNREACH) || $error->getCode() === 101) {
381 $code = Server::ERROR_NETWORK_UNREACHABLE;
382 } elseif ((defined('SOCKET_ECONNREFUSED') && $error->getCode() === SOCKET_ECONNREFUSED) || $error->getCode() === 111 || $error->getMessage() === 'Connection refused') {
383 // Socket component does not currently assign an error code for this, so we have to resort to checking the exception message
384 $code = Server::ERROR_CONNECTION_REFUSED;
385 } elseif ((defined('SOCKET_ETIMEDOUT') && $error->getCode() === SOCKET_ETIMEDOUT) || $error->getCode() === 110 || $error instanceof TimeoutException) {
386 // Socket component does not currently assign an error code for this, but we can rely on the TimeoutException
387 $code = Server::ERROR_TTL;
388 }
389
390 throw new UnexpectedValueException('Unable to connect to remote target', $code, $error);
391 });
392 }
393 }