sockwave 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sockwave-0.1.0/LICENSE +19 -0
- sockwave-0.1.0/PKG-INFO +80 -0
- sockwave-0.1.0/README.md +62 -0
- sockwave-0.1.0/pyproject.toml +27 -0
- sockwave-0.1.0/src/sockwave/__init__.py +0 -0
- sockwave-0.1.0/src/sockwave/cli.py +630 -0
- sockwave-0.1.0/uv.lock +8 -0
sockwave-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
Copyright (c) 2026 Amir Shavit
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
4
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
5
|
+
in the Software without restriction, including without limitation the rights
|
|
6
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
7
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
8
|
+
furnished to do so, subject to the following conditions:
|
|
9
|
+
|
|
10
|
+
The above copyright notice and this permission notice shall be included in all
|
|
11
|
+
copies or substantial portions of the Software.
|
|
12
|
+
|
|
13
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
14
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
15
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
16
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
17
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
18
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
19
|
+
SOFTWARE.
|
sockwave-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: sockwave
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A lightweight TCP proxy and relay
|
|
5
|
+
Author: Amir Shavit
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
License-File: LICENSE
|
|
8
|
+
Keywords: networking,proxy,relay,tcp,tunneling
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Environment :: Console
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
14
|
+
Classifier: Topic :: Internet
|
|
15
|
+
Classifier: Topic :: System :: Networking
|
|
16
|
+
Requires-Python: >=3.13
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
|
|
19
|
+
# sockwave
|
|
20
|
+
|
|
21
|
+
Expose a TCP service through a relay, with end-to-end encryption. Single file, zero dependencies, pure `asyncio`.
|
|
22
|
+
|
|
23
|
+
Run a tiny relay on any public host, and sockwave lets you reach a service behind NAT or a firewall (SSH, a database, a web app) without opening inbound ports. The relay only forwards bytes. It never sees your traffic in the clear.
|
|
24
|
+
|
|
25
|
+
## Features
|
|
26
|
+
|
|
27
|
+
- **End-to-end encrypted**: TLS 1.3 with a pre-shared key derived from your secret. No certificates to manage.
|
|
28
|
+
- **Relay-blind**: the relay pairs connections and pipes ciphertext.
|
|
29
|
+
- **Self-healing**: automatic reconnect with exponential backoff, plus heartbeats to detect dead links.
|
|
30
|
+
- **Proper half-close**: clean EOF handling in both directions.
|
|
31
|
+
- **One file, standard library only**.
|
|
32
|
+
|
|
33
|
+
## Requirements
|
|
34
|
+
|
|
35
|
+
Python 3.13+ (for TLS-PSK support in `ssl`) and optionally [uv](https://docs.astral.sh/uv/), which runs sockwave without a manual install.
|
|
36
|
+
|
|
37
|
+
## Usage
|
|
38
|
+
|
|
39
|
+
```
|
|
40
|
+
uvx sockwave keygen
|
|
41
|
+
uvx sockwave relay HOST:PORT
|
|
42
|
+
uvx sockwave connect HOST:PORT through HOST:PORT key KEY
|
|
43
|
+
uvx sockwave listen HOST:PORT through HOST:PORT key KEY
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Example: reach SSH on a machine behind NAT.
|
|
47
|
+
|
|
48
|
+
```sh
|
|
49
|
+
# 0. Generate a shared key: KEY=$(uvx sockwave keygen)
|
|
50
|
+
|
|
51
|
+
# 1. On a public host: run the relay
|
|
52
|
+
uvx sockwave relay 0.0.0.0:9000
|
|
53
|
+
|
|
54
|
+
# 2. On the machine with the service: publish it
|
|
55
|
+
uvx sockwave connect 127.0.0.1:22 through relay.example.com:9000 key "$KEY"
|
|
56
|
+
|
|
57
|
+
# 3. On your laptop: listen locally
|
|
58
|
+
uvx sockwave listen 127.0.0.1:2222 through relay.example.com:9000 key "$KEY"
|
|
59
|
+
|
|
60
|
+
ssh -p 2222 localhost
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Generate a key once and share it between the `connect` and `listen` sides:
|
|
64
|
+
|
|
65
|
+
```sh
|
|
66
|
+
uvx sockwave keygen
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Keys must be random (at least 128 bits), so use `keygen` rather than choosing your own.
|
|
70
|
+
|
|
71
|
+
## How it works
|
|
72
|
+
|
|
73
|
+
1. `connect` registers with the relay under an ID derived from the key.
|
|
74
|
+
2. `listen` accepts local connections and asks the relay to open one to the matching connector.
|
|
75
|
+
3. The connector dials the target and both sides meet at the relay.
|
|
76
|
+
4. The two ends upgrade the link to TLS 1.3 using a key-derived PSK, then tunnel data through it.
|
|
77
|
+
|
|
78
|
+
## License
|
|
79
|
+
|
|
80
|
+
MIT. See [LICENSE](LICENSE).
|
sockwave-0.1.0/README.md
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# sockwave
|
|
2
|
+
|
|
3
|
+
Expose a TCP service through a relay, with end-to-end encryption. Single file, zero dependencies, pure `asyncio`.
|
|
4
|
+
|
|
5
|
+
Run a tiny relay on any public host, and sockwave lets you reach a service behind NAT or a firewall (SSH, a database, a web app) without opening inbound ports. The relay only forwards bytes. It never sees your traffic in the clear.
|
|
6
|
+
|
|
7
|
+
## Features
|
|
8
|
+
|
|
9
|
+
- **End-to-end encrypted**: TLS 1.3 with a pre-shared key derived from your secret. No certificates to manage.
|
|
10
|
+
- **Relay-blind**: the relay pairs connections and pipes ciphertext.
|
|
11
|
+
- **Self-healing**: automatic reconnect with exponential backoff, plus heartbeats to detect dead links.
|
|
12
|
+
- **Proper half-close**: clean EOF handling in both directions.
|
|
13
|
+
- **One file, standard library only**.
|
|
14
|
+
|
|
15
|
+
## Requirements
|
|
16
|
+
|
|
17
|
+
Python 3.13+ (for TLS-PSK support in `ssl`) and optionally [uv](https://docs.astral.sh/uv/), which runs sockwave without a manual install.
|
|
18
|
+
|
|
19
|
+
## Usage
|
|
20
|
+
|
|
21
|
+
```
|
|
22
|
+
uvx sockwave keygen
|
|
23
|
+
uvx sockwave relay HOST:PORT
|
|
24
|
+
uvx sockwave connect HOST:PORT through HOST:PORT key KEY
|
|
25
|
+
uvx sockwave listen HOST:PORT through HOST:PORT key KEY
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Example: reach SSH on a machine behind NAT.
|
|
29
|
+
|
|
30
|
+
```sh
|
|
31
|
+
# 0. Generate a shared key: KEY=$(uvx sockwave keygen)
|
|
32
|
+
|
|
33
|
+
# 1. On a public host: run the relay
|
|
34
|
+
uvx sockwave relay 0.0.0.0:9000
|
|
35
|
+
|
|
36
|
+
# 2. On the machine with the service: publish it
|
|
37
|
+
uvx sockwave connect 127.0.0.1:22 through relay.example.com:9000 key "$KEY"
|
|
38
|
+
|
|
39
|
+
# 3. On your laptop: listen locally
|
|
40
|
+
uvx sockwave listen 127.0.0.1:2222 through relay.example.com:9000 key "$KEY"
|
|
41
|
+
|
|
42
|
+
ssh -p 2222 localhost
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Generate a key once and share it between the `connect` and `listen` sides:
|
|
46
|
+
|
|
47
|
+
```sh
|
|
48
|
+
uvx sockwave keygen
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Keys must be random (at least 128 bits), so use `keygen` rather than choosing your own.
|
|
52
|
+
|
|
53
|
+
## How it works
|
|
54
|
+
|
|
55
|
+
1. `connect` registers with the relay under an ID derived from the key.
|
|
56
|
+
2. `listen` accepts local connections and asks the relay to open one to the matching connector.
|
|
57
|
+
3. The connector dials the target and both sides meet at the relay.
|
|
58
|
+
4. The two ends upgrade the link to TLS 1.3 using a key-derived PSK, then tunnel data through it.
|
|
59
|
+
|
|
60
|
+
## License
|
|
61
|
+
|
|
62
|
+
MIT. See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "sockwave"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "A lightweight TCP proxy and relay"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
requires-python = ">=3.13"
|
|
8
|
+
authors = [
|
|
9
|
+
{ name = "Amir Shavit" },
|
|
10
|
+
]
|
|
11
|
+
keywords = ["tcp", "proxy", "relay", "tunneling", "networking"]
|
|
12
|
+
classifiers = [
|
|
13
|
+
"Development Status :: 3 - Alpha",
|
|
14
|
+
"Environment :: Console",
|
|
15
|
+
"Operating System :: OS Independent",
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
18
|
+
"Topic :: Internet",
|
|
19
|
+
"Topic :: System :: Networking",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
[project.scripts]
|
|
23
|
+
sockwave = "sockwave.cli:cli"
|
|
24
|
+
|
|
25
|
+
[build-system]
|
|
26
|
+
requires = ["hatchling"]
|
|
27
|
+
build-backend = "hatchling.build"
|
|
File without changes
|
|
@@ -0,0 +1,630 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import base64
|
|
3
|
+
import hashlib
|
|
4
|
+
import logging
|
|
5
|
+
import secrets
|
|
6
|
+
import ssl
|
|
7
|
+
import struct
|
|
8
|
+
import sys
|
|
9
|
+
from enum import IntEnum
|
|
10
|
+
|
|
11
|
+
HANDSHAKE_TIMEOUT = 10
|
|
12
|
+
PING_INTERVAL = 30
|
|
13
|
+
PING_TIMEOUT = 10
|
|
14
|
+
CHUNK = 65535
|
|
15
|
+
MAX_MESSAGE = 64
|
|
16
|
+
RETRY_MIN = 1
|
|
17
|
+
RETRY_MAX = 30
|
|
18
|
+
MIN_KEY_BYTES = 16
|
|
19
|
+
|
|
20
|
+
log = logging.getLogger("sockwave")
|
|
21
|
+
connectors: dict[bytes, "StreamWriter"] = {}
|
|
22
|
+
pending: dict[int, tuple[bytes, asyncio.Future]] = {}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Message(IntEnum):
|
|
26
|
+
CONTROL = 1
|
|
27
|
+
OPEN = 2
|
|
28
|
+
DATA = 3
|
|
29
|
+
FAIL = 4
|
|
30
|
+
REQUEST = 5
|
|
31
|
+
OK = 6
|
|
32
|
+
ERROR = 7
|
|
33
|
+
PING = 8
|
|
34
|
+
PONG = 9
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class Error(IntEnum):
|
|
38
|
+
INVALID = 1
|
|
39
|
+
DUPLICATE_KEY = 2
|
|
40
|
+
UNKNOWN_KEY = 3
|
|
41
|
+
TIMEOUT = 4
|
|
42
|
+
TARGET_UNAVAILABLE = 5
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class RelayError(Exception):
|
|
46
|
+
pass
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class StreamProtocol(asyncio.Protocol):
|
|
50
|
+
def __init__(self, reader: asyncio.StreamReader):
|
|
51
|
+
self.reader = reader
|
|
52
|
+
self.transport = None
|
|
53
|
+
self.exception = None
|
|
54
|
+
self.paused = asyncio.Event()
|
|
55
|
+
self.paused.set()
|
|
56
|
+
|
|
57
|
+
def connection_made(self, transport):
|
|
58
|
+
self.transport = transport
|
|
59
|
+
|
|
60
|
+
def data_received(self, data: bytes):
|
|
61
|
+
self.reader.feed_data(data)
|
|
62
|
+
|
|
63
|
+
def eof_received(self):
|
|
64
|
+
self.reader.feed_eof()
|
|
65
|
+
return False
|
|
66
|
+
|
|
67
|
+
def connection_lost(self, exc):
|
|
68
|
+
self.exception = exc
|
|
69
|
+
if exc:
|
|
70
|
+
self.reader.set_exception(exc)
|
|
71
|
+
else:
|
|
72
|
+
self.reader.feed_eof()
|
|
73
|
+
self.paused.set()
|
|
74
|
+
|
|
75
|
+
def pause_writing(self):
|
|
76
|
+
self.paused.clear()
|
|
77
|
+
|
|
78
|
+
def resume_writing(self):
|
|
79
|
+
self.paused.set()
|
|
80
|
+
|
|
81
|
+
async def drain(self):
|
|
82
|
+
await self.paused.wait()
|
|
83
|
+
if self.exception:
|
|
84
|
+
raise ConnectionError("connection lost") from self.exception
|
|
85
|
+
|
|
86
|
+
def set_transport(self, transport):
|
|
87
|
+
self.transport = transport
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class StreamWriter:
|
|
91
|
+
def __init__(self, protocol: StreamProtocol):
|
|
92
|
+
self.protocol = protocol
|
|
93
|
+
|
|
94
|
+
@property
|
|
95
|
+
def transport(self):
|
|
96
|
+
return self.protocol.transport
|
|
97
|
+
|
|
98
|
+
def write(self, data: bytes):
|
|
99
|
+
self.transport.write(data)
|
|
100
|
+
|
|
101
|
+
async def drain(self):
|
|
102
|
+
await self.protocol.drain()
|
|
103
|
+
|
|
104
|
+
def close(self):
|
|
105
|
+
if self.transport is not None and not self.transport.is_closing():
|
|
106
|
+
self.transport.close()
|
|
107
|
+
|
|
108
|
+
def is_closing(self) -> bool:
|
|
109
|
+
return self.transport is None or self.transport.is_closing()
|
|
110
|
+
|
|
111
|
+
def can_write_eof(self) -> bool:
|
|
112
|
+
return self.transport is not None and self.transport.can_write_eof()
|
|
113
|
+
|
|
114
|
+
def write_eof(self):
|
|
115
|
+
if self.transport is not None:
|
|
116
|
+
self.transport.write_eof()
|
|
117
|
+
|
|
118
|
+
def get_extra_info(self, name: str, default=None):
|
|
119
|
+
if self.transport is None:
|
|
120
|
+
return default
|
|
121
|
+
return self.transport.get_extra_info(name, default)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
async def open_connection(host: str, port: int):
|
|
125
|
+
loop = asyncio.get_running_loop()
|
|
126
|
+
reader = asyncio.StreamReader()
|
|
127
|
+
protocol = StreamProtocol(reader)
|
|
128
|
+
await loop.create_connection(lambda: protocol, host, port)
|
|
129
|
+
return reader, StreamWriter(protocol)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def addr(text: str) -> tuple[str, int]:
|
|
133
|
+
host, sep, port = text.rpartition(":")
|
|
134
|
+
host = host.strip("[]")
|
|
135
|
+
if not sep or not host:
|
|
136
|
+
raise ValueError(f"invalid address: {text}")
|
|
137
|
+
try:
|
|
138
|
+
port = int(port)
|
|
139
|
+
except ValueError as e:
|
|
140
|
+
raise ValueError(f"invalid port: {port}") from e
|
|
141
|
+
if not 0 <= port <= 65535:
|
|
142
|
+
raise ValueError(f"invalid port: {port}")
|
|
143
|
+
return host, port
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def close(*conns):
|
|
147
|
+
for conn in conns:
|
|
148
|
+
if conn:
|
|
149
|
+
try:
|
|
150
|
+
conn[1].close()
|
|
151
|
+
except Exception:
|
|
152
|
+
pass
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def check_key(key: str) -> None:
|
|
156
|
+
try:
|
|
157
|
+
raw = base64.urlsafe_b64decode(key + "=" * (-len(key) % 4))
|
|
158
|
+
except ValueError:
|
|
159
|
+
raw = b""
|
|
160
|
+
if len(raw) < MIN_KEY_BYTES:
|
|
161
|
+
raise ValueError("invalid key; generate one with: sockwave keygen")
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def digest(label: bytes, key: str) -> bytes:
|
|
165
|
+
return hashlib.sha256(label + key.encode()).digest()
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
async def send_message(w, msg: Message, payload: bytes = b""):
|
|
169
|
+
if len(payload) > MAX_MESSAGE:
|
|
170
|
+
raise ValueError("payload too large")
|
|
171
|
+
w.write(struct.pack("!BI", int(msg), len(payload)) + payload)
|
|
172
|
+
await w.drain()
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
async def send_error(w, code: Error):
|
|
176
|
+
await send_message(w, Message.ERROR, bytes([int(code)]))
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
async def read_message(r) -> tuple[Message, bytes]:
|
|
180
|
+
header = await r.readexactly(5)
|
|
181
|
+
msg, length = struct.unpack("!BI", header)
|
|
182
|
+
if length > MAX_MESSAGE:
|
|
183
|
+
raise ValueError("message too large")
|
|
184
|
+
payload = await r.readexactly(length)
|
|
185
|
+
try:
|
|
186
|
+
return Message(msg), payload
|
|
187
|
+
except ValueError as e:
|
|
188
|
+
raise ValueError(f"unknown message type: {msg}") from e
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
async def response(r):
|
|
192
|
+
msg, payload = await read_message(r)
|
|
193
|
+
if msg == Message.ERROR:
|
|
194
|
+
if len(payload) != 1:
|
|
195
|
+
raise ValueError("invalid error response")
|
|
196
|
+
try:
|
|
197
|
+
code = Error(payload[0])
|
|
198
|
+
except ValueError as e:
|
|
199
|
+
raise ValueError(f"unknown error code: {payload[0]}") from e
|
|
200
|
+
raise RelayError(code.name.lower())
|
|
201
|
+
if msg != Message.OK:
|
|
202
|
+
raise ValueError(f"unexpected relay response: {msg.name}")
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
async def request(relay: tuple[str, int], msg: Message, payload: bytes):
|
|
206
|
+
conn = await open_connection(*relay)
|
|
207
|
+
try:
|
|
208
|
+
await send_message(conn[1], msg, payload)
|
|
209
|
+
except BaseException:
|
|
210
|
+
close(conn)
|
|
211
|
+
raise
|
|
212
|
+
return conn
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def context(key: str, server: bool) -> ssl.SSLContext:
|
|
216
|
+
psk = digest(b"psk", key)
|
|
217
|
+
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER if server else ssl.PROTOCOL_TLS_CLIENT)
|
|
218
|
+
ctx.minimum_version = ssl.TLSVersion.TLSv1_3
|
|
219
|
+
ctx.check_hostname = False
|
|
220
|
+
ctx.verify_mode = ssl.CERT_NONE
|
|
221
|
+
if server:
|
|
222
|
+
|
|
223
|
+
def server_cb(identity: str | None) -> bytes | None:
|
|
224
|
+
if identity is not None and identity != "sockwave":
|
|
225
|
+
return None
|
|
226
|
+
return psk
|
|
227
|
+
|
|
228
|
+
ctx.set_psk_server_callback(server_cb)
|
|
229
|
+
else:
|
|
230
|
+
ctx.set_psk_client_callback(lambda hint: ("sockwave", psk))
|
|
231
|
+
return ctx
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
async def secure(conn, key: str, server: bool):
|
|
235
|
+
r, w = conn
|
|
236
|
+
protocol = w.protocol
|
|
237
|
+
loop = asyncio.get_running_loop()
|
|
238
|
+
|
|
239
|
+
await w.drain()
|
|
240
|
+
|
|
241
|
+
async with asyncio.timeout(HANDSHAKE_TIMEOUT):
|
|
242
|
+
transport = await loop.start_tls(
|
|
243
|
+
w.transport,
|
|
244
|
+
protocol,
|
|
245
|
+
context(key, server),
|
|
246
|
+
server_side=server,
|
|
247
|
+
ssl_handshake_timeout=HANDSHAKE_TIMEOUT,
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
if transport is None:
|
|
251
|
+
raise ConnectionError("TLS upgrade failed")
|
|
252
|
+
|
|
253
|
+
protocol.set_transport(transport)
|
|
254
|
+
return r, w
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
async def tunnel(local, remote):
|
|
258
|
+
(lr, lw), (rr, rw) = local, remote
|
|
259
|
+
|
|
260
|
+
async def up():
|
|
261
|
+
try:
|
|
262
|
+
while data := await lr.read(CHUNK):
|
|
263
|
+
log.debug("UP: %d bytes", len(data))
|
|
264
|
+
rw.write(len(data).to_bytes(2, "big") + data)
|
|
265
|
+
await rw.drain()
|
|
266
|
+
log.info("UP: local EOF")
|
|
267
|
+
rw.write(b"\0\0")
|
|
268
|
+
await rw.drain()
|
|
269
|
+
except (ConnectionError, OSError, asyncio.CancelledError):
|
|
270
|
+
raise
|
|
271
|
+
|
|
272
|
+
async def down(up_task: asyncio.Task):
|
|
273
|
+
try:
|
|
274
|
+
while True:
|
|
275
|
+
try:
|
|
276
|
+
header = await rr.readexactly(2)
|
|
277
|
+
except asyncio.IncompleteReadError as e:
|
|
278
|
+
if e.partial:
|
|
279
|
+
raise ValueError("truncated frame header") from e
|
|
280
|
+
log.info("DOWN: remote EOF")
|
|
281
|
+
up_task.cancel()
|
|
282
|
+
return
|
|
283
|
+
|
|
284
|
+
size = int.from_bytes(header, "big")
|
|
285
|
+
if size == 0:
|
|
286
|
+
log.info("DOWN: remote half-close")
|
|
287
|
+
if lw.can_write_eof():
|
|
288
|
+
lw.write_eof()
|
|
289
|
+
return
|
|
290
|
+
|
|
291
|
+
if size > CHUNK:
|
|
292
|
+
raise ValueError(f"frame too large: {size}")
|
|
293
|
+
|
|
294
|
+
data = await rr.readexactly(size)
|
|
295
|
+
log.debug("DOWN: %d bytes", len(data))
|
|
296
|
+
lw.write(data)
|
|
297
|
+
await lw.drain()
|
|
298
|
+
except (ConnectionError, OSError, asyncio.CancelledError):
|
|
299
|
+
up_task.cancel()
|
|
300
|
+
raise
|
|
301
|
+
|
|
302
|
+
async with asyncio.TaskGroup() as tg:
|
|
303
|
+
up_task = tg.create_task(up())
|
|
304
|
+
tg.create_task(down(up_task))
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
async def bridge(local, relay: tuple[str, int], msg: Message, payload: bytes, key: str):
|
|
308
|
+
server = msg == Message.DATA
|
|
309
|
+
remote = None
|
|
310
|
+
tag = payload[:4].hex() if len(payload) >= 4 else "????"
|
|
311
|
+
try:
|
|
312
|
+
remote = await request(relay, msg, payload)
|
|
313
|
+
if not server:
|
|
314
|
+
await response(remote[0])
|
|
315
|
+
remote = await secure(remote, key, server)
|
|
316
|
+
log.info("[%s] tunnel up", tag)
|
|
317
|
+
await tunnel(local, remote)
|
|
318
|
+
except Exception as e:
|
|
319
|
+
log.warning("[%s] %s failed: %r", tag, msg.name.lower(), e)
|
|
320
|
+
finally:
|
|
321
|
+
close(local, remote)
|
|
322
|
+
log.info("[%s] tunnel closed", tag)
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
async def pipe(a, b):
|
|
326
|
+
async def pump(name: str, r, w):
|
|
327
|
+
try:
|
|
328
|
+
while data := await r.read(CHUNK):
|
|
329
|
+
log.debug("relay %s: forwarding %d bytes", name, len(data))
|
|
330
|
+
w.write(data)
|
|
331
|
+
await w.drain()
|
|
332
|
+
log.debug("relay %s: EOF", name)
|
|
333
|
+
if w.can_write_eof():
|
|
334
|
+
try:
|
|
335
|
+
w.write_eof()
|
|
336
|
+
except OSError:
|
|
337
|
+
pass
|
|
338
|
+
except OSError as e:
|
|
339
|
+
log.debug("relay %s: peer disconnected: %r", name, e)
|
|
340
|
+
close(a, b)
|
|
341
|
+
except asyncio.CancelledError:
|
|
342
|
+
raise
|
|
343
|
+
|
|
344
|
+
async with asyncio.TaskGroup() as tg:
|
|
345
|
+
tg.create_task(pump("listener->connector", a[0], b[1]))
|
|
346
|
+
tg.create_task(pump("connector->listener", b[0], a[1]))
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def claim(kid: bytes, cid: int):
|
|
350
|
+
entry = pending.get(cid)
|
|
351
|
+
if entry is None:
|
|
352
|
+
return None
|
|
353
|
+
owner, fut = entry
|
|
354
|
+
if owner == kid and not fut.done():
|
|
355
|
+
pending.pop(cid, None)
|
|
356
|
+
return fut
|
|
357
|
+
return None
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
async def control(kid: bytes, r, w):
|
|
361
|
+
connectors[kid] = w
|
|
362
|
+
log.info("[%s] connector registered", kid[:4].hex())
|
|
363
|
+
try:
|
|
364
|
+
await send_message(w, Message.OK)
|
|
365
|
+
while True:
|
|
366
|
+
msg, payload = await read_message(r)
|
|
367
|
+
if msg == Message.PING and not payload:
|
|
368
|
+
await send_message(w, Message.PONG)
|
|
369
|
+
else:
|
|
370
|
+
raise ValueError(f"invalid control message: {msg.name}")
|
|
371
|
+
finally:
|
|
372
|
+
if connectors.get(kid) is w:
|
|
373
|
+
del connectors[kid]
|
|
374
|
+
|
|
375
|
+
for cid, (owner, fut) in list(pending.items()):
|
|
376
|
+
if owner == kid and not fut.done():
|
|
377
|
+
pending.pop(cid, None)
|
|
378
|
+
fut.set_exception(ConnectionError("connector disconnected"))
|
|
379
|
+
|
|
380
|
+
log.info("[%s] connector unregistered", kid[:4].hex())
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
async def handle_open(kid: bytes, r, w):
|
|
384
|
+
connector = connectors.get(kid)
|
|
385
|
+
if connector is None:
|
|
386
|
+
await send_error(w, Error.UNKNOWN_KEY)
|
|
387
|
+
return
|
|
388
|
+
|
|
389
|
+
cid = secrets.randbits(64)
|
|
390
|
+
loop = asyncio.get_running_loop()
|
|
391
|
+
fut = loop.create_future()
|
|
392
|
+
pending[cid] = (kid, fut)
|
|
393
|
+
|
|
394
|
+
try:
|
|
395
|
+
await send_message(connector, Message.REQUEST, cid.to_bytes(8, "big"))
|
|
396
|
+
|
|
397
|
+
async with asyncio.timeout(HANDSHAKE_TIMEOUT):
|
|
398
|
+
peer = await fut
|
|
399
|
+
except TimeoutError:
|
|
400
|
+
pending.pop(cid, None)
|
|
401
|
+
if not fut.done():
|
|
402
|
+
fut.cancel()
|
|
403
|
+
await send_error(w, Error.TIMEOUT)
|
|
404
|
+
return
|
|
405
|
+
except ConnectionError:
|
|
406
|
+
pending.pop(cid, None)
|
|
407
|
+
if not fut.done():
|
|
408
|
+
fut.cancel()
|
|
409
|
+
await send_error(w, Error.TARGET_UNAVAILABLE)
|
|
410
|
+
return
|
|
411
|
+
except BaseException:
|
|
412
|
+
pending.pop(cid, None)
|
|
413
|
+
if not fut.done():
|
|
414
|
+
fut.cancel()
|
|
415
|
+
raise
|
|
416
|
+
else:
|
|
417
|
+
pending.pop(cid, None)
|
|
418
|
+
|
|
419
|
+
log.info("[%s] paired id=%x", kid[:4].hex(), cid)
|
|
420
|
+
|
|
421
|
+
try:
|
|
422
|
+
await send_message(w, Message.OK)
|
|
423
|
+
await pipe((r, w), peer)
|
|
424
|
+
finally:
|
|
425
|
+
close(peer)
|
|
426
|
+
log.info("[%s] closed id=%x", kid[:4].hex(), cid)
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
async def relay_handler(r, w):
|
|
430
|
+
peer = w.get_extra_info("peername")
|
|
431
|
+
keep = False
|
|
432
|
+
|
|
433
|
+
try:
|
|
434
|
+
async with asyncio.timeout(HANDSHAKE_TIMEOUT):
|
|
435
|
+
msg, payload = await read_message(r)
|
|
436
|
+
|
|
437
|
+
if len(payload) < 32:
|
|
438
|
+
await send_error(w, Error.INVALID)
|
|
439
|
+
return
|
|
440
|
+
|
|
441
|
+
kid, rest = payload[:32], payload[32:]
|
|
442
|
+
|
|
443
|
+
match msg, len(kid), len(rest):
|
|
444
|
+
case Message.CONTROL, 32, 0:
|
|
445
|
+
if kid in connectors:
|
|
446
|
+
await send_error(w, Error.DUPLICATE_KEY)
|
|
447
|
+
else:
|
|
448
|
+
await control(kid, r, w)
|
|
449
|
+
|
|
450
|
+
case Message.OPEN, 32, 0:
|
|
451
|
+
await handle_open(kid, r, w)
|
|
452
|
+
|
|
453
|
+
case Message.DATA, 32, 8:
|
|
454
|
+
cid = int.from_bytes(rest, "big")
|
|
455
|
+
if fut := claim(kid, cid):
|
|
456
|
+
fut.set_result((r, w))
|
|
457
|
+
keep = True
|
|
458
|
+
else:
|
|
459
|
+
await send_error(w, Error.INVALID)
|
|
460
|
+
|
|
461
|
+
case Message.FAIL, 32, 8:
|
|
462
|
+
cid = int.from_bytes(rest, "big")
|
|
463
|
+
if fut := claim(kid, cid):
|
|
464
|
+
fut.set_exception(ConnectionError("target unavailable"))
|
|
465
|
+
await send_message(w, Message.OK)
|
|
466
|
+
else:
|
|
467
|
+
await send_error(w, Error.INVALID)
|
|
468
|
+
|
|
469
|
+
case _:
|
|
470
|
+
await send_error(w, Error.INVALID)
|
|
471
|
+
|
|
472
|
+
except asyncio.IncompleteReadError as e:
|
|
473
|
+
if e.partial:
|
|
474
|
+
log.warning("connection from %s: incomplete message", peer)
|
|
475
|
+
else:
|
|
476
|
+
log.debug("connection from %s: disconnected", peer)
|
|
477
|
+
|
|
478
|
+
except (ConnectionResetError, BrokenPipeError) as e:
|
|
479
|
+
log.debug("connection from %s: disconnected: %r", peer, e)
|
|
480
|
+
|
|
481
|
+
except Exception as e:
|
|
482
|
+
log.warning("connection from %s failed: %r", peer, e)
|
|
483
|
+
|
|
484
|
+
finally:
|
|
485
|
+
if not keep:
|
|
486
|
+
try:
|
|
487
|
+
w.close()
|
|
488
|
+
except Exception:
|
|
489
|
+
pass
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
async def run_relay(bind: tuple[str, int]):
|
|
493
|
+
server = await asyncio.start_server(relay_handler, *bind)
|
|
494
|
+
log.info("relay listening on %s:%d", *bind)
|
|
495
|
+
|
|
496
|
+
async with server:
|
|
497
|
+
await server.serve_forever()
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
async def run_connect(target: tuple[str, int], relay: tuple[str, int], key: str):
|
|
501
|
+
check_key(key)
|
|
502
|
+
|
|
503
|
+
kid = digest(b"id", key)
|
|
504
|
+
tasks: set[asyncio.Task] = set()
|
|
505
|
+
delay = RETRY_MIN
|
|
506
|
+
|
|
507
|
+
async def handle(cid: bytes):
|
|
508
|
+
tag = cid.hex()[:8]
|
|
509
|
+
try:
|
|
510
|
+
local = await open_connection(*target)
|
|
511
|
+
except OSError as e:
|
|
512
|
+
log.warning("[%s] cannot reach target %s:%d: %r", tag, *target, e)
|
|
513
|
+
conn = None
|
|
514
|
+
try:
|
|
515
|
+
conn = await request(relay, Message.FAIL, kid + cid)
|
|
516
|
+
await response(conn[0])
|
|
517
|
+
except Exception as e2:
|
|
518
|
+
log.warning("[%s] fail notice failed: %r", tag, e2)
|
|
519
|
+
finally:
|
|
520
|
+
close(conn)
|
|
521
|
+
return
|
|
522
|
+
|
|
523
|
+
await bridge(local, relay, Message.DATA, kid + cid, key)
|
|
524
|
+
|
|
525
|
+
async def heartbeat(w, pong: asyncio.Event):
|
|
526
|
+
while True:
|
|
527
|
+
await asyncio.sleep(PING_INTERVAL)
|
|
528
|
+
pong.clear()
|
|
529
|
+
await send_message(w, Message.PING)
|
|
530
|
+
try:
|
|
531
|
+
await asyncio.wait_for(pong.wait(), timeout=PING_TIMEOUT)
|
|
532
|
+
except TimeoutError:
|
|
533
|
+
raise ConnectionError(
|
|
534
|
+
f"relay heartbeat timed out after {PING_TIMEOUT}s"
|
|
535
|
+
) from None
|
|
536
|
+
|
|
537
|
+
async def receive(r, pong: asyncio.Event):
|
|
538
|
+
while True:
|
|
539
|
+
msg, payload = await read_message(r)
|
|
540
|
+
if msg == Message.PONG and not payload:
|
|
541
|
+
pong.set()
|
|
542
|
+
continue
|
|
543
|
+
if msg != Message.REQUEST or len(payload) != 8:
|
|
544
|
+
raise ValueError(f"invalid control message: {msg.name}")
|
|
545
|
+
task = asyncio.create_task(handle(payload))
|
|
546
|
+
tasks.add(task)
|
|
547
|
+
task.add_done_callback(tasks.discard)
|
|
548
|
+
|
|
549
|
+
while True:
|
|
550
|
+
conn = None
|
|
551
|
+
try:
|
|
552
|
+
conn = await request(relay, Message.CONTROL, kid)
|
|
553
|
+
await response(conn[0])
|
|
554
|
+
log.info("connected to relay %s:%d", *relay)
|
|
555
|
+
delay = RETRY_MIN
|
|
556
|
+
|
|
557
|
+
pong = asyncio.Event()
|
|
558
|
+
async with asyncio.TaskGroup() as tg:
|
|
559
|
+
tg.create_task(heartbeat(conn[1], pong))
|
|
560
|
+
tg.create_task(receive(conn[0], pong))
|
|
561
|
+
|
|
562
|
+
except Exception as e:
|
|
563
|
+
log.warning("relay connection failed: %r", e)
|
|
564
|
+
finally:
|
|
565
|
+
close(conn)
|
|
566
|
+
for t in list(tasks):
|
|
567
|
+
t.cancel()
|
|
568
|
+
tasks.clear()
|
|
569
|
+
|
|
570
|
+
log.info("retrying in %ds", delay)
|
|
571
|
+
await asyncio.sleep(delay)
|
|
572
|
+
delay = min(delay * 2, RETRY_MAX)
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
async def run_listen(local: tuple[str, int], relay: tuple[str, int], key: str):
|
|
576
|
+
check_key(key)
|
|
577
|
+
|
|
578
|
+
kid = digest(b"id", key)
|
|
579
|
+
|
|
580
|
+
async def handle(r, w):
|
|
581
|
+
peer = w.get_extra_info("peername")
|
|
582
|
+
log.info("client %s connected", peer)
|
|
583
|
+
await bridge((r, w), relay, Message.OPEN, kid, key)
|
|
584
|
+
|
|
585
|
+
server = await asyncio.start_server(handle, *local)
|
|
586
|
+
log.info("listening on %s:%d", *local)
|
|
587
|
+
|
|
588
|
+
async with server:
|
|
589
|
+
await server.serve_forever()
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
async def main():
|
|
593
|
+
match sys.argv[1:]:
|
|
594
|
+
case ["keygen"]:
|
|
595
|
+
print(secrets.token_urlsafe(32))
|
|
596
|
+
|
|
597
|
+
case ["relay", bind]:
|
|
598
|
+
await run_relay(addr(bind))
|
|
599
|
+
|
|
600
|
+
case ["connect", target, "through", relay, "key", key] if key:
|
|
601
|
+
await run_connect(addr(target), addr(relay), key)
|
|
602
|
+
|
|
603
|
+
case ["listen", local, "through", relay, "key", key] if key:
|
|
604
|
+
await run_listen(addr(local), addr(relay), key)
|
|
605
|
+
|
|
606
|
+
case _:
|
|
607
|
+
sys.exit(
|
|
608
|
+
"usage:\n"
|
|
609
|
+
" sockwave keygen\n"
|
|
610
|
+
" sockwave relay HOST:PORT\n"
|
|
611
|
+
" sockwave connect HOST:PORT through HOST:PORT key KEY\n"
|
|
612
|
+
" sockwave listen HOST:PORT through HOST:PORT key KEY"
|
|
613
|
+
)
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
def cli():
|
|
617
|
+
logging.basicConfig(
|
|
618
|
+
level=logging.INFO,
|
|
619
|
+
format="%(asctime)s %(levelname)-7s %(message)s",
|
|
620
|
+
)
|
|
621
|
+
try:
|
|
622
|
+
asyncio.run(main())
|
|
623
|
+
except KeyboardInterrupt:
|
|
624
|
+
pass
|
|
625
|
+
except ValueError as e:
|
|
626
|
+
sys.exit(f"error: {e}")
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
if __name__ == "__main__":
|
|
630
|
+
cli()
|