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
8 changes: 8 additions & 0 deletions .github/workflows/spore.yml
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,11 @@ jobs:
- name: Verify escript
working-directory: ${{ env.WORKDIR }}
run: test -x ./spore && ls -l ./spore

- name: Upload artifact (spore)
uses: actions/upload-artifact@v4
with:
name: spore-${{ runner.os }}-${{ github.sha }}
path: ${{ env.WORKDIR }}/spore
if-no-files-found: error
retention-days: 14
22 changes: 20 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ Spore is a minimal TCP tunnel implemented in Elixir/OTP. It forwards a local TCP
- Client proxies between your local service and remote connections
- Pending-connection manager backed by OTP (Registry + DynamicSupervisor) for robust cleanup
- Socket tuning flags (`--sndbuf`, `--recbuf`) for high-throughput/latency paths
- Optional TLS on control plane (`--tls`); multi-secret auth (comma-separated)
- Access control lists and limits: `--allow`, `--deny`, `--max-conns-per-ip`
- Prometheus metrics endpoint (text exposition)

## Install / Build
```bash
Expand All @@ -20,7 +23,10 @@ This produces an executable named `spore` in the project directory.
## Quickstart
### Server (choose a public range)
```bash
./spore server --min-port 20000 --max-port 21000 --bind-addr 0.0.0.0 [--control-port 7835] [--sndbuf 1048576] [--recbuf 1048576]
./spore server --min-port 20000 --max-port 21000 --bind-addr 0.0.0.0 \
[--control-port 7835] [--tls --certfile cert.pem --keyfile key.pem] \
[--allow "10.0.0.0/8,192.168.0.0/16"] [--deny "0.0.0.0/0"] [--max-conns-per-ip 50] \
[--sndbuf 1048576] [--recbuf 1048576]
```

### Client (forward local 3000; let server assign a port)
Expand Down Expand Up @@ -50,10 +56,21 @@ curl -v 127.0.0.1:<ASSIGNED_PORT>/
## Authentication (optional)
Provide the same secret on both sides to restrict access:
```bash
./spore server --secret SECRET [--control-port 7835] [--sndbuf N] [--recbuf N]
./spore server --secret "secret1,secret2" [--control-port 7835] [--sndbuf N] [--recbuf N]
./spore local --local-port 3000 --to <SERVER_HOST> --secret SECRET [--control-port 7835] [--sndbuf N] [--recbuf N]
```

## Metrics
Spore exposes basic counters and latency sums in Prometheus text format if `SPORE_METRICS_PORT` or `--metrics-port` is set (server-only). Example:
```
spore_connections_incoming_total 42
spore_connections_accepted_total 40
spore_connections_stale_total 2
spore_bytes_proxied_total 1234567
spore_accept_latency_ms_sum 350
spore_accept_latency_ms_count 40
```

## Interoperability
Spore is designed to speak the same control protocol as Bore. You can mix Rust Bore on one side and Spore on the other as long as secrets and addresses match. See Bore docs for protocol details: [bore (Rust)](https://github.com/ekzhang/bore).

Expand All @@ -66,6 +83,7 @@ Spore is designed to speak the same control protocol as Bore. You can mix Rust B
- Client exits with `:eof`: ensure server is reachable at `--to`, secrets match (or are omitted on both), and the control port is open.
- Repeated "removed stale connection": ensure the client is running and a remote connection arrives soon after the client starts (Spore holds pending connections for 10s).
- Low throughput on high-latency links: increase `--sndbuf`/`--recbuf` on both ends to match your bandwidth-delay product.
- TLS client trust: provide `--cacertfile` on the client or use `--insecure` in test environments.

## License
MIT, following the upstream project.
Expand Down
58 changes: 58 additions & 0 deletions lib/spore/acl.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
defmodule Spore.ACL do
@moduledoc false
import Bitwise

@spec allow?(tuple()) :: boolean()
def allow?(ip) do
allow = Application.get_env(:spore, :allow, [])
deny = Application.get_env(:spore, :deny, [])

allowed =
case allow do
[] -> true
_ -> Enum.any?(allow, &match_ip?(ip, &1))
end

denied = Enum.any?(deny, &match_ip?(ip, &1))
allowed and not denied
end

@spec parse_list(String.t()) :: list()
def parse_list(s) when is_binary(s) do
s
|> String.split([",", " ", "\n"], trim: true)
|> Enum.map(&parse_entry/1)
|> Enum.filter(& &1)
end

defp parse_entry(entry) do
case String.split(entry, "/", parts: 2) do
[ip] ->
case :inet.parse_address(String.to_charlist(ip)) do
{:ok, addr} -> {:ip, addr}
_ -> nil
end

[ip, masklen] ->
with {:ok, addr} <- :inet.parse_address(String.to_charlist(ip)),
{len, ""} <- Integer.parse(masklen) do
{:cidr, addr, len}
else
_ -> nil
end
end
end

defp match_ip?(ip, {:ip, addr}), do: ip == addr

defp match_ip?({a, b, c, d}, {:cidr, {a2, b2, c2, d2}, len})
when is_integer(len) and len >= 0 and len <= 32 do
mask = bnot((1 <<< (32 - len)) - 1) &&& 0xFFFFFFFF
ipi = (a <<< 24) + (b <<< 16) + (c <<< 8) + d
base = (a2 <<< 24) + (b2 <<< 16) + (c2 <<< 8) + d2
(ipi &&& mask) == (base &&& mask)
end

defp match_ip?({_, _, _, _, _, _, _, _}, {:cidr, _, _}), do: false
defp match_ip?(_, _), do: false
end
4 changes: 3 additions & 1 deletion lib/spore/application.ex
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ defmodule Spore.Application do
children = [
{Registry, keys: :unique, name: Spore.Pending.Registry},
{DynamicSupervisor, name: Spore.Pending.Supervisor, strategy: :one_for_one},
{Spore.Pending, []}
{Spore.Pending, []},
{Spore.Limits, []},
{Spore.Metrics, []}
]

opts = [strategy: :one_for_one, name: Spore.Supervisor]
Expand Down
31 changes: 31 additions & 0 deletions lib/spore/auth.ex
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,22 @@ defmodule Spore.Auth do
%{key: :crypto.hash(:sha256, secret)}
end

@doc "Create multiple authenticators from a comma-separated list."
def new_many(secret_or_list) do
cond do
is_list(secret_or_list) ->
Enum.map(secret_or_list, &new/1)

is_binary(secret_or_list) ->
secret_or_list
|> String.split([",", " ", "\n"], trim: true)
|> Enum.map(&new/1)

true ->
[]
end
end

@doc "Generate a reply tag for a challenge UUID string."
@spec answer(t, String.t()) :: String.t()
def answer(%{key: key}, challenge_uuid_string) do
Expand Down Expand Up @@ -51,6 +67,21 @@ defmodule Spore.Auth do
end
end

@doc "Server handshake accepting any of a list of authenticators."
def server_handshake_many(auths, d) when is_list(auths) and auths != [] do
challenge = generate_uuid_v4()
{:ok, _} = Spore.Shared.Delimited.send(d, %{"Challenge" => challenge})

case Spore.Shared.Delimited.recv_timeout(d) do
{%{"Authenticate" => tag}, d2} ->
ok = Enum.any?(auths, fn a -> validate(a, challenge, tag) end)
if ok, do: {:ok, d2}, else: {{:error, :invalid_secret}, d2}

{_, d2} ->
{{:error, :missing_authentication}, d2}
end
end

@doc "Client-side handshake: expect Challenge and respond with Authenticate."
def client_handshake(%{key: _} = auth, d) do
case Spore.Shared.Delimited.recv_timeout(d) do
Expand Down
32 changes: 30 additions & 2 deletions lib/spore/cli.ex
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ defmodule Spore.CLI do
port: :integer,
secret: :string,
control_port: :integer,
tls: :boolean,
cacertfile: :string,
insecure: :boolean,
sndbuf: :integer,
recbuf: :integer
],
Expand All @@ -36,6 +39,12 @@ defmodule Spore.CLI do
control_port = Keyword.get(opts, :control_port, nil)

if control_port, do: Application.put_env(:spore, :control_port, control_port)
if Keyword.get(opts, :tls), do: Application.put_env(:spore, :tls, true)

if cacert = Keyword.get(opts, :cacertfile),
do: Application.put_env(:spore, :cacertfile, cacert)

if Keyword.get(opts, :insecure), do: Application.put_env(:spore, :ssl_verify, false)
if sndbuf = Keyword.get(opts, :sndbuf), do: Application.put_env(:spore, :sndbuf, sndbuf)
if recbuf = Keyword.get(opts, :recbuf), do: Application.put_env(:spore, :recbuf, recbuf)

Expand All @@ -61,6 +70,12 @@ defmodule Spore.CLI do
bind_addr: :string,
bind_tunnels: :string,
control_port: :integer,
tls: :boolean,
certfile: :string,
keyfile: :string,
allow: :string,
deny: :string,
max_conns_per_ip: :integer,
sndbuf: :integer,
recbuf: :integer
]
Expand All @@ -74,6 +89,19 @@ defmodule Spore.CLI do
control_port = Keyword.get(opts, :control_port, nil)

if control_port, do: Application.put_env(:spore, :control_port, control_port)
if Keyword.get(opts, :tls), do: Application.put_env(:spore, :tls, true)
if cert = Keyword.get(opts, :certfile), do: Application.put_env(:spore, :certfile, cert)
if key = Keyword.get(opts, :keyfile), do: Application.put_env(:spore, :keyfile, key)

if allow = Keyword.get(opts, :allow),
do: Application.put_env(:spore, :allow, Spore.ACL.parse_list(allow))

if deny = Keyword.get(opts, :deny),
do: Application.put_env(:spore, :deny, Spore.ACL.parse_list(deny))

if m = Keyword.get(opts, :max_conns_per_ip),
do: Application.put_env(:spore, :max_conns_per_ip, m)

if sndbuf = Keyword.get(opts, :sndbuf), do: Application.put_env(:spore, :sndbuf, sndbuf)
if recbuf = Keyword.get(opts, :recbuf), do: Application.put_env(:spore, :recbuf, recbuf)

Expand All @@ -92,8 +120,8 @@ defmodule Spore.CLI do
defp usage(io) do
IO.puts(io, """
Usage:
spore local --local-port <PORT> --to <HOST> [--local-host HOST] [--port PORT] [--secret SECRET] [--control-port N] [--sndbuf N] [--recbuf N]
spore server [--min-port N] [--max-port N] [--secret SECRET] [--bind-addr IP] [--bind-tunnels IP] [--control-port N] [--sndbuf N] [--recbuf N]
spore local --local-port <PORT> --to <HOST> [--local-host HOST] [--port PORT] [--secret SECRET] [--control-port N] [--tls] [--cacertfile PATH] [--insecure] [--sndbuf N] [--recbuf N]
spore server [--min-port N] [--max-port N] [--secret SECRET] [--bind-addr IP] [--bind-tunnels IP] [--control-port N] [--tls] [--certfile PATH] [--keyfile PATH] [--allow CIDRs] [--deny CIDRs] [--max-conns-per-ip N] [--sndbuf N] [--recbuf N]
""")
end
end
6 changes: 3 additions & 3 deletions lib/spore/client.ex
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ defmodule Spore.Client do
{:ok, t} | {:error, term()}
def new(local_host, local_port, to, port, secret) do
with {:ok, socket} <- Shared.connect(to, Shared.control_port(), Shared.network_timeout_ms()) do
d = Delimited.new(socket)
d = Delimited.new(socket, Shared.transport_mod())
auth = if secret, do: Auth.new(secret), else: nil

d =
Expand Down Expand Up @@ -121,7 +121,7 @@ defmodule Spore.Client do
defp handle_connection(id, %__MODULE__{} = state) do
with {:ok, remote_conn} <-
Shared.connect(state.to, Shared.control_port(), Shared.network_timeout_ms()) do
d = Delimited.new(remote_conn)
d = Delimited.new(remote_conn, Shared.transport_mod())

d =
case state.auth do
Expand All @@ -140,7 +140,7 @@ defmodule Spore.Client do
case Shared.connect(state.local_host, state.local_port, Shared.network_timeout_ms()) do
{:ok, local_conn} ->
# Any data already buffered in `d` is intentionally not forwarded; see Rust note
Shared.pipe_bidirectional(remote_conn, local_conn)
Shared.pipe_bidirectional(remote_conn, Shared.transport_mod(), local_conn, :gen_tcp)

{:error, reason} ->
:gen_tcp.close(remote_conn)
Expand Down
45 changes: 45 additions & 0 deletions lib/spore/limits.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
defmodule Spore.Limits do
@moduledoc false
use GenServer

def start_link(_), do: GenServer.start_link(__MODULE__, %{}, name: __MODULE__)

@impl true
def init(state), do: {:ok, state}

def can_open?(ip) do
GenServer.call(__MODULE__, {:can_open, ip})
end

def close(ip) do
GenServer.cast(__MODULE__, {:close, ip})
end

@impl true
def handle_call({:can_open, ip}, _from, state) do
max = Application.get_env(:spore, :max_conns_per_ip, :infinity)
{count, state2} = Map.get_and_update(state, ip, fn v -> {v || 0, (v || 0) + 1} end)

allow =
case max do
:infinity -> true
n when is_integer(n) and n > 0 -> count < n
_ -> true
end

state3 = if allow, do: state2, else: state
{:reply, allow, state3}
end

@impl true
def handle_cast({:close, ip}, state) do
state2 =
update_in(state[ip], fn
nil -> nil
1 -> nil
n when is_integer(n) and n > 1 -> n - 1
end)

{:noreply, state2}
end
end
Loading