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