feat(agent): enrichissement ONVIF authentifié côté agent — pool chiffré via config (#49)

## What

L'enrichissement ONVIF authentifié est déplacé côté **agent**. Le pool de credentials du site (login/mdp) est exposé à l'agent via `GET /api/settings/agent/{id}` sous forme d'enveloppe AES-256-GCM (`AgentCredentialEnvelope`, clé dérivée du SHA-256 de l'API key) — déchiffrable uniquement côté agent. `NetworkCameraScanner` tente `GetDeviceInformation` avec chaque couple du pool (PasswordDigest puis PasswordText) et remonte des devices **déjà identifiés** (fabricant/modèle ONVIF + `CredentialLabel`). Le central persiste et marque le credential utilisé (`LastUsedAt`) — plus aucun appel réseau ONVIF côté central.

## Why

Le central n'est généralement **pas** sur le réseau des caméras : les appels ONVIF authentifiés qu'il faisait après réception des devices bruts échouaient. L'agent, lui, est sur le sous-réseau des caméras — c'est lui qui doit porter l'auth. Enrichissement et identification se font au moment du scan, avant la remontée.

## How

- `AgentCredentialEnvelope` (Application/Security) : AES-256-GCM, clé = SHA-256 de l'API key ; central chiffre (via l'`ApiKeyHash` stocké), agent déchiffre (via sa clé en clair).
- `GetEffectiveAgentConfigQuery` : ajoute `discovery.credentials` (pool chiffré) au dict de config.
- `SettingsController.GetEffectiveConfig` : accepte l'API key agent (vérification par site) en plus du JWT admin — corrige au passage un 403 latent sur cet endpoint.
- `NetworkCameraScanner` : probe ONVIF authentifié avec le pool (anonyme d'abord, puis chaque couple).
- `AgentCredentialStore` (mémoire, jamais sur disque) : reçoit le pool déchiffré par `ConfigReceiverService`, lu par `AgentDiscoveryService`.
- `CameraDiscoveryService` : suppression de l'enrichissement réseau ; persistance + `MarkUsed` via `CredentialLabel` ; vendor déduit du fabricant ONVIF remonté.
- `SitesController` : broadcast `ConfigReload` après add/delete credential pour que les agents re-fetch leur pool.
- Multi-agents : inchangé — upsert par (site, IP) et anti-doublon IP/MAC à la confirmation évitent les caméras en double même si un agent est éteint.

## Testing

- `dotnet build Heimdall.slnx` : 0 erreur / 0 warning.
- Application 346 verts, Agent 108 verts, Infrastructure 143 verts (hors Testcontainers).
- Web.Tests 213 verts — nouveaux bUnit : DiscoveriesPage (5) + SiteDetail credentials (4).

## Breaking Changes

Aucun changement de schéma (pas de migration). Comportement API : `GET /api/settings/agent/{id}` accepte désormais l'API key agent (accès élargi au cas d'usage prévu).

Related to #48

Co-authored-by: nonobis <nonobis@tordais.cc>
Reviewed-on: https://forgejo.tordais.cc/nonobis/Heimdall/pulls/49
This commit is contained in:
Arnaud Dartoisandnonobis committed 2026-08-11 16:15:41 +02:00
1 parent a4503e76ac
commit f8f2b08d29
46 files changed
+5563 -52

No files matched your search

@@ -0,0 +1,546 @@
using System.Collections.Concurrent;
using System.Globalization;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Xml.Linq;
using Heimdall.Application.DTOs;
using Microsoft.Extensions.Logging;
namespace Heimdall.Agent.Services;
/// <summary>
/// Lightweight local-network camera scanner used by the agent.
/// The agent lives on the camera network (the Central usually does not), so it
/// probes its own subnet: TCP port scan for common camera ports, an HTTP
/// header probe, ONVIF WS-Discovery (unicast), and an ARP table lookup for the
/// MAC address. When the site's credential pool is available (shipped by the
/// Central in the agent config, encrypted), the scanner performs the
/// <b>authenticated</b> ONVIF GetDeviceInformation calls itself — protected
/// cameras that refuse anonymous probing are identified (manufacturer, model)
/// using each credential pair. Raw+enriched results are posted to the Central
/// (POST /api/agents/{id}/discovery), which only persists them.
/// </summary>
public sealed class NetworkCameraScanner
{
private static readonly int[] CameraPorts = [80, 443, 554, 8554, 3702, 8899, 37777];
private static readonly TimeSpan PortTimeout = TimeSpan.FromMilliseconds(250);
private static readonly TimeSpan HttpTimeout = TimeSpan.FromSeconds(2);
private static readonly TimeSpan OnvifUdpTimeout = TimeSpan.FromMilliseconds(500);
// ReSharper disable once InconsistentNaming
private static readonly XNamespace SoapNs = "http://www.w3.org/2003/05/soap-envelope";
// ReSharper disable once InconsistentNaming
private static readonly XNamespace WsdNs = "http://schemas.xmlsoap.org/ws/2005/04/discovery";
// ReSharper disable once InconsistentNaming
private static readonly XNamespace WsaNs = "http://schemas.xmlsoap.org/ws/2004/08/addressing";
// ReSharper disable once InconsistentNaming
private static readonly XNamespace TdnNs = "http://www.onvif.org/ver10/network/wsdl";
// ReSharper disable once InconsistentNaming
private static readonly XNamespace TdsNs = "http://www.onvif.org/ver10/device/wsdl";
// ReSharper disable once InconsistentNaming
private static readonly XNamespace WsseNs = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
private readonly ILogger<NetworkCameraScanner> _logger;
private readonly string? _localIp;
public NetworkCameraScanner(ILogger<NetworkCameraScanner> logger)
{
_logger = logger;
_localIp = GetLocalIpv4();
}
/// <summary>
/// Scan the local subnet for camera-like devices. Returns an empty list
/// when the local network cannot be determined. When <paramref name="credentialPool"/>
/// is provided, ONVIF device information is fetched with authentication
/// (each pair is tried, PasswordDigest then PasswordText) so protected
/// cameras are identified with their ONVIF manufacturer/model.
/// </summary>
public async Task<IReadOnlyList<AgentDiscoveredDevice>> ScanAsync(
CancellationToken ct, IReadOnlyList<AgentCameraCredential>? credentialPool = null)
{
var (subnetCidr, localIp) = GetLocalSubnetCidr();
if (subnetCidr is null)
{
_logger.LogWarning("Camera discovery: unable to determine local subnet, skipping scan");
return [];
}
var ips = ExpandSubnet(subnetCidr);
_logger.LogInformation("Camera discovery: scanning {Subnet} ({Count} hosts, {Pool} credential pair(s))",
subnetCidr, ips.Count, credentialPool?.Count ?? 0);
var results = new ConcurrentBag<AgentDiscoveredDevice>();
using var throttler = new SemaphoreSlim(40);
var tasks = ips.Select(async ip =>
{
if (ct.IsCancellationRequested) return;
if (ip == localIp) return;
await throttler.WaitAsync(ct).ConfigureAwait(false);
try
{
var device = await ProbeHostAsync(ip, credentialPool, ct).ConfigureAwait(false);
if (device is not null)
results.Add(device);
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
// stop probing
}
catch (Exception ex)
{
_logger.LogTrace(ex, "Probe error for {Ip}", ip);
}
finally
{
throttler.Release();
}
});
await Task.WhenAll(tasks).ConfigureAwait(false);
_logger.LogInformation("Camera discovery: {Found} candidate device(s) on {Subnet}", results.Count, subnetCidr);
return results.ToList();
}
private async Task<AgentDiscoveredDevice?> ProbeHostAsync(
string ip, IReadOnlyList<AgentCameraCredential>? credentialPool, CancellationToken ct)
{
var openPorts = await ScanPortsAsync(ip, ct).ConfigureAwait(false);
if (openPorts.Count == 0)
return null;
HttpProbe? http = null;
if (openPorts.Contains(80) || openPorts.Contains(443))
{
var webPort = openPorts.Contains(80) ? 80 : 443;
http = await ProbeHttpAsync(ip, webPort, ct).ConfigureAwait(false);
}
OnvifProbe? onvif = null;
if (openPorts.Contains(3702))
onvif = await ProbeOnvifAsync(ip, 3702, credentialPool, ct).ConfigureAwait(false);
var mac = GetArpMac(ip);
return new AgentDiscoveredDevice(
Ip: ip,
IsReachable: true,
OpenPorts: [.. openPorts],
MacAddress: mac,
Vendor: null,
Hostname: null,
HttpServerHeader: http?.ServerHeader,
HttpStatusCode: http?.StatusCode,
HttpPort: http?.Port,
OnvifDeviceServiceUrl: onvif?.DeviceServiceUrl,
OnvifName: onvif?.Name,
OnvifHardware: onvif?.Hardware,
OnvifPort: onvif is not null ? 3702 : null,
HomeKitName: null,
HomeKitDeviceId: null,
HomeKitModel: null,
CredentialLabel: onvif?.CredentialLabel);
}
private static async Task<List<int>> ScanPortsAsync(string ip, CancellationToken ct)
{
var open = new ConcurrentBag<int>();
var tasks = CameraPorts.Select(async port =>
{
using var client = new TcpClient();
var connectTask = client.ConnectAsync(IPAddress.Parse(ip), port, ct).AsTask();
var completed = await Task.WhenAny(connectTask, Task.Delay(PortTimeout, ct)).ConfigureAwait(false);
if (completed == connectTask && client.Connected)
open.Add(port);
client.Close();
});
await Task.WhenAll(tasks).ConfigureAwait(false);
return [.. open.Order()];
}
private async Task<HttpProbe?> ProbeHttpAsync(string ip, int port, CancellationToken ct)
{
try
{
using var handler = new HttpClientHandler
{
AllowAutoRedirect = false,
ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator,
};
using var client = new HttpClient(handler) { Timeout = HttpTimeout };
using var request = new HttpRequestMessage(HttpMethod.Get, $"http://{ip}:{port}/");
request.Headers.UserAgent.ParseAdd("HeimdallAgent/1.0");
using var response = await client.SendAsync(request, ct).ConfigureAwait(false);
var serverHeader = response.Headers.TryGetValues("Server", out var values)
? string.Join(",", values)
: null;
return new HttpProbe(port, (int)response.StatusCode, serverHeader);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger.LogTrace(ex, "HTTP probe failed for {Ip}:{Port}", ip, port);
return null;
}
}
private async Task<OnvifProbe?> ProbeOnvifAsync(
string ip, int port, IReadOnlyList<AgentCameraCredential>? credentialPool, CancellationToken ct)
{
try
{
using var udp = new UdpClient();
udp.Client.ReceiveTimeout = (int)OnvifUdpTimeout.TotalMilliseconds;
udp.Connect(ip, port);
var messageId = Guid.NewGuid().ToString();
var probe = $@"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope xmlns:soap=""{SoapNs.NamespaceName}""
xmlns:wsa=""{WsaNs.NamespaceName}""
xmlns:wsd=""{WsdNs.NamespaceName}""
xmlns:tdn=""{TdnNs.NamespaceName}"">
<soap:Header>
<wsa:Action soap:mustUnderstand=""1"">{WsdNs.NamespaceName}/Probe</wsa:Action>
<wsa:MessageID soap:mustUnderstand=""1"">uuid:{messageId}</wsa:MessageID>
<wsa:To soap:mustUnderstand=""1"">urn:schemas-xmlsoap-org:ws:2005:04:discovery</wsa:To>
</soap:Header>
<soap:Body>
<wsd:Probe>
<wsd:Types>tdn:NetworkVideoTransmitter</wsd:Types>
</wsd:Probe>
</soap:Body>
</soap:Envelope>";
await udp.SendAsync(Encoding.UTF8.GetBytes(probe), ct).ConfigureAwait(false);
var result = await udp.ReceiveAsync(ct).ConfigureAwait(false);
var xml = Encoding.UTF8.GetString(result.Buffer);
var doc = XDocument.Parse(xml);
var xaddrs = doc.Descendants(XName.Get("XAddrs", WsdNs.NamespaceName))
.SelectMany(e => e.Value.Split(' ', StringSplitOptions.RemoveEmptyEntries))
.ToList();
if (xaddrs.Count == 0)
return null;
var deviceServiceUrl = xaddrs[0];
var detail = await GetDeviceInformationWithCredentialsAsync(deviceServiceUrl, credentialPool, ct).ConfigureAwait(false);
return new OnvifProbe(deviceServiceUrl, detail?.Manufacturer, detail?.Model, detail?.CredentialLabel);
}
catch (SocketException ex) when (ex.SocketErrorCode is SocketError.TimedOut or SocketError.ConnectionRefused)
{
return null;
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
throw;
}
catch (Exception ex)
{
_logger.LogTrace(ex, "ONVIF probe failed for {Ip}:{Port}", ip, port);
return null;
}
}
/// <summary>
/// Fetch ONVIF device information, trying the site credential pool so that
/// protected cameras respond. Order: anonymous first (open cameras), then
/// each pair of the pool (PasswordDigest, then PasswordText for laxer
/// WS-Security implementations). Returns null when nothing works.
/// </summary>
private async Task<OnvifDetail?> GetDeviceInformationWithCredentialsAsync(
string deviceServiceUrl, IReadOnlyList<AgentCameraCredential>? credentialPool, CancellationToken ct)
{
// 1. Anonymous (cameras without auth or with default-open ONVIF).
var anonymous = await GetDeviceInformationAsync(deviceServiceUrl, null, null, null, ct).ConfigureAwait(false);
if (anonymous is not null)
return anonymous;
// 2. Credential pool, if provided by the Central.
if (credentialPool is not null)
{
foreach (var credential in credentialPool)
{
var digest = await GetDeviceInformationAsync(
deviceServiceUrl, credential.Username, credential.Password, "PasswordDigest", ct).ConfigureAwait(false);
if (digest is not null)
{
_logger.LogInformation(
"ONVIF auth succeeded with credential '{Label}' for {Url}", credential.Label, deviceServiceUrl);
return digest with { CredentialLabel = credential.Label };
}
var text = await GetDeviceInformationAsync(
deviceServiceUrl, credential.Username, credential.Password, "PasswordText", ct).ConfigureAwait(false);
if (text is not null)
{
_logger.LogInformation(
"ONVIF auth (PasswordText) succeeded with credential '{Label}' for {Url}", credential.Label, deviceServiceUrl);
return text with { CredentialLabel = credential.Label };
}
}
}
return null;
}
private async Task<OnvifDetail?> GetDeviceInformationAsync(
string deviceServiceUrl, string? username, string? password, string? passwordType, CancellationToken ct)
{
try
{
using var client = new HttpClient { Timeout = HttpTimeout };
var soap = BuildSoapEnvelope(username, password, passwordType);
using var content = new StringContent(soap, Encoding.UTF8, "application/soap+xml");
using var response = await client.PostAsync(deviceServiceUrl, content, ct).ConfigureAwait(false);
if (!response.IsSuccessStatusCode)
return null;
var responseXml = await response.Content.ReadAsStringAsync(ct).ConfigureAwait(false);
var doc = XDocument.Parse(responseXml);
var info = doc.Root?.Element(SoapNs + "Body")?.Element(XName.Get("GetDeviceInformationResponse", TdsNs.NamespaceName));
if (info is null)
return null;
return new OnvifDetail(
info.Element(XName.Get("Manufacturer", TdsNs.NamespaceName))?.Value,
info.Element(XName.Get("Model", TdsNs.NamespaceName))?.Value);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger.LogTrace(ex, "GetDeviceInformation failed for {Url}", deviceServiceUrl);
return null;
}
}
/// <summary>
/// Build the GetDeviceInformation SOAP envelope, adding a WS-Security
/// UsernameToken when credentials are provided (PasswordDigest or
/// PasswordText, matching ONVIF interop requirements).
/// </summary>
private static string BuildSoapEnvelope(string? username, string? password, string? passwordType)
{
var securityHeader = string.Empty;
if (username is not null && passwordType is not null)
{
if (passwordType == "PasswordDigest")
{
var nonce = new byte[16];
RandomNumberGenerator.Fill(nonce);
var created = DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture);
// ONVIF WS-Security PasswordDigest is defined by the standard to use SHA1
// (digest = Base64(SHA1(nonce + created + password))). Required for
// interoperability with ONVIF cameras — not used for application security.
#pragma warning disable CA5350 // Do Not Use Weak Cryptographic Algorithms
var digest = SHA1.HashData([.. nonce, .. Encoding.UTF8.GetBytes(created + password)]);
#pragma warning restore CA5350
securityHeader = $@"
<soap:Header>
<Security xmlns=""{WsseNs.NamespaceName}"">
<UsernameToken>
<Username>{username}</Username>
<Password Type=""{WsseNs.NamespaceName}#PasswordDigest"">{Convert.ToBase64String(digest)}</Password>
<Nonce>{Convert.ToBase64String(nonce)}</Nonce>
<Created>{created}</Created>
</UsernameToken>
</Security>
</soap:Header>";
}
else
{
securityHeader = $@"
<soap:Header>
<Security xmlns=""{WsseNs.NamespaceName}"">
<UsernameToken>
<Username>{username}</Username>
<Password Type=""{WsseNs.NamespaceName}#PasswordText"">{password}</Password>
</UsernameToken>
</Security>
</soap:Header>";
}
}
return $@"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope xmlns:soap=""{SoapNs.NamespaceName}""
xmlns:tds=""{TdsNs.NamespaceName}"">{securityHeader}
<soap:Body>
<tds:GetDeviceInformation />
</soap:Body>
</soap:Envelope>";
}
// ─── Network helpers ────────────────────────────────────────────────
private static string? GetLocalIpv4()
{
foreach (var ni in NetworkInterface.GetAllNetworkInterfaces())
{
if (ni.OperationalStatus != OperationalStatus.Up)
continue;
foreach (var addr in ni.GetIPProperties().UnicastAddresses)
{
if (IsCandidateNetwork(addr.Address))
return addr.Address.ToString();
}
}
return null;
}
/// <summary>
/// True for a routable private IPv4 that is a plausible camera LAN.
/// Excludes loopback and common virtualisation/docker ranges
/// (172.16.0.0/12, 100.64.0.0/10) so the scanner targets the real LAN.
/// </summary>
private static bool IsCandidateNetwork(IPAddress address)
{
if (address.AddressFamily != AddressFamily.InterNetwork || IPAddress.IsLoopback(address))
return false;
var b = address.GetAddressBytes();
if (b[0] == 172 && b[1] is >= 16 and <= 31)
return false; // docker / private virtualisation
if (b[0] == 100 && b[1] is >= 64 and <= 127)
return false; // CGNAT
return true;
}
/// <summary>Return the local subnet as CIDR (e.g. 192.168.1.0/24) plus the local IP.</summary>
private (string? Cidr, string? LocalIp) GetLocalSubnetCidr()
{
foreach (var ni in NetworkInterface.GetAllNetworkInterfaces())
{
if (ni.OperationalStatus != OperationalStatus.Up)
continue;
foreach (var addr in ni.GetIPProperties().UnicastAddresses)
{
if (!IsCandidateNetwork(addr.Address))
continue;
var mask = addr.IPv4Mask;
if (mask is null)
continue;
var prefix = CountPrefixBits(mask.GetAddressBytes());
var network = NetworkAddress(addr.Address.GetAddressBytes(), mask.GetAddressBytes());
var cidr = $"{new IPAddress(network)}/{prefix}";
_logger.LogDebug("Local subnet detected: {Cidr} (interface {Interface})", cidr, ni.Name);
return (cidr, addr.Address.ToString());
}
}
return (null, null);
}
private static int CountPrefixBits(byte[] mask)
{
var count = 0;
foreach (var b in mask)
{
for (var i = 7; i >= 0; i--)
{
if ((b & (1 << i)) == 0)
return count;
count++;
}
}
return count;
}
private static byte[] NetworkAddress(byte[] ip, byte[] mask)
{
var network = new byte[4];
for (var i = 0; i < 4; i++)
network[i] = (byte)(ip[i] & mask[i]);
return network;
}
/// <summary>Expand a CIDR to host IPs (skipping network/broadcast, capped at 65 536).</summary>
internal static List<string> ExpandSubnet(string subnetCidr)
{
var parts = subnetCidr.Split('/');
if (parts.Length != 2)
return [];
if (!IPAddress.TryParse(parts[0], out var ip))
return [];
if (!int.TryParse(parts[1], out var prefixLength) || prefixLength is < 0 or > 32)
return [];
var ipBytes = ip.GetAddressBytes();
if (BitConverter.IsLittleEndian)
Array.Reverse(ipBytes);
var uintIp = BitConverter.ToUInt32(ipBytes, 0);
uint mask;
long hostCount;
int startOffset;
if (prefixLength >= 32)
{
mask = uint.MaxValue;
hostCount = 1;
startOffset = 0;
}
else if (prefixLength == 31)
{
mask = uint.MaxValue << 1;
hostCount = 2;
startOffset = 0;
}
else
{
mask = uint.MaxValue << (32 - prefixLength);
hostCount = (1L << (32 - prefixLength)) - 2;
startOffset = 1;
}
if (hostCount < 0)
hostCount = 0;
if (hostCount > 65536)
hostCount = 65536;
var network = uintIp & mask;
var ips = new List<string>((int)hostCount);
for (var i = 0; i < hostCount; i++)
{
var hostIp = network + (uint)(i + startOffset);
var bytes = BitConverter.GetBytes(hostIp);
if (BitConverter.IsLittleEndian)
Array.Reverse(bytes);
ips.Add(new IPAddress(bytes).ToString());
}
return ips;
}
/// <summary>Read the ARP table (/proc/net/arp) to resolve an IP's MAC address.</summary>
private static string? GetArpMac(string ip)
{
try
{
var lines = File.ReadAllLines("/proc/net/arp");
foreach (var line in lines.Skip(1))
{
var fields = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (fields.Length >= 4 && fields[0] == ip && fields[3] != "00:00:00:00:00:00")
return fields[3];
}
}
catch (Exception)
{
// ARP table unavailable (non-Linux or restricted container) — best effort.
}
return null;
}
private sealed record HttpProbe(int Port, int StatusCode, string? ServerHeader);
private sealed record OnvifProbe(string DeviceServiceUrl, string? Name, string? Hardware, string? CredentialLabel = null);
private sealed record OnvifDetail(string? Manufacturer, string? Model, string? CredentialLabel = null);
}