Files
IT-Nexus/agent-cs/Services/RtcService.cs
Simon Grüssing 3ea28def4c Add: Dauerhaftes Bildschirm-Übertragung-Overlay während RDP-Session (v2.6.0)
- RdpActiveIndicatorWindow: TeamViewer-Style Overlay unten rechts, solange
  RDP-Capture läuft. Zeigt Dauer der Sitzung + pulsierenden roten Punkt
- User kann per "Trennen"-Button selbst die Sitzung beenden (TCP-Signal
  an Service, cancelt Capture-Loop sofort — auch nach Screen-Wechsel)
- Overlay läuft als separater User-Prozess via SessionSpawner, wird vom
  Service direkt gekillt wenn Sitzung endet (rdp_stop oder Disconnect)
- Version: 2.5.0 → 2.6.0

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-19 12:06:50 +02:00

292 lines
11 KiB
C#

using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace ITNexusAgent.Services;
// WebSocket-Brücke: empfängt rdp_start vom Browser, spawnt Screen-Capture-Helper
// in der User-Session (via schtasks), leitet JPEG-Frames als rdp_frame weiter
public class RtcService
{
private readonly string _serverUrl;
private readonly string _agentKey;
private readonly string _hostname;
private int _indicatorPid = -1;
private TcpListener? _indicatorListener;
private CancellationTokenSource? _userDisconnectCts;
public RtcService(string serverUrl, string agentKey, string hostname)
{
_serverUrl = serverUrl;
_agentKey = agentKey;
_hostname = hostname;
}
public async Task RunAsync(CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
try { await ConnectAsync(ct); }
catch (Exception ex) { AgentWorker.Log($"RDP: {ex.Message}"); }
if (!ct.IsCancellationRequested)
await Task.Delay(TimeSpan.FromSeconds(15), ct).ContinueWith(_ => { });
}
}
private async Task ConnectAsync(CancellationToken ct)
{
var wsUrl = _serverUrl
.Replace("https://", "wss://")
.Replace("http://", "ws://")
+ $"/ws?type=rdp-agent&key={Uri.EscapeDataString(_agentKey)}&hostname={Uri.EscapeDataString(_hostname)}";
using var ws = new ClientWebSocket();
await ws.ConnectAsync(new Uri(wsUrl), ct);
AgentWorker.Log("RDP: Bereit");
CancellationTokenSource? captureCts = null;
var buf = new byte[4096];
while (ws.State == WebSocketState.Open && !ct.IsCancellationRequested)
{
WebSocketReceiveResult res;
try { res = await ws.ReceiveAsync(new ArraySegment<byte>(buf), ct); }
catch { break; }
if (res.MessageType == WebSocketMessageType.Close) break;
var raw = Encoding.UTF8.GetString(buf, 0, res.Count);
JObject? obj;
try { obj = JObject.Parse(raw); } catch { continue; }
var type = obj["type"]?.ToString();
if (type == "rdp_start" && captureCts == null)
{
var screenIdx = obj["screen"]?.ToObject<int>() ?? 0;
captureCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
_ = ConsentAndCaptureAsync(ws, screenIdx, captureCts.Token);
AgentWorker.Log($"RDP: Consent angefordert (screen={screenIdx})");
}
else if (type == "rdp_switch_screen" && captureCts != null)
{
// Consent bereits erteilt — nur Screen wechseln, kein erneuter Dialog
var newScreen = obj["screen"]?.ToObject<int>() ?? 0;
captureCts.Cancel();
captureCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
var switchToken = _userDisconnectCts != null
? CancellationTokenSource.CreateLinkedTokenSource(captureCts.Token, _userDisconnectCts.Token).Token
: captureCts.Token;
_ = CapturePipeLoopAsync(ws, newScreen, switchToken);
AgentWorker.Log($"RDP: Screen gewechselt zu {newScreen}");
}
else if (type == "rdp_stop" && captureCts != null)
{
captureCts.Cancel();
captureCts = null;
StopIndicator();
AgentWorker.Log("RDP: Screen-Capture gestoppt");
}
}
captureCts?.Cancel();
StopIndicator();
AgentWorker.Log("RDP: Getrennt");
}
private void StopIndicator()
{
_userDisconnectCts?.Cancel();
_userDisconnectCts = null;
try { _indicatorListener?.Stop(); } catch { }
_indicatorListener = null;
if (_indicatorPid > 0)
{
try { Process.GetProcessById(_indicatorPid).Kill(); } catch { }
_indicatorPid = -1;
}
}
private async Task ConsentAndCaptureAsync(ClientWebSocket ws, int screenIdx, CancellationToken ct)
{
var exePath = System.Diagnostics.Process.GetCurrentProcess().MainModule!.FileName;
var consentListener = new TcpListener(IPAddress.Loopback, 0);
consentListener.Start();
var consentPort = ((IPEndPoint)consentListener.LocalEndpoint).Port;
if (!SpawnConsentHelper(exePath, consentPort.ToString()))
{
consentListener.Stop();
AgentWorker.Log("RDP: Consent-Helper fehlgeschlagen, verweigere Zugriff");
var failed = Encoding.UTF8.GetBytes("{\"type\":\"rdp_denied\",\"reason\":\"consent_spawn_failed\"}");
if (ws.State == WebSocketState.Open)
await ws.SendAsync(new ArraySegment<byte>(failed), WebSocketMessageType.Text, true, CancellationToken.None);
return;
}
// Browser informieren dass auf User-Zustimmung gewartet wird
var pending = Encoding.UTF8.GetBytes("{\"type\":\"rdp_consent_pending\"}");
if (ws.State == WebSocketState.Open)
await ws.SendAsync(new ArraySegment<byte>(pending), WebSocketMessageType.Text, true, CancellationToken.None);
bool accepted = false;
try
{
using var timeoutCts = new CancellationTokenSource(TimeSpan.FromSeconds(35));
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, timeoutCts.Token);
using var tcp = await consentListener.AcceptTcpClientAsync(linked.Token);
var b = tcp.GetStream().ReadByte();
accepted = b == 1;
}
catch { accepted = false; }
finally { consentListener.Stop(); }
if (!accepted)
{
AgentWorker.Log("RDP: User hat Zugriff abgelehnt");
var denied = Encoding.UTF8.GetBytes("{\"type\":\"rdp_denied\"}");
if (ws.State == WebSocketState.Open)
await ws.SendAsync(new ArraySegment<byte>(denied), WebSocketMessageType.Text, true, CancellationToken.None);
return;
}
AgentWorker.Log("RDP: User hat Zugriff erlaubt, starte Capture");
SpawnIndicator(exePath);
var combinedToken = _userDisconnectCts != null
? CancellationTokenSource.CreateLinkedTokenSource(ct, _userDisconnectCts.Token).Token
: ct;
await CapturePipeLoopAsync(ws, screenIdx, combinedToken);
}
// Zeigt dauerhaftes "Bildschirm wird übertragen"-Overlay (TeamViewer-Style) solange Capture läuft.
// User kann per Klick selbst trennen — Signal landet hier als CancellationTokenSource.Cancel().
private void SpawnIndicator(string exePath)
{
try
{
_indicatorListener = new TcpListener(IPAddress.Loopback, 0);
_indicatorListener.Start();
var port = ((IPEndPoint)_indicatorListener.LocalEndpoint).Port;
_userDisconnectCts = new CancellationTokenSource();
var listener = _indicatorListener;
var disconnectCts = _userDisconnectCts;
_ = Task.Run(async () =>
{
try
{
using var tcp = await listener.AcceptTcpClientAsync();
tcp.GetStream().ReadByte();
disconnectCts.Cancel();
AgentWorker.Log("RDP: User hat über Overlay getrennt");
}
catch { }
});
_indicatorPid = SessionSpawner.SpawnInUserSession(exePath, $"--rdp-indicator {port}");
}
catch (Exception ex)
{
AgentWorker.Log($"RDP: Indicator-Start fehlgeschlagen: {ex.Message}");
}
}
private static bool SpawnConsentHelper(string exePath, string portStr)
{
var pid = SessionSpawner.SpawnInUserSession(exePath, $"--rdp-consent {portStr}");
return pid > 0;
}
private async Task CapturePipeLoopAsync(ClientWebSocket ws, int screenIdx, CancellationToken ct)
{
var exePath = System.Diagnostics.Process.GetCurrentProcess().MainModule!.FileName;
// TCP Loopback: kein ACL-Problem zwischen SYSTEM-Service und User-Prozess
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
if (!SpawnCaptureHelper(exePath, port.ToString(), screenIdx))
{
listener.Stop();
AgentWorker.Log("RDP: Helper-Start fehlgeschlagen");
return;
}
TcpClient? tcp = null;
try
{
using var connectCts = new CancellationTokenSource(TimeSpan.FromSeconds(15));
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, connectCts.Token);
tcp = await listener.AcceptTcpClientAsync(linked.Token);
}
catch
{
listener.Stop();
AgentWorker.Log("RDP: Helper hat sich nicht verbunden");
return;
}
finally { listener.Stop(); }
AgentWorker.Log($"RDP: Helper verbunden (Port {port}), sende Frames...");
using (tcp)
{
var stream = tcp.GetStream();
var lenBuf = new byte[4];
while (!ct.IsCancellationRequested && tcp.Connected && ws.State == WebSocketState.Open)
{
try
{
var read = 0;
while (read < 4)
{
var n = await stream.ReadAsync(lenBuf.AsMemory(read, 4 - read), ct);
if (n == 0) goto done;
read += n;
}
var jpegLen = BitConverter.ToInt32(lenBuf);
if (jpegLen <= 0 || jpegLen > 5_000_000) continue;
var jpeg = new byte[jpegLen];
read = 0;
while (read < jpegLen)
{
var n = await stream.ReadAsync(jpeg.AsMemory(read, jpegLen - read), ct);
if (n == 0) goto done;
read += n;
}
var payload = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new
{
type = "rdp_frame",
data = Convert.ToBase64String(jpeg)
}));
if (ws.State == WebSocketState.Open)
await ws.SendAsync(new ArraySegment<byte>(payload), WebSocketMessageType.Text, true, CancellationToken.None);
}
catch (OperationCanceledException) { break; }
catch (Exception ex) { AgentWorker.Log($"RDP: TCP-Fehler: {ex.Message}"); break; }
}
}
done:
AgentWorker.Log("RDP: Frame-Loop beendet");
}
private static bool SpawnCaptureHelper(string exePath, string portStr, int screenIdx = 0)
{
var pid = SessionSpawner.SpawnInUserSession(exePath, $"--rdp-capture {portStr} {screenIdx}");
return pid > 0;
}
}