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
23 changes: 14 additions & 9 deletions docs/ingame-verification.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ Players can link their BYOND key to Discord without editing their BYOND profile.
1. In Discord, the player runs `/approveme` **without** a ckey. CivilizationBot replies
privately with a single-use code such as `ABCD-EFGH`, valid for 10 minutes.
2. In any Civ13 server, the player opens the OOC tab, clicks **Verify Discord** and types the code.
3. The game sends `ckey` + `code` to its own bot as the `discord_verify` webhook method
(`/webhook/<server>/discord_verify?key=<WEBAPI_TOKEN>&data={"ckey","code"}`) and shows the
JSON `{ok, message}` answer to the player.
3. The game POSTs `{"ckey","code"}` as JSON to its own bot at `<WEBHOOK_ADDRESS>/discord_verify`
(for example `/webhook/<server>/discord_verify`) with the webhook key in the `X-Webhook-Key`
header, and shows the JSON `{ok, message}` answer to the player. Neither the key nor the code is
ever part of a URL, so proxies and access logs never see them; a key in the query string is refused.
The game only sends this to a loopback (`127.0.0.1`/`localhost`) or `https://` address.

BYOND has already signed the player in, so the game proves the ckey and the private code proves
the Discord account. Bans, investigations, existing links, the BYOND account age rule and the
Expand All @@ -20,15 +22,18 @@ out of in-game verification for ten minutes. Codes are kept in memory only.
- **CivilizationBot** (primary, writes the verified list) redeems the code itself.
- **VZGCivilizationBot** (desktop profile with the read-only hosted verifier) cannot register anyone.
It forwards the request to the primary bot's `POST /verified/ingame` endpoint next to the hosted
verified list (`verification_source.url` + `/ingame`), signed with `X-Ingame-Verify-Time` and
`X-Ingame-Verify-Signature` (HMAC-SHA256 of `time + "\n" + body` with the shared secret), then passes the primary bot's answer back to the game. The link reaches the desktop game through
verified list (`verification_source.url` + `/ingame`), sealed with the shared secret
(`InGameVerification::seal`: AES-256-GCM under an HKDF key), then passes the primary bot's answer
back to the game. The answer is sealed too and bound to the request it answers. The link reaches the desktop game through
the normal hosted verified-list refresh and access-file sync.

Both bots need the same random secret as `INGAME_VERIFY_TOKEN`: in the primary bot's `.env` and
in the desktop profile's environment file. Without it the primary bot refuses relays (403) and the
desktop bot tells players to use `/approveme` in Discord instead. The secret itself is never sent, so
the plain-HTTP `http://civ13.com:55555` source is acceptable: a captured request expires after 60 seconds
and its code is single use. Anyone holding the secret could link any ckey to a Discord user with a live
code, so keep it out of logs and chat.
desktop bot tells players to use `/approveme` in Discord instead. The secret itself is never sent and
the ckey and code are encrypted end to end, so someone watching the plain-HTTP `http://civ13.com:55555`
source sees neither and cannot redeem the code for their own account; a changed byte, the wrong
direction, a stale (over 60 seconds) or swapped message is refused. An `https://` source works too.
Anyone holding the secret could link any ckey to a Discord user with a live code, so keep it out of
logs and chat.

`/approveme` is re-registered on every start so existing installs get the optional ckey.
7 changes: 6 additions & 1 deletion src/Civ13/HttpHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -599,7 +599,12 @@ public function __isWhitelisted(ServerRequestInterface $request, string $ip): bo
// Native webhook_send places its secret beside method/data, not inside JSON.
$outerKey = $request->getQueryParams()['key'] ?? null;
if (str_starts_with($request->getUri()->getPath(), '/webhook/')) {
// A trusted network address is not authentication of a game event.
// A trusted network address is not authentication of a game event. Newer game requests
// (in-game verification) send the key in the X-Webhook-Key header, never in the URL.
$headerKey = $request->getHeaderLine('X-Webhook-Key');
if ($this->key !== '' && $headerKey !== '' && hash_equals($this->key, $headerKey)) {
return true;
}
return $this->key !== '' && is_string($outerKey) && hash_equals($this->key, $outerKey);
}
if ($this->key) {
Expand Down
73 changes: 33 additions & 40 deletions src/Civ13/HttpServiceManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -351,19 +351,25 @@ public function handleShutdownNoticeWebhook(ServerRequestInterface $request, Gam
}

/**
* In-game verification (Civ13 code/modules/client/discord_verify.dm): the game sends the
* player's ckey and the code they typed. The primary bot redeems it; a desktop bot with a
* read-only verifier relays it to the primary bot. Once authenticated the answer is always
* 200 JSON {ok, message}, which the game shows to the player.
* In-game verification (Civ13 code/modules/client/discord_verify.dm): the game POSTs the
* player's ckey and the code they typed as JSON, with the webhook key in the X-Webhook-Key
* header, so neither secret is ever part of a URL. The primary bot redeems it; a desktop bot
* with a read-only verifier relays it, encrypted, to the primary bot. Once authenticated the
* answer is always 200 JSON {ok, message}, which the game shows to the player.
*/
public function handleDiscordVerifyWebhook(ServerRequestInterface $request, GameServer $gameserver): HttpResponse
{
$secret = $this->civ13->options['http_key'] ?? '';
$key = $request->getQueryParams()['key'] ?? null;
if (!is_string($secret) || $secret === '' || !is_string($key) || !hash_equals($secret, $key) || $gameserver->legacy_relay) {
$key = $request->getHeaderLine('X-Webhook-Key');
if (!is_string($secret) || $secret === '' || $key === '' || !hash_equals($secret, $key) || $gameserver->legacy_relay) {
return new HttpResponse(HttpResponse::STATUS_FORBIDDEN);
}
if (!$data = self::inGameVerifyRequest(self::decodeParamData($request))) {
if ($request->getMethod() !== 'POST') {
return new HttpResponse(HttpResponse::STATUS_METHOD_NOT_ALLOWED);
}
$body = (string) $request->getBody();
$data = strlen($body) <= 1024 ? json_decode($body, true, 4) : null;
if (!is_array($data) || !$data = self::inGameVerifyRequest($data)) {
return new HttpResponse(HttpResponse::STATUS_BAD_REQUEST);
}
if (!$this->civ13->verifier->readOnly) {
Expand All @@ -374,7 +380,11 @@ public function handleDiscordVerifyWebhook(ServerRequestInterface $request, Game
return HttpResponse::json(\React\Async\await($this->relayInGameVerification($data['ckey'], $data['code'])));
}

/** Primary bot: in-game registrations relayed by a desktop bot that shares INGAME_VERIFY_TOKEN (HMAC-signed, see below). */
/**
* Primary bot: in-game registrations relayed by a desktop bot that shares INGAME_VERIFY_TOKEN.
* Request and answer are sealed with it ({@see InGameVerification::seal()}), so the code is
* never readable on the wire even over plain HTTP, and the answer is bound to its request.
*/
public function handleInGameVerifyRelay(ServerRequestInterface $request): HttpResponse
{
$secret = $this->civ13->options['ingame_verify_key'] ?? '';
Expand All @@ -384,38 +394,39 @@ public function handleInGameVerifyRelay(ServerRequestInterface $request): HttpRe
if ($request->getMethod() !== 'POST') {
return new HttpResponse(HttpResponse::STATUS_METHOD_NOT_ALLOWED);
}
$body = (string) $request->getBody();
if (strlen($body) > 1024 || !self::inGameRelaySignatureValid($secret, $request->getHeaderLine('X-Ingame-Verify-Time'), $body, $request->getHeaderLine('X-Ingame-Verify-Signature'))) {
$opened = InGameVerification::open($secret, 'request', (string) $request->getBody());
if ($opened === null) {
return new HttpResponse(HttpResponse::STATUS_FORBIDDEN);
}
$data = json_decode($body, true, 4);
if (!is_array($data) || !$data = self::inGameVerifyRequest($data)) {
if (!$data = self::inGameVerifyRequest($opened['payload'])) {
return new HttpResponse(HttpResponse::STATUS_BAD_REQUEST);
}
$answer = $this->civ13->verifier->redeemInGame($data['ckey'], $data['code']);

return HttpResponse::json($this->civ13->verifier->redeemInGame($data['ckey'], $data['code']));
return HttpResponse::plaintext(InGameVerification::seal($secret, 'response', $answer, $opened['nonce']))
->withHeader('Content-Type', 'application/json');
}

/** Desktop bot: forwards to the primary bot. Resolves {ok, message}; never rejects. */
/** Desktop bot: forwards to the primary bot, sealed both ways. Resolves {ok, message}; never rejects. */
public function relayInGameVerification(string $ckey, string $code): PromiseInterface
{
$url = InGameVerification::relayUrl($this->civ13->verifier->verify_url);
$key = $this->civ13->options['ingame_verify_key'] ?? '';
if ($url === null || !is_string($key) || $key === '') {
return \React\Promise\resolve(['ok' => false, 'message' => 'Verifying from this server is not set up yet. Use /approveme in Discord instead.']);
}

$body = json_encode(['ckey' => $ckey, 'code' => $code], JSON_THROW_ON_ERROR);
$time = (string) time();
$body = InGameVerification::seal($key, 'request', ['ckey' => $ckey, 'code' => $code]);
$nonce = InGameVerification::nonceOf($body);

return $this->civ13->browser->withTimeout(10.0)->withRejectErrorResponse(false)->post(
$url,
['Content-Type' => 'application/json', 'X-Ingame-Verify-Time' => $time, 'X-Ingame-Verify-Signature' => self::inGameRelaySignature($key, $time, $body)],
['Content-Type' => 'application/json'],
$body
)->then(function (ResponseInterface $response): array {
$body = json_decode((string) $response->getBody(), true, 4);
if ($response->getStatusCode() === 200 && is_array($body) && is_bool($body['ok'] ?? null) && is_string($body['message'] ?? null)) {
return ['ok' => $body['ok'], 'message' => mb_substr($body['message'], 0, 400)];
)->then(function (ResponseInterface $response) use ($key, $nonce): array {
$opened = $response->getStatusCode() === 200 ? InGameVerification::open($key, 'response', (string) $response->getBody(), $nonce) : null;
$answer = $opened['payload'] ?? null;
if (is_array($answer) && is_bool($answer['ok'] ?? null) && is_string($answer['message'] ?? null)) {
return ['ok' => $answer['ok'], 'message' => mb_substr($answer['message'], 0, 400)];
}
$this->logger->warning('In-game verification relay refused', ['status' => $response->getStatusCode()]);

Expand All @@ -427,24 +438,6 @@ public function relayInGameVerification(string $ckey, string $code): PromiseInte
});
}

/**
* The relay may cross plain HTTP, so the shared secret never travels: the desktop bot signs
* time + body with it. A captured request is useless after a minute, and its code is single use.
*/
public static function inGameRelaySignature(string $secret, string $time, string $body): string
{
return hash_hmac('sha256', $time."\n".$body, $secret);
}

public static function inGameRelaySignatureValid(string $secret, string $time, string $body, string $signature, ?int $now = null): bool
{
if ($secret === '' || preg_match('/^[0-9]{1,12}$/D', $time) !== 1 || abs(($now ?? time()) - (int) $time) > 60 || preg_match('/^[0-9a-f]{64}$/D', $signature) !== 1) {
return false;
}

return hash_equals(self::inGameRelaySignature($secret, $time, $body), $signature);
}

/** {ckey, code} from the game or a relay, or null. The game sends a BYOND ckey: lower-case letters and digits. */
public static function inGameVerifyRequest(array $data): ?array
{
Expand Down
69 changes: 65 additions & 4 deletions src/Civ13/InGameVerification.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,11 @@
* already knows their BYOND key (BYOND signed them in), so the code proves the
* Discord side and the game proves the ckey; no BYOND profile token is needed.
*
* The game sends `ckey` + `code` to its own bot (`/webhook/<server>/discord_verify`).
* The primary bot redeems it here. A desktop bot with a read-only verifier cannot
* register anyone, so it forwards the same request to the primary bot's
* `/verified/ingame` relay endpoint and hands the answer back to the game.
* The game POSTs `ckey` + `code` to its own bot (`/webhook/<server>/discord_verify`,
* key in a header, nothing secret in the URL). The primary bot redeems it here. A desktop
* bot with a read-only verifier cannot register anyone, so it forwards the request, sealed
* with INGAME_VERIFY_TOKEN ({@see seal()}), to the primary bot's `/verified/ingame` relay
* endpoint and hands the sealed answer back to the game.
*
* Codes live only in memory: a bot restart simply asks players for a new code.
*/
Expand Down Expand Up @@ -162,6 +163,66 @@ public static function relayUrl(string $verify_url): ?string
return rtrim($verify_url, '/').'/ingame';
}

public const SEAL_WINDOW = 60; // seconds a sealed relay message stays valid
private const NONCE_BYTES = 12;
private const TAG_BYTES = 16;

/**
* Relay messages between a desktop bot and the primary bot are sealed with AES-256-GCM
* (OpenSSL, already required by the portable profile) under a key derived from INGAME_VERIFY_TOKEN: the code is never readable
* on the wire, a changed byte is rejected, and each message carries its direction and time.
* An answer also carries the nonce of the request it answers, so it can't be swapped.
*/
public static function seal(string $secret, string $direction, array $payload, ?string $answers = null, ?int $now = null): string
{
$nonce = random_bytes(self::NONCE_BYTES);
$plain = json_encode(['d' => $direction, 't' => $now ?? time(), 'r' => $answers, 'p' => $payload], JSON_THROW_ON_ERROR);
$tag = '';
$cipher = openssl_encrypt($plain, 'aes-256-gcm', self::sealKey($secret), OPENSSL_RAW_DATA, $nonce, $tag, '', self::TAG_BYTES);
if (!is_string($cipher)) {
throw new \RuntimeException('Could not seal the relay message');
}

return json_encode(['v' => 1, 'n' => base64_encode($nonce), 'c' => base64_encode($cipher.$tag)], JSON_THROW_ON_ERROR);
}

/** @return array{payload: array, nonce: string}|null null for anything forged, stale, mismatched or malformed */
public static function open(string $secret, string $direction, string $body, ?string $answers = null, ?int $now = null): ?array
{
if ($secret === '' || strlen($body) > 4096) {
return null;
}
$outer = json_decode($body, true, 3);
if (!is_array($outer) || ($outer['v'] ?? null) !== 1 || !is_string($outer['n'] ?? null) || !is_string($outer['c'] ?? null)) {
return null;
}
$nonce = base64_decode($outer['n'], true);
$cipher = base64_decode($outer['c'], true);
if (!is_string($nonce) || strlen($nonce) !== self::NONCE_BYTES || !is_string($cipher) || strlen($cipher) < self::TAG_BYTES) {
return null;
}
$plain = openssl_decrypt(substr($cipher, 0, -self::TAG_BYTES), 'aes-256-gcm', self::sealKey($secret), OPENSSL_RAW_DATA, $nonce, substr($cipher, -self::TAG_BYTES));
$inner = is_string($plain) ? json_decode($plain, true, 6) : null;
if (!is_array($inner) || ($inner['d'] ?? null) !== $direction || !is_int($inner['t'] ?? null)
|| abs(($now ?? time()) - $inner['t']) > self::SEAL_WINDOW || !is_array($inner['p'] ?? null)
|| ($inner['r'] ?? null) !== $answers) {
return null;
}

return ['payload' => $inner['p'], 'nonce' => $outer['n']];
}

/** The base64 nonce of a sealed message, which its answer must name. */
public static function nonceOf(string $sealed): string
{
return (string) (json_decode($sealed, true, 3)['n'] ?? '');
}

private static function sealKey(string $secret): string
{
return hash_hkdf('sha256', $secret, 32, 'civ13 in-game verification relay v1');
}

/** The player-facing reply to `/approveme` without a ckey. */
public static function codeMessage(string $code): string
{
Expand Down
Loading
Loading