- CaptureModeRunner: captures desktop in user session via schtasks, sends JPEG frames over named pipe to service - RtcService: creates named pipe server, spawns helper via schtasks (same pattern as NotificationService), reads frames and forwards to WS - Program.cs: added --rdp-capture <pipeName> mode - Multi-monitor: captures all screens combined Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
211 lines
7.4 KiB
C#
211 lines
7.4 KiB
C#
using System.Diagnostics;
|
|
using System.IO.Pipes;
|
|
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;
|
|
|
|
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)
|
|
{
|
|
captureCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
|
_ = CapturePipeLoopAsync(ws, captureCts.Token);
|
|
AgentWorker.Log("RDP: Screen-Capture gestartet");
|
|
}
|
|
else if (type == "rdp_stop" && captureCts != null)
|
|
{
|
|
captureCts.Cancel();
|
|
captureCts = null;
|
|
AgentWorker.Log("RDP: Screen-Capture gestoppt");
|
|
}
|
|
}
|
|
|
|
captureCts?.Cancel();
|
|
AgentWorker.Log("RDP: Getrennt");
|
|
}
|
|
|
|
private async Task CapturePipeLoopAsync(ClientWebSocket ws, CancellationToken ct)
|
|
{
|
|
var pipeName = $"it-nexus-rdp-{Guid.NewGuid():N}";
|
|
var exePath = System.Diagnostics.Process.GetCurrentProcess().MainModule!.FileName;
|
|
|
|
using var pipeServer = new NamedPipeServerStream(
|
|
pipeName, PipeDirection.In, 1,
|
|
PipeTransmissionMode.Byte, PipeOptions.Asynchronous);
|
|
|
|
// Helper via schtasks in User-Session starten
|
|
if (!SpawnCaptureHelper(exePath, pipeName))
|
|
{
|
|
AgentWorker.Log("RDP: Helper-Start fehlgeschlagen");
|
|
return;
|
|
}
|
|
|
|
try
|
|
{
|
|
using var connectCts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
|
|
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct, connectCts.Token);
|
|
await pipeServer.WaitForConnectionAsync(linked.Token);
|
|
}
|
|
catch
|
|
{
|
|
AgentWorker.Log("RDP: Helper hat sich nicht verbunden");
|
|
return;
|
|
}
|
|
|
|
AgentWorker.Log("RDP: Helper verbunden, sende Frames...");
|
|
|
|
var lenBuf = new byte[4];
|
|
while (!ct.IsCancellationRequested && pipeServer.IsConnected && ws.State == WebSocketState.Open)
|
|
{
|
|
try
|
|
{
|
|
// 4-Byte Länge lesen
|
|
var read = 0;
|
|
while (read < 4)
|
|
{
|
|
var n = await pipeServer.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;
|
|
|
|
// JPEG-Daten lesen
|
|
var jpeg = new byte[jpegLen];
|
|
read = 0;
|
|
while (read < jpegLen)
|
|
{
|
|
var n = await pipeServer.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: Pipe-Fehler: {ex.Message}"); break; }
|
|
}
|
|
|
|
done:
|
|
AgentWorker.Log("RDP: Frame-Loop beendet");
|
|
}
|
|
|
|
private static bool SpawnCaptureHelper(string exePath, string pipeName)
|
|
{
|
|
try
|
|
{
|
|
var fullUser = NotificationService.GetLoggedOnUser();
|
|
if (string.IsNullOrEmpty(fullUser))
|
|
{
|
|
AgentWorker.Log("RDP: Kein eingeloggter User gefunden");
|
|
return false;
|
|
}
|
|
|
|
var taskName = $"ITNexus-RDP-{pipeName[^8..]}";
|
|
|
|
Process.Start(new ProcessStartInfo("schtasks.exe", $"/delete /tn \"{taskName}\" /f")
|
|
{ CreateNoWindow = true })?.WaitForExit();
|
|
|
|
var triggerTime = DateTime.Now.AddMinutes(60).ToString("HH:mm:ss");
|
|
var ruArg = fullUser.StartsWith("AzureAD\\", StringComparison.OrdinalIgnoreCase)
|
|
? "/ru \"INTERACTIVE\""
|
|
: $"/ru \"{fullUser}\"";
|
|
|
|
var args = $"/create /tn \"{taskName}\" /tr \"\\\"{exePath}\\\" --rdp-capture {pipeName}\" " +
|
|
$"/sc ONCE /st {triggerTime} {ruArg} /it /f";
|
|
|
|
var p = Process.Start(new ProcessStartInfo("schtasks.exe", args)
|
|
{ CreateNoWindow = true, RedirectStandardError = true, UseShellExecute = false });
|
|
p?.WaitForExit();
|
|
|
|
if (p?.ExitCode != 0)
|
|
{
|
|
AgentWorker.Log($"RDP: schtasks create fehlgeschlagen (ExitCode={p?.ExitCode})");
|
|
return false;
|
|
}
|
|
|
|
Process.Start(new ProcessStartInfo("schtasks.exe", $"/run /tn \"{taskName}\"")
|
|
{ CreateNoWindow = true })?.WaitForExit();
|
|
|
|
// Aufräumen nach kurzer Zeit
|
|
_ = Task.Run(async () =>
|
|
{
|
|
await Task.Delay(5000);
|
|
Process.Start(new ProcessStartInfo("schtasks.exe", $"/delete /tn \"{taskName}\" /f")
|
|
{ CreateNoWindow = true })?.WaitForExit();
|
|
});
|
|
|
|
AgentWorker.Log($"RDP: Helper gestartet als '{fullUser}' (Task: {taskName})");
|
|
return true;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
AgentWorker.Log($"RDP: SpawnHelper Fehler: {ex.Message}");
|
|
return false;
|
|
}
|
|
}
|
|
}
|