DiscoverOpnsenseCommand.cs 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. using System.ComponentModel;
  2. using RackPeek.Domain.Discovery;
  3. using RackPeek.Domain.Resources;
  4. using Spectre.Console;
  5. using Spectre.Console.Cli;
  6. namespace Shared.Rcl.Commands.Discovery;
  7. public sealed class DiscoverOpnsenseSettings : DiscoverSettings {
  8. [CommandOption("--host <URL>")]
  9. [Description("OPNsense host, e.g. https://firewall.lan. A bare host name gets https.")]
  10. public string? Host { get; init; }
  11. [CommandOption("--key <KEY>")]
  12. [Description("API key. Defaults to RPK_OPN_KEY.")]
  13. public string? Key { get; init; }
  14. [CommandOption("--secret <SECRET>")]
  15. [Description("API secret. Defaults to RPK_OPN_SECRET.")]
  16. public string? Secret { get; init; }
  17. [CommandOption("--insecure")]
  18. [Description("Accept a self-signed certificate, which OPNsense ships with by default.")]
  19. public bool Insecure { get; init; }
  20. [CommandOption("--include-public")]
  21. [Description("Also record neighbours on public addresses, such as the ISP equipment on the WAN leg.")]
  22. public bool IncludePublic { get; init; }
  23. public string? ResolvedKey =>
  24. DiscoveryPublisher.Resolve(Key, OpnsenseApiClient.KeyEnvironmentVariable);
  25. public string? ResolvedSecret =>
  26. DiscoveryPublisher.Resolve(Secret, OpnsenseApiClient.SecretEnvironmentVariable);
  27. public override ValidationResult Validate() {
  28. if (string.IsNullOrWhiteSpace(Host))
  29. return ValidationResult.Error("Pass --host, e.g. --host https://firewall.lan");
  30. if (string.IsNullOrWhiteSpace(ResolvedKey))
  31. return ValidationResult.Error(
  32. $"No API key. Pass --key or set {OpnsenseApiClient.KeyEnvironmentVariable}.");
  33. if (string.IsNullOrWhiteSpace(ResolvedSecret))
  34. return ValidationResult.Error(
  35. $"No API secret. Pass --secret or set {OpnsenseApiClient.SecretEnvironmentVariable}.");
  36. return base.Validate();
  37. }
  38. }
  39. /// <summary>
  40. /// Reads an OPNsense firewall's neighbour table and emits every machine on it.
  41. /// <para>
  42. /// The collector for everything a sweep can see but not identify. ARP is
  43. /// link-local, so sweeping from one host yields a MAC only for that host's own
  44. /// segment and an address for everything else — and an address alone cannot
  45. /// survive a DHCP re-lease or be matched to anything. The firewall routes every
  46. /// subnet, so its table has the MAC for all of them.
  47. /// </para>
  48. /// </summary>
  49. public sealed class DiscoverOpnsenseCommand : AsyncCommand<DiscoverOpnsenseSettings> {
  50. protected override async Task<int> ExecuteAsync(
  51. CommandContext context,
  52. DiscoverOpnsenseSettings settings,
  53. CancellationToken cancellationToken) {
  54. using var client = new OpnsenseApiClient(
  55. settings.Host!,
  56. settings.ResolvedKey!,
  57. settings.ResolvedSecret!,
  58. settings.Insecure);
  59. List<Resource> resources;
  60. try {
  61. resources = await OpnsenseDiscovery.ReadAsync(client, settings.IncludePublic, cancellationToken);
  62. }
  63. catch (Exception ex) when (
  64. ex is HttpRequestException or IOException or TimeoutException
  65. || (ex is TaskCanceledException && !cancellationToken.IsCancellationRequested)) {
  66. AnsiConsole.MarkupLine(
  67. $"[red]Could not read {Markup.Escape(client.Endpoint)}.[/] {Markup.Escape(ex.Message)}");
  68. // A self-signed certificate is the other common cause, and its message is
  69. // opaque enough to be worth naming.
  70. if (!settings.Insecure && ex is HttpRequestException { StatusCode: null })
  71. AnsiConsole.MarkupLine(
  72. "[grey]If the firewall uses its own certificate, add --insecure.[/]");
  73. return 1;
  74. }
  75. if (resources.Count == 0)
  76. AnsiConsole.MarkupLine(
  77. "[grey]The firewall's ARP table is empty. It only holds neighbours it has "
  78. + "spoken to recently, so this is normal on a quiet network.[/]");
  79. return await DiscoveryOutput.EmitAsync(resources, settings, cancellationToken);
  80. }
  81. }