H5: Security review, and fixes for connection-slot exhaustion
docs/SECURITY_REVIEW.md lists the scope, nine findings and what was done. - High, fixed: a peer that connects and stops answering kept its ENet slot for up to 15 s after being turned away, so one address could fill every slot. Flood refusals now disconnect at once (reason in the disconnect data, which NetClient now honours for REASON_BUSY), peers told to leave get 1 s to acknowledge, and when slots run short the longest-waiting silent guest makes room. - Medium, mitigated: ENet holds half-open slots for spoofed CONNECTs that the script never sees. The host now has 512 slots (NetServer.peer_slots). - Medium, fixed: SourceLimiter, handshakes per source and the list server's per-address cap count an IPv6 /64 as one source. - Low, fixed: CommandLog refuses a header with non-numeric fields instead of raising errors. - tools/godot.sh unsets DISPLAY and WAYLAND_DISPLAY so the engine's error alerts can never reach the host desktop. - A test fixture's 10.0.0.9 is now the documentation address 192.0.2.9. Tests: 4 new handshake tests with real non-acknowledging ENet peers, test_source_limiter (3), a CommandLog type test. make check, make fuzz, make client-check, make discovery-check and make soak-selfcheck pass. Closes #58 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+13
-6
@@ -160,13 +160,14 @@ People join a server three ways, none needing a third-party service:
|
||||
a CHALLENGE carrying a token derived from a per-start secret and the sender's
|
||||
address and port, and lists the server only when a REGISTER echoes it. Servers are
|
||||
listed under the address their packets come from, never a claimed one. Entries
|
||||
expire after 45 s, with at most 8 per address and 256 in all. Clients ask for the
|
||||
expire after 45 s, with at most 8 per address (per /64 for IPv6) and 256 in all. Clients ask for the
|
||||
list four servers per page, one page after another.
|
||||
|
||||
The messages are in `NetDiscovery`. Every QUERY is padded to 512 bytes and no answer
|
||||
is larger, so neither the beacon nor the list server can amplify a spoofed request.
|
||||
Both rate-limit each source address (`SourceLimiter`: 20 packets a second, at most
|
||||
4,096 addresses tracked per second).
|
||||
Both rate-limit each source (`SourceLimiter`: 20 packets a second, at most 4,096
|
||||
sources tracked per second). A source is an IPv4 address, or an IPv6 address's whole
|
||||
/64, since one ordinary connection is handed a /64 (H5).
|
||||
|
||||
**Lobby, backfill and late arrivals.** People who connect during the lobby or the
|
||||
countdown take places (`Match.join()`); bots are only added when the match starts,
|
||||
@@ -199,9 +200,15 @@ likes. The server's defences, and the tests that attack them
|
||||
commands and an exact length, or it is dropped whole. At most 32 game packets per
|
||||
player are kept per poll. Anything on the control channel after the handshake is
|
||||
dropped.
|
||||
- **Bounded connections.** At most 32 new connections per address per 10 s and 8
|
||||
handshakes in progress per address (`REASON_BUSY`), a 5 s handshake timeout, and
|
||||
ENet's own peer limit.
|
||||
- **Bounded connections.** At most 32 new connections per source per 10 s and 8
|
||||
handshakes in progress per source (`REASON_BUSY`), and a 5 s handshake timeout.
|
||||
No slot is left to a silent stranger for long (H5): a connection turned away for
|
||||
flooding is dropped at once, with the reason only in the disconnect's data; a peer
|
||||
told to leave has 1 s to acknowledge before it is cut off; and when ENet's slots
|
||||
run short, the guest that has waited longest for its HELLO makes room. The host
|
||||
has 512 slots whatever the player limit, because ENet takes a slot for every
|
||||
CONNECT before the sender has proved its address and never reports those
|
||||
half-open slots to the script; see docs/SECURITY_REVIEW.md.
|
||||
- **Parsers.** Every decoder refuses malformed input by returning an empty result,
|
||||
never by raising an error. `make fuzz` feeds 1,000,000 mutated and random messages
|
||||
to all of them, the snapshot receiver and the list server, and checks for engine
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
# Security review (H5)
|
||||
|
||||
Reviewed on 2026-11-14 against commit `e3c0d28` plus the fixes below. Tidewall has no
|
||||
accounts, payments, chat or user-generated files, so the review is mostly about two
|
||||
things: a hostile peer must not crash a server, corrupt a match or lock people out,
|
||||
and the public repository must not leak anything about the machines it is built on.
|
||||
|
||||
Severity follows the usual scale. **High** and **critical** findings are fixed, with
|
||||
regression tests. Lower ones are fixed when the fix is small and safe, and otherwise
|
||||
recorded here as accepted, with the reason.
|
||||
|
||||
## Scope
|
||||
|
||||
| Area | Files | How it was checked |
|
||||
|---|---|---|
|
||||
| Game handshake and transport | `src/net/net_protocol.gd`, `net_server.gd`, `net_client.gd`, `source_limiter.gd` | Read; `test/net/test_net_handshake.gd` (20 tests, 4 new) |
|
||||
| Player input | `src/net/net_snapshot.gd` (`decode_input`), `src/sim/player_command.gd`, `src/server/net_game.gd`, the simulation's use of each command field | Read every use of `selection`, `material`, `view_lag`, `tick`; `test/server/test_hostile_client.gd` |
|
||||
| Server-to-client messages | `net_snapshot.gd`, `net_world.gd`, `net_fx.gd`, `net_feed.gd` | Read; `make fuzz` |
|
||||
| LAN discovery and list server | `src/net/net_discovery.gd`, `src/server/server_beacon.gd`, `list_server.gd` | Read; `test/net/test_net_discovery.gd`, `test/server/test_list_server.gd` |
|
||||
| Health endpoint | `src/server/health_server.gd` | Read; `test/server/test_health_server.gd` |
|
||||
| Server configuration and files | `src/server/server_config.gd`, `command_log.gd`, `src/client/game_settings.gd`, `input_settings.gd`, `key_bindings.gd` | Read; `test_command_log.gd` (1 new test) |
|
||||
| Packaging | `packaging/docker/`, `packaging/systemd/`, `packaging/server/`, `packaging/dist/` | Read; `make server-package-check` covers non-root and read-only |
|
||||
| Repository contents | every tracked file and the whole git history | `git grep` and `git log -p` for keys, passwords, tokens, private and internal addresses, host names and home paths |
|
||||
|
||||
## Findings
|
||||
|
||||
### H5-1 High, fixed: one address could hold every connection slot
|
||||
|
||||
ENet has a fixed number of peer slots, and a peer keeps its slot until ENet hears it
|
||||
leave or times it out (5 to 15 s). The server turned every unwanted peer away with
|
||||
`peer_disconnect_later`, which waits for the REJECT to be acknowledged. A client that
|
||||
connects and then stops answering never acknowledges, so:
|
||||
|
||||
- each connection refused for flooding (`REASON_BUSY`) kept its slot for up to 15 s,
|
||||
and a single address could open them faster than they expired, until the server had
|
||||
no slots left and real players' connections were silently dropped;
|
||||
- silent guests (8 per address, each for the 5 s handshake timeout) did the same from
|
||||
four addresses.
|
||||
|
||||
**Fix** (`NetServer`):
|
||||
- A connection refused for flooding is dropped at once with `peer_disconnect_now`; the
|
||||
reason travels as the disconnect's data. `NetClient` now accepts `REASON_BUSY` from
|
||||
that data (`NetProtocol.is_server_reason`), so the player still reads "Too many
|
||||
connections from your address".
|
||||
- A peer told to leave has `leave_grace_msec` (1 s) to acknowledge, then is cut off.
|
||||
- When the slots run short (one left), peers already told to leave go first, then the
|
||||
guest that has waited longest for its HELLO. An honest client sends HELLO within one
|
||||
round trip, so it is never the oldest guest for long.
|
||||
|
||||
**Tests:** `test_a_flood_from_one_address_cannot_hold_the_slots`,
|
||||
`test_silent_guests_make_room_for_a_newcomer`,
|
||||
`test_a_peer_that_never_acknowledges_leaving_is_cut_off`,
|
||||
`test_busy_reaches_the_client_without_a_reject_message`. The silent peers in these tests
|
||||
are real ENet hosts that complete the connection and then never service their socket
|
||||
again.
|
||||
|
||||
### H5-2 Medium, mitigated: half-open connections from spoofed addresses
|
||||
|
||||
ENet takes a slot for each CONNECT it receives and answers it, before the sender has
|
||||
shown it can receive at that address. The slot is held for ENet's own timeout, and
|
||||
the script is never told about it (Godot reports a peer only once the handshake
|
||||
completes), so nothing in GDScript can see or evict it. Someone able to send packets
|
||||
with forged source addresses could keep every slot half-open with a few packets a
|
||||
second, and each answer goes to the forged address.
|
||||
|
||||
This is a property of ENet, not of Tidewall's code, and fixing it properly would mean
|
||||
changing the engine. **Mitigation:** the server now creates 512 ENet slots whatever
|
||||
its player limit (`NetServer.peer_slots`), so filling them takes hundreds of forged
|
||||
packets every few seconds instead of a few dozen. The per-source limits and the
|
||||
eviction in H5-1 still govern every connection that completes. This has not been
|
||||
tested against a real spoofing attack: the tests can't forge source addresses. A
|
||||
public server operator's best protection is a network that drops forged packets and
|
||||
an upstream per-source rate limit.
|
||||
|
||||
### H5-3 Medium, fixed: one IPv6 connection counted as millions of senders
|
||||
|
||||
`SourceLimiter` and the per-address caps keyed on the full address. An ordinary IPv6
|
||||
connection is given a whole /64, so one user could rotate addresses to get a fresh
|
||||
allowance each time, fill the limiter's table of 4,096 sources (locking everyone else
|
||||
out for the rest of the window), take the list server's 256 entries (every address
|
||||
there can answer its own CHALLENGE), or hold more handshakes than the per-address cap.
|
||||
|
||||
**Fix:** `SourceLimiter.source_of()` maps an IPv6 address to its /64 (and an
|
||||
IPv4-mapped address to the IPv4 address). The limiter, the server's handshakes per
|
||||
source and the list server's entries per address all count by source.
|
||||
**Tests:** `test/net/test_source_limiter.gd` (3 tests).
|
||||
|
||||
Accepted: someone holding many /64s (a /48 has 65,536) or many IPv4 addresses can
|
||||
still fill the list server or the limiter's table. The list server is optional,
|
||||
self-hosted and has nothing to steal; entries expire in 45 s.
|
||||
|
||||
### H5-4 Low, fixed: a damaged replay file could raise script errors
|
||||
|
||||
`CommandLog.from_bytes` checks every length, but took JSON values with `int()` without
|
||||
checking their type, so a hand-edited header holding an array or object where a
|
||||
number belongs raised an engine error instead of being refused. Replay files are only
|
||||
read from a path given on the command line, so this was never reachable from the
|
||||
network. **Fix:** only numbers and booleans are read. **Test:**
|
||||
`test_a_header_with_the_wrong_types_is_refused_without_errors`.
|
||||
|
||||
### H5-5 Low, accepted: a server can make a client spend memory
|
||||
|
||||
A client trusts the server it chose to join for the size of the world: every WORLD,
|
||||
SNAPSHOT, FX and FEED message is length-checked and validated (and fuzzed), but a
|
||||
hostile server could still send many valid pieces or large reliable messages (ENet's
|
||||
limit is 32 MB a packet). The player picked the server, and the worst case is the game
|
||||
running out of memory or being closed. Not worth bounding further for v1.0.
|
||||
|
||||
### H5-6 Low, accepted: names are not authenticated
|
||||
|
||||
There are no accounts, so anyone can join under any name. Names are cleaned (control,
|
||||
formatting, bidirectional and private-use characters removed, 16 characters) and made
|
||||
unique on the server with a number. The UI never interprets markup in names (no
|
||||
BBCode-enabled labels exist in `src/`).
|
||||
|
||||
### H5-7 Low, accepted: claimed view lag
|
||||
|
||||
A command says how far behind the shooter was seeing (`view_lag`), and the server
|
||||
rewinds other players by that much when judging a hit. A modified client can always
|
||||
claim the maximum, `Tuning.LAG_COMPENSATION_MAX_TICKS` (15 ticks, 0.5 s). This is the
|
||||
usual trade-off of lag compensation and is bounded. Nothing else in a command can
|
||||
claim a position, hit, target or item (see "Trusting nothing from clients" in
|
||||
docs/ARCHITECTURE.md).
|
||||
|
||||
### H5-8 Info: release builds stop on a null call
|
||||
|
||||
Godot release templates end the process (exit 139) on a GDScript call on null, where a
|
||||
debug build reports an error and carries on. A remote input that reached such a call
|
||||
would therefore stop a packaged server. The parsers and the simulation are fuzzed and
|
||||
tested in debug builds, where any script error fails the run, and the server packages
|
||||
restart on failure (`Restart=on-failure`, `restart: unless-stopped`). Recorded so a
|
||||
future crash report is read with this in mind.
|
||||
|
||||
### H5-9 Info: the container base image is not pinned by digest
|
||||
|
||||
`packaging/docker/Dockerfile` starts `FROM debian:13`. A rebuild picks up Debian's
|
||||
security updates, which is what a server image wants, at the cost of exact
|
||||
reproducibility. The engine inside is checked against `tools/engine.sha512`.
|
||||
|
||||
## Checked and found sound
|
||||
|
||||
- **Handshake.** One HELLO per guest, exact lengths, strict UTF-8 (overlong forms and
|
||||
surrogates refused), a 96-byte cap, nothing on the control channel after joining,
|
||||
32 game packets per player per poll.
|
||||
- **Input.** An INPUT has an exact length and at most `MAX_INPUT_COMMANDS` commands.
|
||||
Every field is clamped on decode. A tick behind the last one taken, or more than
|
||||
`MAX_COMMAND_LEAD_TICKS` ahead, is ignored. `selection` is bounds-checked in
|
||||
`Inventory.select` and `Building.target` (which returns null, handled by
|
||||
`Building.check`), `material` by `Materials.is_valid`, `view_lag` clamped in
|
||||
`Weapons`.
|
||||
- **Discovery and list server.** No answer is larger than the 512-byte QUERY that asked
|
||||
for it, so neither can amplify a forged request; a REGISTER is answered with a
|
||||
smaller CHALLENGE. The token is a SHA-256 of a per-start random secret, address and
|
||||
port, so a server can only be listed at an address where it receives. A server's
|
||||
CHALLENGE handling only accepts one from a list server it chose. Both rate-limit
|
||||
each source and bound packets handled per frame.
|
||||
- **Health endpoint.** Loopback by default, at most 8 connections, 2 KiB and 2 s per
|
||||
request, `GET /health` only, no input reflected in the answer. The Docker health
|
||||
check talks to it on loopback inside the container.
|
||||
- **Configuration.** Unknown or malformed options are errors; a config file can't
|
||||
include another; `--health-bind` must be an IP address; server names are cleaned
|
||||
like player names. Files are read only from paths the operator gives.
|
||||
- **Client settings.** Read with `ConfigFile` from the player's own `user://`, each
|
||||
value type-checked with a fallback.
|
||||
- **Packaging.** The Docker service runs as an unprivileged user with a read-only root,
|
||||
all capabilities dropped and `no-new-privileges`; only the game port is published.
|
||||
The systemd unit uses `DynamicUser`, `ProtectSystem=strict`, `ProtectHome`,
|
||||
`PrivateDevices`, an empty capability set and restricted address families. The
|
||||
launcher quotes its arguments and keeps engine state in its own directory.
|
||||
- **Repository.** No keys, passwords, tokens, internal host names, private network
|
||||
addresses or home paths in any tracked file or in history. Example addresses use the
|
||||
documentation ranges (192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24, 2001:db8::/32);
|
||||
one test fixture that used 10.0.0.9 now uses 192.0.2.9. Every commit is authored by
|
||||
the project's own identity.
|
||||
|
||||
## Not covered
|
||||
|
||||
- No external penetration test or review by a second person.
|
||||
- Nothing was tested against forged source addresses (H5-2) or over a real WAN.
|
||||
- Godot and ENet themselves were not audited; the engine is the official 4.7.2 build,
|
||||
checked against its published SHA-512 sums.
|
||||
@@ -92,7 +92,7 @@ func poll(now_msec: int = -1) -> void:
|
||||
var data: int = int(event[2])
|
||||
var reason: int = close_reason
|
||||
if reason == NetProtocol.REASON_NONE:
|
||||
reason = data if data > NetProtocol.REASON_NONE and data <= NetProtocol.REASON_KICKED \
|
||||
reason = data if NetProtocol.is_server_reason(data) \
|
||||
else (NetProtocol.REASON_NO_ANSWER if state == CONNECTING else NetProtocol.REASON_LOST)
|
||||
_close(reason)
|
||||
if state == CONNECTING and now - _since_msec >= connect_timeout_msec:
|
||||
|
||||
@@ -85,6 +85,12 @@ static func clean_name(raw: String, max_chars: int = NAME_MAX_CHARS, max_bytes:
|
||||
return kept if not kept.is_empty() else fallback
|
||||
|
||||
|
||||
## True for a reason a server sends when it ends a connection, which a client may take
|
||||
## from the disconnect's data when the REJECT before it was lost or never sent.
|
||||
static func is_server_reason(reason: int) -> bool:
|
||||
return (reason > REASON_NONE and reason <= REASON_KICKED) or reason == REASON_BUSY
|
||||
|
||||
|
||||
static func encode_hello(player_name: String, version: int = VERSION) -> PackedByteArray:
|
||||
var name_bytes: PackedByteArray = clean_name(player_name).to_utf8_buffer()
|
||||
var out: StreamPeerBuffer = _writer()
|
||||
|
||||
+78
-11
@@ -5,6 +5,13 @@
|
||||
## A connection is a guest until its HELLO is accepted. Guests can't do anything else,
|
||||
## get one try, and are dropped if they stay silent past the handshake timeout. Player
|
||||
## handles are positive, count up from 1 and are never reused while the server runs.
|
||||
##
|
||||
## ENet has a fixed number of peer slots (the player limit plus a few), and a peer that
|
||||
## stops answering keeps its slot until ENet times it out. So no slot is left to a
|
||||
## silent stranger for long (H5): a connection turned away for flooding is dropped at
|
||||
## once, a peer told to leave gets `leave_grace_msec` to acknowledge before it is cut
|
||||
## off, and when the slots run short the guest that has waited longest for its HELLO
|
||||
## makes room for the newcomer. An honest client says HELLO within one round trip.
|
||||
class_name NetServer
|
||||
extends RefCounted
|
||||
|
||||
@@ -32,12 +39,26 @@ var bad_packets: int = 0
|
||||
var connect_limiter: SourceLimiter = SourceLimiter.new(32, 10000, 4096)
|
||||
## Connections from one address still in the handshake at once.
|
||||
var max_guests_per_address: int = 8
|
||||
## ENet peer slots to create at least. ENet takes a slot for every CONNECT it is sent,
|
||||
## before the sender has proved it receives at its address, and holds it for ENet's
|
||||
## own timeout without ever reporting it here, so spoofed CONNECTs can only be outlasted,
|
||||
## not seen. Headroom makes that take hundreds of packets every few seconds instead of
|
||||
## a few dozen (H5). Never fewer than the player limit plus 8. Set before listen().
|
||||
var peer_slots: int = 512
|
||||
## Milliseconds a peer being turned away keeps its slot while the notice is delivered.
|
||||
var leave_grace_msec: int = 1000
|
||||
## Silent guests dropped to make room for newcomers, and peers cut off after their
|
||||
## grace, so far.
|
||||
var evicted: int = 0
|
||||
|
||||
var _host: ENetConnection = null
|
||||
## Peers that haven't finished the handshake: ENetPacketPeer -> msec they connected.
|
||||
var _guests: Dictionary = {}
|
||||
## Peers being turned away: ENetPacketPeer -> the reason, until ENet reports them gone.
|
||||
## Peers being turned away: ENetPacketPeer -> {"reason", "since"}, until ENet reports
|
||||
## them gone or their grace runs out.
|
||||
var _leaving: Dictionary = {}
|
||||
## ENet peer slots on the host.
|
||||
var _capacity: int = 0
|
||||
## Handle -> {"peer": ENetPacketPeer, "name": String}.
|
||||
var _players: Dictionary = {}
|
||||
## ENetPacketPeer -> handle.
|
||||
@@ -52,8 +73,9 @@ var _packets_from: Dictionary = {}
|
||||
func listen(port: int, address: String = "*") -> Error:
|
||||
close()
|
||||
var host: ENetConnection = ENetConnection.new()
|
||||
# Room for a few guests beyond the player limit, so a full server can say so.
|
||||
var error: Error = host.create_host_bound(address, port, max_players + 8, NetProtocol.CHANNEL_COUNT)
|
||||
# Room for guests beyond the player limit, so a full server can say so.
|
||||
_capacity = clampi(maxi(peer_slots, max_players + 8), 1, 4095)
|
||||
var error: Error = host.create_host_bound(address, port, _capacity, NetProtocol.CHANNEL_COUNT)
|
||||
if error != OK:
|
||||
return error
|
||||
_host = host
|
||||
@@ -77,6 +99,11 @@ func guest_count() -> int:
|
||||
return _guests.size()
|
||||
|
||||
|
||||
## Peers told to leave that haven't gone yet.
|
||||
func leaving_count() -> int:
|
||||
return _leaving.size()
|
||||
|
||||
|
||||
func handles() -> Array[int]:
|
||||
var result: Array[int] = []
|
||||
for handle: int in _players:
|
||||
@@ -110,16 +137,23 @@ func poll(now_msec: int = -1) -> void:
|
||||
peer.set_timeout(NetProtocol.PEER_TIMEOUT_LIMIT, peer_timeout_min_msec, peer_timeout_max_msec)
|
||||
var address: String = peer.get_remote_address()
|
||||
if not connect_limiter.allow(address, now) or _guests_from(address) >= max_guests_per_address:
|
||||
_refuse(peer, NetProtocol.REASON_BUSY)
|
||||
# A flood: the reason goes only as the disconnect's data, and the
|
||||
# slot is free again at once.
|
||||
events.append({"type": "refused", "reason": NetProtocol.REASON_BUSY})
|
||||
peer.peer_disconnect_now(NetProtocol.REASON_BUSY)
|
||||
continue
|
||||
_guests[peer] = now
|
||||
_guests[peer] = {"since": now, "source": SourceLimiter.source_of(address)}
|
||||
_make_room(peer)
|
||||
ENetConnection.EVENT_DISCONNECT:
|
||||
_gone(peer, int(event[2]))
|
||||
ENetConnection.EVENT_RECEIVE:
|
||||
_received(peer, int(event[3]), peer.get_packet())
|
||||
for peer: ENetPacketPeer in _guests.keys():
|
||||
if now - int(_guests[peer]) >= handshake_timeout_msec:
|
||||
_refuse(peer, NetProtocol.REASON_HANDSHAKE_TIMEOUT)
|
||||
if now - int(_guests[peer]["since"]) >= handshake_timeout_msec:
|
||||
_refuse(peer, NetProtocol.REASON_HANDSHAKE_TIMEOUT, now)
|
||||
for peer: ENetPacketPeer in _leaving.keys():
|
||||
if now - int(_leaving[peer]["since"]) >= leave_grace_msec:
|
||||
_cut_off(peer)
|
||||
|
||||
|
||||
## Sends `bytes` to a player. Returns false if they aren't connected.
|
||||
@@ -139,7 +173,7 @@ func kick(handle: int, reason: int = NetProtocol.REASON_KICKED) -> bool:
|
||||
events.append({"type": "left", "handle": handle, "name": name_of(handle), "reason": reason})
|
||||
_players.erase(handle)
|
||||
_handle_of.erase(peer)
|
||||
_leaving[peer] = reason
|
||||
_leaving[peer] = {"reason": reason, "since": Time.get_ticks_msec()}
|
||||
peer.send(NetProtocol.CHANNEL_CONTROL, NetProtocol.encode_reject(reason), ENetPacketPeer.FLAG_RELIABLE)
|
||||
peer.peer_disconnect_later(reason)
|
||||
return true
|
||||
@@ -209,9 +243,9 @@ func _received(peer: ENetPacketPeer, channel: int, bytes: PackedByteArray) -> vo
|
||||
|
||||
|
||||
## Turns a guest away: tells it why, then disconnects once that has been delivered.
|
||||
func _refuse(peer: ENetPacketPeer, reason: int) -> void:
|
||||
func _refuse(peer: ENetPacketPeer, reason: int, now: int = -1) -> void:
|
||||
_guests.erase(peer)
|
||||
_leaving[peer] = reason
|
||||
_leaving[peer] = {"reason": reason, "since": now if now >= 0 else Time.get_ticks_msec()}
|
||||
events.append({"type": "refused", "reason": reason})
|
||||
peer.send(NetProtocol.CHANNEL_CONTROL, NetProtocol.encode_reject(reason), ENetPacketPeer.FLAG_RELIABLE)
|
||||
peer.peer_disconnect_later(reason)
|
||||
@@ -238,14 +272,47 @@ func _any_active(peers: Array) -> bool:
|
||||
return false
|
||||
|
||||
|
||||
## Guests from the same source as `address` (an IPv6 address counts with its /64).
|
||||
func _guests_from(address: String) -> int:
|
||||
var source: String = SourceLimiter.source_of(address)
|
||||
var count: int = 0
|
||||
for peer: ENetPacketPeer in _guests:
|
||||
if peer.get_remote_address() == address:
|
||||
if _guests[peer]["source"] == source:
|
||||
count += 1
|
||||
return count
|
||||
|
||||
|
||||
## Drops a peer that was told to leave and hasn't acknowledged, freeing its slot. The
|
||||
## reason goes again as the disconnect's data.
|
||||
func _cut_off(peer: ENetPacketPeer) -> void:
|
||||
var reason: int = int(_leaving[peer]["reason"])
|
||||
_leaving.erase(peer)
|
||||
evicted += 1
|
||||
if peer.is_active():
|
||||
peer.peer_disconnect_now(reason)
|
||||
|
||||
|
||||
## Keeps a slot free for the next connection: when the newest guest took the last but
|
||||
## one, peers already told to leave go first, then the guest that has waited longest.
|
||||
func _make_room(newest: ENetPacketPeer) -> void:
|
||||
if _guests.size() + _players.size() + _leaving.size() < _capacity - 1:
|
||||
return
|
||||
for peer: ENetPacketPeer in _leaving.keys():
|
||||
_cut_off(peer)
|
||||
if _guests.size() + _players.size() < _capacity - 1:
|
||||
return
|
||||
var oldest: ENetPacketPeer = null
|
||||
for peer: ENetPacketPeer in _guests:
|
||||
if peer != newest and (oldest == null or int(_guests[peer]["since"]) < int(_guests[oldest]["since"])):
|
||||
oldest = peer
|
||||
if oldest == null:
|
||||
return
|
||||
_guests.erase(oldest)
|
||||
evicted += 1
|
||||
events.append({"type": "refused", "reason": NetProtocol.REASON_HANDSHAKE_TIMEOUT})
|
||||
oldest.peer_disconnect_now(NetProtocol.REASON_HANDSHAKE_TIMEOUT)
|
||||
|
||||
|
||||
## `wanted`, or `wanted` with a number after it if someone here already has that name.
|
||||
func _unique_name(wanted: String) -> String:
|
||||
var taken: Dictionary = {}
|
||||
|
||||
@@ -3,6 +3,10 @@
|
||||
## the list server) so a flood from one address is mostly ignored. Memory is bounded:
|
||||
## once `max_sources` addresses have been seen in a window, new ones are refused
|
||||
## until the next window.
|
||||
##
|
||||
## Limits count sources, not addresses: an IPv4 address is one source, and an IPv6
|
||||
## address counts with the rest of its /64, since one ordinary connection is handed a
|
||||
## whole /64 and could otherwise pass for millions of senders (H5).
|
||||
class_name SourceLimiter
|
||||
extends RefCounted
|
||||
|
||||
@@ -25,6 +29,7 @@ func _init(packets_per_window: int = 20, window: int = 1000, sources: int = 4096
|
||||
## True if a packet from `address` may be handled now. `now_msec` is for tests.
|
||||
func allow(address: String, now_msec: int = -1) -> bool:
|
||||
var now: int = now_msec if now_msec >= 0 else Time.get_ticks_msec()
|
||||
address = source_of(address)
|
||||
if _window_start < 0 or now - _window_start >= window_msec:
|
||||
_window_start = now
|
||||
_counts.clear()
|
||||
@@ -42,3 +47,55 @@ func allow(address: String, now_msec: int = -1) -> bool:
|
||||
## Addresses being counted in the current window.
|
||||
func tracked() -> int:
|
||||
return _counts.size()
|
||||
|
||||
|
||||
## The source an address counts as: an IPv4 address (also when written IPv4-mapped,
|
||||
## "::ffff:192.0.2.1") as itself, an IPv6 address as its /64 prefix ("2001:db8:0:1::/64"),
|
||||
## and anything that isn't an IP address unchanged.
|
||||
static func source_of(address: String) -> String:
|
||||
var text: String = address.strip_edges()
|
||||
var zone: int = text.find("%")
|
||||
if zone >= 0:
|
||||
text = text.substr(0, zone)
|
||||
if not text.contains(":"):
|
||||
return text
|
||||
var lower: String = text.to_lower()
|
||||
if lower.begins_with("::ffff:") and lower.contains("."):
|
||||
return lower.substr(7)
|
||||
var groups: PackedStringArray = _ipv6_groups(lower)
|
||||
if groups.is_empty():
|
||||
return address
|
||||
return "%s:%s:%s:%s::/64" % [groups[0], groups[1], groups[2], groups[3]]
|
||||
|
||||
|
||||
## The eight groups of an IPv6 address, each without leading zeros, or empty if it
|
||||
## doesn't parse.
|
||||
static func _ipv6_groups(text: String) -> PackedStringArray:
|
||||
var halves: PackedStringArray = text.split("::")
|
||||
if halves.size() > 2:
|
||||
return PackedStringArray()
|
||||
var head: PackedStringArray = halves[0].split(":", false) if not halves[0].is_empty() else PackedStringArray()
|
||||
var tail: PackedStringArray = PackedStringArray()
|
||||
if halves.size() == 2 and not halves[1].is_empty():
|
||||
tail = halves[1].split(":", false)
|
||||
# An embedded IPv4 tail ("::1.2.3.4") counts as two groups; only the prefix matters.
|
||||
var parts: int = head.size() + tail.size()
|
||||
if not tail.is_empty() and tail[tail.size() - 1].contains("."):
|
||||
parts += 1
|
||||
elif tail.is_empty() and not head.is_empty() and head[head.size() - 1].contains("."):
|
||||
parts += 1
|
||||
if (halves.size() == 1 and parts != 8) or parts > 8:
|
||||
return PackedStringArray()
|
||||
var groups: PackedStringArray = PackedStringArray()
|
||||
groups.append_array(head)
|
||||
for _index: int in 8 - parts:
|
||||
groups.append("0")
|
||||
groups.append_array(tail)
|
||||
for index: int in mini(groups.size(), 4):
|
||||
var group: String = groups[index]
|
||||
if group.is_empty() or group.length() > 4 or not group.is_valid_hex_number():
|
||||
return PackedStringArray()
|
||||
groups[index] = "%x" % group.hex_to_int()
|
||||
if groups.size() < 4:
|
||||
return PackedStringArray()
|
||||
return groups
|
||||
|
||||
@@ -137,7 +137,9 @@ static func from_bytes(bytes: PackedByteArray) -> CommandLog:
|
||||
var result: CommandLog = CommandLog.new(str(head["seed"]).to_int(), clampi(int(head.get("humans", 0)), 0, Tuning.SOLO_PLAYERS))
|
||||
var rule_values: Dictionary = head["rules"]
|
||||
for key: String in RULE_KEYS:
|
||||
if not rule_values.has(key):
|
||||
# A hand-edited or damaged file could hold any JSON here; int() of an array or
|
||||
# a dictionary is an error, so only numbers and booleans are read (H5).
|
||||
if not rule_values.has(key) or not _is_number(rule_values[key]):
|
||||
return null
|
||||
if key == "fill_with_bots":
|
||||
result.rules.fill_with_bots = bool(rule_values[key])
|
||||
@@ -145,10 +147,12 @@ static func from_bytes(bytes: PackedByteArray) -> CommandLog:
|
||||
result.rules.set(key, int(rule_values[key]))
|
||||
result.rules.max_players = clampi(result.rules.max_players, 1, Tuning.SOLO_PLAYERS)
|
||||
result.rules.team_size = maxi(result.rules.team_size, 1)
|
||||
result.final_tick = int(head.get("final_tick", 0))
|
||||
result.final_tick = int(head.get("final_tick", 0)) if _is_number(head.get("final_tick", 0)) else 0
|
||||
result.final_hash = str(head.get("final_hash", ""))
|
||||
if head.get("winners") is Array:
|
||||
for winner: Variant in head["winners"]:
|
||||
if not _is_number(winner):
|
||||
return null
|
||||
result.winners.append(int(winner))
|
||||
if head.get("notes") is Dictionary:
|
||||
result.notes = head["notes"]
|
||||
@@ -156,6 +160,10 @@ static func from_bytes(bytes: PackedByteArray) -> CommandLog:
|
||||
return result
|
||||
|
||||
|
||||
static func _is_number(value: Variant) -> bool:
|
||||
return value is int or value is float or value is bool
|
||||
|
||||
|
||||
## Writes the log to `path`, creating its folder. Returns OK or the error.
|
||||
func save(path: String) -> Error:
|
||||
var folder: String = path.get_base_dir()
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
## A server is listed under the address its packets come from, never one it claims,
|
||||
## and only after it has echoed a CHALLENGE token sent to that address, so nobody can
|
||||
## list a machine they don't control. Entries expire unless renewed, there is a cap
|
||||
## per address and overall, and every source is rate-limited.
|
||||
## per address (per /64 for IPv6) and overall, and every source is rate-limited.
|
||||
class_name ListServer
|
||||
extends RefCounted
|
||||
|
||||
@@ -137,10 +137,12 @@ func _answer(page: int, to_ip: String, to_port: int) -> void:
|
||||
_send(NetDiscovery.encode_list(page, pages, chosen), to_ip, to_port)
|
||||
|
||||
|
||||
## Entries from the same source as `address` (an IPv6 address counts with its /64).
|
||||
func _count_at(address: String) -> int:
|
||||
var source: String = SourceLimiter.source_of(address)
|
||||
var count: int = 0
|
||||
for key: String in _entries:
|
||||
if _entries[key]["address"] == address:
|
||||
if SourceLimiter.source_of(String(_entries[key]["address"])) == source:
|
||||
count += 1
|
||||
return count
|
||||
|
||||
|
||||
@@ -389,3 +389,97 @@ func test_a_graceful_shutdown_reaches_clients_on_a_lossy_link() -> void:
|
||||
assert_eq(client.close_reason, NetProtocol.REASON_SHUTDOWN, "%s was told the server stopped" % client.player_name)
|
||||
for relay: UdpRelay in relays:
|
||||
relay.close()
|
||||
|
||||
|
||||
## H5: a peer that connects and then never answers again: it doesn't say hello, and
|
||||
## doesn't acknowledge being turned away, so ENet alone would keep its slot for seconds.
|
||||
func _silent(silent: Array[ENetConnection]) -> void:
|
||||
var host: ENetConnection = ENetConnection.new()
|
||||
assert_eq(host.create_host(1, NetProtocol.CHANNEL_COUNT), OK)
|
||||
host.connect_to_host(HOST, server.port(), NetProtocol.CHANNEL_COUNT)
|
||||
silent.append(host)
|
||||
var connected: Array[bool] = [false]
|
||||
_pump(func() -> bool:
|
||||
var event: Array = host.service(0)
|
||||
if event[0] == ENetConnection.EVENT_CONNECT:
|
||||
connected[0] = true
|
||||
return connected[0], 2000)
|
||||
# The acknowledgement goes out on the next service; send it, then never again.
|
||||
host.flush()
|
||||
var before: int = server.guest_count() + _events("refused").size() + server.evicted
|
||||
_pump(func() -> bool: return server.guest_count() + _events("refused").size() + server.evicted > before, 1000)
|
||||
|
||||
|
||||
func _destroy(silent: Array[ENetConnection]) -> void:
|
||||
for host: ENetConnection in silent:
|
||||
host.destroy()
|
||||
|
||||
|
||||
func test_a_flood_from_one_address_cannot_hold_the_slots() -> void:
|
||||
server.close()
|
||||
server.max_players = 2
|
||||
server.peer_slots = 0
|
||||
server.connect_limiter = SourceLimiter.new(3, 60000)
|
||||
server.max_guests_per_address = 3
|
||||
server.handshake_timeout_msec = 60000
|
||||
assert_eq(server.listen(0, HOST), OK)
|
||||
# Ten slots: three silent guests, then peers turned away for flooding.
|
||||
var silent: Array[ENetConnection] = []
|
||||
for _index: int in 9:
|
||||
_silent(silent)
|
||||
assert_eq(server.guest_count(), 3)
|
||||
assert_eq(server.leaving_count(), 0, "peers turned away for flooding don't keep a slot")
|
||||
assert_eq(_events("refused").size(), 6)
|
||||
# The flood has passed; a real player still finds a slot.
|
||||
server.connect_limiter = SourceLimiter.new(32, 10000)
|
||||
server.max_guests_per_address = 8
|
||||
var client: NetClient = _client("After")
|
||||
assert_true(_pump(func() -> bool: return client.state == NetClient.JOINED or client.state == NetClient.CLOSED, 3000))
|
||||
assert_eq(client.state, NetClient.JOINED)
|
||||
_destroy(silent)
|
||||
|
||||
|
||||
func test_silent_guests_make_room_for_a_newcomer() -> void:
|
||||
server.close()
|
||||
server.max_players = 2
|
||||
server.peer_slots = 0
|
||||
server.max_guests_per_address = 64
|
||||
server.handshake_timeout_msec = 60000
|
||||
assert_eq(server.listen(0, HOST), OK)
|
||||
# More silent guests than the ten slots: the oldest make way, one slot stays free.
|
||||
var silent: Array[ENetConnection] = []
|
||||
for _index: int in 12:
|
||||
_silent(silent)
|
||||
assert_true(server.guest_count() <= 9, "a slot is kept free, %d guests" % server.guest_count())
|
||||
assert_true(server.evicted >= 3)
|
||||
var client: NetClient = _client("Newcomer")
|
||||
assert_true(_pump(func() -> bool: return client.state == NetClient.JOINED or client.state == NetClient.CLOSED, 3000))
|
||||
assert_eq(client.state, NetClient.JOINED)
|
||||
assert_eq(server.player_count(), 1)
|
||||
_destroy(silent)
|
||||
|
||||
|
||||
func test_a_peer_that_never_acknowledges_leaving_is_cut_off() -> void:
|
||||
server.close()
|
||||
server.max_players = 2
|
||||
server.handshake_timeout_msec = 100
|
||||
server.leave_grace_msec = 300
|
||||
assert_eq(server.listen(0, HOST), OK)
|
||||
var silent: Array[ENetConnection] = []
|
||||
_silent(silent)
|
||||
assert_true(_pump(func() -> bool: return server.leaving_count() == 1, 2000), "the silent guest was told to go")
|
||||
assert_true(_pump(func() -> bool: return server.leaving_count() == 0, 2000), "and cut off after its grace")
|
||||
assert_eq(server.evicted, 1)
|
||||
_destroy(silent)
|
||||
|
||||
|
||||
## H5: a client turned away for flooding learns why from the disconnect alone.
|
||||
func test_busy_reaches_the_client_without_a_reject_message() -> void:
|
||||
assert_true(NetProtocol.is_server_reason(NetProtocol.REASON_BUSY))
|
||||
assert_false(NetProtocol.is_server_reason(NetProtocol.REASON_NONE))
|
||||
assert_false(NetProtocol.is_server_reason(NetProtocol.REASON_LOST))
|
||||
server.connect_limiter = SourceLimiter.new(1, 60000)
|
||||
var first: NetClient = _client("First")
|
||||
var second: NetClient = _client("Second")
|
||||
assert_true(_pump(func() -> bool: return second.state == NetClient.CLOSED and first.state == NetClient.JOINED))
|
||||
assert_eq(second.close_reason, NetProtocol.REASON_BUSY)
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
extends TestCase
|
||||
|
||||
## H5: the rate limiter counts sources, and an IPv6 sender counts with its whole /64.
|
||||
|
||||
|
||||
func test_sources_group_ipv6_by_its_64_and_keep_ipv4_whole() -> void:
|
||||
assert_eq(SourceLimiter.source_of("192.0.2.7"), "192.0.2.7")
|
||||
assert_eq(SourceLimiter.source_of("::ffff:192.0.2.7"), "192.0.2.7", "IPv4-mapped counts as the IPv4 address")
|
||||
assert_eq(SourceLimiter.source_of("2001:db8:0:1::5"), "2001:db8:0:1::/64")
|
||||
assert_eq(SourceLimiter.source_of("2001:0DB8:0000:0001:ffff:1:2:3"), "2001:db8:0:1::/64")
|
||||
assert_eq(SourceLimiter.source_of("2001:db8::1"), "2001:db8:0:0::/64")
|
||||
assert_eq(SourceLimiter.source_of("::1"), "0:0:0:0::/64")
|
||||
assert_eq(SourceLimiter.source_of("fe80::1%eth0"), "fe80:0:0:0::/64")
|
||||
assert_eq(SourceLimiter.source_of("2001:db8:1:2:3:4:192.0.2.1"), "2001:db8:1:2::/64")
|
||||
assert_ne(SourceLimiter.source_of("2001:db8:0:1::5"), SourceLimiter.source_of("2001:db8:0:2::5"))
|
||||
# Not an address: left as it is, never an error.
|
||||
for odd: String in ["", "x", "1:2:3", "1::2::3", "zzzz::1", "12345::1"]:
|
||||
assert_eq(SourceLimiter.source_of(odd), odd)
|
||||
|
||||
|
||||
func test_one_ipv6_64_shares_one_allowance() -> void:
|
||||
var limiter: SourceLimiter = SourceLimiter.new(3, 1000, 16)
|
||||
for index: int in 3:
|
||||
assert_true(limiter.allow("2001:db8:0:1::%x" % (index + 1), 0))
|
||||
assert_false(limiter.allow("2001:db8:0:1::ffff", 0), "a fourth address in the same /64 is over the limit")
|
||||
assert_true(limiter.allow("2001:db8:0:2::1", 0), "the next /64 has its own allowance")
|
||||
assert_eq(limiter.tracked(), 2)
|
||||
|
||||
|
||||
func test_rotating_addresses_in_one_64_cannot_fill_the_table() -> void:
|
||||
var limiter: SourceLimiter = SourceLimiter.new(1000000, 1000, 4)
|
||||
for index: int in 5000:
|
||||
limiter.allow("2001:db8:0:1:%x::1" % index, 0)
|
||||
assert_eq(limiter.tracked(), 1)
|
||||
assert_true(limiter.allow("192.0.2.1", 0), "others are still let in")
|
||||
@@ -0,0 +1 @@
|
||||
uid://wnkqkkalmafs
|
||||
@@ -103,3 +103,34 @@ func test_bad_bytes_are_refused_without_errors() -> void:
|
||||
var short: PackedByteArray = good.duplicate()
|
||||
short.encode_u32(8 + head_size, CommandLog.RECORD_SIZE * 40)
|
||||
assert_null(CommandLog.from_bytes(short))
|
||||
|
||||
|
||||
## H5: a header whose fields are the wrong kind of JSON is refused, never an error.
|
||||
func test_a_header_with_the_wrong_types_is_refused_without_errors() -> void:
|
||||
var good: PackedByteArray = _log().to_bytes()
|
||||
var head_size: int = good.decode_u32(4)
|
||||
var head: Dictionary = JSON.parse_string(good.slice(8, 8 + head_size).get_string_from_utf8())
|
||||
var records: PackedByteArray = good.slice(8 + head_size)
|
||||
var bad_rule: Dictionary = head.duplicate(true)
|
||||
bad_rule["rules"]["max_players"] = [1, 2]
|
||||
var bad_winner: Dictionary = head.duplicate(true)
|
||||
bad_winner["winners"] = [{"x": 1}]
|
||||
var bad_tick: Dictionary = head.duplicate(true)
|
||||
bad_tick["final_tick"] = {"x": 1}
|
||||
for changed: Dictionary in [bad_rule, bad_winner]:
|
||||
assert_null(CommandLog.from_bytes(_with_head(changed, records)))
|
||||
var read: CommandLog = CommandLog.from_bytes(_with_head(bad_tick, records))
|
||||
assert_not_null(read, "a bad final tick alone still leaves a usable log")
|
||||
assert_eq(read.final_tick, 0)
|
||||
assert_eq(read.count(), 3)
|
||||
|
||||
|
||||
func _with_head(head: Dictionary, records: PackedByteArray) -> PackedByteArray:
|
||||
var text: PackedByteArray = JSON.stringify(head).to_utf8_buffer()
|
||||
var out: StreamPeerBuffer = StreamPeerBuffer.new()
|
||||
out.big_endian = false
|
||||
out.put_data(CommandLog.MAGIC.to_ascii_buffer())
|
||||
out.put_u32(text.size())
|
||||
out.put_data(text)
|
||||
out.put_data(records)
|
||||
return out.data_array
|
||||
|
||||
@@ -159,7 +159,7 @@ func test_practice_and_join_say_what_was_asked() -> void:
|
||||
assert_eq(GameSettings.load_from(PATH).last_server, "127.0.0.1:24999")
|
||||
# A found server, chosen from the list.
|
||||
menus.show_servers([
|
||||
{"name": "Old", "players": 9, "max_players": 24, "address": "10.0.0.9", "port": 24650, "source": "lan", "compatible": false},
|
||||
{"name": "Old", "players": 9, "max_players": 24, "address": "192.0.2.9", "port": 24650, "source": "lan", "compatible": false},
|
||||
{"name": "Harbour", "players": 3, "max_players": 24, "address": "127.0.0.1", "port": 24651, "source": "lan", "compatible": true},
|
||||
] as Array[Dictionary])
|
||||
menus._servers.select(0)
|
||||
|
||||
@@ -58,6 +58,9 @@ touch "$repo/tools/godot/.gdignore"
|
||||
args=("--path" "$repo")
|
||||
if [[ "${TIDEWALL_GODOT_DISPLAY:-0}" != "1" ]]; then
|
||||
args+=("--headless")
|
||||
# Even headless, the engine shows its error alerts (a script that can't run, say)
|
||||
# through zenity or kdialog on whatever display the environment names. Name none.
|
||||
unset DISPLAY WAYLAND_DISPLAY
|
||||
fi
|
||||
|
||||
exec "$binary" "${args[@]}" "$@"
|
||||
|
||||
Reference in New Issue
Block a user