socksclient.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  1. "use strict";
  2. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  3. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  4. return new (P || (P = Promise))(function (resolve, reject) {
  5. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  6. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  7. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  8. step((generator = generator.apply(thisArg, _arguments || [])).next());
  9. });
  10. };
  11. Object.defineProperty(exports, "__esModule", { value: true });
  12. exports.SocksClientError = exports.SocksClient = void 0;
  13. const events_1 = require("events");
  14. const net = require("net");
  15. const ip = require("ip");
  16. const smart_buffer_1 = require("smart-buffer");
  17. const constants_1 = require("../common/constants");
  18. const helpers_1 = require("../common/helpers");
  19. const receivebuffer_1 = require("../common/receivebuffer");
  20. const util_1 = require("../common/util");
  21. Object.defineProperty(exports, "SocksClientError", { enumerable: true, get: function () { return util_1.SocksClientError; } });
  22. class SocksClient extends events_1.EventEmitter {
  23. constructor(options) {
  24. super();
  25. this.options = Object.assign({}, options);
  26. // Validate SocksClientOptions
  27. (0, helpers_1.validateSocksClientOptions)(options);
  28. // Default state
  29. this.setState(constants_1.SocksClientState.Created);
  30. }
  31. /**
  32. * Creates a new SOCKS connection.
  33. *
  34. * Note: Supports callbacks and promises. Only supports the connect command.
  35. * @param options { SocksClientOptions } Options.
  36. * @param callback { Function } An optional callback function.
  37. * @returns { Promise }
  38. */
  39. static createConnection(options, callback) {
  40. return new Promise((resolve, reject) => {
  41. // Validate SocksClientOptions
  42. try {
  43. (0, helpers_1.validateSocksClientOptions)(options, ['connect']);
  44. }
  45. catch (err) {
  46. if (typeof callback === 'function') {
  47. callback(err);
  48. return resolve(err); // Resolves pending promise (prevents memory leaks).
  49. }
  50. else {
  51. return reject(err);
  52. }
  53. }
  54. const client = new SocksClient(options);
  55. client.connect(options.existing_socket);
  56. client.once('established', (info) => {
  57. client.removeAllListeners();
  58. if (typeof callback === 'function') {
  59. callback(null, info);
  60. resolve(info); // Resolves pending promise (prevents memory leaks).
  61. }
  62. else {
  63. resolve(info);
  64. }
  65. });
  66. // Error occurred, failed to establish connection.
  67. client.once('error', (err) => {
  68. client.removeAllListeners();
  69. if (typeof callback === 'function') {
  70. callback(err);
  71. resolve(err); // Resolves pending promise (prevents memory leaks).
  72. }
  73. else {
  74. reject(err);
  75. }
  76. });
  77. });
  78. }
  79. /**
  80. * Creates a new SOCKS connection chain to a destination host through 2 or more SOCKS proxies.
  81. *
  82. * Note: Supports callbacks and promises. Only supports the connect method.
  83. * Note: Implemented via createConnection() factory function.
  84. * @param options { SocksClientChainOptions } Options
  85. * @param callback { Function } An optional callback function.
  86. * @returns { Promise }
  87. */
  88. static createConnectionChain(options, callback) {
  89. return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
  90. // Validate SocksClientChainOptions
  91. try {
  92. (0, helpers_1.validateSocksClientChainOptions)(options);
  93. }
  94. catch (err) {
  95. if (typeof callback === 'function') {
  96. callback(err);
  97. return resolve(err); // Resolves pending promise (prevents memory leaks).
  98. }
  99. else {
  100. return reject(err);
  101. }
  102. }
  103. let sock;
  104. // Shuffle proxies
  105. if (options.randomizeChain) {
  106. (0, util_1.shuffleArray)(options.proxies);
  107. }
  108. try {
  109. // tslint:disable-next-line:no-increment-decrement
  110. for (let i = 0; i < options.proxies.length; i++) {
  111. const nextProxy = options.proxies[i];
  112. // If we've reached the last proxy in the chain, the destination is the actual destination, otherwise it's the next proxy.
  113. const nextDestination = i === options.proxies.length - 1
  114. ? options.destination
  115. : {
  116. host: options.proxies[i + 1].host ||
  117. options.proxies[i + 1].ipaddress,
  118. port: options.proxies[i + 1].port,
  119. };
  120. // Creates the next connection in the chain.
  121. const result = yield SocksClient.createConnection({
  122. command: 'connect',
  123. proxy: nextProxy,
  124. destination: nextDestination,
  125. // Initial connection ignores this as sock is undefined. Subsequent connections re-use the first proxy socket to form a chain.
  126. });
  127. // If sock is undefined, assign it here.
  128. if (!sock) {
  129. sock = result.socket;
  130. }
  131. }
  132. if (typeof callback === 'function') {
  133. callback(null, { socket: sock });
  134. resolve({ socket: sock }); // Resolves pending promise (prevents memory leaks).
  135. }
  136. else {
  137. resolve({ socket: sock });
  138. }
  139. }
  140. catch (err) {
  141. if (typeof callback === 'function') {
  142. callback(err);
  143. resolve(err); // Resolves pending promise (prevents memory leaks).
  144. }
  145. else {
  146. reject(err);
  147. }
  148. }
  149. }));
  150. }
  151. /**
  152. * Creates a SOCKS UDP Frame.
  153. * @param options
  154. */
  155. static createUDPFrame(options) {
  156. const buff = new smart_buffer_1.SmartBuffer();
  157. buff.writeUInt16BE(0);
  158. buff.writeUInt8(options.frameNumber || 0);
  159. // IPv4/IPv6/Hostname
  160. if (net.isIPv4(options.remoteHost.host)) {
  161. buff.writeUInt8(constants_1.Socks5HostType.IPv4);
  162. buff.writeUInt32BE(ip.toLong(options.remoteHost.host));
  163. }
  164. else if (net.isIPv6(options.remoteHost.host)) {
  165. buff.writeUInt8(constants_1.Socks5HostType.IPv6);
  166. buff.writeBuffer(ip.toBuffer(options.remoteHost.host));
  167. }
  168. else {
  169. buff.writeUInt8(constants_1.Socks5HostType.Hostname);
  170. buff.writeUInt8(Buffer.byteLength(options.remoteHost.host));
  171. buff.writeString(options.remoteHost.host);
  172. }
  173. // Port
  174. buff.writeUInt16BE(options.remoteHost.port);
  175. // Data
  176. buff.writeBuffer(options.data);
  177. return buff.toBuffer();
  178. }
  179. /**
  180. * Parses a SOCKS UDP frame.
  181. * @param data
  182. */
  183. static parseUDPFrame(data) {
  184. const buff = smart_buffer_1.SmartBuffer.fromBuffer(data);
  185. buff.readOffset = 2;
  186. const frameNumber = buff.readUInt8();
  187. const hostType = buff.readUInt8();
  188. let remoteHost;
  189. if (hostType === constants_1.Socks5HostType.IPv4) {
  190. remoteHost = ip.fromLong(buff.readUInt32BE());
  191. }
  192. else if (hostType === constants_1.Socks5HostType.IPv6) {
  193. remoteHost = ip.toString(buff.readBuffer(16));
  194. }
  195. else {
  196. remoteHost = buff.readString(buff.readUInt8());
  197. }
  198. const remotePort = buff.readUInt16BE();
  199. return {
  200. frameNumber,
  201. remoteHost: {
  202. host: remoteHost,
  203. port: remotePort,
  204. },
  205. data: buff.readBuffer(),
  206. };
  207. }
  208. /**
  209. * Internal state setter. If the SocksClient is in an error state, it cannot be changed to a non error state.
  210. */
  211. setState(newState) {
  212. if (this.state !== constants_1.SocksClientState.Error) {
  213. this.state = newState;
  214. }
  215. }
  216. /**
  217. * Starts the connection establishment to the proxy and destination.
  218. * @param existingSocket Connected socket to use instead of creating a new one (internal use).
  219. */
  220. connect(existingSocket) {
  221. this.onDataReceived = (data) => this.onDataReceivedHandler(data);
  222. this.onClose = () => this.onCloseHandler();
  223. this.onError = (err) => this.onErrorHandler(err);
  224. this.onConnect = () => this.onConnectHandler();
  225. // Start timeout timer (defaults to 30 seconds)
  226. const timer = setTimeout(() => this.onEstablishedTimeout(), this.options.timeout || constants_1.DEFAULT_TIMEOUT);
  227. // check whether unref is available as it differs from browser to NodeJS (#33)
  228. if (timer.unref && typeof timer.unref === 'function') {
  229. timer.unref();
  230. }
  231. // If an existing socket is provided, use it to negotiate SOCKS handshake. Otherwise create a new Socket.
  232. if (existingSocket) {
  233. this.socket = existingSocket;
  234. }
  235. else {
  236. this.socket = new net.Socket();
  237. }
  238. // Attach Socket error handlers.
  239. this.socket.once('close', this.onClose);
  240. this.socket.once('error', this.onError);
  241. this.socket.once('connect', this.onConnect);
  242. this.socket.on('data', this.onDataReceived);
  243. this.setState(constants_1.SocksClientState.Connecting);
  244. this.receiveBuffer = new receivebuffer_1.ReceiveBuffer();
  245. if (existingSocket) {
  246. this.socket.emit('connect');
  247. }
  248. else {
  249. this.socket.connect(this.getSocketOptions());
  250. if (this.options.set_tcp_nodelay !== undefined &&
  251. this.options.set_tcp_nodelay !== null) {
  252. this.socket.setNoDelay(!!this.options.set_tcp_nodelay);
  253. }
  254. }
  255. // Listen for established event so we can re-emit any excess data received during handshakes.
  256. this.prependOnceListener('established', (info) => {
  257. setImmediate(() => {
  258. if (this.receiveBuffer.length > 0) {
  259. const excessData = this.receiveBuffer.get(this.receiveBuffer.length);
  260. info.socket.emit('data', excessData);
  261. }
  262. info.socket.resume();
  263. });
  264. });
  265. }
  266. // Socket options (defaults host/port to options.proxy.host/options.proxy.port)
  267. getSocketOptions() {
  268. return Object.assign(Object.assign({}, this.options.socket_options), { host: this.options.proxy.host || this.options.proxy.ipaddress, port: this.options.proxy.port });
  269. }
  270. /**
  271. * Handles internal Socks timeout callback.
  272. * Note: If the Socks client is not BoundWaitingForConnection or Established, the connection will be closed.
  273. */
  274. onEstablishedTimeout() {
  275. if (this.state !== constants_1.SocksClientState.Established &&
  276. this.state !== constants_1.SocksClientState.BoundWaitingForConnection) {
  277. this.closeSocket(constants_1.ERRORS.ProxyConnectionTimedOut);
  278. }
  279. }
  280. /**
  281. * Handles Socket connect event.
  282. */
  283. onConnectHandler() {
  284. this.setState(constants_1.SocksClientState.Connected);
  285. // Send initial handshake.
  286. if (this.options.proxy.type === 4) {
  287. this.sendSocks4InitialHandshake();
  288. }
  289. else {
  290. this.sendSocks5InitialHandshake();
  291. }
  292. this.setState(constants_1.SocksClientState.SentInitialHandshake);
  293. }
  294. /**
  295. * Handles Socket data event.
  296. * @param data
  297. */
  298. onDataReceivedHandler(data) {
  299. /*
  300. All received data is appended to a ReceiveBuffer.
  301. This makes sure that all the data we need is received before we attempt to process it.
  302. */
  303. this.receiveBuffer.append(data);
  304. // Process data that we have.
  305. this.processData();
  306. }
  307. /**
  308. * Handles processing of the data we have received.
  309. */
  310. processData() {
  311. // If we have enough data to process the next step in the SOCKS handshake, proceed.
  312. while (this.state !== constants_1.SocksClientState.Established &&
  313. this.state !== constants_1.SocksClientState.Error &&
  314. this.receiveBuffer.length >= this.nextRequiredPacketBufferSize) {
  315. // Sent initial handshake, waiting for response.
  316. if (this.state === constants_1.SocksClientState.SentInitialHandshake) {
  317. if (this.options.proxy.type === 4) {
  318. // Socks v4 only has one handshake response.
  319. this.handleSocks4FinalHandshakeResponse();
  320. }
  321. else {
  322. // Socks v5 has two handshakes, handle initial one here.
  323. this.handleInitialSocks5HandshakeResponse();
  324. }
  325. // Sent auth request for Socks v5, waiting for response.
  326. }
  327. else if (this.state === constants_1.SocksClientState.SentAuthentication) {
  328. this.handleInitialSocks5AuthenticationHandshakeResponse();
  329. // Sent final Socks v5 handshake, waiting for final response.
  330. }
  331. else if (this.state === constants_1.SocksClientState.SentFinalHandshake) {
  332. this.handleSocks5FinalHandshakeResponse();
  333. // Socks BIND established. Waiting for remote connection via proxy.
  334. }
  335. else if (this.state === constants_1.SocksClientState.BoundWaitingForConnection) {
  336. if (this.options.proxy.type === 4) {
  337. this.handleSocks4IncomingConnectionResponse();
  338. }
  339. else {
  340. this.handleSocks5IncomingConnectionResponse();
  341. }
  342. }
  343. else {
  344. this.closeSocket(constants_1.ERRORS.InternalError);
  345. break;
  346. }
  347. }
  348. }
  349. /**
  350. * Handles Socket close event.
  351. * @param had_error
  352. */
  353. onCloseHandler() {
  354. this.closeSocket(constants_1.ERRORS.SocketClosed);
  355. }
  356. /**
  357. * Handles Socket error event.
  358. * @param err
  359. */
  360. onErrorHandler(err) {
  361. this.closeSocket(err.message);
  362. }
  363. /**
  364. * Removes internal event listeners on the underlying Socket.
  365. */
  366. removeInternalSocketHandlers() {
  367. // Pauses data flow of the socket (this is internally resumed after 'established' is emitted)
  368. this.socket.pause();
  369. this.socket.removeListener('data', this.onDataReceived);
  370. this.socket.removeListener('close', this.onClose);
  371. this.socket.removeListener('error', this.onError);
  372. this.socket.removeListener('connect', this.onConnect);
  373. }
  374. /**
  375. * Closes and destroys the underlying Socket. Emits an error event.
  376. * @param err { String } An error string to include in error event.
  377. */
  378. closeSocket(err) {
  379. // Make sure only one 'error' event is fired for the lifetime of this SocksClient instance.
  380. if (this.state !== constants_1.SocksClientState.Error) {
  381. // Set internal state to Error.
  382. this.setState(constants_1.SocksClientState.Error);
  383. // Destroy Socket
  384. this.socket.destroy();
  385. // Remove internal listeners
  386. this.removeInternalSocketHandlers();
  387. // Fire 'error' event.
  388. this.emit('error', new util_1.SocksClientError(err, this.options));
  389. }
  390. }
  391. /**
  392. * Sends initial Socks v4 handshake request.
  393. */
  394. sendSocks4InitialHandshake() {
  395. const userId = this.options.proxy.userId || '';
  396. const buff = new smart_buffer_1.SmartBuffer();
  397. buff.writeUInt8(0x04);
  398. buff.writeUInt8(constants_1.SocksCommand[this.options.command]);
  399. buff.writeUInt16BE(this.options.destination.port);
  400. // Socks 4 (IPv4)
  401. if (net.isIPv4(this.options.destination.host)) {
  402. buff.writeBuffer(ip.toBuffer(this.options.destination.host));
  403. buff.writeStringNT(userId);
  404. // Socks 4a (hostname)
  405. }
  406. else {
  407. buff.writeUInt8(0x00);
  408. buff.writeUInt8(0x00);
  409. buff.writeUInt8(0x00);
  410. buff.writeUInt8(0x01);
  411. buff.writeStringNT(userId);
  412. buff.writeStringNT(this.options.destination.host);
  413. }
  414. this.nextRequiredPacketBufferSize =
  415. constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks4Response;
  416. this.socket.write(buff.toBuffer());
  417. }
  418. /**
  419. * Handles Socks v4 handshake response.
  420. * @param data
  421. */
  422. handleSocks4FinalHandshakeResponse() {
  423. const data = this.receiveBuffer.get(8);
  424. if (data[1] !== constants_1.Socks4Response.Granted) {
  425. this.closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedConnection} - (${constants_1.Socks4Response[data[1]]})`);
  426. }
  427. else {
  428. // Bind response
  429. if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.bind) {
  430. const buff = smart_buffer_1.SmartBuffer.fromBuffer(data);
  431. buff.readOffset = 2;
  432. const remoteHost = {
  433. port: buff.readUInt16BE(),
  434. host: ip.fromLong(buff.readUInt32BE()),
  435. };
  436. // If host is 0.0.0.0, set to proxy host.
  437. if (remoteHost.host === '0.0.0.0') {
  438. remoteHost.host = this.options.proxy.ipaddress;
  439. }
  440. this.setState(constants_1.SocksClientState.BoundWaitingForConnection);
  441. this.emit('bound', { remoteHost, socket: this.socket });
  442. // Connect response
  443. }
  444. else {
  445. this.setState(constants_1.SocksClientState.Established);
  446. this.removeInternalSocketHandlers();
  447. this.emit('established', { socket: this.socket });
  448. }
  449. }
  450. }
  451. /**
  452. * Handles Socks v4 incoming connection request (BIND)
  453. * @param data
  454. */
  455. handleSocks4IncomingConnectionResponse() {
  456. const data = this.receiveBuffer.get(8);
  457. if (data[1] !== constants_1.Socks4Response.Granted) {
  458. this.closeSocket(`${constants_1.ERRORS.Socks4ProxyRejectedIncomingBoundConnection} - (${constants_1.Socks4Response[data[1]]})`);
  459. }
  460. else {
  461. const buff = smart_buffer_1.SmartBuffer.fromBuffer(data);
  462. buff.readOffset = 2;
  463. const remoteHost = {
  464. port: buff.readUInt16BE(),
  465. host: ip.fromLong(buff.readUInt32BE()),
  466. };
  467. this.setState(constants_1.SocksClientState.Established);
  468. this.removeInternalSocketHandlers();
  469. this.emit('established', { remoteHost, socket: this.socket });
  470. }
  471. }
  472. /**
  473. * Sends initial Socks v5 handshake request.
  474. */
  475. sendSocks5InitialHandshake() {
  476. const buff = new smart_buffer_1.SmartBuffer();
  477. // By default we always support no auth.
  478. const supportedAuthMethods = [constants_1.Socks5Auth.NoAuth];
  479. // We should only tell the proxy we support user/pass auth if auth info is actually provided.
  480. // Note: As of Tor v0.3.5.7+, if user/pass auth is an option from the client, by default it will always take priority.
  481. if (this.options.proxy.userId || this.options.proxy.password) {
  482. supportedAuthMethods.push(constants_1.Socks5Auth.UserPass);
  483. }
  484. // Custom auth method?
  485. if (this.options.proxy.custom_auth_method !== undefined) {
  486. supportedAuthMethods.push(this.options.proxy.custom_auth_method);
  487. }
  488. // Build handshake packet
  489. buff.writeUInt8(0x05);
  490. buff.writeUInt8(supportedAuthMethods.length);
  491. for (const authMethod of supportedAuthMethods) {
  492. buff.writeUInt8(authMethod);
  493. }
  494. this.nextRequiredPacketBufferSize =
  495. constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5InitialHandshakeResponse;
  496. this.socket.write(buff.toBuffer());
  497. this.setState(constants_1.SocksClientState.SentInitialHandshake);
  498. }
  499. /**
  500. * Handles initial Socks v5 handshake response.
  501. * @param data
  502. */
  503. handleInitialSocks5HandshakeResponse() {
  504. const data = this.receiveBuffer.get(2);
  505. if (data[0] !== 0x05) {
  506. this.closeSocket(constants_1.ERRORS.InvalidSocks5IntiailHandshakeSocksVersion);
  507. }
  508. else if (data[1] === constants_1.SOCKS5_NO_ACCEPTABLE_AUTH) {
  509. this.closeSocket(constants_1.ERRORS.InvalidSocks5InitialHandshakeNoAcceptedAuthType);
  510. }
  511. else {
  512. // If selected Socks v5 auth method is no auth, send final handshake request.
  513. if (data[1] === constants_1.Socks5Auth.NoAuth) {
  514. this.socks5ChosenAuthType = constants_1.Socks5Auth.NoAuth;
  515. this.sendSocks5CommandRequest();
  516. // If selected Socks v5 auth method is user/password, send auth handshake.
  517. }
  518. else if (data[1] === constants_1.Socks5Auth.UserPass) {
  519. this.socks5ChosenAuthType = constants_1.Socks5Auth.UserPass;
  520. this.sendSocks5UserPassAuthentication();
  521. // If selected Socks v5 auth method is the custom_auth_method, send custom handshake.
  522. }
  523. else if (data[1] === this.options.proxy.custom_auth_method) {
  524. this.socks5ChosenAuthType = this.options.proxy.custom_auth_method;
  525. this.sendSocks5CustomAuthentication();
  526. }
  527. else {
  528. this.closeSocket(constants_1.ERRORS.InvalidSocks5InitialHandshakeUnknownAuthType);
  529. }
  530. }
  531. }
  532. /**
  533. * Sends Socks v5 user & password auth handshake.
  534. *
  535. * Note: No auth and user/pass are currently supported.
  536. */
  537. sendSocks5UserPassAuthentication() {
  538. const userId = this.options.proxy.userId || '';
  539. const password = this.options.proxy.password || '';
  540. const buff = new smart_buffer_1.SmartBuffer();
  541. buff.writeUInt8(0x01);
  542. buff.writeUInt8(Buffer.byteLength(userId));
  543. buff.writeString(userId);
  544. buff.writeUInt8(Buffer.byteLength(password));
  545. buff.writeString(password);
  546. this.nextRequiredPacketBufferSize =
  547. constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5UserPassAuthenticationResponse;
  548. this.socket.write(buff.toBuffer());
  549. this.setState(constants_1.SocksClientState.SentAuthentication);
  550. }
  551. sendSocks5CustomAuthentication() {
  552. return __awaiter(this, void 0, void 0, function* () {
  553. this.nextRequiredPacketBufferSize =
  554. this.options.proxy.custom_auth_response_size;
  555. this.socket.write(yield this.options.proxy.custom_auth_request_handler());
  556. this.setState(constants_1.SocksClientState.SentAuthentication);
  557. });
  558. }
  559. handleSocks5CustomAuthHandshakeResponse(data) {
  560. return __awaiter(this, void 0, void 0, function* () {
  561. return yield this.options.proxy.custom_auth_response_handler(data);
  562. });
  563. }
  564. handleSocks5AuthenticationNoAuthHandshakeResponse(data) {
  565. return __awaiter(this, void 0, void 0, function* () {
  566. return data[1] === 0x00;
  567. });
  568. }
  569. handleSocks5AuthenticationUserPassHandshakeResponse(data) {
  570. return __awaiter(this, void 0, void 0, function* () {
  571. return data[1] === 0x00;
  572. });
  573. }
  574. /**
  575. * Handles Socks v5 auth handshake response.
  576. * @param data
  577. */
  578. handleInitialSocks5AuthenticationHandshakeResponse() {
  579. return __awaiter(this, void 0, void 0, function* () {
  580. this.setState(constants_1.SocksClientState.ReceivedAuthenticationResponse);
  581. let authResult = false;
  582. if (this.socks5ChosenAuthType === constants_1.Socks5Auth.NoAuth) {
  583. authResult = yield this.handleSocks5AuthenticationNoAuthHandshakeResponse(this.receiveBuffer.get(2));
  584. }
  585. else if (this.socks5ChosenAuthType === constants_1.Socks5Auth.UserPass) {
  586. authResult =
  587. yield this.handleSocks5AuthenticationUserPassHandshakeResponse(this.receiveBuffer.get(2));
  588. }
  589. else if (this.socks5ChosenAuthType === this.options.proxy.custom_auth_method) {
  590. authResult = yield this.handleSocks5CustomAuthHandshakeResponse(this.receiveBuffer.get(this.options.proxy.custom_auth_response_size));
  591. }
  592. if (!authResult) {
  593. this.closeSocket(constants_1.ERRORS.Socks5AuthenticationFailed);
  594. }
  595. else {
  596. this.sendSocks5CommandRequest();
  597. }
  598. });
  599. }
  600. /**
  601. * Sends Socks v5 final handshake request.
  602. */
  603. sendSocks5CommandRequest() {
  604. const buff = new smart_buffer_1.SmartBuffer();
  605. buff.writeUInt8(0x05);
  606. buff.writeUInt8(constants_1.SocksCommand[this.options.command]);
  607. buff.writeUInt8(0x00);
  608. // ipv4, ipv6, domain?
  609. if (net.isIPv4(this.options.destination.host)) {
  610. buff.writeUInt8(constants_1.Socks5HostType.IPv4);
  611. buff.writeBuffer(ip.toBuffer(this.options.destination.host));
  612. }
  613. else if (net.isIPv6(this.options.destination.host)) {
  614. buff.writeUInt8(constants_1.Socks5HostType.IPv6);
  615. buff.writeBuffer(ip.toBuffer(this.options.destination.host));
  616. }
  617. else {
  618. buff.writeUInt8(constants_1.Socks5HostType.Hostname);
  619. buff.writeUInt8(this.options.destination.host.length);
  620. buff.writeString(this.options.destination.host);
  621. }
  622. buff.writeUInt16BE(this.options.destination.port);
  623. this.nextRequiredPacketBufferSize =
  624. constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader;
  625. this.socket.write(buff.toBuffer());
  626. this.setState(constants_1.SocksClientState.SentFinalHandshake);
  627. }
  628. /**
  629. * Handles Socks v5 final handshake response.
  630. * @param data
  631. */
  632. handleSocks5FinalHandshakeResponse() {
  633. // Peek at available data (we need at least 5 bytes to get the hostname length)
  634. const header = this.receiveBuffer.peek(5);
  635. if (header[0] !== 0x05 || header[1] !== constants_1.Socks5Response.Granted) {
  636. this.closeSocket(`${constants_1.ERRORS.InvalidSocks5FinalHandshakeRejected} - ${constants_1.Socks5Response[header[1]]}`);
  637. }
  638. else {
  639. // Read address type
  640. const addressType = header[3];
  641. let remoteHost;
  642. let buff;
  643. // IPv4
  644. if (addressType === constants_1.Socks5HostType.IPv4) {
  645. // Check if data is available.
  646. const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;
  647. if (this.receiveBuffer.length < dataNeeded) {
  648. this.nextRequiredPacketBufferSize = dataNeeded;
  649. return;
  650. }
  651. buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4));
  652. remoteHost = {
  653. host: ip.fromLong(buff.readUInt32BE()),
  654. port: buff.readUInt16BE(),
  655. };
  656. // If given host is 0.0.0.0, assume remote proxy ip instead.
  657. if (remoteHost.host === '0.0.0.0') {
  658. remoteHost.host = this.options.proxy.ipaddress;
  659. }
  660. // Hostname
  661. }
  662. else if (addressType === constants_1.Socks5HostType.Hostname) {
  663. const hostLength = header[4];
  664. const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(hostLength); // header + host length + host + port
  665. // Check if data is available.
  666. if (this.receiveBuffer.length < dataNeeded) {
  667. this.nextRequiredPacketBufferSize = dataNeeded;
  668. return;
  669. }
  670. buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(5));
  671. remoteHost = {
  672. host: buff.readString(hostLength),
  673. port: buff.readUInt16BE(),
  674. };
  675. // IPv6
  676. }
  677. else if (addressType === constants_1.Socks5HostType.IPv6) {
  678. // Check if data is available.
  679. const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;
  680. if (this.receiveBuffer.length < dataNeeded) {
  681. this.nextRequiredPacketBufferSize = dataNeeded;
  682. return;
  683. }
  684. buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4));
  685. remoteHost = {
  686. host: ip.toString(buff.readBuffer(16)),
  687. port: buff.readUInt16BE(),
  688. };
  689. }
  690. // We have everything we need
  691. this.setState(constants_1.SocksClientState.ReceivedFinalResponse);
  692. // If using CONNECT, the client is now in the established state.
  693. if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.connect) {
  694. this.setState(constants_1.SocksClientState.Established);
  695. this.removeInternalSocketHandlers();
  696. this.emit('established', { remoteHost, socket: this.socket });
  697. }
  698. else if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.bind) {
  699. /* If using BIND, the Socks client is now in BoundWaitingForConnection state.
  700. This means that the remote proxy server is waiting for a remote connection to the bound port. */
  701. this.setState(constants_1.SocksClientState.BoundWaitingForConnection);
  702. this.nextRequiredPacketBufferSize =
  703. constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHeader;
  704. this.emit('bound', { remoteHost, socket: this.socket });
  705. /*
  706. If using Associate, the Socks client is now Established. And the proxy server is now accepting UDP packets at the
  707. given bound port. This initial Socks TCP connection must remain open for the UDP relay to continue to work.
  708. */
  709. }
  710. else if (constants_1.SocksCommand[this.options.command] === constants_1.SocksCommand.associate) {
  711. this.setState(constants_1.SocksClientState.Established);
  712. this.removeInternalSocketHandlers();
  713. this.emit('established', {
  714. remoteHost,
  715. socket: this.socket,
  716. });
  717. }
  718. }
  719. }
  720. /**
  721. * Handles Socks v5 incoming connection request (BIND).
  722. */
  723. handleSocks5IncomingConnectionResponse() {
  724. // Peek at available data (we need at least 5 bytes to get the hostname length)
  725. const header = this.receiveBuffer.peek(5);
  726. if (header[0] !== 0x05 || header[1] !== constants_1.Socks5Response.Granted) {
  727. this.closeSocket(`${constants_1.ERRORS.Socks5ProxyRejectedIncomingBoundConnection} - ${constants_1.Socks5Response[header[1]]}`);
  728. }
  729. else {
  730. // Read address type
  731. const addressType = header[3];
  732. let remoteHost;
  733. let buff;
  734. // IPv4
  735. if (addressType === constants_1.Socks5HostType.IPv4) {
  736. // Check if data is available.
  737. const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv4;
  738. if (this.receiveBuffer.length < dataNeeded) {
  739. this.nextRequiredPacketBufferSize = dataNeeded;
  740. return;
  741. }
  742. buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4));
  743. remoteHost = {
  744. host: ip.fromLong(buff.readUInt32BE()),
  745. port: buff.readUInt16BE(),
  746. };
  747. // If given host is 0.0.0.0, assume remote proxy ip instead.
  748. if (remoteHost.host === '0.0.0.0') {
  749. remoteHost.host = this.options.proxy.ipaddress;
  750. }
  751. // Hostname
  752. }
  753. else if (addressType === constants_1.Socks5HostType.Hostname) {
  754. const hostLength = header[4];
  755. const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseHostname(hostLength); // header + host length + port
  756. // Check if data is available.
  757. if (this.receiveBuffer.length < dataNeeded) {
  758. this.nextRequiredPacketBufferSize = dataNeeded;
  759. return;
  760. }
  761. buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(5));
  762. remoteHost = {
  763. host: buff.readString(hostLength),
  764. port: buff.readUInt16BE(),
  765. };
  766. // IPv6
  767. }
  768. else if (addressType === constants_1.Socks5HostType.IPv6) {
  769. // Check if data is available.
  770. const dataNeeded = constants_1.SOCKS_INCOMING_PACKET_SIZES.Socks5ResponseIPv6;
  771. if (this.receiveBuffer.length < dataNeeded) {
  772. this.nextRequiredPacketBufferSize = dataNeeded;
  773. return;
  774. }
  775. buff = smart_buffer_1.SmartBuffer.fromBuffer(this.receiveBuffer.get(dataNeeded).slice(4));
  776. remoteHost = {
  777. host: ip.toString(buff.readBuffer(16)),
  778. port: buff.readUInt16BE(),
  779. };
  780. }
  781. this.setState(constants_1.SocksClientState.Established);
  782. this.removeInternalSocketHandlers();
  783. this.emit('established', { remoteHost, socket: this.socket });
  784. }
  785. }
  786. get socksClientOptions() {
  787. return Object.assign({}, this.options);
  788. }
  789. }
  790. exports.SocksClient = SocksClient;
  791. //# sourceMappingURL=socksclient.js.map