feat: listen mode for scanning by the NetBox Synchronizer, Intune and GPO deployment
Build Windows agent / build (win-arm64) (push) Canceled after 0s
Build Windows agent / build (win-x64) (push) Canceled after 0s

- New "mode" setting: "netbox" (default, unchanged), "listen" (no NetBox access needed; the
  inventory is served on a TCP port for the NetBox Synchronizer desktop app) or "both"
- Listen protocol v1: HMAC-SHA256 signed requests with nonce and timestamp, AES-256-GCM encrypted
  inventory, optional allowed_networks; the inventory has the shape of the desktop app's WinRM scan
- New options --serve, --print and --version
- install.ps1 sets up the listener task (at startup, restarted on failure) and the firewall rule for
  listen mode, removes what a changed mode no longer needs and stays idempotent
- New gpo-startup.ps1 for Group Policy startup scripts: installs or updates from a share only when
  agent.exe or config.json changed
- README, messages and scripts in English

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
MrBlakeandClaude Opus 5.5 committed 2026-11-18 11:01:46 +01:00
1 parent d632f0d383
commit 0098b49787
14 files changed
+788 -90

No files matched your search

+2
View File
@@ -23,6 +23,8 @@ jobs:
path: |
dist/${{ matrix.runtime }}/agent.exe
config.example.json
config.listen.example.json
scripts/install.ps1
scripts/uninstall.ps1
scripts/gpo-startup.ps1
+1 -1
View File
@@ -6,7 +6,7 @@
<Nullable>enable</Nullable>
<AssemblyName>agent</AssemblyName>
<RootNamespace>NetBoxWindowsAgent</RootNamespace>
<Version>0.1.0</Version>
<Version>0.2.0</Version>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.Management" Version="8.0.0" />
+193 -26
View File
@@ -1,6 +1,6 @@
# NetBox Client Agent for Windows
Inventories a Windows PC automatically in NetBox and in the
Inventories a Windows PC for NetBox and the
[netbox-inventory](https://github.com/ArnesSI/netbox-inventory) plugin. The
result is a single, self-contained `agent.exe`; the client does not need .NET
installed.
@@ -10,11 +10,27 @@ installed.
| **Type** | Command-line agent (.NET 8) |
| **Platform** | Windows (x64, ARM64) |
| **NetBox** | `4.2` or newer recommended |
| **Deployment** | Intune (Win32 app) or Group Policy (startup script), fully unattended |
| **Repository** | <https://git.mrblake.cc/MrBlake/Netbox-Client-Agent-for-Windows> |
## Modes
The agent runs in one of three modes, set by `mode` in `config.json`:
| Mode | What it does | Needs on the client |
|---|---|---|
| `netbox` (default) | Writes the PC directly to NetBox once a day | NetBox URL and API token |
| `listen` | Serves the inventory on a TCP port; the **NetBox Synchronizer** desktop app scans IP ranges and transfers the PCs to NetBox after a preview | Only a shared scan key – **no NetBox access** |
| `both` | Both of the above | Both |
The agent is invisible to users: it runs as SYSTEM in the background (session
0), shows no window and causes no prompts. The installer creates the firewall
rule before the listener starts, so Windows never asks users to allow network
access.
## Features
After the first run, the agent creates or updates:
In mode `netbox`, the agent creates or updates after the first run:
- a `DCIM > Device` for the Windows PC,
- a linked inventory asset,
@@ -30,8 +46,19 @@ the existing objects. No NetBox objects are ever deleted.
> from 4.2 on. Modules are meant for replaceable hardware in NetBox; for PC
> inventory, CPU, memory and disks are deliberately mapped onto this model.
In mode `listen`, the NetBox Synchronizer (page *Windows-Clients*, target
mode *NetBox-Agent*) scans IP ranges, lists every PC that answers and
transfers the selected ones with model, serial number, operating system,
interfaces, MAC and IP addresses – the same way as its agentless WinRM scan.
Disks, memory modules and the software list are shown in the app as well.
## Requirements
Building requires the [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0)
or newer.
For mode `netbox`:
1. `netbox-inventory` is installed.
2. A device role with the slug `windows-client` exists.
3. The site and location named in the configuration exist, if used.
@@ -45,8 +72,8 @@ The agent deliberately does not create sites or device roles. NetBox requires a
site for every device; a location is optional. Manufacturers, device types and
detected hardware types are created as needed.
Building requires the [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0)
or newer.
For mode `listen`: the NetBox Synchronizer desktop app and TCP access from the
admin PC to the clients on `listen_port` (default 8731).
## Installation
@@ -63,20 +90,34 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass `
-Runtime win-x64
```
The result is `dist\win-x64\agent.exe`.
The result is `dist\win-x64\agent.exe` (`-Runtime win-arm64` for ARM devices).
### 2. Create the configuration
Mode `netbox`:
```powershell
Copy-Item .\config.example.json .\dist\win-x64\config.json
notepad .\dist\win-x64\config.json
```
Mode `listen`: in the NetBox Synchronizer open *Windows-Clients*, choose
*NetBox-Agent (Netzwerk-Scan)*, create a key and click
*Agent-Konfiguration speichern …*. This writes a ready `config.json`
(see also `config.listen.example.json`).
See [Configuration](#configuration) for all options.
### 3. Test the connection
### 3. Test
The dry run reads hardware and NetBox but deliberately writes nothing:
Show what the agent collects (any mode):
```powershell
.\dist\win-x64\agent.exe --config .\dist\win-x64\config.json --print
```
Mode `netbox` – the dry run reads hardware and NetBox but deliberately writes
nothing:
```powershell
.\dist\win-x64\agent.exe `
@@ -84,14 +125,25 @@ The dry run reads hardware and NetBox but deliberately writes nothing:
--dry-run
```
Expected output (the agent's messages are in German):
Expected output:
```text
Erfasst: CLIENT01, LENOVO 21MW, S/N ABC123
Dry-Run erfolgreich; keine Änderungen geschrieben.
Collected: CLIENT01, LENOVO 21MW, S/N ABC123
Dry run successful; nothing was written.
```
### 4. First real synchronisation
Mode `listen` – serve in the foreground (Ctrl+C stops) and scan this PC from
the NetBox Synchronizer:
```powershell
.\dist\win-x64\agent.exe --config .\dist\win-x64\config.json --serve
```
When started by hand like this, Windows Firewall may ask once whether
`agent.exe` may accept connections – this only happens in manual tests. An
installed agent has its firewall rule and never asks.
### 4. First real synchronisation (mode `netbox`)
```powershell
.\dist\win-x64\agent.exe `
@@ -101,7 +153,7 @@ Dry-Run erfolgreich; keine Änderungen geschrieben.
Expected output:
```text
Synchronisiert: Device #123, Asset #456
Synchronized: device #123, asset #456
```
### 5. Install permanently
@@ -119,9 +171,21 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass `
The script:
- copies the executable and configuration to `C:\Program Files\NetBox Windows Agent`,
- restricts access to the API token to SYSTEM and local administrators,
- creates the daily scheduled task `NetBox Windows Agent`,
- starts the first synchronisation immediately.
- restricts access to the API token and scan key to SYSTEM and local administrators,
- mode `netbox`/`both`: creates the daily scheduled task `NetBox Windows Agent`
and starts the first synchronisation immediately,
- mode `listen`/`both`: adds the inbound firewall rule `NetBox Windows Agent`
for `listen_port` (domain and private profile, limited to
`allowed_networks`), then creates and starts the scheduled task
`NetBox Windows Agent Listener` (runs as SYSTEM at startup, restarted after
failures),
- removes tasks and the firewall rule that a changed mode no longer needs,
- can be run again at any time to update the agent or its configuration.
The installation state only depends on the installed executable, configuration
and scheduled tasks. A temporary NetBox or network error during the first
synchronisation does not undo the installation; the scheduled task retries the
synchronisation later.
## Uninstall
@@ -132,12 +196,15 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass `
-File .\scripts\uninstall.ps1
```
This removes both scheduled tasks, the firewall rule and the install folder.
## Configuration
Minimal example:
### Mode `netbox`
```json
{
"mode": "netbox",
"netbox_url": "https://netbox.example.com",
"api_token": "YOUR_NETBOX_TOKEN",
"region": "emea",
@@ -155,9 +222,47 @@ Minimal example:
}
```
`site` must be the slug of an existing NetBox site, since NetBox requires a site
for every device. `location` is optional and may be removed or set to `null`.
`region` narrows the site lookup.
`mode` may be omitted; `netbox` is the default. `site` must be the slug of an
existing NetBox site, since NetBox requires a site for every device. `location`
is optional and may be removed or set to `null`. `region` narrows the site
lookup.
### Mode `listen`
```json
{
"mode": "listen",
"listen_port": 8731,
"scan_key": "the key from the NetBox Synchronizer",
"allowed_networks": ["10.0.0.0/24"],
"inventory_cache_seconds": 300,
"collect_software": true,
"max_software_entries": 250
}
```
| Setting | Meaning |
|---|---|
| `listen_port` | TCP port of the agent (default 8731) |
| `scan_key` | Shared secret of all agents of one customer (at least 16 characters); only a NetBox Synchronizer with the same key can read the inventory |
| `allowed_networks` | Optional networks in CIDR notation that may connect, e.g. the admin network. Empty = any address. Used for the firewall rule and checked by the agent |
| `inventory_cache_seconds` | The inventory is collected on request and reused for this time |
For mode `both`, combine the settings of both modes.
### Security of the listen mode
- `GET /v1/info` answers without authentication, with the agent name and
version only.
- `GET /v1/inventory` needs an HMAC-SHA256 signature (key derived from
`scan_key`) over a random nonce and the current time. Requests older than five
minutes and repeated nonces are rejected.
- The inventory is returned encrypted with AES-256-GCM (a separate key derived
from `scan_key`), so serial numbers and software lists never cross the network
in clear text – without needing TLS certificates.
- The clocks of client and admin PC may differ by at most five minutes (domain
time synchronisation is enough).
- The agent only reads data; it accepts no commands.
### Self-signed certificate
@@ -200,6 +305,10 @@ Custom fields are not required by default. To use them, create them for
## Usage
Both distribution methods are fully unattended: the installer runs as SYSTEM,
needs no user interaction and no administrator on the client, and the agent
stays invisible to users.
### Distribution with Intune
Package these four files together as a Win32 app (`.intunewin`):
@@ -223,23 +332,82 @@ powershell.exe -NoProfile -ExecutionPolicy Bypass -File .\uninstall.ps1
Install behavior:
System
Device restart behavior:
No specific action
Detection rule (rule type "File"):
Path: C:\Program Files\NetBox Windows Agent
File or folder: agent.exe
Detection method: File or folder exists
Detection method: String (version)
Operator: Greater than or equal to
Value: 0.2.0 (the version of agent.exe, see agent.exe --version)
Associated with a 32-bit app on 64-bit clients: No
```
Assign the app as **Required** to a device group so it installs without user
action. The version rule lets Intune update clients with an older agent. After
changes to `agent.exe`, `config.json` or the installation scripts, rebuild the
`.intunewin` package and upload it again under
**App > Properties > App package file** – a change in the local repository does
not update a package that was already uploaded. A changed `config.json` alone
(for example a new scan key) is not detected by the version rule; publish it as
a new app that supersedes the old one, or use Group Policy.
### Distribution with Group Policy
1. Create a folder on a share that the group **Domain Computers** can read, for
example `\\fileserver\NetBoxAgent$`, and copy these files into it:
```text
agent.exe
config.json
install.ps1
uninstall.ps1
gpo-startup.ps1
```
2. Create a GPO linked to the OU of the computers:
**Computer Configuration > Policies > Windows Settings > Scripts
(Startup/Shutdown) > Startup > PowerShell Scripts > Add** – script name
`\\fileserver\NetBoxAgent$\gpo-startup.ps1`, no parameters.
3. Make sure the share is reachable at startup:
**Computer Configuration > Policies > Administrative Templates > System >
Logon > Always wait for the network at computer startup and logon** =
*Enabled*.
At every startup the script compares `agent.exe` and `config.json` on the share
with the installed version. If nothing changed, it does nothing; if a file
changed or the agent is missing, it runs `install.ps1` from the share. To update
all computers, replace the files on the share. The script logs to
`C:\ProgramData\NetBox Windows Agent\gpo-startup.log`.
To remove the agent from all computers of the GPO, add the script parameter
`-Uninstall`.
> `config.json` on the share is readable by all domain computers. In mode
> `listen` it contains the scan key, in mode `netbox` the NetBox API token – use
> a token with only the permissions listed above.
### Troubleshooting
**`agent.exe fehlt im Quellverzeichnis`** (agent.exe missing in source
directory) — `SourceDirectory` must be the folder that contains both
`agent.exe` and `config.json`:
**`agent.exe is missing in the source directory`** — `SourceDirectory` must be
the folder that contains both `agent.exe` and `config.json`:
```powershell
-SourceDirectory .\dist\win-x64
```
**The NetBox Synchronizer does not find an agent** — check that the task
`NetBox Windows Agent Listener` is running, test the port from the admin PC with
`Test-NetConnection <client> -Port 8731`, check firewalls between the networks
and that the admin PC is inside `allowed_networks`. The firewall rule applies to
the *Domain* and *Private* network profiles, not to *Public*.
**"Agent-Schlüssel stimmt nicht" in the NetBox Synchronizer** (wrong key) — the
key in the app and `scan_key` on the client differ; distribute the
configuration again.
**`RemoteCertificateNameMismatch` or `RemoteCertificateChainErrors`** — set
`allow_insecure_tls` to `true` for testing. Permanently, install the correct
internal CA and use a certificate name that matches the URL.
@@ -265,9 +433,8 @@ Enter the slug of an existing site in `config.json`:
detection rule, the `Path` field must contain only the folder. `agent.exe`
belongs in the separate `File or folder` field.
**`400 Bad Request`** — the full response after `FEHLER:` (error) names the
field NetBox rejected. Often the configured device role, site or location is
missing.
**`400 Bad Request`** — the full response after `ERROR:` names the field NetBox
rejected. Often the configured device role, site or location is missing.
## Development
+1
View File
@@ -1,4 +1,5 @@
{
"mode": "netbox",
"netbox_url": "https://netbox.example.com",
"api_token": "CHANGE_ME",
"region": "emea",
+9
View File
@@ -0,0 +1,9 @@
{
"mode": "listen",
"listen_port": 8731,
"scan_key": "CHANGE_ME_TO_THE_KEY_FROM_THE_NETBOX_SYNCHRONIZER",
"allowed_networks": ["10.0.0.0/24"],
"inventory_cache_seconds": 300,
"collect_software": true,
"max_software_entries": 250
}
+62
View File
@@ -0,0 +1,62 @@
<#
.SYNOPSIS
Group Policy computer startup script: installs or updates the NetBox Windows Agent from a share.
.DESCRIPTION
Put agent.exe, config.json, install.ps1 and this script into one folder on a share that
"Domain Computers" can read, e.g. \\fileserver\NetBoxAgent$ or \\domain\NETLOGON\NetBoxAgent,
and add this script as a PowerShell startup script:
Computer Configuration > Policies > Windows Settings > Scripts (Startup/Shutdown) > Startup
> PowerShell Scripts > \\fileserver\NetBoxAgent$\gpo-startup.ps1
It runs as SYSTEM at every startup. When agent.exe and config.json on the share are unchanged and
the agent is installed, it does nothing. Otherwise it runs install.ps1 from the share.
Set -Uninstall to remove the agent from all computers of the GPO.
A log is written to %ProgramData%\NetBox Windows Agent\gpo-startup.log.
#>
param(
[string]$SourceDirectory = $PSScriptRoot,
[string]$InstallDirectory = "$env:ProgramFiles\NetBox Windows Agent",
[switch]$Uninstall
)
$ErrorActionPreference = 'Stop'
$logDirectory = Join-Path $env:ProgramData 'NetBox Windows Agent'
New-Item -ItemType Directory -Path $logDirectory -Force | Out-Null
$log = Join-Path $logDirectory 'gpo-startup.log'
function Write-Log([string]$Text) { Add-Content -LiteralPath $log -Value "$(Get-Date -Format s) $Text" -Encoding UTF8 }
try {
if ($Uninstall) {
if (Test-Path -LiteralPath $InstallDirectory) {
& (Join-Path $SourceDirectory 'uninstall.ps1') -InstallDirectory $InstallDirectory
Write-Log 'Uninstalled.'
}
exit 0
}
$sourceAgent = Join-Path $SourceDirectory 'agent.exe'
$sourceConfig = Join-Path $SourceDirectory 'config.json'
if (-not (Test-Path -LiteralPath $sourceAgent) -or -not (Test-Path -LiteralPath $sourceConfig)) {
throw "agent.exe or config.json not found in $SourceDirectory (share not reachable yet?)"
}
$wanted = @{
agent = (Get-FileHash -LiteralPath $sourceAgent -Algorithm SHA256).Hash
config = (Get-FileHash -LiteralPath $sourceConfig -Algorithm SHA256).Hash
}
$stateFile = Join-Path $InstallDirectory 'install-state.json'
$current = if (Test-Path -LiteralPath $stateFile) { Get-Content -LiteralPath $stateFile -Raw | ConvertFrom-Json } else { $null }
$installed = (Test-Path -LiteralPath (Join-Path $InstallDirectory 'agent.exe')) -and $current -and
$current.agent -eq $wanted.agent -and $current.config -eq $wanted.config
$tasksPresent = (Get-ScheduledTask -TaskName 'NetBox Windows Agent*' -ErrorAction SilentlyContinue)
if ($installed -and $tasksPresent) {
# Up to date – make sure the listener runs (it normally starts by its own startup trigger).
if ($current.mode -in 'listen', 'both') { Start-ScheduledTask -TaskName 'NetBox Windows Agent Listener' -ErrorAction SilentlyContinue }
exit 0
}
Write-Log "Installing from $SourceDirectory"
$output = & (Join-Path $SourceDirectory 'install.ps1') -SourceDirectory $SourceDirectory -InstallDirectory $InstallDirectory 2>&1
$output | ForEach-Object { Write-Log " $_" }
Write-Log 'Done.'
exit 0
} catch {
Write-Log "ERROR: $($_.Exception.Message)"
exit 1
}
+87 -13
View File
@@ -1,3 +1,16 @@
<#
.SYNOPSIS
Installs or updates the NetBox Windows Agent (Intune Win32 app, GPO startup script or manual).
.DESCRIPTION
Copies agent.exe and config.json to the install directory, restricts access to SYSTEM and
administrators and sets up what the configured mode needs:
netbox daily scheduled task "NetBox Windows Agent" that writes to NetBox
listen scheduled task "NetBox Windows Agent Listener" (at startup, restarted on failure) and an
inbound firewall rule, so the NetBox Synchronizer desktop app can scan the inventory
both both of the above
The script is idempotent: running it again updates the files and the tasks.
#>
param(
[string]$SourceDirectory = $PSScriptRoot,
[string]$InstallDirectory = "$env:ProgramFiles\NetBox Windows Agent",
@@ -5,11 +18,34 @@ param(
[string]$StartTime = '09:00'
)
$ErrorActionPreference = 'Stop'
if (-not (Test-Path (Join-Path $SourceDirectory 'agent.exe'))) { throw 'agent.exe fehlt im Quellverzeichnis.' }
if (-not (Test-Path (Join-Path $SourceDirectory 'config.json'))) { throw 'config.json fehlt im Quellverzeichnis.' }
$syncTask = 'NetBox Windows Agent'
$listenerTask = 'NetBox Windows Agent Listener'
$firewallRule = 'NetBoxWindowsAgent'
$sourceAgent = Join-Path $SourceDirectory 'agent.exe'
$sourceConfig = Join-Path $SourceDirectory 'config.json'
if (-not (Test-Path -LiteralPath $sourceAgent)) { throw 'agent.exe is missing in the source directory.' }
if (-not (Test-Path -LiteralPath $sourceConfig)) { throw 'config.json is missing in the source directory.' }
if ($Schedule -ne 'DAILY') { throw "Only the schedule 'DAILY' is supported." }
$config = Get-Content -LiteralPath $sourceConfig -Raw | ConvertFrom-Json
$mode = if ($config.mode) { [string]$config.mode } else { 'netbox' }
if ($mode -notin 'netbox', 'listen', 'both') { throw "config.json: mode must be 'netbox', 'listen' or 'both'." }
$port = if ($config.listen_port) { [int]$config.listen_port } else { 8731 }
$allowed = @($config.allowed_networks | Where-Object { $_ })
$syncs = $mode -in 'netbox', 'both'
$listens = $mode -in 'listen', 'both'
# A running listener locks agent.exe – stop it before the files are replaced.
Stop-ScheduledTask -TaskName $listenerTask -ErrorAction SilentlyContinue
Get-Process -Name agent -ErrorAction SilentlyContinue |
Where-Object { $_.Path -and $_.Path.StartsWith($InstallDirectory, [StringComparison]::OrdinalIgnoreCase) } |
Stop-Process -Force -ErrorAction SilentlyContinue
Start-Sleep -Milliseconds 500
New-Item -ItemType Directory -Path $InstallDirectory -Force | Out-Null
Copy-Item (Join-Path $SourceDirectory 'agent.exe') (Join-Path $InstallDirectory 'agent.exe') -Force
Copy-Item (Join-Path $SourceDirectory 'config.json') (Join-Path $InstallDirectory 'config.json') -Force
Copy-Item -LiteralPath $sourceAgent -Destination (Join-Path $InstallDirectory 'agent.exe') -Force
Copy-Item -LiteralPath $sourceConfig -Destination (Join-Path $InstallDirectory 'config.json') -Force
$acl = Get-Acl $InstallDirectory
$acl.SetAccessRuleProtection($true, $false)
$administratorsSid = New-Object System.Security.Principal.SecurityIdentifier('S-1-5-32-544')
@@ -19,21 +55,59 @@ $system = New-Object System.Security.AccessControl.FileSystemAccessRule($systemS
$acl.SetAccessRule($admins); $acl.SetAccessRule($system); Set-Acl $InstallDirectory $acl
$agentPath = Join-Path $InstallDirectory 'agent.exe'
$configPath = Join-Path $InstallDirectory 'config.json'
if ($Schedule -ne 'DAILY') { throw "Derzeit wird nur Schedule 'DAILY' unterstützt." }
$principal = New-ScheduledTaskPrincipal -UserId 'S-1-5-18' -LogonType ServiceAccount -RunLevel Highest
# --- NetBox sync (mode netbox/both) -------------------------------------------------------------
if ($syncs) {
$action = New-ScheduledTaskAction -Execute $agentPath -Argument "--config `"$configPath`""
$trigger = New-ScheduledTaskTrigger -Daily -At $StartTime
$principal = New-ScheduledTaskPrincipal -UserId 'S-1-5-18' -LogonType ServiceAccount -RunLevel Highest
$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -ExecutionTimeLimit (New-TimeSpan -Minutes 15)
Register-ScheduledTask -TaskName 'NetBox Windows Agent' -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Force | Out-Null
Register-ScheduledTask -TaskName $syncTask -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Force | Out-Null
} else {
Unregister-ScheduledTask -TaskName $syncTask -Confirm:$false -ErrorAction SilentlyContinue
}
# --- Listener for the NetBox Synchronizer (mode listen/both) ------------------------------------
Remove-NetFirewallRule -Name $firewallRule -ErrorAction SilentlyContinue
if ($listens) {
$action = New-ScheduledTaskAction -Execute $agentPath -Argument "--config `"$configPath`" --serve"
$trigger = New-ScheduledTaskTrigger -AtStartup
$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries `
-ExecutionTimeLimit (New-TimeSpan -Seconds 0) -RestartCount 999 -RestartInterval (New-TimeSpan -Minutes 1) `
-MultipleInstances IgnoreNew
Register-ScheduledTask -TaskName $listenerTask -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Force | Out-Null
$remote = if ($allowed.Count -gt 0) { $allowed } else { 'Any' }
New-NetFirewallRule -Name $firewallRule -DisplayName 'NetBox Windows Agent' -Direction Inbound -Protocol TCP `
-LocalPort $port -Program $agentPath -RemoteAddress $remote -Profile Domain, Private -Action Allow | Out-Null
Start-ScheduledTask -TaskName $listenerTask
} else {
Unregister-ScheduledTask -TaskName $listenerTask -Confirm:$false -ErrorAction SilentlyContinue
}
# --- First NetBox sync ----------------------------------------------------------------------------
if ($syncs) {
& $agentPath --config $configPath
$syncExitCode = $LASTEXITCODE
if ($syncExitCode -ne 0) {
Write-Warning "Der Agent wurde installiert, aber die erste NetBox-Synchronisation ist mit Exitcode $syncExitCode fehlgeschlagen. Die geplante Aufgabe versucht es erneut."
Write-Warning "The agent is installed, but the first NetBox sync failed with exit code $syncExitCode. The scheduled task retries it."
} else {
Write-Host 'Die erste NetBox-Synchronisation war erfolgreich.'
Write-Host 'The first NetBox sync was successful.'
}
if (-not (Test-Path -LiteralPath $agentPath)) { throw 'Installation fehlgeschlagen: agent.exe wurde nicht installiert.' }
if (-not (Test-Path -LiteralPath $configPath)) { throw 'Installation fehlgeschlagen: config.json wurde nicht installiert.' }
if (-not (Get-ScheduledTask -TaskName 'NetBox Windows Agent' -ErrorAction SilentlyContinue)) { throw 'Installation fehlgeschlagen: Die geplante Aufgabe fehlt.' }
Write-Host 'NetBox Windows Agent wurde erfolgreich installiert.'
}
# --- Checks (decide the Intune installation state) -----------------------------------------------
if (-not (Test-Path -LiteralPath $agentPath)) { throw 'Installation failed: agent.exe was not installed.' }
if (-not (Test-Path -LiteralPath $configPath)) { throw 'Installation failed: config.json was not installed.' }
if ($syncs -and -not (Get-ScheduledTask -TaskName $syncTask -ErrorAction SilentlyContinue)) { throw 'Installation failed: the scheduled task is missing.' }
if ($listens -and -not (Get-ScheduledTask -TaskName $listenerTask -ErrorAction SilentlyContinue)) { throw 'Installation failed: the listener task is missing.' }
# Fingerprint of the installed files, used by gpo-startup.ps1 to skip unchanged installations.
$state = [ordered]@{
agent = (Get-FileHash -LiteralPath $agentPath -Algorithm SHA256).Hash
config = (Get-FileHash -LiteralPath $configPath -Algorithm SHA256).Hash
mode = $mode
installed = (Get-Date).ToString('o')
}
$state | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $InstallDirectory 'install-state.json') -Encoding UTF8
Write-Host "NetBox Windows Agent was installed successfully (mode '$mode')."
exit 0
+8 -1
View File
@@ -1,9 +1,16 @@
param([string]$InstallDirectory = "$env:ProgramFiles\NetBox Windows Agent")
$ErrorActionPreference = 'Stop'
Unregister-ScheduledTask -TaskName 'NetBox Windows Agent' -Confirm:$false -ErrorAction SilentlyContinue
Stop-ScheduledTask -TaskName 'NetBox Windows Agent Listener' -ErrorAction SilentlyContinue
Unregister-ScheduledTask -TaskName 'NetBox Windows Agent Listener' -Confirm:$false -ErrorAction SilentlyContinue
Remove-NetFirewallRule -Name 'NetBoxWindowsAgent' -ErrorAction SilentlyContinue
if (Test-Path -LiteralPath $InstallDirectory) {
$resolved = (Resolve-Path -LiteralPath $InstallDirectory).Path
$programFiles = (Resolve-Path -LiteralPath $env:ProgramFiles).Path
if (-not $resolved.StartsWith($programFiles + '\', [StringComparison]::OrdinalIgnoreCase)) { throw "Unsicheres Ziel: $resolved" }
if (-not $resolved.StartsWith($programFiles + '\', [StringComparison]::OrdinalIgnoreCase)) { throw "Unsafe target: $resolved" }
Get-Process -Name agent -ErrorAction SilentlyContinue |
Where-Object { $_.Path -and $_.Path.StartsWith($resolved, [StringComparison]::OrdinalIgnoreCase) } |
Stop-Process -Force -ErrorAction SilentlyContinue
Start-Sleep -Milliseconds 500
Remove-Item -LiteralPath $resolved -Recurse -Force
}
+73 -10
View File
@@ -7,27 +7,76 @@ internal static class HardwareCollector
{
public static HardwareInfo Collect(bool collectSoftware = true, int maxSoftwareEntries = 250)
{
var computer = First("Win32_ComputerSystem", "Manufacturer", "Model", "TotalPhysicalMemory");
var product = First("Win32_ComputerSystemProduct", "UUID");
var bios = First("Win32_BIOS", "SerialNumber");
var os = First("Win32_OperatingSystem", "Caption", "Version", "OSArchitecture");
var cpu = First("Win32_Processor", "Name");
var computer = First("Win32_ComputerSystem", "Name", "Domain", "PartOfDomain", "Manufacturer", "Model",
"TotalPhysicalMemory", "UserName");
var product = First("Win32_ComputerSystemProduct", "UUID", "Name", "Version");
var bios = First("Win32_BIOS", "SerialNumber", "SMBIOSBIOSVersion");
var os = First("Win32_OperatingSystem", "Caption", "Version", "BuildNumber", "OSArchitecture", "InstallDate",
"LastBootUpTime");
var enclosure = FirstOrDefault("Win32_SystemEnclosure", "ChassisTypes");
var processors = Query("Win32_Processor", "Name", "NumberOfCores").ToList();
var disks = Query("Win32_DiskDrive", "DeviceID", "Model", "SerialNumber", "Size")
.Select(x => new DiskInfo(S(x, "DeviceID"), S(x, "Model"), S(x, "SerialNumber"), U(x, "Size"))).ToList();
var networks = Query("Win32_NetworkAdapterConfiguration", "Description", "MACAddress", "IPAddress")
.Where(x => x["MACAddress"] is not null)
.Select(x => new NetworkInfo(S(x, "Description"), S(x, "MACAddress"),
(x["IPAddress"] as string[] ?? []).Where(ip => !ip.StartsWith("169.254.")).ToList())).ToList();
Strings(x, "IPAddress").Where(ip => !ip.StartsWith("169.254.")).ToList())).ToList();
var memoryModules = Query("Win32_PhysicalMemory", "BankLabel", "DeviceLocator", "Manufacturer", "PartNumber", "SerialNumber", "Capacity")
.Select(x => new MemoryInfo(
string.IsNullOrWhiteSpace(S(x, "BankLabel")) ? S(x, "DeviceLocator") : S(x, "BankLabel"),
S(x, "Manufacturer"), S(x, "PartNumber"), S(x, "SerialNumber"), U(x, "Capacity"))).ToList();
return new HardwareInfo(Environment.MachineName, S(computer, "Manufacturer"), S(computer, "Model"),
S(bios, "SerialNumber"), S(product, "UUID"), S(os, "Caption"), S(os, "Version"),
S(os, "OSArchitecture"), S(cpu, "Name"), U(computer, "TotalPhysicalMemory"), disks, networks,
memoryModules, collectSoftware ? CollectSoftware(maxSoftwareEntries) : []);
return new HardwareInfo
{
Hostname = Environment.MachineName,
Domain = S(computer, "Domain"),
PartOfDomain = computer["PartOfDomain"] is true,
Manufacturer = S(computer, "Manufacturer"),
Model = S(computer, "Model"),
ProductName = S(product, "Name"),
ProductVersion = S(product, "Version"),
Serial = S(bios, "SerialNumber"),
Uuid = S(product, "UUID"),
BiosVersion = S(bios, "SMBIOSBIOSVersion"),
Chassis = enclosure?["ChassisTypes"] is ushort[] types ? types.Select(t => (int)t).ToList() : [],
User = S(computer, "UserName"),
WindowsCaption = S(os, "Caption"),
WindowsVersion = S(os, "Version"),
WindowsBuild = S(os, "BuildNumber"),
WindowsDisplayVersion = RegistryString(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "DisplayVersion"),
Architecture = S(os, "OSArchitecture"),
Installed = CimDate(S(os, "InstallDate")),
LastBoot = CimDate(S(os, "LastBootUpTime")),
Processor = processors.Count > 0 ? S(processors[0], "Name") : "",
Cores = processors.Sum(p => (int)U(p, "NumberOfCores")),
MemoryBytes = U(computer, "TotalPhysicalMemory"),
Disks = disks,
Networks = networks,
Nics = CollectNics(),
MemoryModules = memoryModules,
Software = collectSoftware ? CollectSoftware(maxSoftwareEntries) : [],
};
}
private static IReadOnlyList<NicInfo> CollectNics()
{
var adapters = Query("Win32_NetworkAdapter", "InterfaceIndex", "PhysicalAdapter", "NetConnectionID", "Speed")
.Where(x => x["PhysicalAdapter"] is true)
.GroupBy(x => U(x, "InterfaceIndex"))
.ToDictionary(g => g.Key, g => g.First());
var nics = new List<NicInfo>();
foreach (var config in Query("Win32_NetworkAdapterConfiguration", "IPEnabled", "InterfaceIndex", "Description",
"MACAddress", "IPAddress", "IPSubnet", "DefaultIPGateway", "DHCPEnabled"))
{
if (config["IPEnabled"] is not true) continue;
adapters.TryGetValue(U(config, "InterfaceIndex"), out var adapter);
nics.Add(new NicInfo(adapter is null ? "" : S(adapter, "NetConnectionID"), S(config, "Description"),
S(config, "MACAddress"), Strings(config, "IPAddress"), Strings(config, "IPSubnet"),
Strings(config, "DefaultIPGateway"), config["DHCPEnabled"] is true, adapter is not null,
adapter is null ? 0 : U(adapter, "Speed")));
}
return nics;
}
private static IReadOnlyList<SoftwareInfo> CollectSoftware(int maximum)
@@ -51,7 +100,19 @@ internal static class HardwareCollector
return software.Values.OrderBy(x => x.Name, StringComparer.OrdinalIgnoreCase).Take(Math.Clamp(maximum, 0, 1000)).ToList();
}
private static string RegistryString(string key, string value)
{
using var hive = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
using var sub = hive.OpenSubKey(key);
return Convert.ToString(sub?.GetValue(value))?.Trim() ?? "";
}
// CIM datetime "20240115083000.000000+060" -> "2024-01-15T08:30:00"
private static string CimDate(string value) =>
value.Length >= 14 ? $"{value[..4]}-{value[4..6]}-{value[6..8]}T{value[8..10]}:{value[10..12]}:{value[12..14]}" : "";
private static ManagementBaseObject First(string cls, params string[] fields) => Query(cls, fields).First();
private static ManagementBaseObject? FirstOrDefault(string cls, params string[] fields) => Query(cls, fields).FirstOrDefault();
private static IEnumerable<ManagementBaseObject> Query(string cls, params string[] fields)
{
using var searcher = new ManagementObjectSearcher($"SELECT {string.Join(',', fields)} FROM {cls}");
@@ -59,4 +120,6 @@ internal static class HardwareCollector
}
private static string S(ManagementBaseObject x, string key) => Convert.ToString(x[key])?.Trim() ?? "";
private static ulong U(ManagementBaseObject x, string key) => ulong.TryParse(Convert.ToString(x[key]), out var n) ? n : 0;
private static List<string> Strings(ManagementBaseObject x, string key) =>
(x[key] as string[] ?? []).Where(s => !string.IsNullOrWhiteSpace(s)).ToList();
}
+204
View File
@@ -0,0 +1,204 @@
using System.Collections.Concurrent;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
namespace NetBoxWindowsAgent;
/// <summary>
/// Serves the inventory to the NetBox Synchronizer desktop app ("listen" mode).
///
/// Protocol v1 over plain HTTP:
/// GET /v1/info unauthenticated: agent name, version and protocol
/// GET /v1/inventory?nonce=N&amp;ts=T header X-Agent-Signature: hex(HMAC-SHA256(authKey, "GET\n/v1/inventory\nN\nT"))
/// The inventory is returned encrypted with AES-256-GCM (encKey, random 12 byte IV, the request nonce as
/// associated data): {"protocol":1,"iv":base64,"data":base64(ciphertext||tag)}.
/// authKey = HMAC-SHA256(UTF8(scan_key), "netbox-agent auth v1"), encKey = HMAC-SHA256(UTF8(scan_key), "netbox-agent enc v1").
/// Requests older than 5 minutes and repeated nonces are rejected.
/// </summary>
internal sealed class InventoryServer(AgentConfig config, Func<HardwareInfo> collect)
{
private static readonly Regex NonceFormat = new("^[0-9a-f]{32}$", RegexOptions.Compiled);
private readonly byte[] _authKey = DeriveKey(config.ScanKey, "netbox-agent auth v1");
private readonly byte[] _encKey = DeriveKey(config.ScanKey, "netbox-agent enc v1");
private readonly ConcurrentDictionary<string, long> _nonces = new();
private readonly List<IPNetwork> _allowed = config.AllowedNetworks.Select(IPNetwork.Parse).ToList();
private readonly SemaphoreSlim _collectLock = new(1, 1);
private byte[]? _cached;
private DateTime _cachedAt;
public static byte[] DeriveKey(string secret, string purpose) =>
HMACSHA256.HashData(Encoding.UTF8.GetBytes(secret), Encoding.UTF8.GetBytes(purpose));
public async Task Run(CancellationToken cancel)
{
var listener = new TcpListener(IPAddress.IPv6Any, config.ListenPort);
listener.Server.DualMode = true;
listener.Start();
Console.WriteLine($"Listening on TCP port {config.ListenPort} (protocol v{AgentInfo.Protocol}).");
while (!cancel.IsCancellationRequested)
{
var client = await listener.AcceptTcpClientAsync(cancel);
_ = Task.Run(() => Handle(client), cancel);
}
}
private async Task Handle(TcpClient client)
{
using (client)
{
try
{
client.ReceiveTimeout = client.SendTimeout = 10000;
var stream = client.GetStream();
var remote = (client.Client.RemoteEndPoint as IPEndPoint)?.Address ?? IPAddress.None;
if (remote.IsIPv4MappedToIPv6) remote = remote.MapToIPv4();
var (status, body) = await Respond(stream, remote);
var bytes = Encoding.UTF8.GetBytes(body);
var header = $"HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {bytes.Length}\r\n" +
"Cache-Control: no-store\r\nConnection: close\r\n\r\n";
await stream.WriteAsync(Encoding.ASCII.GetBytes(header));
await stream.WriteAsync(bytes);
}
catch (Exception ex) when (ex is IOException or SocketException or ObjectDisposedException)
{
// client went away
}
}
}
private async Task<(string Status, string Body)> Respond(NetworkStream stream, IPAddress remote)
{
if (_allowed.Count > 0 && !_allowed.Any(network => network.Contains(remote)))
return ("403 Forbidden", Error("address not allowed"));
var request = await ReadRequest(stream);
if (request is null) return ("400 Bad Request", Error("bad request"));
var (method, target, headers) = request.Value;
if (method != "GET") return ("405 Method Not Allowed", Error("only GET"));
var path = target.Split('?')[0];
var query = ParseQuery(target);
if (path == "/v1/info")
return ("200 OK", JsonSerializer.Serialize(new { agent = "netbox-windows-agent", version = AgentInfo.Version,
protocol = AgentInfo.Protocol }));
if (path != "/v1/inventory") return ("404 Not Found", Error("not found"));
var nonce = query.GetValueOrDefault("nonce", "");
if (!NonceFormat.IsMatch(nonce) || !long.TryParse(query.GetValueOrDefault("ts", ""), out var ts))
return ("400 Bad Request", Error("nonce or ts missing"));
var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
if (Math.Abs(now - ts) > 300) return ("401 Unauthorized", Error("clock skew too large"));
var expected = HMACSHA256.HashData(_authKey, Encoding.UTF8.GetBytes($"GET\n/v1/inventory\n{nonce}\n{ts}"));
byte[] given;
try { given = Convert.FromHexString(headers.GetValueOrDefault("x-agent-signature", "")); }
catch (FormatException) { given = []; }
if (!CryptographicOperations.FixedTimeEquals(expected, given)) return ("401 Unauthorized", Error("wrong key"));
foreach (var old in _nonces.Where(item => now - item.Value > 600).Select(item => item.Key).ToList())
_nonces.TryRemove(old, out _);
if (!_nonces.TryAdd(nonce, now)) return ("401 Unauthorized", Error("nonce reused"));
var plain = await Inventory();
var iv = RandomNumberGenerator.GetBytes(12);
var cipher = new byte[plain.Length];
var tag = new byte[16];
using (var aes = new AesGcm(_encKey, 16)) aes.Encrypt(iv, plain, cipher, tag, Encoding.ASCII.GetBytes(nonce));
return ("200 OK", JsonSerializer.Serialize(new { protocol = AgentInfo.Protocol, iv = Convert.ToBase64String(iv),
data = Convert.ToBase64String([.. cipher, .. tag]) }));
}
private async Task<byte[]> Inventory()
{
await _collectLock.WaitAsync();
try
{
if (_cached is null || DateTime.UtcNow - _cachedAt > TimeSpan.FromSeconds(Math.Max(0, config.InventoryCacheSeconds)))
{
_cached = JsonSerializer.SerializeToUtf8Bytes(InventoryDocument.Build(collect()));
_cachedAt = DateTime.UtcNow;
}
return _cached;
}
finally { _collectLock.Release(); }
}
private static async Task<(string Method, string Target, Dictionary<string, string> Headers)?> ReadRequest(NetworkStream stream)
{
var buffer = new byte[8192];
var length = 0;
while (length < buffer.Length)
{
var read = await stream.ReadAsync(buffer.AsMemory(length));
if (read == 0) break;
length += read;
if (Encoding.ASCII.GetString(buffer, 0, length).Contains("\r\n\r\n")) break;
}
var text = Encoding.ASCII.GetString(buffer, 0, length);
var end = text.IndexOf("\r\n\r\n", StringComparison.Ordinal);
if (end < 0) return null;
var lines = text[..end].Split("\r\n");
var first = lines[0].Split(' ');
if (first.Length != 3) return null;
var headers = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (var line in lines.Skip(1))
{
var colon = line.IndexOf(':');
if (colon > 0) headers[line[..colon].Trim().ToLowerInvariant()] = line[(colon + 1)..].Trim();
}
return (first[0], first[1], headers);
}
private static Dictionary<string, string> ParseQuery(string target)
{
var result = new Dictionary<string, string>();
var index = target.IndexOf('?');
if (index < 0) return result;
foreach (var part in target[(index + 1)..].Split('&', StringSplitOptions.RemoveEmptyEntries))
{
var pair = part.Split('=', 2);
result[Uri.UnescapeDataString(pair[0])] = pair.Length > 1 ? Uri.UnescapeDataString(pair[1]) : "";
}
return result;
}
private static string Error(string text) => JsonSerializer.Serialize(new { error = text });
}
/// <summary>Inventory in the shape of the WinRM scan of the desktop app, plus agent-only details.</summary>
internal static class InventoryDocument
{
public static Dictionary<string, object?> Build(HardwareInfo hw) => new()
{
["ok"] = true,
["source"] = "agent",
["agent_version"] = AgentInfo.Version,
["collected_at"] = DateTimeOffset.UtcNow.ToString("O"),
["name"] = hw.Hostname,
["domain"] = hw.Domain,
["part_of_domain"] = hw.PartOfDomain,
["manufacturer"] = hw.Manufacturer,
["model"] = hw.Model,
["product_name"] = hw.ProductName,
["product_version"] = hw.ProductVersion,
["serial"] = hw.Serial,
["uuid"] = hw.Uuid,
["bios_version"] = hw.BiosVersion,
["chassis"] = hw.Chassis,
["user"] = hw.User,
["memory"] = hw.MemoryBytes,
["cpu"] = hw.Processor,
["cores"] = hw.Cores,
["os"] = hw.WindowsCaption,
["os_version"] = hw.WindowsVersion,
["os_build"] = hw.WindowsBuild,
["os_display_version"] = hw.WindowsDisplayVersion,
["os_architecture"] = hw.Architecture,
["installed"] = hw.Installed,
["last_boot"] = hw.LastBoot,
["nics"] = hw.Nics,
["disks"] = hw.Disks,
["memory_modules"] = hw.MemoryModules,
["software"] = hw.Software,
};
}
+75 -8
View File
@@ -2,8 +2,17 @@ using System.Text.Json.Serialization;
namespace NetBoxWindowsAgent;
internal static class AgentInfo
{
public const string Version = "0.2.0";
public const int Protocol = 1;
}
internal sealed class AgentConfig
{
// "netbox": write to NetBox directly (default), "listen": only serve the inventory to the
// NetBox Synchronizer desktop app, "both": do both.
[JsonPropertyName("mode")] public string Mode { get; set; } = "netbox";
[JsonPropertyName("netbox_url")] public string NetBoxUrl { get; set; } = "";
[JsonPropertyName("api_token")] public string ApiToken { get; set; } = "";
[JsonPropertyName("region")] public string Region { get; set; } = "";
@@ -19,17 +28,75 @@ internal sealed class AgentConfig
[JsonPropertyName("create_interfaces")] public bool CreateInterfaces { get; set; } = true;
[JsonPropertyName("tags")] public List<string> Tags { get; set; } = [];
[JsonPropertyName("custom_fields")] public Dictionary<string, string> CustomFields { get; set; } = new();
// Listen mode
[JsonPropertyName("listen_port")] public int ListenPort { get; set; } = 8731;
[JsonPropertyName("scan_key")] public string ScanKey { get; set; } = "";
[JsonPropertyName("allowed_networks")] public List<string> AllowedNetworks { get; set; } = [];
[JsonPropertyName("inventory_cache_seconds")] public int InventoryCacheSeconds { get; set; } = 300;
[JsonIgnore] public bool SyncsNetBox => Mode is "netbox" or "both";
[JsonIgnore] public bool Listens => Mode is "listen" or "both";
}
internal sealed record HardwareInfo(
string Hostname, string Manufacturer, string Model, string Serial, string Uuid,
string WindowsCaption, string WindowsVersion, string Architecture, string Processor,
ulong MemoryBytes, IReadOnlyList<DiskInfo> Disks, IReadOnlyList<NetworkInfo> Networks,
IReadOnlyList<MemoryInfo> MemoryModules, IReadOnlyList<SoftwareInfo> Software);
internal sealed record DiskInfo(string DeviceId, string Model, string Serial, ulong SizeBytes);
internal sealed class HardwareInfo
{
public string Hostname { get; init; } = "";
public string Domain { get; init; } = "";
public bool PartOfDomain { get; init; }
public string Manufacturer { get; init; } = "";
public string Model { get; init; } = "";
public string ProductName { get; init; } = "";
public string ProductVersion { get; init; } = "";
public string Serial { get; init; } = "";
public string Uuid { get; init; } = "";
public string BiosVersion { get; init; } = "";
public IReadOnlyList<int> Chassis { get; init; } = [];
public string User { get; init; } = "";
public string WindowsCaption { get; init; } = "";
public string WindowsVersion { get; init; } = "";
public string WindowsBuild { get; init; } = "";
public string WindowsDisplayVersion { get; init; } = "";
public string Architecture { get; init; } = "";
public string Installed { get; init; } = "";
public string LastBoot { get; init; } = "";
public string Processor { get; init; } = "";
public int Cores { get; init; }
public ulong MemoryBytes { get; init; }
public IReadOnlyList<DiskInfo> Disks { get; init; } = [];
public IReadOnlyList<NetworkInfo> Networks { get; init; } = [];
public IReadOnlyList<NicInfo> Nics { get; init; } = [];
public IReadOnlyList<MemoryInfo> MemoryModules { get; init; } = [];
public IReadOnlyList<SoftwareInfo> Software { get; init; } = [];
}
internal sealed record DiskInfo(
[property: JsonPropertyName("device_id")] string DeviceId,
[property: JsonPropertyName("model")] string Model,
[property: JsonPropertyName("serial")] string Serial,
[property: JsonPropertyName("size")] ulong SizeBytes);
internal sealed record NetworkInfo(string Name, string MacAddress, IReadOnlyList<string> IpAddresses);
internal sealed record MemoryInfo(string Bank, string Manufacturer, string PartNumber, string Serial, ulong CapacityBytes);
internal sealed record SoftwareInfo(string Name, string Version, string Publisher);
internal sealed record MemoryInfo(
[property: JsonPropertyName("bank")] string Bank,
[property: JsonPropertyName("manufacturer")] string Manufacturer,
[property: JsonPropertyName("part_number")] string PartNumber,
[property: JsonPropertyName("serial")] string Serial,
[property: JsonPropertyName("capacity")] ulong CapacityBytes);
internal sealed record SoftwareInfo(
[property: JsonPropertyName("name")] string Name,
[property: JsonPropertyName("version")] string Version,
[property: JsonPropertyName("publisher")] string Publisher);
// Same shape as the WinRM scan of the NetBox Synchronizer desktop app.
internal sealed record NicInfo(
[property: JsonPropertyName("name")] string Name,
[property: JsonPropertyName("description")] string Description,
[property: JsonPropertyName("mac")] string Mac,
[property: JsonPropertyName("ips")] IReadOnlyList<string> Ips,
[property: JsonPropertyName("masks")] IReadOnlyList<string> Masks,
[property: JsonPropertyName("gateway")] IReadOnlyList<string> Gateway,
[property: JsonPropertyName("dhcp")] bool Dhcp,
[property: JsonPropertyName("physical")] bool Physical,
[property: JsonPropertyName("speed")] ulong Speed);
internal sealed class Page<T>
{
+3 -3
View File
@@ -17,7 +17,7 @@ internal sealed class NetBoxClient : IDisposable
_http = new HttpClient(handler) { BaseAddress = new Uri(config.NetBoxUrl.TrimEnd('/') + "/"), Timeout = TimeSpan.FromSeconds(config.TimeoutSeconds) };
_http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", config.ApiToken);
_http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
_http.DefaultRequestHeaders.UserAgent.ParseAdd("NetBox-Windows-Agent/0.1.0");
_http.DefaultRequestHeaders.UserAgent.ParseAdd($"NetBox-Windows-Agent/{AgentInfo.Version}");
}
public async Task<NetBoxObject?> FindOne(string endpoint, params (string Key, string? Value)[] filters)
@@ -25,7 +25,7 @@ internal sealed class NetBoxClient : IDisposable
var query = string.Join('&', filters.Where(f => !string.IsNullOrWhiteSpace(f.Value))
.Select(f => $"{Uri.EscapeDataString(f.Key)}={Uri.EscapeDataString(f.Value!)}"));
var page = await Send<Page<NetBoxObject>>(HttpMethod.Get, $"api/{endpoint}/?limit=2&{query}");
if (page.Count > 1) throw new InvalidOperationException($"NetBox-Abfrage für {endpoint} ist nicht eindeutig.");
if (page.Count > 1) throw new InvalidOperationException($"NetBox query for {endpoint} is ambiguous.");
return page.Results.SingleOrDefault();
}
@@ -42,7 +42,7 @@ internal sealed class NetBoxClient : IDisposable
var body = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
throw new InvalidOperationException($"NetBox {method} {uri}: {(int)response.StatusCode} {response.ReasonPhrase}: {body}");
return JsonSerializer.Deserialize<T>(body, _json) ?? throw new InvalidOperationException("NetBox lieferte eine leere Antwort.");
return JsonSerializer.Deserialize<T>(body, _json) ?? throw new InvalidOperationException("NetBox returned an empty response.");
}
public void Dispose() => _http.Dispose();
}
+59 -17
View File
@@ -7,36 +7,78 @@ static async Task<int> MainAsync(string[] args)
{
try
{
var configPath = ValueAfter(args, "--config") ?? Path.Combine(AppContext.BaseDirectory, "config.json");
var dryRun = args.Contains("--dry-run");
if (args.Contains("--help")) { Usage(); return 0; }
if (!File.Exists(configPath)) throw new FileNotFoundException("Konfigurationsdatei nicht gefunden.", configPath);
if (args.Contains("--version")) { Console.WriteLine(AgentInfo.Version); return 0; }
var configPath = ValueAfter(args, "--config") ?? Path.Combine(AppContext.BaseDirectory, "config.json");
if (!File.Exists(configPath)) throw new FileNotFoundException("Configuration file not found.", configPath);
var config = JsonSerializer.Deserialize<AgentConfig>(await File.ReadAllTextAsync(configPath), new JsonSerializerOptions(JsonSerializerDefaults.Web))
?? throw new InvalidOperationException("Konfiguration ist leer.");
?? throw new InvalidOperationException("Configuration is empty.");
Validate(config);
var hardware = HardwareCollector.Collect(config.CollectSoftware, config.MaxSoftwareEntries);
Console.WriteLine($"Erfasst: {hardware.Hostname}, {hardware.Manufacturer} {hardware.Model}, S/N {hardware.Serial}");
using var client = new NetBoxClient(config);
var result = await new SyncService(client, config).Sync(hardware, dryRun);
Console.WriteLine(dryRun ? "Dry-Run erfolgreich; keine Änderungen geschrieben." : $"Synchronisiert: Device #{result.DeviceId}, Asset #{result.AssetId}");
HardwareInfo Collect() => HardwareCollector.Collect(config.CollectSoftware, config.MaxSoftwareEntries);
if (args.Contains("--print"))
{
Console.WriteLine(JsonSerializer.Serialize(InventoryDocument.Build(Collect()), new JsonSerializerOptions { WriteIndented = true }));
return 0;
}
catch (Exception ex)
if (args.Contains("--serve"))
{
if (!config.Listens) throw new InvalidOperationException("--serve requires \"mode\": \"listen\" or \"both\".");
using var cancel = new CancellationTokenSource();
Console.CancelKeyPress += (_, e) => { e.Cancel = true; cancel.Cancel(); };
await new InventoryServer(config, Collect).Run(cancel.Token);
return 0;
}
if (!config.SyncsNetBox)
{
Console.WriteLine("Mode \"listen\": nothing to sync. The inventory is served by \"agent.exe --serve\".");
return 0;
}
var dryRun = args.Contains("--dry-run");
var hardware = Collect();
Console.WriteLine($"Collected: {hardware.Hostname}, {hardware.Manufacturer} {hardware.Model}, S/N {hardware.Serial}");
using var client = new NetBoxClient(config);
var result = await new SyncService(client, config).Sync(hardware, dryRun);
Console.WriteLine(dryRun ? "Dry run successful; nothing was written." : $"Synchronized: device #{result.DeviceId}, asset #{result.AssetId}");
return 0;
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
var messages = new List<string>();
for (Exception? current = ex; current is not null; current = current.InnerException)
if (!messages.Contains(current.Message)) messages.Add(current.Message);
Console.Error.WriteLine($"FEHLER: {string.Join(" -> ", messages)}");
Console.Error.WriteLine($"ERROR: {string.Join(" -> ", messages)}");
return 1;
}
catch (OperationCanceledException)
{
return 0;
}
}
static string? ValueAfter(string[] args, string key) { var i = Array.IndexOf(args, key); return i >= 0 && i + 1 < args.Length ? args[i + 1] : null; }
static void Validate(AgentConfig c)
{
if (!Uri.TryCreate(c.NetBoxUrl, UriKind.Absolute, out var uri) || (uri.Scheme != "https" && uri.Scheme != "http")) throw new InvalidOperationException("netbox_url ist ungültig.");
if (string.IsNullOrWhiteSpace(c.ApiToken) || c.ApiToken == "CHANGE_ME") throw new InvalidOperationException("api_token fehlt.");
if (string.IsNullOrWhiteSpace(c.DeviceRole)) throw new InvalidOperationException("device_role fehlt.");
if (string.IsNullOrWhiteSpace(c.Site)) throw new InvalidOperationException("site fehlt. NetBox verlangt für jedes DCIM Device eine Site; nur location ist optional.");
if (c.MaxSoftwareEntries < 0 || c.MaxSoftwareEntries > 1000) throw new InvalidOperationException("max_software_entries muss zwischen 0 und 1000 liegen.");
if (c.Mode is not ("netbox" or "listen" or "both")) throw new InvalidOperationException("mode must be \"netbox\", \"listen\" or \"both\".");
if (c.MaxSoftwareEntries < 0 || c.MaxSoftwareEntries > 1000) throw new InvalidOperationException("max_software_entries must be between 0 and 1000.");
if (c.SyncsNetBox)
{
if (!Uri.TryCreate(c.NetBoxUrl, UriKind.Absolute, out var uri) || (uri.Scheme != "https" && uri.Scheme != "http")) throw new InvalidOperationException("netbox_url is invalid.");
if (string.IsNullOrWhiteSpace(c.ApiToken) || c.ApiToken == "CHANGE_ME") throw new InvalidOperationException("api_token is missing.");
if (string.IsNullOrWhiteSpace(c.DeviceRole)) throw new InvalidOperationException("device_role is missing.");
if (string.IsNullOrWhiteSpace(c.Site)) throw new InvalidOperationException("site is missing. NetBox requires a site for every DCIM device; only location is optional.");
}
static void Usage() => Console.WriteLine("agent.exe [--config PFAD] [--dry-run] [--help]");
if (c.Listens)
{
if (c.ScanKey.Length < 16 || c.ScanKey == "CHANGE_ME") throw new InvalidOperationException("scan_key must have at least 16 characters.");
if (c.ListenPort is < 1 or > 65535) throw new InvalidOperationException("listen_port is invalid.");
foreach (var network in c.AllowedNetworks)
if (!System.Net.IPNetwork.TryParse(network, out _)) throw new InvalidOperationException($"allowed_networks: \"{network}\" is not a network in CIDR notation.");
}
}
static void Usage() => Console.WriteLine("""
agent.exe [--config PATH] [--dry-run] collect and write to NetBox (mode "netbox" or "both")
agent.exe [--config PATH] --serve serve the inventory to the NetBox Synchronizer (mode "listen" or "both")
agent.exe [--config PATH] --print print the collected inventory as JSON
agent.exe --version | --help
""");
+11 -11
View File
@@ -9,7 +9,7 @@ internal sealed class SyncService(NetBoxClient client, AgentConfig config)
var manufacturer = await EnsureManufacturer(hw.Manufacturer, dryRun);
var deviceType = await EnsureDeviceType(manufacturer, hw.Model, dryRun);
var role = await client.FindOne("dcim/device-roles", ("slug", config.DeviceRole))
?? throw new InvalidOperationException($"Geräterolle '{config.DeviceRole}' fehlt in NetBox.");
?? throw new InvalidOperationException($"Device role '{config.DeviceRole}' does not exist in NetBox.");
var device = await client.FindOne("dcim/devices", ("serial", hw.Serial));
var customFields = BuildCustomFields(hw);
@@ -33,7 +33,7 @@ internal sealed class SyncService(NetBoxClient client, AgentConfig config)
var assetPayload = new Dictionary<string, object?> {
["name"] = hw.Hostname, ["serial"] = hw.Serial, ["status"] = "used",
["device_type"] = deviceType.Id, ["device"] = device.Id,
["description"] = $"Windows-Client; UUID {hw.Uuid}", ["comments"] = inventoryReport
["description"] = $"Windows client; UUID {hw.Uuid}", ["comments"] = inventoryReport
};
if (asset is null) {
if (dryRun) return (device.Id, 0);
@@ -90,13 +90,13 @@ internal sealed class SyncService(NetBoxClient client, AgentConfig config)
var filters = new List<(string, string?)> { ("slug", config.Site) };
if (!string.IsNullOrWhiteSpace(config.Region)) filters.Add(("region", config.Region));
return await client.FindOne("dcim/sites", filters.ToArray())
?? throw new InvalidOperationException($"Standort '{config.Site}' (Region '{config.Region}') fehlt in NetBox.");
?? throw new InvalidOperationException($"Site '{config.Site}' (region '{config.Region}') does not exist in NetBox.");
}
private async Task<NetBoxObject?> ResolveLocation(NetBoxObject? site)
{
if (string.IsNullOrWhiteSpace(config.Location)) return null;
return await client.FindOne("dcim/locations", ("slug", config.Location), ("site_id", site?.Id.ToString()))
?? throw new InvalidOperationException($"Lokation '{config.Location}' fehlt in NetBox.");
?? throw new InvalidOperationException($"Location '{config.Location}' does not exist in NetBox.");
}
private async Task<NetBoxObject> EnsureManufacturer(string name, bool dryRun)
{
@@ -117,7 +117,7 @@ internal sealed class SyncService(NetBoxClient client, AgentConfig config)
private Dictionary<string, object> BuildCustomFields(HardwareInfo hw)
{
var available = new Dictionary<string, object> {
["agent_version"] = "0.1.0", ["windows_version"] = hw.WindowsVersion,
["agent_version"] = AgentInfo.Version, ["windows_version"] = hw.WindowsVersion,
["device_uuid"] = hw.Uuid, ["last_sync"] = DateTimeOffset.UtcNow.ToString("O")
};
return config.CustomFields.Where(x => available.ContainsKey(x.Key)).ToDictionary(x => x.Value, x => available[x.Key]);
@@ -125,17 +125,17 @@ internal sealed class SyncService(NetBoxClient client, AgentConfig config)
private static string HardwareSummary(HardwareInfo hw)
{
var lines = new List<string> {
"Automatisch durch NetBox Windows Agent aktualisiert.", "", "## Hardware",
$"- System: {hw.Manufacturer} {hw.Model}", $"- Seriennummer: {hw.Serial}", $"- UUID: {hw.Uuid}",
$"- Betriebssystem: {hw.WindowsCaption} {hw.WindowsVersion} ({hw.Architecture})",
$"- CPU: {hw.Processor}", $"- RAM: {hw.MemoryBytes / 1073741824d:F1} GiB", "", "### Datenträger"
"Updated automatically by the NetBox Windows Agent.", "", "## Hardware",
$"- System: {hw.Manufacturer} {hw.Model}", $"- Serial number: {hw.Serial}", $"- UUID: {hw.Uuid}",
$"- Operating system: {hw.WindowsCaption} {hw.WindowsVersion} ({hw.Architecture})",
$"- CPU: {hw.Processor}", $"- RAM: {hw.MemoryBytes / 1073741824d:F1} GiB", "", "### Disks"
};
lines.AddRange(hw.Disks.Select(d => $"- {d.Model} — {d.SizeBytes / 1000000000d:F0} GB — S/N {d.Serial} — {d.DeviceId}"));
lines.AddRange(["", "### Netzwerk"]);
lines.AddRange(["", "### Network"]);
lines.AddRange(hw.Networks.Select(n => $"- {n.Name} — {n.MacAddress} — {string.Join(", ", n.IpAddresses)}"));
if (hw.Software.Count > 0)
{
lines.AddRange(["", $"## Installierte Software ({hw.Software.Count})"]);
lines.AddRange(["", $"## Installed software ({hw.Software.Count})"]);
lines.AddRange(hw.Software.Select(s => $"- {s.Name}{(string.IsNullOrWhiteSpace(s.Version) ? "" : $" {s.Version}")}{(string.IsNullOrWhiteSpace(s.Publisher) ? "" : $" — {s.Publisher}")}"));
}
return string.Join('\n', lines);