Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 8 additions & 7 deletions .github/workflows/core.yml
Original file line number Diff line number Diff line change
Expand Up @@ -47,16 +47,17 @@ jobs:
- name: Run optimized unittest contracts
run: python -O -m unittest discover -s tests -p "test_*.py" -v

- name: Run pytest collection
run: python -m pytest -q
- name: Run pytest with coverage report
run: python -m pytest -q --cov=pproxy --cov-report=term-missing

- name: Lint contract and smoke tests
- name: Lint source and tests for syntax and undefined names
run: >-
python -m ruff check
tests/test_contracts.py
tests/test_websocket.py
tests/test_malformed_inputs.py
tests/test_leaks.py
pproxy tests
--select E9,F821

- name: Run proxy-level setup smoke benchmark
run: python tests/benchmark_setup.py --connections 10

- name: Build a wheel
run: python -m build --wheel
5 changes: 4 additions & 1 deletion .github/workflows/optional.yml
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,10 @@ jobs:
cache: pip

- name: Install the selected optional extra
run: python -m pip install ".[${{ matrix.extra }}]"
run: python -m pip install -c constraints/optional.txt ".[${{ matrix.extra }}]"

- name: Import the optional backend
run: python -c "import importlib; importlib.import_module('${{ matrix.module }}')"

- name: Run optional adapter contracts
run: python -m unittest tests.test_optional_adapters tests.test_optional_runtime -v
6 changes: 4 additions & 2 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ Usage

options:
-h, --help show this help message and exit
-l LISTEN tcp server uri (default: http+socks4+socks5://:8080/)
-l LISTEN tcp server uri (default: http+socks4+socks5://127.0.0.1:8080/)
-r RSERVER tcp remote server uri (default: direct)
-ul ULISTEN udp server setting uri (default: none)
-ur URSERVER udp remote server uri (default: direct)
Expand Down Expand Up @@ -351,6 +351,8 @@ URI Syntax

- *pproxy* ciphers have pure python implementations. Program will switch to C cipher if there is C implementation available within pycryptodome_. Otherwise, use pure python cipher.

- RC4, RC4-MD5, Blowfish-CFB, CAST5-CFB, and DES-CFB are retained for wire compatibility only. Selecting one emits a warning; new deployments should prefer an AEAD cipher such as chacha20-ietf-poly1305 or aes-256-gcm.

- AEAD ciphers use additional payload after each packet. The underlying protocol is different. Specifications: AEAD_.

- Some pure python ciphers (aes-256-cfb1-py) is quite slow, and is not recommended to use without PyPy speedup. Try install pycryptodome_ and use C version cipher instead.
Expand Down Expand Up @@ -694,7 +696,7 @@ Examples

$ pproxy -l http://:8080 -r ssh://remote_server.com/#login::private_key_path

SSH connection known_hosts feature is disabled by default.
SSH server host-key verification uses AsyncSSH's known_hosts configuration by default. For controlled compatibility tests only, add the explicit ``insecure`` URI modifier (for example, ``ssh+insecure://``).

- SSH jump

Expand Down
6 changes: 6 additions & 0 deletions constraints/optional.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Compatibility ranges exercised by the optional-backend CI jobs.
h2>=4.0,<5
asyncssh>=2.5.0,<3
aioquic>=0.9.7,<2
pycryptodome>=3.7.2,<4
uvloop>=0.13.0,<1
18 changes: 17 additions & 1 deletion pproxy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,16 @@

from . import server
from .config import ProxyConfig
from .errors import ProtocolError
from .errors import (
AuthenticationError,
BlockedConnection,
ConfigurationError,
ConnectionClosed,
ProtocolError,
RequestError,
UpstreamError,
UnsupportedProtocol,
)

ProxyFactory = Callable[[str], Any]
RuleFactory = Callable[[str], Callable[[str], Any]]
Expand All @@ -16,11 +25,18 @@

__all__ = [
"DIRECT",
"AuthenticationError",
"BlockedConnection",
"ConfigurationError",
"ConnectionClosed",
"Connection",
"ProtocolError",
"ProxyFactory",
"ProxyConfig",
"Rule",
"RuleFactory",
"Server",
"RequestError",
"UpstreamError",
"UnsupportedProtocol",
]
21 changes: 17 additions & 4 deletions pproxy/admin.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import json
import asyncio

from .runtime import ADMIN_BODY_LIMIT

config = {}
MAX_ADMIN_BODY = ADMIN_BODY_LIMIT


async def reply_http(reply, ver, code, content):
Expand All @@ -21,13 +24,23 @@ async def configs_handler(reply, **kwarg):
ver = kwarg.get('ver')

if method == 'GET':
data = {"argv": config['argv']}
data = {
"reload": bool(config.get('reload')),
"actions": ["reload"],
}
value = json.dumps(data).encode()
await reply_http(reply, ver, '200 OK', value)
elif method == 'POST':
config['argv'] = kwarg.get('content').decode().split(' ')
try:
request = json.loads(kwarg.get('content', b'{}'))
except (TypeError, UnicodeDecodeError, json.JSONDecodeError):
await reply_http(reply, ver, '400 Bad Request', b'invalid JSON')
return
if request != {'action': 'reload'}:
await reply_http(reply, ver, '400 Bad Request', b'unsupported action')
return
config['reload'] = True
data = {"result": 'ok'}
data = {"result": 'reload scheduled'}
value = json.dumps(data).encode()
await reply_http(reply, ver, '200 OK', value)
raise KeyboardInterrupt
Expand Down
6 changes: 4 additions & 2 deletions pproxy/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def main(args=None):
+ '\nSupported protocols: http,socks4,socks5,shadowsocks,shadowsocksr,redirect,pf,tunnel',
epilog=f'Online help: <{__url__}>',
)
parser.add_argument('-l', dest='listen', default=[], action='append', type=runtime.proxies_by_uri, help='tcp server uri (default: http+socks4+socks5://:8080/)')
parser.add_argument('-l', dest='listen', default=[], action='append', type=runtime.proxies_by_uri, help='tcp server uri (default: http+socks4+socks5://127.0.0.1:8080/)')
parser.add_argument('-r', dest='rserver', default=[], action='append', type=runtime.proxies_by_uri, help='tcp remote server uri (default: direct)')
parser.add_argument('-ul', dest='ulisten', default=[], action='append', type=runtime.proxies_by_uri, help='udp server setting uri (default: none)')
parser.add_argument('-ur', dest='urserver', default=[], action='append', type=runtime.proxies_by_uri, help='udp remote server uri (default: direct)')
Expand Down Expand Up @@ -48,7 +48,7 @@ def main(args=None):
asyncio.run(runtime.test_url(args.test, args.rserver))
return
if not args.listen and not args.ulisten:
args.listen.append(runtime.proxies_by_uri('http+socks4+socks5://:8080/'))
args.listen.append(runtime.proxies_by_uri(runtime.DEFAULT_LISTENER_URI))
args.httpget = {}
if args.pac:
pactext = 'function FindProxyForURL(u,h){' + (f'var b=/^(:?{args.block.__self__.pattern})$/i;if(b.test(h))return "";' if args.block else '')
Expand Down Expand Up @@ -82,6 +82,8 @@ def main(args=None):
admin.config.update({'argv': origin_argv, 'servers': servers, 'args': args, 'loop': loop})

def print_fn(option, bind=None):
if runtime.is_unauthenticated_wildcard(option):
print('WARNING: wildcard listener has no authentication; use loopback or configure credentials')
print('Serving on', (bind or option.bind), 'by', ','.join(i.name for i in option.protos) + ('(SSL)' if option.sslclient else ''), '({}{})'.format(option.cipher.name, ' ' + ','.join(i.name() for i in option.cipher.plugins) if option.cipher and option.cipher.plugins else '') if option.cipher else '')

for option in args.listen:
Expand Down
96 changes: 68 additions & 28 deletions pproxy/cipher.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import os, hashlib, hmac
import copy
import os
import hashlib
import hmac
import warnings
from . import transport
from .errors import require
from .errors import ProtocolError, require

LEGACY_CIPHERS = frozenset({'rc4', 'rc4-md5', 'bf-cfb', 'cast5-cfb', 'des-cfb'})

class BaseCipher(object):
PYTHON = False
Expand Down Expand Up @@ -68,8 +74,12 @@ def decrypt(self, s):
ret.extend(self.decrypt_and_verify(self._buffer[:self._declen], self._buffer[self._declen:self._declen+self.TAG_LENGTH]))
del self._buffer[:self._declen+self.TAG_LENGTH]
self._declen = None
except Exception:
return bytes([0])
# Crypto backends expose different exception classes; any failure must
# discard the packet state and fail closed.
except Exception as exc:
self._buffer.clear()
self._declen = None
raise ProtocolError('invalid AEAD packet') from exc
return bytes(ret)
def encrypt(self, s):
ret = bytearray()
Expand Down Expand Up @@ -241,10 +251,16 @@ def decrypt(self, data):
return self.pdecrypt(self.reader_cipher.decrypt(data))

def feed_data(self, data):
for decrypt in self.reader.decrypts:
data = decrypt(data)
if not data:
return
try:
for decrypt in self.reader.decrypts:
data = decrypt(data)
if not data:
return
except ProtocolError:
close = getattr(self.writer, 'close', None)
if close is not None:
close()
raise
self._raw_read(data)

def write(self, data):
Expand All @@ -267,6 +283,42 @@ def attach(self):
self.writer.write = self.write
return self.reader_cipher, self.writer_cipher

class CipherFactory:
"""Immutable cipher configuration that creates connection-local sessions."""

def __init__(self, cipher, key, name, ota=False, plugins=None):
self.cipher = cipher
self.key = key
self.name = name
self.ota = ota
self.legacy = name.removesuffix('-py') in LEGACY_CIPHERS
self.plugins = list(plugins or ())
self.datagram = PacketCipher(cipher, key, name)

def __call__(self, reader, writer, pdecrypt, pdecrypt2, pencrypt, pencrypt2):
return StreamCipherAdapter(
self.cipher,
self.key,
reader,
writer,
pdecrypt,
pdecrypt2,
pencrypt,
pencrypt2,
self.ota,
).attach()

def for_connection(self):
"""Return a session whose plugin state belongs to one connection."""
return CipherFactory(
self.cipher,
self.key,
self.name,
self.ota,
(copy.deepcopy(plugin) for plugin in self.plugins),
)


MAP = {cls.name(): cls for name, cls in globals().items() if name.endswith('_Cipher')}

def get_cipher(cipher_key):
Expand All @@ -281,7 +333,7 @@ def get_cipher(cipher_key):
try:
if __import__('Crypto').version_info < (3, 4):
cipher = None
except Exception:
except ImportError:
cipher = None
if cipher is None:
cipher = MAP_PY.get(cipher_name)
Expand All @@ -291,22 +343,10 @@ def get_cipher(cipher_key):
if cipher is None:
return 'this cipher needs library: "pip3 install pycryptodome"', None
cipher_name += ('-py' if cipher.PYTHON else '')
def apply_cipher(reader, writer, pdecrypt, pdecrypt2, pencrypt, pencrypt2):
return StreamCipherAdapter(
cipher,
key,
reader,
writer,
pdecrypt,
pdecrypt2,
pencrypt,
pencrypt2,
ota,
).attach()
apply_cipher.cipher = cipher
apply_cipher.key = key
apply_cipher.name = cipher_name
apply_cipher.ota = ota
apply_cipher.plugins = []
apply_cipher.datagram = PacketCipher(cipher, key, cipher_name)
return None, apply_cipher
if cipher_name.removesuffix('-py') in LEGACY_CIPHERS:
warnings.warn(
f'legacy cipher {cipher_name!r} is retained for compatibility; prefer an AEAD cipher',
UserWarning,
stacklevel=2,
)
return None, CipherFactory(cipher, key, cipher_name, ota)
8 changes: 4 additions & 4 deletions pproxy/cipherpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ def __init__(self, key):
buf = self.encrypt(buf)
self.p[i:i+2] = struct.unpack('>II', buf)
def encrypt(self, s):
s = data.to_bytes(8, 'big') if isinstance(s, int) else s
s = s.to_bytes(8, 'big') if isinstance(s, int) else s
sl, sr = struct.unpack('>II', s)
sl ^= self.p[0]
for i in self.p[1:17]:
Expand Down Expand Up @@ -361,7 +361,7 @@ def __init__(self, key):
e.append((e[i-8&0xf8|i+1&0x7]&0x7f)<<9|e[i-8&0xf8|i+2&0x7]>>7)
self.e = [e[i*6:i*6+6] for i in range(9)]
def encrypt(self, s):
s = data.to_bytes(8, 'big') if isinstance(s, int) else s
s = s.to_bytes(8, 'big') if isinstance(s, int) else s
M = lambda a,b: (a*b-(a*b>>16)+(a*b&0xffff<a*b>>16) if a else 1-b if b else 1-a)&0xffff
s0, s1, s2, s3 = struct.unpack('>4H', s)
for e in self.e[:-1]:
Expand All @@ -387,7 +387,7 @@ def __init__(self, key):
self.e.append((self.G((key0>>32)+(key1>>32)-kc), self.G(key0-key1+kc)))
key0, key1 = (key0, (key1<<8|key1>>56)&(1<<64)-1) if i&1 else ((key0<<56|key0>>8)&(1<<64)-1, key1)
def encrypt(self, s):
s = data.to_bytes(16, 'big') if isinstance(s, int) else s
s = s.to_bytes(16, 'big') if isinstance(s, int) else s
s0, s1, s2, s3 = struct.unpack('>4I', s)
for k0, k1 in self.e:
t0 = self.G(s2^k0^s3^k1)
Expand All @@ -413,7 +413,7 @@ def __init__(self, key):
e[i] = self.S[e[i+1]^e[i+len(key)]]
self.e = struct.unpack('<64H', e)
def encrypt(self, s):
s = data.to_bytes(8, 'big') if isinstance(s, int) else s
s = s.to_bytes(8, 'big') if isinstance(s, int) else s
s = list(struct.unpack('<4H', s))
for j in self.B:
s[j&3] = s[j&3]+self.e[j]+(s[j+3&3]&s[j+2&3])+(~s[j+3&3]&s[j+1&3])<<j%4*4//3+1&0xffff|(s[j&3]+self.e[j]+(s[j+3&3]&s[j+2&3])+(~s[j+3&3]&s[j+1&3])&0xffff)>>15-j%4*4//3 if j>=0 else s[j]+self.e[s[j+3]&0x3f]
Expand Down
1 change: 1 addition & 0 deletions pproxy/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ class ProxyConfig:
lbind: Any
sslclient: Any
sslserver: Any
insecure_host_key: bool = False

def as_kwargs(self) -> dict[str, Any]:
"""Return constructor arguments without exposing dataclass internals."""
Expand Down
31 changes: 31 additions & 0 deletions pproxy/errors.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,21 @@
"""Exceptions and validation helpers shared by protocol adapters."""


class ConnectionClosed(ConnectionError):
"""Raised when a peer closes before completing a protocol exchange."""

def __init__(self, message='Connection closed'):
super().__init__(message)


class ConfigurationError(ValueError):
"""Raised when a proxy URI or runtime option cannot be used."""


class UpstreamError(ConnectionError):
"""Raised when an upstream proxy or destination cannot be prepared."""


class ProtocolError(AssertionError):
"""Raised when an input does not satisfy a protocol contract.

Expand All @@ -9,6 +24,22 @@ class ProtocolError(AssertionError):
"""


class AuthenticationError(ProtocolError):
"""Raised when a peer fails protocol authentication."""


class RequestError(ProtocolError):
"""Raised when a peer sends an invalid or unsupported request."""


class UnsupportedProtocol(ProtocolError):
"""Raised when no configured protocol accepts the input."""


class BlockedConnection(ProtocolError):
"""Raised when a configured rule blocks a destination."""


def require(condition, message=""):
"""Raise :class:`ProtocolError` when *condition* is false."""
if not condition:
Expand Down
Loading