N9: Server-side cheat and abuse protection
- A hostile test client crafts INPUT packets byte by byte and sends them through NetGame.take_input() into a real match: extreme axes, the same tick claimed repeatedly, the whole lead window at once, past, far-future and maximum ticks, fire toggled every tick with slot swaps, builds aimed anywhere with junk kinds and materials and no materials, and pickup/drop/select tricks. Speed stays within sprint speed per tick, shots within the weapon's rate, pieces within build reach and paid for, and every item is conserved. - Fix: a command tick beyond the simulation's lead window no longer moves NetGame's dedupe marker, so one bogus far-future tick can't lock out a player's real commands. - Connections are rate-limited per address (32 per 10 s, 8 handshakes in progress) with a new REASON_BUSY and a message for it. - ParserFuzz mutates real messages from a bot match and random bytes and feeds them to every network decoder, the snapshot receiver and the list server. 20,000 per make check; make fuzz runs 1,000,000 (about 40 s): no errors, 2.9 KB of memory growth. - ARCHITECTURE.md: "Trusting nothing from clients". Closes #40 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -35,6 +35,7 @@ continuity.
|
||||
| `tools/godot.sh -- --list-server [--port=N]` | Runs a list server (default UDP port 24660). Game servers started with `--listen --list=HOST[:PORT] --name=NAME` register with it; see `src/server/list_server.gd`. |
|
||||
| `tools/godot.sh -- --browse [--list=HOST[:PORT]] [--lan-target=IP] [--lan-port=N]` | Looks for servers on the LAN and in list servers and prints them as one JSON line. Menus (A10) will show the same list. |
|
||||
| `make discovery-check` | Starts a list server and a game server as processes and checks `--browse` finds the game both on the LAN (loopback) and through the list (about 15 s). |
|
||||
| `make fuzz` | Feeds 1,000,000 malformed messages (`FUZZ_MESSAGES=N`, `FUZZ_SEED=N`) to every network parser and fails on any engine error or memory growth (about 40 s). |
|
||||
| `make client-captures` | Renders what a network client sees on the barge, gliding and landed (`captures/client_<stage>.png`). Needs Docker. Look at them. |
|
||||
| `make capture-test` | Proves the capture harness works and rejects a blank frame. Needs Docker, so it isn't part of `make check`. |
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Tidewall build entry points. Everything runs headless with the repo-local engine.
|
||||
GODOT := tools/godot.sh
|
||||
|
||||
.PHONY: check import parse test test-selfcheck smoke capture-test terrain-capture binaries verify-engine bot-matches match match-captures client-check client-captures discovery-check
|
||||
.PHONY: check import parse test test-selfcheck smoke capture-test terrain-capture binaries verify-engine bot-matches match match-captures client-check client-captures discovery-check fuzz
|
||||
|
||||
## Everything that must pass before a push.
|
||||
check: verify-engine binaries parse test test-selfcheck smoke
|
||||
@@ -51,6 +51,12 @@ match-captures: import
|
||||
client-check: import
|
||||
@tools/client_check.sh
|
||||
|
||||
## Feeds FUZZ_MESSAGES (default 1,000,000) malformed messages to every network parser.
|
||||
FUZZ_MESSAGES ?= 1000000
|
||||
FUZZ_SEED ?= 1
|
||||
fuzz: import
|
||||
@nice -n 15 $(GODOT) --script res://tools/fuzz_parsers.gd -- --messages=$(FUZZ_MESSAGES) --seed=$(FUZZ_SEED)
|
||||
|
||||
## Finds a real game server on the LAN (over loopback) and through a real list server.
|
||||
discovery-check: import
|
||||
@tools/discovery_check.sh
|
||||
|
||||
@@ -177,6 +177,36 @@ during results, becomes a watcher (`Match.watch()`): they spectate a living play
|
||||
and take a place ahead of any bots when the next lobby opens. The server still turns
|
||||
people away when `NetServer.max_players` people are connected.
|
||||
|
||||
## Trusting nothing from clients
|
||||
|
||||
Tidewall is open source, so anyone can build a client that sends whatever bytes it
|
||||
likes. The server's defences, and the tests that attack them
|
||||
(`test/server/test_hostile_client.gd`, `test/net/test_net_handshake.gd`,
|
||||
`test/net/test_parser_fuzz.gd`, `make fuzz`):
|
||||
|
||||
- **Intent only.** A command carries movement axes, look, buttons, a slot, a
|
||||
material and a view lag. There is no position, velocity, hit, target or item in
|
||||
it, so speed, teleport, aimbot-by-claim and duplication can't even be expressed.
|
||||
Every field is clamped on decode, and the simulation applies its own limits:
|
||||
sprint speed, the weapon's fire interval, build reach (`Tuning.BUILD_RANGE`) and
|
||||
material cost, pickup reach, one pickup or drop per press, lag compensation at
|
||||
most `Tuning.LAG_COMPENSATION_MAX_TICKS`.
|
||||
- **One command per tick.** Each tick's command is taken once, the first time it
|
||||
arrives. A tick already past or more than `Tuning.MAX_COMMAND_LEAD_TICKS` ahead is
|
||||
ignored, and a far-future tick can't move the dedupe marker and lock out the real
|
||||
ones.
|
||||
- **Bounded messages.** An INPUT has at most `NetSnapshot.MAX_INPUT_COMMANDS`
|
||||
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.
|
||||
- **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
|
||||
errors and memory growth.
|
||||
|
||||
## Snapshot format
|
||||
|
||||
`NetSnapshot` (`src/net/`) owns the layouts. An entity travels as a **record**: a list
|
||||
|
||||
@@ -39,6 +39,8 @@ const REASON_LEFT: int = 7
|
||||
## Client-side only: nothing answered, or the connection went quiet.
|
||||
const REASON_NO_ANSWER: int = 8
|
||||
const REASON_LOST: int = 9
|
||||
## Too many connections from one address in a short time.
|
||||
const REASON_BUSY: int = 10
|
||||
|
||||
const NAME_MAX_CHARS: int = 16
|
||||
const NAME_MAX_BYTES: int = 64
|
||||
@@ -168,6 +170,8 @@ static func reason_text(reason: int, server_version: int = 0, own_version: int =
|
||||
return "The server removed you from the game."
|
||||
REASON_LEFT:
|
||||
return "You left the game."
|
||||
REASON_BUSY:
|
||||
return "Too many connections from your address just now. Wait a few seconds and try again."
|
||||
REASON_NO_ANSWER:
|
||||
return "No answer from the server. Check the address and port, and that the server is running."
|
||||
REASON_LOST:
|
||||
|
||||
@@ -27,6 +27,11 @@ var packets: Array[Dictionary] = []
|
||||
var max_packets_per_poll: int = 32
|
||||
## Malformed or unexpected packets dropped so far.
|
||||
var bad_packets: int = 0
|
||||
## New connections allowed from one address per window. Generous enough for a LAN
|
||||
## party behind one router joining at once; a flood from one address is turned away.
|
||||
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
|
||||
|
||||
var _host: ENetConnection = null
|
||||
## Peers that haven't finished the handshake: ENetPacketPeer -> msec they connected.
|
||||
@@ -103,6 +108,10 @@ func poll(now_msec: int = -1) -> void:
|
||||
match kind:
|
||||
ENetConnection.EVENT_CONNECT:
|
||||
peer.set_timeout(0, 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)
|
||||
continue
|
||||
_guests[peer] = now
|
||||
ENetConnection.EVENT_DISCONNECT:
|
||||
_gone(peer, int(event[2]))
|
||||
@@ -209,6 +218,14 @@ func _gone(peer: ENetPacketPeer, data: int) -> void:
|
||||
_handle_of.erase(peer)
|
||||
|
||||
|
||||
func _guests_from(address: String) -> int:
|
||||
var count: int = 0
|
||||
for peer: ENetPacketPeer in _guests:
|
||||
if peer.get_remote_address() == address:
|
||||
count += 1
|
||||
return count
|
||||
|
||||
|
||||
## `wanted`, or `wanted` with a number after it if someone here already has that name.
|
||||
func _unique_name(wanted: String) -> String:
|
||||
var taken: Dictionary = {}
|
||||
|
||||
@@ -90,8 +90,11 @@ func take_input(handle: int, bytes: PackedByteArray) -> void:
|
||||
# Packets repeat recent commands; each tick's command is offered once, whether
|
||||
# or not the simulation takes it. The newest tick received is echoed either way,
|
||||
# so a client whose commands come too late or too early can tell.
|
||||
# A tick further ahead than the simulation would ever take is ignored outright,
|
||||
# so a corrupt or hostile one can't push the marker past every real command.
|
||||
var furthest: int = loop.sim.tick + Tuning.MAX_COMMAND_LEAD_TICKS
|
||||
for command: PlayerCommand in input["commands"]:
|
||||
if command.tick <= int(_last_command[handle]):
|
||||
if command.tick <= int(_last_command[handle]) or command.tick > furthest:
|
||||
continue
|
||||
_last_command[handle] = command.tick
|
||||
sender.note_command(handle, command.tick)
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
## Feeds malformed messages to every parser that reads bytes from the network: the
|
||||
## handshake, inputs, snapshots, match notices, world and inventory messages, and
|
||||
## discovery, plus the stateful snapshot receiver and the list server's handler.
|
||||
## Messages are mutations of real ones taken from a running match (bit flips,
|
||||
## truncation, extension, splices, runs of 0x00 and 0xFF, a different type byte) and
|
||||
## plain random bytes.
|
||||
##
|
||||
## Used by test_parser_fuzz.gd with a small count and by `make fuzz` with 1,000,000.
|
||||
## Nothing here may raise an engine error; whoever runs it checks that.
|
||||
class_name ParserFuzz
|
||||
extends RefCounted
|
||||
|
||||
const MAX_LENGTH: int = 1600
|
||||
|
||||
var rng: RandomNumberGenerator = RandomNumberGenerator.new()
|
||||
## Real messages to mutate.
|
||||
var seeds: Array[PackedByteArray] = []
|
||||
var messages: int = 0
|
||||
## Messages some parser accepted as well formed.
|
||||
var accepted: int = 0
|
||||
## Static memory in use after the warm-up and at the end, in bytes.
|
||||
var memory_start: int = 0
|
||||
var memory_end: int = 0
|
||||
var memory_peak: int = 0
|
||||
|
||||
var _receiver: SnapshotReceiver = SnapshotReceiver.new()
|
||||
var _list: ListServer = ListServer.new()
|
||||
|
||||
|
||||
func _init(fuzz_seed: int) -> void:
|
||||
rng.seed = fuzz_seed
|
||||
# The list server has no socket here, so it answers nothing; and no rate limit,
|
||||
# so every message reaches its parser.
|
||||
_list.limiter = SourceLimiter.new(1 << 30)
|
||||
|
||||
|
||||
## Takes real messages from a short bot match: snapshots, world, inventory and match
|
||||
## notices, plus one of every handshake and discovery message.
|
||||
func collect_seeds() -> void:
|
||||
var loop: ServerLoop = ServerLoop.new(9, 1, 5, null)
|
||||
var game: NetGame = NetGame.new(loop, NetServer.new())
|
||||
game.adopt(1)
|
||||
seeds.append(game.world_notice())
|
||||
seeds.append(game.match_notice())
|
||||
for tick: int in 150:
|
||||
loop.run_tick()
|
||||
game.after_tick()
|
||||
if not game.world_changes.is_empty():
|
||||
seeds.append(game.world_changes)
|
||||
for bytes: PackedByteArray in game.own_changes.values():
|
||||
seeds.append(bytes)
|
||||
if tick % 10 == 0:
|
||||
seeds.append(game.snapshot_for(1))
|
||||
var command: PlayerCommand = PlayerCommand.from_input(12, Vector2(0.3, 1.0), 1.0, 0.2, PlayerCommand.BUTTON_FIRE, 2, 1)
|
||||
seeds.append(NetSnapshot.encode_input(40, [command, command] as Array[PlayerCommand]))
|
||||
seeds.append(NetProtocol.encode_hello("Fuzzer"))
|
||||
seeds.append(NetProtocol.encode_welcome(3, 77, 24, "Fuzzer"))
|
||||
seeds.append(NetProtocol.encode_reject(NetProtocol.REASON_FULL))
|
||||
var info: Dictionary = NetDiscovery.info(24650, 3, 24, 1, "Fuzz Harbour")
|
||||
seeds.append(NetDiscovery.encode_query(1))
|
||||
seeds.append(NetDiscovery.encode_info(info))
|
||||
seeds.append(NetDiscovery.encode_register(5, info))
|
||||
seeds.append(NetDiscovery.encode_challenge(5))
|
||||
info["address"] = "192.0.2.4"
|
||||
seeds.append(NetDiscovery.encode_list(0, 1, [info, info] as Array[Dictionary]))
|
||||
|
||||
|
||||
## Runs `count` messages through every parser.
|
||||
func run(count: int) -> void:
|
||||
if seeds.is_empty():
|
||||
collect_seeds()
|
||||
var warm: int = mini(count, 2000)
|
||||
for index: int in count:
|
||||
if index == warm:
|
||||
memory_start = OS.get_static_memory_usage()
|
||||
feed(next_message())
|
||||
if index % 10000 == 0:
|
||||
memory_peak = maxi(memory_peak, OS.get_static_memory_usage())
|
||||
memory_end = OS.get_static_memory_usage()
|
||||
memory_peak = maxi(memory_peak, memory_end)
|
||||
|
||||
|
||||
func next_message() -> PackedByteArray:
|
||||
if rng.randf() < 0.15:
|
||||
var noise: PackedByteArray = PackedByteArray()
|
||||
noise.resize(rng.randi_range(0, MAX_LENGTH))
|
||||
for index: int in noise.size():
|
||||
noise[index] = rng.randi() & 0xFF
|
||||
return noise
|
||||
var bytes: PackedByteArray = seeds[rng.randi_range(0, seeds.size() - 1)].duplicate()
|
||||
for _change: int in rng.randi_range(1, 4):
|
||||
_mutate(bytes)
|
||||
if bytes.size() > MAX_LENGTH:
|
||||
bytes.resize(MAX_LENGTH)
|
||||
return bytes
|
||||
|
||||
|
||||
func feed(bytes: PackedByteArray) -> void:
|
||||
messages += 1
|
||||
var results: Array = [
|
||||
NetProtocol.decode_hello(bytes), NetProtocol.decode_welcome(bytes), NetProtocol.decode_reject(bytes),
|
||||
NetSnapshot.decode_input(bytes), NetSnapshot.decode_snapshot(bytes), NetSnapshot.decode_match(bytes),
|
||||
NetWorld.decode_world(bytes), NetWorld.decode_own(bytes),
|
||||
NetDiscovery.decode_query(bytes), NetDiscovery.decode_info(bytes), NetDiscovery.decode_register(bytes),
|
||||
NetDiscovery.decode_challenge(bytes), NetDiscovery.decode_list(bytes),
|
||||
]
|
||||
for result: Dictionary in results:
|
||||
if not result.is_empty():
|
||||
accepted += 1
|
||||
break
|
||||
_receiver.apply(bytes)
|
||||
_list.handle(bytes, "198.51.100.%d" % (messages % 250 + 1), 40000 + messages % 13, messages)
|
||||
# Keep the list server's state from being the thing that grows.
|
||||
if messages % 5000 == 0:
|
||||
_list.expire(messages + ListServer.ENTRY_TTL_MSEC + 1)
|
||||
|
||||
|
||||
func listed() -> int:
|
||||
return _list.entry_count()
|
||||
|
||||
|
||||
func _mutate(bytes: PackedByteArray) -> void:
|
||||
match rng.randi_range(0, 6):
|
||||
0:
|
||||
if not bytes.is_empty():
|
||||
var at: int = rng.randi_range(0, bytes.size() - 1)
|
||||
bytes[at] = bytes[at] ^ (1 << rng.randi_range(0, 7))
|
||||
1:
|
||||
if not bytes.is_empty():
|
||||
bytes[rng.randi_range(0, bytes.size() - 1)] = rng.randi() & 0xFF
|
||||
2:
|
||||
bytes.resize(rng.randi_range(0, bytes.size()))
|
||||
3:
|
||||
for _extra: int in rng.randi_range(1, 64):
|
||||
bytes.append(rng.randi() & 0xFF)
|
||||
4:
|
||||
# A run of 0x00 or 0xFF: large counts, long varints, zero lengths.
|
||||
if not bytes.is_empty():
|
||||
var at: int = rng.randi_range(0, bytes.size() - 1)
|
||||
var fill: int = 0xFF if rng.randf() < 0.5 else 0x00
|
||||
for index: int in range(at, mini(at + rng.randi_range(1, 12), bytes.size())):
|
||||
bytes[index] = fill
|
||||
5:
|
||||
var other: PackedByteArray = seeds[rng.randi_range(0, seeds.size() - 1)]
|
||||
if not other.is_empty() and not bytes.is_empty():
|
||||
var cut: int = rng.randi_range(0, bytes.size() - 1)
|
||||
var from: int = rng.randi_range(0, other.size() - 1)
|
||||
bytes.resize(cut)
|
||||
bytes.append_array(other.slice(from))
|
||||
6:
|
||||
if not bytes.is_empty():
|
||||
var types: Array[int] = [
|
||||
NetProtocol.MSG_HELLO, NetProtocol.MSG_WELCOME, NetProtocol.MSG_REJECT, NetSnapshot.MSG_MATCH,
|
||||
NetWorld.MSG_WORLD, NetWorld.MSG_OWN, NetSnapshot.MSG_SNAPSHOT, NetSnapshot.MSG_INPUT,
|
||||
]
|
||||
bytes[0] = types[rng.randi_range(0, types.size() - 1)]
|
||||
@@ -0,0 +1 @@
|
||||
uid://rpodlivhv7av
|
||||
@@ -300,3 +300,36 @@ func test_two_servers_cannot_share_a_port() -> void:
|
||||
assert_ne(other.listen(server.port(), HOST), OK)
|
||||
assert_false(other.is_listening())
|
||||
assert_true(server.is_listening())
|
||||
|
||||
|
||||
func test_a_burst_of_connections_from_one_address_is_turned_away() -> void:
|
||||
server.connect_limiter = SourceLimiter.new(3, 60000)
|
||||
var burst: Array[NetClient] = []
|
||||
for index: int in 5:
|
||||
burst.append(_client("Wave %d" % index))
|
||||
assert_true(_pump(func() -> bool:
|
||||
var settled: int = 0
|
||||
for client: NetClient in burst:
|
||||
if client.state == NetClient.JOINED or client.state == NetClient.CLOSED:
|
||||
settled += 1
|
||||
return settled == burst.size()))
|
||||
var joined: int = 0
|
||||
for client: NetClient in burst:
|
||||
if client.state == NetClient.JOINED:
|
||||
joined += 1
|
||||
else:
|
||||
assert_eq(client.close_reason, NetProtocol.REASON_BUSY)
|
||||
assert_eq(joined, 3)
|
||||
assert_eq(server.player_count(), 3)
|
||||
assert_true(NetProtocol.reason_text(NetProtocol.REASON_BUSY).begins_with("Too many connections"))
|
||||
|
||||
|
||||
func test_handshakes_held_open_from_one_address_are_capped() -> void:
|
||||
server.max_guests_per_address = 2
|
||||
# Raw peers that connect and never say hello.
|
||||
for _index: int in 4:
|
||||
_raw()
|
||||
assert_true(_pump(func() -> bool: return _events("refused").size() >= 2))
|
||||
assert_eq(server.guest_count(), 2)
|
||||
for event: Dictionary in _events("refused"):
|
||||
assert_eq(event["reason"], NetProtocol.REASON_BUSY)
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
extends TestCase
|
||||
|
||||
## Issue N9: malformed messages never crash a parser or make memory grow. This runs a
|
||||
## short pass on every `make check`; `make fuzz` runs 1,000,000 messages.
|
||||
|
||||
|
||||
func test_malformed_messages_are_refused_without_errors_or_growth() -> void:
|
||||
var fuzz: ParserFuzz = ParserFuzz.new(2026)
|
||||
fuzz.collect_seeds()
|
||||
assert_true(fuzz.seeds.size() > 20, "%d real messages to mutate" % fuzz.seeds.size())
|
||||
# Every seed is a message some parser takes.
|
||||
for bytes: PackedByteArray in fuzz.seeds:
|
||||
var before: int = fuzz.accepted
|
||||
fuzz.feed(bytes)
|
||||
assert_eq(fuzz.accepted, before + 1, "a seed of %d bytes, type %d, was refused" % [bytes.size(), bytes[0]])
|
||||
fuzz.run(20000)
|
||||
assert_eq(fuzz.messages, 20000 + fuzz.seeds.size())
|
||||
assert_true(fuzz.accepted > fuzz.seeds.size(), "some mutations still parse, so parsers are reached past the first byte")
|
||||
assert_eq(fuzz.listed(), 0, "no mutation guessed a list server's token")
|
||||
var growth: int = fuzz.memory_end - fuzz.memory_start
|
||||
assert_true(growth < 8 * 1024 * 1024, "memory grew %d bytes" % growth)
|
||||
@@ -0,0 +1 @@
|
||||
uid://dpkot3jo4k6pc
|
||||
@@ -0,0 +1,259 @@
|
||||
extends TestCase
|
||||
|
||||
## Issue N9: a hostile client tries the usual cheats and every one fails. Its packets
|
||||
## are crafted byte by byte, outside anything the real client would send, and go in
|
||||
## through NetGame.take_input(), the same door a network packet uses, into a real
|
||||
## match on a real island. The server trusts nothing in them but intent.
|
||||
|
||||
const HOSTILE: int = 1
|
||||
const VICTIM: int = 2
|
||||
|
||||
var loop: ServerLoop
|
||||
var game: NetGame
|
||||
var rng: RandomNumberGenerator
|
||||
|
||||
|
||||
func before_each() -> void:
|
||||
var rules: MatchRules = MatchRules.immediate()
|
||||
rules.max_players = 2
|
||||
rules.min_players = 1
|
||||
rules.fill_with_bots = false
|
||||
loop = ServerLoop.new(77, 2, 0, rules)
|
||||
game = NetGame.new(loop, NetServer.new())
|
||||
game.adopt(HOSTILE)
|
||||
game.adopt(VICTIM)
|
||||
assert_true(loop.match_flow.in_match())
|
||||
rng = RandomNumberGenerator.new()
|
||||
rng.seed = 1999
|
||||
# Both off the barge and standing on level dry ground, as if they had landed.
|
||||
var spot: Vector3 = _level_spot()
|
||||
_stand(HOSTILE, spot)
|
||||
_stand(VICTIM, spot + Vector3(0.0, 0.0, 6.0))
|
||||
|
||||
|
||||
func _player(handle: int) -> SimEntity:
|
||||
return loop.sim.entities.find(int(loop.match_flow.entity_of[handle]))
|
||||
|
||||
|
||||
func _stand(handle: int, at: Vector3) -> void:
|
||||
var player: SimEntity = _player(handle)
|
||||
player.drop_state = Drop.NONE
|
||||
player.position = at
|
||||
player.velocity = Vector3.ZERO
|
||||
player.on_ground = true
|
||||
|
||||
|
||||
## A dry, level point well inland.
|
||||
func _level_spot() -> Vector3:
|
||||
var ground: SimGround = loop.sim.ground
|
||||
var centre: float = Tuning.WORLD_SIZE_METRES * 0.5
|
||||
for ring: int in range(0, 400, 8):
|
||||
for step: int in 16:
|
||||
var angle: float = TAU * step / 16.0
|
||||
var x: float = centre + cos(angle) * ring
|
||||
var z: float = centre + sin(angle) * ring
|
||||
var height: float = ground.terrain_height(x, z)
|
||||
if height < Tuning.ISLAND_BEACH_TOP + 6.0:
|
||||
continue
|
||||
var flat: bool = true
|
||||
for offset: Vector2 in [Vector2(8, 0), Vector2(-8, 0), Vector2(0, 8), Vector2(0, -8), Vector2(0, 14)]:
|
||||
if absf(ground.terrain_height(x + offset.x, z + offset.y) - height) > 0.6:
|
||||
flat = false
|
||||
if flat:
|
||||
return Vector3(x, height, z)
|
||||
fail("no level ground on this island")
|
||||
return Vector3.ZERO
|
||||
|
||||
|
||||
## A command's 15 bytes with any value in any field, past what PlayerCommand.encode()
|
||||
## would ever produce.
|
||||
func _raw_command(tick: int, move_x: int, move_y: int, yaw: int, pitch: int, buttons: int, selection: int, material: int, view_lag: int) -> PackedByteArray:
|
||||
var bytes: PackedByteArray = PackedByteArray()
|
||||
bytes.resize(PlayerCommand.ENCODED_SIZE)
|
||||
bytes.encode_u32(0, tick & 0xFFFFFFFF)
|
||||
bytes.encode_s8(4, move_x)
|
||||
bytes.encode_s8(5, move_y)
|
||||
bytes.encode_u16(6, yaw & 0xFFFF)
|
||||
bytes.encode_s16(8, pitch)
|
||||
bytes.encode_u16(10, buttons & 0xFFFF)
|
||||
bytes.encode_u8(12, selection & 0xFF)
|
||||
bytes.encode_u8(13, material & 0xFF)
|
||||
bytes.encode_u8(14, view_lag & 0xFF)
|
||||
return bytes
|
||||
|
||||
|
||||
func _packet(commands: Array[PackedByteArray]) -> PackedByteArray:
|
||||
var bytes: PackedByteArray = PackedByteArray([NetSnapshot.MSG_INPUT, 0, 0, 0, 0, commands.size()])
|
||||
for command: PackedByteArray in commands:
|
||||
bytes.append_array(command)
|
||||
return bytes
|
||||
|
||||
|
||||
## Sends the hostile packet for this tick, then runs it.
|
||||
func _tick(commands: Array[PackedByteArray]) -> void:
|
||||
game.take_input(HOSTILE, _packet(commands))
|
||||
loop.run_tick()
|
||||
game.after_tick()
|
||||
|
||||
|
||||
func _horizontal(a: Vector3, b: Vector3) -> float:
|
||||
return Vector2(a.x - b.x, a.z - b.z).length()
|
||||
|
||||
|
||||
func test_speed_and_teleport_cheats_move_no_faster_than_sprinting() -> void:
|
||||
var player: SimEntity = _player(HOSTILE)
|
||||
var limit: float = Tuning.SPRINT_SPEED / Tuning.TICK_RATE_HZ + 0.001
|
||||
var start: Vector3 = player.position
|
||||
var fastest: float = 0.0
|
||||
var ticks: int = 150
|
||||
for _index: int in ticks:
|
||||
var now: int = loop.sim.tick
|
||||
var commands: Array[PackedByteArray] = []
|
||||
# The most extreme axes the bytes allow, sprint and jump, the same tick sent
|
||||
# several times with different contents, and every tick of the lead window
|
||||
# filled at once, as if the client could play ahead of the server.
|
||||
for copy: int in 3:
|
||||
commands.append(_raw_command(now + 1, -128, -128, 8192, 0, PlayerCommand.BUTTON_SPRINT | PlayerCommand.BUTTON_JUMP | 0xFE00, 0, 0, 255))
|
||||
for ahead: int in range(2, NetSnapshot.MAX_INPUT_COMMANDS - 4):
|
||||
commands.append(_raw_command(now + ahead, -128 if ahead % 2 == 0 else 127, -128, 8192 * ahead, 0, 0xFFFF, 255, 255, 255))
|
||||
# Ticks the server can never take: long past, far future, and the largest.
|
||||
commands.append(_raw_command(now - 500, 127, 127, 0, 0, 0xFFFF, 0, 0, 0))
|
||||
commands.append(_raw_command(now + 10000, 127, 127, 0, 0, 0xFFFF, 0, 0, 0))
|
||||
commands.append(_raw_command(0xFFFFFFFF, 127, 127, 0, 0, 0xFFFF, 0, 0, 0))
|
||||
assert_eq(commands.size(), NetSnapshot.MAX_INPUT_COMMANDS)
|
||||
var before: Vector3 = player.position
|
||||
_tick(commands)
|
||||
fastest = maxf(fastest, _horizontal(player.position, before))
|
||||
assert_true(fastest <= limit, "fastest step %.4f m against a limit of %.4f m" % [fastest, limit])
|
||||
assert_true(_horizontal(player.position, start) <= limit * ticks)
|
||||
assert_true(_horizontal(player.position, start) > 1.0, "the cheater still moves: commands weren't simply refused")
|
||||
|
||||
|
||||
func test_a_packet_with_too_many_commands_is_refused_whole() -> void:
|
||||
var commands: Array[PackedByteArray] = []
|
||||
for ahead: int in NetSnapshot.MAX_INPUT_COMMANDS + 1:
|
||||
commands.append(_raw_command(loop.sim.tick + 1 + ahead, 127, 127, 0, 0, 0, 0, 0, 0))
|
||||
var bad: int = game.bad_inputs
|
||||
_tick(commands)
|
||||
assert_eq(game.bad_inputs, bad + 1)
|
||||
|
||||
|
||||
func test_a_far_future_command_does_not_lock_out_the_real_ones() -> void:
|
||||
var player: SimEntity = _player(HOSTILE)
|
||||
var start: Vector3 = player.position
|
||||
_tick([_raw_command(0xFFFFFFFF, 0, 0, 0, 0, 0, 0, 0, 0)] as Array[PackedByteArray])
|
||||
for _index: int in 30:
|
||||
_tick([_raw_command(loop.sim.tick + 1, 0, 127, 0, 0, 0, 0, 0, 0)] as Array[PackedByteArray])
|
||||
assert_true(_horizontal(player.position, start) > 1.0, "commands after a bogus far-future one are still taken")
|
||||
|
||||
|
||||
func test_rapid_fire_is_held_to_the_weapons_rate() -> void:
|
||||
var player: SimEntity = _player(HOSTILE)
|
||||
var code: int = ItemCatalog.code_of("dock_carbine")
|
||||
Inventory.give(player, code, 1)
|
||||
Inventory.give(player, ItemCatalog.get_def(code).ammo_code, 999)
|
||||
var interval: int = ItemCatalog.get_def(code).fire_interval_ticks()
|
||||
var shots: int = 0
|
||||
var ticks: int = 240
|
||||
for index: int in ticks:
|
||||
var now: int = loop.sim.tick
|
||||
# Fire pressed, released and pressed again within one tick's packet, fire on
|
||||
# every tick of the lead window, and a slot change every tick to try to skip
|
||||
# the cooldown.
|
||||
var commands: Array[PackedByteArray] = []
|
||||
for ahead: int in range(1, mini(12, NetSnapshot.MAX_INPUT_COMMANDS + 1)):
|
||||
var buttons: int = PlayerCommand.BUTTON_FIRE if (index + ahead) % 2 == 0 else PlayerCommand.BUTTON_FIRE | PlayerCommand.BUTTON_AIM
|
||||
commands.append(_raw_command(now + ahead, 0, 0, 0, 0, buttons, 1 + (index % 2), 0, 255))
|
||||
_tick(commands)
|
||||
for event: Dictionary in loop.sim.events:
|
||||
if event["type"] == "shot" and event["player"] == player.id:
|
||||
shots += 1
|
||||
var most: int = ceili(float(ticks) / interval) + 1
|
||||
assert_true(shots <= most, "%d shots in %d ticks; the weapon allows %d" % [shots, ticks, most])
|
||||
|
||||
|
||||
func test_building_out_of_range_or_without_materials_fails() -> void:
|
||||
var player: SimEntity = _player(HOSTILE)
|
||||
for code: int in Materials.NAMES.size():
|
||||
player.materials[code] = 0
|
||||
var kinds: Array[int] = [StructureSet.WALL, StructureSet.FLOOR, StructureSet.RAMP, StructureSet.ROOF, StructureSet.BREAKWATER]
|
||||
# Without materials, nothing at all, whatever is claimed.
|
||||
for index: int in 60:
|
||||
_tick([_raw_command(loop.sim.tick + 1, 0, 0, rng.randi() & 0xFFFF, rng.randi_range(-32768, 32767), PlayerCommand.BUTTON_BUILD | PlayerCommand.BUTTON_FIRE, kinds[index % kinds.size()], rng.randi_range(0, 255), 255)] as Array[PackedByteArray])
|
||||
assert_eq(loop.sim.structures.count(), 0, "nothing is built on credit")
|
||||
# With materials, every piece placed is within reach, whatever the aim, the kind
|
||||
# and material bytes, and the claimed lag.
|
||||
for code: int in Materials.NAMES.size():
|
||||
player.materials[code] = 999
|
||||
var placed: int = 0
|
||||
var farthest: float = 0.0
|
||||
for index: int in 300:
|
||||
var eye: Vector3 = Harvest.eye(player)
|
||||
# Half the time a real kind and material, so pieces do get placed.
|
||||
var honest: bool = index % 2 == 0
|
||||
var kind: int = kinds[rng.randi_range(0, kinds.size() - 1)] if honest else rng.randi_range(0, 255)
|
||||
var material: int = rng.randi_range(0, Materials.NAMES.size() - 1) if honest else rng.randi_range(0, 255)
|
||||
_tick([_raw_command(loop.sim.tick + 1, rng.randi_range(-128, 127), rng.randi_range(-128, 127), rng.randi() & 0xFFFF,
|
||||
rng.randi_range(-32768, 32767), PlayerCommand.BUTTON_BUILD | PlayerCommand.BUTTON_FIRE, kind, material, 255)] as Array[PackedByteArray])
|
||||
for event: Dictionary in loop.sim.events:
|
||||
if event["type"] != "piece_placed":
|
||||
continue
|
||||
placed += 1
|
||||
assert_true(int(event["material"]) < Materials.NAMES.size())
|
||||
var piece: StructureSet.Piece = loop.sim.structures.find(int(event["piece"]))
|
||||
var nearest: float = INF
|
||||
for box: AABB in piece.boxes:
|
||||
var closest: Vector3 = eye.clamp(box.position, box.end)
|
||||
nearest = minf(nearest, closest.distance_to(eye))
|
||||
farthest = maxf(farthest, nearest)
|
||||
assert_true(placed > 0, "honest-looking build commands among the noise still build")
|
||||
assert_true(farthest <= Tuning.BUILD_RANGE + 0.01, "a piece %.2f m away; reach is %.2f m" % [farthest, Tuning.BUILD_RANGE])
|
||||
|
||||
|
||||
## Everything of every kind, carried and on the ground. Rounds in magazines aren't
|
||||
## counted; nothing here fires or reloads.
|
||||
func _all_items() -> Dictionary:
|
||||
var totals: Dictionary = {}
|
||||
var sim: Simulation = loop.sim
|
||||
for handle: int in [HOSTILE, VICTIM]:
|
||||
var player: SimEntity = _player(handle)
|
||||
for slot: int in Inventory.slot_count():
|
||||
if player.slot_items[slot] != Inventory.EMPTY:
|
||||
totals[player.slot_items[slot]] = int(totals.get(player.slot_items[slot], 0)) + player.slot_counts[slot]
|
||||
for index: int in player.ammo.size():
|
||||
var ammo_code: int = Inventory.ammo_code(index)
|
||||
totals[ammo_code] = int(totals.get(ammo_code, 0)) + player.ammo[index]
|
||||
for pickup_id: int in sim.pickups:
|
||||
var pickup: SimEntity = sim.entities.find(pickup_id)
|
||||
totals[pickup.item] = int(totals.get(pickup.item, 0)) + pickup.item_count
|
||||
for code: int in totals.keys():
|
||||
if totals[code] == 0:
|
||||
totals.erase(code)
|
||||
return totals
|
||||
|
||||
|
||||
func test_item_duplication_tricks_create_nothing() -> void:
|
||||
var player: SimEntity = _player(HOSTILE)
|
||||
# A few things to juggle, at the cheater's feet and in hand.
|
||||
for id: String in ["dock_carbine", "signal_revolver"]:
|
||||
Inventory.spawn_pickup(loop.sim, player.position, ItemCatalog.code_of(id), 1)
|
||||
Inventory.give(player, ItemCatalog.code_of("dock_carbine"), 1)
|
||||
var before: Dictionary = _all_items()
|
||||
var tricks: Array[int] = [
|
||||
PlayerCommand.BUTTON_INTERACT, PlayerCommand.BUTTON_DROP, PlayerCommand.BUTTON_INTERACT | PlayerCommand.BUTTON_DROP,
|
||||
PlayerCommand.BUTTON_DROP | PlayerCommand.BUTTON_BUILD, PlayerCommand.BUTTON_INTERACT | PlayerCommand.BUTTON_CROUCH, 0,
|
||||
]
|
||||
for index: int in 600:
|
||||
var now: int = loop.sim.tick
|
||||
var commands: Array[PackedByteArray] = []
|
||||
# The same tick claimed over and over with different buttons and slots, and
|
||||
# selections outside the inventory.
|
||||
for copy: int in rng.randi_range(1, 6):
|
||||
var buttons: int = tricks[rng.randi_range(0, tricks.size() - 1)]
|
||||
var ahead: int = 1 if copy < 3 else rng.randi_range(1, 4)
|
||||
commands.append(_raw_command(now + ahead, rng.randi_range(-4, 4), rng.randi_range(-4, 4), rng.randi() & 0xFFFF, 0, buttons, rng.randi_range(0, 255), 0, rng.randi_range(0, 255)))
|
||||
_tick(commands)
|
||||
# Lying in the same place keeps things in reach.
|
||||
if _horizontal(player.position, _player(VICTIM).position) > 20.0:
|
||||
player.position = _player(VICTIM).position - Vector3(0.0, 0.0, 6.0)
|
||||
assert_eq(_all_items(), before, "items were neither made nor lost")
|
||||
@@ -0,0 +1 @@
|
||||
uid://ou8g1ntcs3dr
|
||||
@@ -0,0 +1,37 @@
|
||||
## Runs ParserFuzz (test/net/parser_fuzz.gd) over many malformed messages and fails on
|
||||
## any engine or script error, or if memory grows by more than 16 MiB past warm-up.
|
||||
##
|
||||
## tools/godot.sh --script res://tools/fuzz_parsers.gd -- --messages=N --seed=N
|
||||
##
|
||||
## `make fuzz` runs 1,000,000. Prints one JSON line; exits 0 when clean, 1 otherwise.
|
||||
extends SceneTree
|
||||
|
||||
const MAX_GROWTH_BYTES: int = 16 * 1024 * 1024
|
||||
|
||||
|
||||
func _init() -> void:
|
||||
var count: int = 1000000
|
||||
var fuzz_seed: int = 1
|
||||
for arg: String in OS.get_cmdline_user_args():
|
||||
if arg.begins_with("--messages="):
|
||||
count = arg.get_slice("=", 1).to_int()
|
||||
elif arg.begins_with("--seed="):
|
||||
fuzz_seed = arg.get_slice("=", 1).to_int()
|
||||
var errors: ErrorCounter = ErrorCounter.new()
|
||||
OS.add_logger(errors)
|
||||
var started: int = Time.get_ticks_msec()
|
||||
var fuzz: ParserFuzz = ParserFuzz.new(fuzz_seed)
|
||||
fuzz.run(count)
|
||||
var growth: int = fuzz.memory_end - fuzz.memory_start
|
||||
var ok: bool = errors.count() == 0 and growth <= MAX_GROWTH_BYTES and fuzz.listed() == 0
|
||||
var report: Dictionary = {
|
||||
"event": "fuzz", "ok": ok, "messages": fuzz.messages, "seeds": fuzz.seeds.size(),
|
||||
"accepted": fuzz.accepted, "errors": errors.count(), "memory_growth_bytes": growth,
|
||||
"memory_peak_bytes": fuzz.memory_peak, "listed": fuzz.listed(), "seed": fuzz_seed,
|
||||
"wall_ms": Time.get_ticks_msec() - started,
|
||||
}
|
||||
if errors.count() > 0:
|
||||
report["first_error"] = errors.first()
|
||||
print(JSON.stringify(report))
|
||||
OS.remove_logger(errors)
|
||||
quit(0 if ok else 1)
|
||||
@@ -0,0 +1 @@
|
||||
uid://67w0j6otc671
|
||||
Reference in New Issue
Block a user