Coder Social home page Coder Social logo

socratex's Introduction

Socratex

MIT licensed Node.js Package, Docker Image CodeQL

A Secure Web Proxy. Which is fast, secure, and easy to use.

This project is under active development. Everything may change soon.

Socratex extends the native net.createServer, and it acts as a real transparent HTTPS-proxy built on top of TCP-level.

It's a real HTTPS proxy, not HTTPS over HTTP. It allows upstream client-request dynamically to other proxies or works as a single layer encrypted proxy.

Socratex will request and set up the certificate automatically, and it will automatically renew the certificate when it expires. You don't need to worry about the dirty work about HTTPS/SSL.

It supports Basic Proxy-Authentication and Token-Based-Authentication as default. Socratex will create a new token at the first run, you don't need to worry about it.

Screen Shot 2022-04-15 at 8 47 01 PM

Why another proxy?

First of all, many people in particular countries need proxy software that is easy to deploy and could be used to secure their network traffic. Second, because of the limitation on App Store, especially in China, VPN and proxy software are not allowed to be used. So we need to find a way to avoid censorship without any client apps. Secure Web Proxy is the only choice and a promising one.

Deploy a Secure Web Proxy within 10 seconds

You need a domain name and set an A-record pointed to your cloud virtual machine.

Usually, that virtual machine can not be located in China.

Assumes that you have a workable Node.js (v16 or above) environment.

Now let's make the magic happen!

  • Modern method:
$ sudo su
# cd ~
# npx socratex --domain=example.com --bypass=cn
  • Classic method:
$ git clone [email protected]:Leask/socratex.git
$ cd socratex
$ npm install
$ sudo ./main.mjs --domain=example.com --bypass=cn
  • With Docker:
$ touch ~/.socratex.json
$ docker pull leask/socratex
$ docker run -d --restart=always -p 80:80 -p 443:443 \
    -v ~/.socratex.json:/root/.socratex.json \
    leask/socratex --domain=example.com --bypass=cn

If everything works fine, you should see a message like this:

[SOCRATEX Vx.y.z] https://github.com/Leask/socratex
[SOCRATEX] Secure Web Proxy started at https://example.com:443 (IPv6 ::).
[SOCRATEX] HTTP Server started at http://example.com:80 (IPv6 ::).
[SSL] Creating new private-key and CSR...
[SSL] Done.
[SSL] Updating certificate...
[SSL] Done.
[SOCRATEX] * Token authentication:
[SOCRATEX]   - PAC:  https://example.com/proxy.pac?token=959c298e-9f38-b201-2e7e-14af54469889
[SOCRATEX]   - WPAD: https://example.com/wpad.dat?token=959c298e-9f38-b201-2e7e-14af54469889
[SOCRATEX]   - Log:  https://example.com/console?token=959c298e-9f38-b201-2e7e-14af54469889
[SOCRATEX] * Basic authentication:
[SOCRATEX]   - PAC:   https://foo:[email protected]/proxy.pac
[SOCRATEX]   - WPAD:  https://foo:[email protected]/wpad.dat
[SOCRATEX]   - Log:   https://foo:[email protected]/console
[SOCRATEX]   - Proxy: https://foo:[email protected]

Copy the PAC url or WPAD url and paste it into your system's Automatic Proxy Configuration settings. That is all you need to do.

Screen Shot 2022-04-15 at 5 26 22 PM

Screen Shot 2022-04-15 at 5 25 41 PM

Note: You can also use the log url to monitor the system's activity.

Command line args

All args are optional. In most cases, you just need to set the domain name. Of cause, you can also set the bypass countries to reduce proxy traffics.

Param Type Description
domain String Domain to deploy the proxy.
http With/Without Use HTTP-only-mode for testing only.
bypass String Bypass IPs in these countries, could be multiple, example: --bypass=CN --bypass=US
user String Use user and password to enable Basic Authorization.
password String Use user and password to enable Basic Authorization.
token String Use to enable Token Authorization.
address String Activate/Handle Proxy-Authentication. Returns or solves to Boolean.
port Number Default 443 to handle incoming connection.

Limitations

Why not use sudo npx ... directly?

Socratex works at default HTTP (80) and HTTPS (443) ports. You need to be root to listen to these ports on some systems. Because of this issue: npm/cli#3110, if you are in a folder NOT OWN by root, you CAN NOT use sudo npm ... or sudo npx ... directly to run socratex.

Why doesn't work with iOS?

Socratex can be used with macOS, Chrome OS, Windows, Linux and Android. But it's NOT compatible with iOS currently. Because iOS does not support Secure Web Proxy yet. I will keep an eye on this issue and try any possible walk-around solutions.

Why name it Socratex?

Socratex was named after Socrates, a Greek philosopher from Athens credited as the founder of Western philosophy and among the first moral philosophers of the ethical tradition of thought.

Socrates

Image credit: The Death of Socrates, by Jacques-Louis David (1787)

Programmable proxy

Programmable proxy

////////////////////////////////////////////////////////////////////////////////
// NO NEED TO READ ANYTHING BELOW IF YOU ARE NOT GOING TO CUSTOMIZE THE PROXY //
////////////////////////////////////////////////////////////////////////////////

You can also use socratex as a programmable proxy to meet your own needs.

$ npm i -s socratex

Socratex is an ES6 module, so you can use it in your modern Node.js projects.

import { Socratex } from 'socratex';

const [port, address, options] = ['4698', '': {}];

const socratex = new Socratex(options);

socratex.listen(port, address, async () => {
    console.log('TCP-Proxy-Server started at: ', server.address());
});

Options object use to customize the proxy

options should be an object.

Param Type Description
basicAuth Function/AsyncFunction Activate/Handle Proxy-Authentication. Returns or solves to Boolean.
tokenAuth Function/AsyncFunction Activate/Handle Proxy-Authentication. Returns or solves to Boolean.
upstream Function/AsyncFunction The proxy to be used to upstreaming requests. Returns String.
tcpOutgoingAddress Function/AsyncFunction The localAddress to use while sending requests. Returns String.
injectData Function/AsyncFunction The edited data to upstream. Returns Buffer or string.
injectResponse Function/AsyncFunction The edited response to return to connected client. Returns Buffer or string.
keys Function/AsyncFunction The keys to use while handshake. It will work only if intercept is true. Returns Object or false.
logLevel Number Default 0 to log all messages.
intercept Boolean Activate interception of encrypted communications. False as default.

upstream, tcpOutgoingAddress, injectData & injectResponse options

The options are functions having follow parameters:

Param Type Description
data Buffer The received data.
session Session Object containing info/data about Tunnel.
  • upstream-Function need to return/resolve a String with format -> IP:PORT or USER:PWD@IP:PORT of used http-proxy. If 'localhost' is returned/resolved, then the host-self will be used as proxy.
  • tcpOutgoingAddress-Function need to return a String with format -> IP.
  • injectData-Function need to return a String or buffer for the new spoofed data. This will be upstreamed as request.
  • injectResponse-Function need to return a String or buffer for the new received data.

Note: These functions will be executed before first tcp-socket-connection is established.

Upstream to other proxies

If you don't want to use the host of active instance self, then you need to upstream connections to another http-proxy. This can be done with upstream attribute.

const options = {
    upstream: async () => { return 'x.x.x.x:3128'; },
};

The Basic Authorization mechanism

This activate basic authorization mechanism. The Auth-function will be executed while handling Proxy-Authentications.

Param Type Description
username String The client username.
password String The client password
session Session Object containing info/data about Tunnel

Note: It needs to return True/False or a Promise that resolves to boolean (isAuthenticated).

const options = {
    basicAuth: async (user, password) => user === 'bar' && password === 'foo';
};

The Token Authorization mechanism

This activate token authorization mechanism. The Auth-function will be executed while handling Proxy-Authentications.

Param Type Description
token String The client token.
session Session Object containing info/data about Tunnel

Note: It needs to return True/False or a Promise that resolves to boolean (isAuthenticated).

const options = {
    tokenAuth: async (token) => token === 'a-very-long-token';
};

Interception

This feature is in very early stage, and it's for web development only. The callbacks injectData & injectResponse could be used to intercept/spoof communication. These functions are executed with the data and session arguments.

Intercepting HTTPS

The boolean attribute intercept allows to break SSL-Communication between Source & Destination. This will activate Security-Alarm by most used browsers.

const [uaToSwitch, switchWith] = ['curl 7.79.1', 'a-fake-user-agent'];
const options = {
    intercept: true,
    injectData(data, session) {
        if (session.isHttps && data.toString().match(uaToSwitch)) {
            return Buffer.from(data.toString().replace(uaToSwitch, switchWith));
        }
        return data;
    },
};
curl -x localhost:8080 -k http://ifconfig.io/ua
curl 7.79.1

curl -x localhost:8080 -k https://ifconfig.me/ua
a-fake-user-agent

The keys Function

You can use this option to provide your own self-signed certificate.

If activated needs to return an Object {key:'String', cert:'String'} like native tls_connect_options.key & tls_connect_options.cert or false statement.

If no object is returned, then default keys will be used to update communication.

Param Type Description
session Session Object containing info/data about Tunnel.

Note: This function will be executed before TLS-Handshake.

Session-instance

The Session-instance is a Object containing info/data about Tunnel.

Use .getConnections() to get the current connections.

setInterval(() => {
    const connections = socratex.getConnections();
    console.log([new Date()], 'OPEN =>', Object.keys(connections).length)
}, 3000);

The connection items in the connections array include useful attributes/methods:

  • isHttps - Is session encrypted.
  • getTunnelStats() - Get Stats for this tunnel
  • getId() - Get Own ID-Session
  • isAuthenticated() - Is the session authenticated by user or not.
  • ... (More APIS tobe documented)

Dynamically routing

This example upstreams only requests for ifconfig.me to another proxy, for all other requests will be used localhost.

const options = {
    upstream(data, session) {
        return data.toString().includes('ifconfig.me')
            ? 'x.x.x.x:3128' : 'localhost';
    },
});

Testing with curl:

curl -x 127.0.0.1:8080 https://ifconfig.me
x.x.x.x

curl -x 127.0.0.1:8080 https://ifconfig.co
y.y.y.y

socratex's People

Contributors

leask avatar wy15 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

socratex's Issues

error,不支持的协议,请问是什么问题。

debian11系统 ,npm 9.8.0
使用没问题。日志存在报错。
安装方式Classic method
以下为报错部分的log
[SOCRATEX 2023-08-25T04:02:02.468Z] (15) ::ffff:89.45.6.117:39294 E: 00B85EB76A7F0000:error:0A0000C1:SSL routines:tls_post_process_client_hello:no shared cipher:../deps/openssl/openssl/ssl/statem/statem_srvr.c:2240:

[SOCRATEX 2023-08-25T04:02:04.522Z] (15) ::ffff:89.45.6.117:39322 E: 00B85EB76A7F0000:error:0A000102:SSL routines:tls_early_post_process_client_hello:unsupported protocol:../deps/openssl/openssl/ssl/statem/statem_srvr.c:1677:

[SOCRATEX 2023-08-25T04:02:06.554Z] (13) ::ffff:51.81.245.138:42790 E: Proxy Authorization Required
[SOCRATEX 2023-08-25T04:02:07.152Z] (15) ::ffff:51.81.245.138:42796 E: Proxy Authorization Required
[SOCRATEX 2023-08-25T04:02:07.289Z] (13) ::ffff:89.45.6.117:36594 E: read ECONNRESET
[SOCRATEX 2023-08-25T04:02:07.683Z] (13) ::ffff:89.45.6.117:36604 E: 00B85EB76A7F0000:error:0A0000C1:SSL routines:tls_early_post_process_client_hello:no shared cipher:../deps/openssl/openssl/ssl/statem/statem_srvr.c:1762:

[SOCRATEX 2023-08-25T04:02:07.729Z] (13) ::ffff:89.45.6.117:36618 E: 00B85EB76A7F0000:error:0A00006C:SSL routines:tls_parse_ctos_key_share:bad key share:../deps/openssl/openssl/ssl/statem/extensions_srvr.c:646:

errors when installing socratex

I tried to install socratex using modern method and classic method. I got the following errors in both ways.


node:events:491
throw er; // Unhandled 'error' event
^

Error: bind EADDRINUSE null:443
at listenOnPrimaryHandle (node:net:1842:18)
at rr (node:internal/cluster/child:163:12)
at Worker. (node:internal/cluster/child:113:7)
at process.onInternalMessage (node:internal/cluster/utils:49:5)
at process.emit (node:events:525:35)
at emit (node:internal/child_process:944:14)
at process.processTicksAndRejections (node:internal/process/task_queues:83:21)
Emitted 'error' event on Server instance at:
at listenOnPrimaryHandle (node:net:1843:21)
at rr (node:internal/cluster/child:163:12)
[... lines matching original stack trace ...]
at process.processTicksAndRejections (node:internal/process/task_queues:83:21) {
errno: -98,
code: 'EADDRINUSE',
syscall: 'bind',
address: null,
port: 443
}

Node.js v19.9.0
[2@49972] Worker exited with error code: 1.

It just repeated the above errors.

安全问题

  1. Token authentication 链接去掉 token 后仍可访问服务及日志输出等。
  2. Basic authentication 去掉用户名及密码仍可访问服务及日志输出等。

"Unexpected reserved word"

Following the instructions and got this error when trying to start the proxy:

file:///root/.npm/_npx/cf6c8ea642fc233a/node_modules/socratex/main.mjs:31
await utilitas.locate(utilitas.__(import.meta.url, 'package.json')); // keep 1st
^^^^^

SyntaxError: Unexpected reserved word
    at Loader.moduleStrategy (internal/modules/esm/translators.js:133:18)
    at async link (internal/modules/esm/module_job.js:42:21)

ssl证书无效

报错如下,似乎是没有自签证书还是客户端无法识别自签证书?运行端口是默认的80和443

[SOCRATEX 2023-03-30T20:19:53.963Z] (1) ::ffff:13.215.205.50:33982 E: 00789CEF337F0000:error:0A000416:SSL routines:ssl3_read_bytes:sslv3 alert certificate unknown:../deps/openssl/openssl/ssl/record/rec_layer_s3.c:1605:SSL alert number 46

无法代理telegram

你好,谢谢更新!很欣喜得知这个项目,使用非常简便!

目前唯一遇到的问题是无法代理telegram桌面软件的流量,报错如下:
E: 10404FB5FFFF0000:error:0A00009C:SSL routines:ssl3_get_record:http request:../deps/openssl/openssl/ssl/record/ssl3_record.c:345:
E: 10404FB5FFFF0000:error:0A00009B:SSL routines:ssl3_get_record:https proxy request:../deps/openssl/openssl/ssl/record/ssl3_record.c:349:

我猜测可能是因为telegram使用的是mtproxy加密协议,走tcp流量?

有办法支持吗?

期待解答,谢谢!

CA证书

这个是https代理,那除了域名指向IP外,需要配置好https证书?
如果需要,使用什么证书?

failed to set up socratex

I tried to deploy socratex following the instructions but got errors as below:

node:internal/process/esm_loader:100
internalBinding('errors').triggerUncaughtException(
^

AssertionError [ERR_ASSERTION]: Width must be between $ and 119.
at globalThis.assert (file:///home/dana_cheng/socratex/node_modules/utilitas/lib/horizon.mjs:15:22)
at Module.renderBox (file:///home/dana_cheng/socratex/node_modules/utilitas/lib/utilitas.mjs:534:5)
at initPrimary (file:///home/dana_cheng/socratex/main.mjs:146:30)
at runFunc (file:///home/dana_cheng/socratex/node_modules/utilitas/lib/callosum.mjs:27:52)
at Module.init (file:///home/dana_cheng/socratex/node_modules/utilitas/lib/callosum.mjs:121:15)
at async file:///home/dana_cheng/socratex/main.mjs:118:1 {
generatedMessage: false,
code: 'ERR_ASSERTION',
actual: false,
expected: true,
operator: '==',
status: undefined
}

Node.js v19.9.0

I tried both modern method and classic method. Same errors.

Also I tried to install it with Docker. I got nothing but this:
09350b3ddcbbd137b50681fe7119cb3198005627f8aabf90520b4fe62318374b

I tried to set it up on two Ubuntu VMs. I am stuck with the same error. Not sure what's missing?

不知道哪里出问题了

不知道哪里出问题了,log:
`E: 40F880BB3E7F0000:error:0A000416:SSL routines:ssl3_read_bytes:sslv3 alert certificate unknown:../deps/openssl/openssl/ssl/record/rec_layer_s3.c:1605:SSL alert number 46

E: 40F880BB3E7F0000:error:0A000416:SSL routines:ssl3_read_bytes:sslv3 alert certificate unknown:../deps/openssl/openssl/ssl/record/rec_layer_s3.c:1605:SSL alert number 46

E: 40F880BB3E7F0000:error:0A000102:SSL routines:tls_early_post_process_client_hello:unsupported protocol:../deps/openssl/openssl/ssl/statem/statem_srvr.c:1677:`

我注意到有一个类似的 issue 提出,但似乎并没有真正解决就被关闭了。

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.