SOCKSServer.js.html 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>SOCKSServer.js - Documentation</title>
  6. <script src="scripts/prettify/prettify.js"></script>
  7. <script src="scripts/prettify/lang-css.js"></script>
  8. <!--[if lt IE 9]>
  9. <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
  10. <![endif]-->
  11. <link type="text/css" rel="stylesheet" href="styles/prettify.css">
  12. <link type="text/css" rel="stylesheet" href="styles/jsdoc.css">
  13. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  14. </head>
  15. <body>
  16. <input type="checkbox" id="nav-trigger" class="nav-trigger" />
  17. <label for="nav-trigger" class="navicon-button x">
  18. <div class="navicon"></div>
  19. </label>
  20. <label for="nav-trigger" class="overlay"></label>
  21. <nav>
  22. <h2><a href="index.html">Home</a></h2><h3>Classes</h3><ul><li><a href="ControlServer.html">ControlServer</a><ul class='methods'><li data-type='method'><a href="ControlServer.html#.instance_info">instance_info</a></li><li data-type='method'><a href="ControlServer.html#close">close</a></li><li data-type='method'><a href="ControlServer.html#createDNSServer">createDNSServer</a></li><li data-type='method'><a href="ControlServer.html#createHTTPServer">createHTTPServer</a></li><li data-type='method'><a href="ControlServer.html#createSOCKSServer">createSOCKSServer</a></li><li data-type='method'><a href="ControlServer.html#createTorPool">createTorPool</a></li><li data-type='method'><a href="ControlServer.html#listen">listen</a></li><li data-type='method'><a href="ControlServer.html#listenTcp">listenTcp</a></li><li data-type='method'><a href="ControlServer.html#listenWs">listenWs</a></li></ul></li><li><a href="DNSServer.html">DNSServer</a><ul class='methods'><li data-type='method'><a href="DNSServer.html#listen">listen</a></li></ul></li><li><a href="HTTPServer.html">HTTPServer</a><ul class='methods'><li data-type='method'><a href="HTTPServer.html#listen">listen</a></li></ul></li><li><a href="SOCKSServer.html">SOCKSServer</a><ul class='methods'><li data-type='method'><a href="SOCKSServer.html#listen">listen</a></li></ul></li><li><a href="TorPool.html">TorPool</a><ul class='methods'><li data-type='method'><a href="TorPool.html#add">add</a></li><li data-type='method'><a href="TorPool.html#add_instance_to_group">add_instance_to_group</a></li><li data-type='method'><a href="TorPool.html#add_instance_to_group_at">add_instance_to_group_at</a></li><li data-type='method'><a href="TorPool.html#add_instance_to_group_by_name">add_instance_to_group_by_name</a></li><li data-type='method'><a href="TorPool.html#create">create</a></li><li data-type='method'><a href="TorPool.html#create_instance">create_instance</a></li><li data-type='method'><a href="TorPool.html#exit">exit</a></li><li data-type='method'><a href="TorPool.html#get_config_at">get_config_at</a></li><li data-type='method'><a href="TorPool.html#get_config_by_name">get_config_by_name</a></li><li data-type='method'><a href="TorPool.html#instance_at">instance_at</a></li><li data-type='method'><a href="TorPool.html#instance_by_name">instance_by_name</a></li><li data-type='method'><a href="TorPool.html#instances_by_group">instances_by_group</a></li><li data-type='method'><a href="TorPool.html#new_identites">new_identites</a></li><li data-type='method'><a href="TorPool.html#new_identites_by_group">new_identites_by_group</a></li><li data-type='method'><a href="TorPool.html#new_identity_at">new_identity_at</a></li><li data-type='method'><a href="TorPool.html#new_identity_by_name">new_identity_by_name</a></li><li data-type='method'><a href="TorPool.html#next">next</a></li><li data-type='method'><a href="TorPool.html#next_by_group">next_by_group</a></li><li data-type='method'><a href="TorPool.html#remove">remove</a></li><li data-type='method'><a href="TorPool.html#remove_at">remove_at</a></li><li data-type='method'><a href="TorPool.html#remove_by_name">remove_by_name</a></li><li data-type='method'><a href="TorPool.html#remove_instance_from_group">remove_instance_from_group</a></li><li data-type='method'><a href="TorPool.html#remove_instance_from_group_at">remove_instance_from_group_at</a></li><li data-type='method'><a href="TorPool.html#remove_instance_from_group_by_name">remove_instance_from_group_by_name</a></li><li data-type='method'><a href="TorPool.html#set_config_all">set_config_all</a></li><li data-type='method'><a href="TorPool.html#set_config_at">set_config_at</a></li><li data-type='method'><a href="TorPool.html#set_config_by_group">set_config_by_group</a></li><li data-type='method'><a href="TorPool.html#set_config_by_name">set_config_by_name</a></li><li data-type='method'><a href="TorPool.html#signal_all">signal_all</a></li><li data-type='method'><a href="TorPool.html#signal_at">signal_at</a></li><li data-type='method'><a href="TorPool.html#signal_by_group">signal_by_group</a></li><li data-type='method'><a href="TorPool.html#signal_by_name">signal_by_name</a></li></ul></li><li><a href="TorProcess.html">TorProcess</a><ul class='methods'><li data-type='method'><a href="TorProcess.html#create">create</a></li><li data-type='method'><a href="TorProcess.html#exit">exit</a></li><li data-type='method'><a href="TorProcess.html#get_config">get_config</a></li><li data-type='method'><a href="TorProcess.html#new_identity">new_identity</a></li><li data-type='method'><a href="TorProcess.html#set_config">set_config</a></li><li data-type='method'><a href="TorProcess.html#signal">signal</a></li></ul></li></ul><h3>Modules</h3><ul><li><a href="module-tor-router.html">tor-router</a></li><li><a href="module-tor-router_ControlServer.html">tor-router/ControlServer</a></li><li><a href="module-tor-router_default_config.html">tor-router/default_config</a></li><li><a href="module-tor-router_default_ports.html">tor-router/default_ports</a></li><li><a href="module-tor-router_DNSServer.html">tor-router/DNSServer</a></li><li><a href="module-tor-router_HTTPServer.html">tor-router/HTTPServer</a></li><li><a href="module-tor-router_launch.html">tor-router/launch</a></li><li><a href="module-tor-router_nconf_load_env.html">tor-router/nconf_load_env</a></li><li><a href="module-tor-router_SOCKSServer.html">tor-router/SOCKSServer</a></li><li><a href="module-tor-router_TorPool.html">tor-router/TorPool</a></li><li><a href="module-tor-router_TorProcess.html">tor-router/TorProcess</a></li><li><a href="module-tor-router_winston_silent_logger.html">tor-router/winston_silent_logger</a></li></ul><h3>Events</h3><ul><li><a href="DNSServer.html#event:instance-connection">instance-connection</a></li><li><a href="HTTPServer.html#event:instance-connection">instance-connection</a></li><li><a href="SOCKSServer.html#event:instance-connection">instance-connection</a></li><li><a href="TorPool.html#event:instance_created">instance_created</a></li><li><a href="TorProcess.html#event:control_listen">control_listen</a></li><li><a href="TorProcess.html#event:controller_ready">controller_ready</a></li><li><a href="TorProcess.html#event:dns_listen">dns_listen</a></li><li><a href="TorProcess.html#event:error">error</a></li><li><a href="TorProcess.html#event:process_exit">process_exit</a></li><li><a href="TorProcess.html#event:ready">ready</a></li><li><a href="TorProcess.html#event:socks_listen">socks_listen</a></li></ul><h3>Global</h3><ul><li><a href="global.html#assembleHost">assembleHost</a></li><li><a href="global.html#cleanUp">cleanUp</a></li><li><a href="global.html#env_whitelist">env_whitelist</a></li><li><a href="global.html#logger">logger</a></li><li><a href="global.html#main">main</a></li><li><a href="global.html#nconf">nconf</a></li><li><a href="global.html#REALM">REALM</a></li><li><a href="global.html#setup_nconf_env">setup_nconf_env</a></li><li><a href="global.html#TOR_ROUTER_PROXY_AGENT">TOR_ROUTER_PROXY_AGENT</a></li></ul>
  23. </nav>
  24. <div id="main">
  25. <h1 class="page-title">SOCKSServer.js</h1>
  26. <section>
  27. <article>
  28. <pre class="prettyprint source linenums"><code>const socks = require('socksv5');
  29. const Promise = require('bluebird');
  30. const { Server } = socks;
  31. /**
  32. * Configuration for the "proxy by name" feature (connecting to specific instances or groups of instances using the username field when connecting).
  33. * @typedef ProxyByNameConfig
  34. *
  35. * @property {boolean} [deny_unidentified_users=false] - Deny unauthenticated (e.g. no username - socks://my-server:9050) users access to the proxy server.
  36. * @property {string} mode - Either "group" for routing to a group of instances or "individual" for routing to individual instances.
  37. */
  38. /**
  39. * Details on the source of a connection the proxy server.
  40. * @typedef InstanceConnectionSource
  41. * @property {string} hostname - Hostname where the connection was made from.
  42. * @property {number} port - Port where the connection was made from.
  43. * @property {boolean} by_name - Indicates whether the connection was made using a username (made to a specific instance or group of instances).
  44. * @property {string} proto - The protocol of the connection "socks", "http", "http-connect" or "dns"
  45. */
  46. /**
  47. * A SOCKS5 proxy server that will route requests to instances in the TorPool provided.
  48. * @extends Server
  49. */
  50. class SOCKSServer extends Server{
  51. /**
  52. * Callback for `authenticate_user`.
  53. * @callback SOCKSServer~authenticate_user_callback
  54. * @param {boolean} allow - Indicates if the connection should be allowed.
  55. * @param {boolean} user - Indicates if the connection should have a session (authentication was successful).
  56. */
  57. /**
  58. * Binds the server to a port and IP Address.
  59. *
  60. * @async
  61. * @param {number} port - The port to bind to.
  62. * @param {string} [host="::"] - Address to bind to. Will default to :: or 0.0.0.0 if not specified.
  63. * @returns {Promise}
  64. *
  65. */
  66. async listen() {
  67. return await new Promise((resolve, reject) => {
  68. let args = Array.from(arguments);
  69. let inner_func = super.listen;
  70. args.push(() => {
  71. let args = Array.from(arguments);
  72. resolve.apply(args);
  73. });
  74. inner_func.apply(this, args);
  75. });
  76. }
  77. /**
  78. * Retrieves an instance from the pool or an instance from a group by the name provided.
  79. * @param {string} username - Name of the group or instance to route to.
  80. * @returns {TorProcess}
  81. * @throws If {@link SOCKSServer#proxy_by_name} is set to an invalid value.
  82. * @throws If the name of the instance or group provided is invalid.
  83. * @private
  84. */
  85. get_instance_pbn(username) {
  86. if (this.proxy_by_name.mode === 'individual')
  87. return this.tor_pool.instance_by_name(username);
  88. else if (this.proxy_by_name.mode === 'group') {
  89. return this.tor_pool.next_by_group(username);
  90. } else
  91. throw Error(`Unknown "proxy_by_name" mode ${this.proxy_by_name.mode}`);
  92. }
  93. /**
  94. * Checks the username provided against all groups (for "group" mode) or all instances (for "individual" mode).
  95. * @param {string} username
  96. * @param {string} password
  97. * @param {SOCKSServer~authenticate_user_callback} callback - Callback for `authenticate_user`.
  98. * @throws If {@link SOCKSServer#proxy_by_name} is invalid.
  99. * @private
  100. */
  101. authenticate_user(username, password, callback) {
  102. let deny_un = this.proxy_by_name.deny_unidentified_users;
  103. // No username and deny unindentifed then deny
  104. if (!username &amp;&amp; deny_un) callback(false);
  105. // Otherwise if there is no username allow
  106. else if (!username) callback(true);
  107. if (this.proxy_by_name.mode === 'individual'){
  108. if (!this.tor_pool.instance_names.includes(username)) return callback(false);
  109. }
  110. else if (this.proxy_by_name.mode === 'group') {
  111. if (!this.tor_pool.group_names.has(username)) return callback(false);
  112. }
  113. else
  114. throw Error(`Unknown "proxy_by_name" mode "${this.proxy_by_name.mode}"`);
  115. // Otherwise allow
  116. callback(true, true);
  117. }
  118. /**
  119. * Creates an instance of `SOCKSServer`.
  120. * @param {TorPool} tor_pool - The pool of instances that will be used for requests
  121. * @param {Logger} [logger] - Winston logger that will be used for logging. If not specified will disable logging.
  122. * @param {ProxyByNameConfig} [proxy_by_name] - Enable routing to specific instances or groups of instances using the username field (socks://instance-1:@my-server:9050) when connecting.
  123. */
  124. constructor(tor_pool, logger, proxy_by_name) {
  125. /**
  126. * Handles SOCKS5 inbound connections.
  127. *
  128. * @function handle_connections
  129. * @param {object} info - Information about the inbound connection.
  130. * @param {Function} accept - Callback that allows the connection.
  131. * @param {Function} deny - Callback that denies the connection.
  132. * @private
  133. */
  134. const handle_connections = (info, accept, deny) => {
  135. let inbound_socket = accept(true);
  136. let instance;
  137. if (inbound_socket.user)
  138. instance = this.get_instance_pbn(inbound_socket.user);
  139. let outbound_socket;
  140. let buffer = [];
  141. let onInboundData = (data) => buffer.push(data)
  142. let onClose = (error) => {
  143. inbound_socket &amp;&amp; inbound_socket.end();
  144. outbound_socket &amp;&amp; outbound_socket.end();
  145. inbound_socket = outbound_socket = buffer = void(0);
  146. if (error)
  147. this.logger.error(`[socks]: an error occured: ${error.message}`)
  148. };
  149. if (!inbound_socket) return;
  150. inbound_socket.on('close', onClose);
  151. inbound_socket.on('data', onInboundData);
  152. inbound_socket.on('error', onClose);
  153. let connect = (tor_instance) => {
  154. let source = { hostname: info.srcAddr, port: info.srcPort, proto: 'socks', by_name: Boolean(instance) };
  155. let socks_port = tor_instance.socks_port;
  156. socks.connect({
  157. host: info.dstAddr,
  158. port: info.dstPort,
  159. proxyHost: '127.0.0.1',
  160. proxyPort: socks_port,
  161. localDNS: false,
  162. auths: [ socks.auth.None() ]
  163. }, ($outbound_socket) => {
  164. /**
  165. * Fires when the proxy has made a connection through an instance.
  166. *
  167. * @event SOCKSServer#instance-connection
  168. * @param {TorProcess} instance - Instance that has been connected to.
  169. * @param {InstanceConnectionSource} source - Details on the source of the connection.
  170. */
  171. this.emit('instance_connection', tor_instance, source);
  172. this.logger.verbose(`[socks]: ${source.hostname}:${source.port} → 127.0.0.1:${socks_port}${tor_instance.definition.Name ? ' ('+tor_instance.definition.Name+')' : '' } → ${info.dstAddr}:${info.dstPort}`)
  173. outbound_socket = $outbound_socket;
  174. outbound_socket &amp;&amp; outbound_socket.on('close', onClose);
  175. inbound_socket &amp;&amp; inbound_socket.removeListener('data', onInboundData);
  176. inbound_socket &amp;&amp; inbound_socket.on('data', (data) => {
  177. outbound_socket &amp;&amp; outbound_socket.write(data);
  178. });
  179. outbound_socket &amp;&amp; outbound_socket.on('data', (data) => {
  180. inbound_socket &amp;&amp; inbound_socket.write(data);
  181. });
  182. outbound_socket &amp;&amp; outbound_socket.on('error', onClose);
  183. while (buffer &amp;&amp; buffer.length &amp;&amp; outbound_socket) {
  184. outbound_socket.write(buffer.shift());
  185. }
  186. });
  187. };
  188. if (instance) {
  189. if (instance.ready) {
  190. connect(instance);
  191. }
  192. else {
  193. this.logger.debug(`[socks]: a connection has been attempted to "${instance.instance_name}", but it is not live... waiting for the instance to come online`);
  194. instance.once('ready', (() => connect(instance)));
  195. }
  196. }
  197. else if (this.tor_pool.instances.length) {
  198. connect(this.tor_pool.next());
  199. } else {
  200. this.logger.debug(`[socks]: a connection has been attempted, but no tor instances are live... waiting for an instance to come online`);
  201. this.tor_pool.once('instance_created', connect);
  202. }
  203. }
  204. super(handle_connections);
  205. let auth = socks.auth.None();
  206. if (proxy_by_name) {
  207. auth = socks.auth.UserPassword(this.authenticate_user.bind(this));
  208. }
  209. this.useAuth(auth);
  210. /**
  211. * Winston logger to use.
  212. *
  213. * @type {Logger}
  214. * @public
  215. */
  216. this.logger = logger || require('./winston_silent_logger');
  217. /**
  218. * Pool of instances use to service requests.
  219. *
  220. * @type {TorPool}
  221. * @public
  222. */
  223. this.tor_pool = tor_pool;
  224. /**
  225. * Configuration for the "proxy by name" feature.
  226. *
  227. * @type {ProxyByNameConfig}
  228. * @public
  229. */
  230. this.proxy_by_name = proxy_by_name;
  231. this.logger.debug(`[socks]: connecting to a specific instance by name has ben turned ${proxy_by_name ? 'on' : 'off'}`);
  232. }
  233. };
  234. /**
  235. * Module that contains the {@link SOCKSServer} class.
  236. * @module tor-router/SOCKSServer
  237. * @see SOCKSServer
  238. */
  239. module.exports = SOCKSServer;</code></pre>
  240. </article>
  241. </section>
  242. </div>
  243. <br class="clear">
  244. <footer>
  245. Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.5.5</a> on Tue Sep 25 2018 12:53:23 GMT-0400 (Eastern Daylight Time) using the <a href="https://github.com/clenemt/docdash">docdash</a> theme.
  246. </footer>
  247. <script>prettyPrint();</script>
  248. <script src="scripts/linenumber.js"></script>
  249. </body>
  250. </html>