socksclient.js 35 KB

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