🛡️ Check MS Defender
A comprehensive Nagios plugin for monitoring Microsoft Defender for Endpoint API endpoints. Built with modern Python practices and designed for enterprise monitoring environments.
✨ Features
- 🔐 Dual Authentication - Support for Client Secret and Certificate-based authentication
- 🎯 Multiple Endpoints - Monitor onboarding status, last seen, vulnerabilities, products with CVEs, alerts, and machine details
- 📊 Nagios Compatible - Standard exit codes and performance data output
- 🏗️ Clean Architecture - Modular design with testable components
- 🔧 Flexible Configuration - File-based configuration with sensible defaults
- 📈 Verbose Logging - Multi-level debugging support
- 🐍 Modern Python - Built with Python 3.10+ using type hints and async patterns
🚀 Quick Start
Installation
# Create virtual environment (recommended)
python -m venv /usr/local/libexec/nagios/check_msdefender
source /usr/local/libexec/nagios/check_msdefender/bin/activate
# Install from source
pip install git+https://github.com/lduchosal/check_msdefender.git
Basic Usage
# Check machine onboarding status
check_msdefender onboarding -d machine.domain.tld
# Check last seen (with custom thresholds)
check_msdefender lastseen -d machine.domain.tld -W 7 -C 30
# Check vulnerabilities
check_msdefender vulnerabilities -d machine.domain.tld -W 10 -C 100
# Check products with CVE vulnerabilities
check_msdefender products -d machine.domain.tld -W 5 -C 1
# Check alerts
check_msdefender alerts -d machine.domain.tld -W 1 -C 5
# Check incidents (correlated alert groups)
check_msdefender incidents -d machine.domain.tld -W 1 -C 5
# List all machines
check_msdefender machines
# Get detailed machine info
check_msdefender detail -d machine.domain.tld
# Dump every detail of an incident to a text file (for LLM analysis / debugging)
check_msdefender incident-detail 199 -o incident-199.txt
📋 Available Commands
| Command | Description | Default Thresholds |
|---|---|---|
onboarding |
Check machine onboarding status | W:1, C:2 |
lastseen |
Days since machine last seen | W:7, C:30 |
vulnerabilities |
Vulnerability score calculation | W:10, C:100 |
products |
Count of vulnerable software with CVEs | W:5, C:1 |
alerts |
Count of unresolved alerts | W:1, C:0 |
incidents |
Count of unresolved incidents (correlated alerts) | W:1, C:0 |
machines |
List all machines | W:10, C:25 |
detail |
Get detailed machine information | - |
incident-detail |
Full text report of one incident (not a Nagios check) | - |
Vulnerability Scoring
The vulnerability score is calculated as:
- Critical vulnerabilities × 100
- High vulnerabilities × 10
- Medium vulnerabilities × 5
- Low vulnerabilities × 1
Products CVE Monitoring
The products command monitors installed software with known CVE vulnerabilities:
- Groups CVEs by software (name, version, vendor)
- Shows CVE details including severity levels and disk paths
- Counts vulnerable software (not individual CVEs)
- Default thresholds: Warning at 5 vulnerable software, Critical at 1
- Displays up to 10 software entries with first 5 CVEs per software
--verify-paths: dropping what the host no longer carries
Microsoft's SoftwareVulnerabilitiesByMachine export is a snapshot regenerated on
Microsoft's own cadence, so an uninstalled product keeps being reported for days, and so
does a product that has already been patched. The export carries its own evidence: the
disk and registry paths where each product was seen.
With --verify-paths, the check submits those paths to the machine in a single remote
command and drops every product the host no longer confirms:
removed- none of the reported paths exists any moreupgraded- the file is there, but in a version above the one reported
Everything the host cannot answer for keeps its score: a path that could not be read
(DENIED), an unreachable drive or share, a product the export gave no path for, or a
probe that failed altogether. A failed probe never turns the check green - the raw
score is what gets compared to the thresholds, and the output says so.
The rule is per product, not per path: one copy still on disk in the reported version keeps the whole product counted, however many other copies are gone. A leftover binary that exists but can never run (another CPU architecture, say) is an exception to register, not a stale entry.
The first line always says that the host was asked, even when nothing was excluded, and every path listed under a product carries the host's answer, the paths that keep it in the score first:
2 vulnerable products, score: 547 (raw 712, 1 stale excluded: 165), path verification: 27 paths, 5 absent, 0 unreadable
python 3.12.9.0 (python) - Score: 442, ...
- [PRESENT 3.12.9] c:\program files\...\rust-lldb\win\aarch64\bin\python.exe
- [ABSENT] c:\program files\...\rust-lldb\win\x64\bin\python.exe
Excluded products stay visible under Stale entries excluded, with the reason and the
path that decided it, and the perfdata keeps the raw curve:
products=3319;500;2000 raw=6743 stale=3424 unverified=2
The probe itself is a command template, so the check is not tied to any one transport:
[verify]
# {host} is replaced by the machine's DNS name; the template is split shell-style and
# run without a shell. Default: ssh to the Nagios command account.
command = ssh -o BatchMode=yes -o ConnectTimeout=5 -l nagioscmd {host} powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File c:/programdata/nagioscmd/scripts/test_paths.ps1
# Seconds; spent on top of the API calls, so keep the sum under the Nagios
# service_check_timeout. Default: 20
timeout = 20
The name dialed is the one Defender reports for the machine. When the monitoring server
reaches it under a different name -- a Nagios host_name whose alias is the Defender
name, say -- pass that name with --verify-host, or the probe fails on a host key it has
never seen while every other check on that host works:
check_msdefender products -d $HOSTALIAS$ --verify-paths --verify-host $HOSTNAME$
Paths go in on stdin, one per line; the command answers one line per path:
STATE<TAB>VERSION<TAB>PATH
where STATE is PRESENT, ABSENT, DENIED or ERROR. A reference implementation for
Windows hosts ships with the Arcantel winnagioscmd Ansible role as test_paths.ps1.
Alert Monitoring
The alerts command monitors unresolved security alerts for a machine:
- Counts only unresolved alerts (status ≠ "Resolved")
- Excludes informational alerts when critical/warning alerts exist
- Shows alert details including creation time, title, and severity
- Default thresholds: Warning at 1 alert, Critical at 0 (meaning any alert triggers warning)
Incident Monitoring
An incident is a group of correlated alerts that Microsoft Defender aggregates to describe a
single attack. Each alert carries the incidentId of the incident it belongs to. The incidents
command:
- Queries the device-scoped alerts endpoint (
/api/machines/{id}/alerts) so no alert is dropped behind a tenant-wide page-size cap - Counts distinct unresolved incidents (alerts grouped by
incidentId, status ≠ "Resolved") - Surfaces the most severe alert of each incident in the output
- Default thresholds: Warning at 1 incident, Critical at 0 (meaning any incident triggers warning)
Incident Detail Report
incident-detail is an analysis tool, not a check: it writes everything known about one
incident as structured plain text, meant to be handed to a model or read while debugging. It
needs the Graph permissions SecurityIncident.Read.All and ThreatHunting.Read.All for the
full report (see Required API permissions).
check_msdefender incident-detail 199 # report on stdout
check_msdefender incident-detail 199 -o incident-199.txt # report to a file
check_msdefender incident-detail da8131a3..._1 # any alert id of the incident
check_msdefender incident-detail 199 --json -o raw.json # raw collected JSON
check_msdefender incident-detail 199 --window 30 # wider timeline (minutes)
check_msdefender incident-detail 199 --timeline-limit 0 # no timeline
check_msdefender incident-detail 199 --no-graph # WindowsDefenderATP API only
- Reference: the integer incident id, or the id of any of its alerts. A GUID (tenant, machine or investigation id) is refused: Defender incident ids are integers.
- Incident (Graph): title, severity, status, classification/determination, assignee, priority score, resolving comment, tags, portal link, description.
- Summary: time span, severities, statuses, classification, MITRE techniques, machines, accounts, evidence counts by type and by verdict/remediation status.
- Machines: the full machine record of each device involved, fetched once.
- Evidence: devices, processes (command line, parent, PID, account, hashes), files (hashes, size, publisher), users, IPs, URLs, registry keys, with verdict, remediation and detection status, deduplicated across alerts and numbered; each alert lists the evidence it cites.
- Alerts: every populated field in chronological order (description and recommendation kept
whole, portal link), analyst comments; without Graph, the entities of
/api/alerts/{id}/user|files|ips|domains. - Timeline (Advanced Hunting, stands in for the portal's attack story): one line per event
over the incident's activity span widened by
--windowminutes (default 10). It follows the evidence processes, their parents and up to three generations of children, and lists what they did (processes, files, network, registry, DLL loads); files whose hash is in evidence, logons and Defender's own events (antivirus, ASR...) are kept too. Each table is capped by--timeline-limit(default 500) and the report saysfirst 500 of Nwhen it cuts. - Resolved incidents are reported too, unlike the checks.
- A call the app is not allowed to make (HTTP 403) is written in the report as
unavailableinstead of failing it; if the Graph incident cannot be read, the WindowsDefenderATP alerts API stands in. - The incident activity log (status/classification history of the portal's Activity tab) is exposed by no API and is not in the report.
Onboarding Status Values
0- Onboarded ✅1- InsufficientInfo ⚠️2- Unknown ❌
⚙️ Configuration
Authentication Setup
Create check_msdefender.ini in your Nagios directory or current working directory:
Client Secret Authentication
[auth]
client_id = your-application-client-id
client_secret = your-client-secret
tenant_id = your-azure-tenant-id
[settings]
timeout = 30
Certificate Authentication
[auth]
client_id = your-application-client-id
tenant_id = your-azure-tenant-id
certificate_path = /path/to/certificate.pem
private_key_path = /path/to/private_key.pem
[settings]
timeout = 30
Transient API errors
Throttling (429) and transient server errors (500/502/503/504) are retried up to
3 attempts with backoff, honouring Retry-After capped at 5 s, so a passing
Microsoft outage no longer turns into an UNKNOWN that lasts until the next retry.
Timeouts are not retried, to keep the check inside Nagios' service_check_timeout.
Once the retries are spent the check reports a single line, e.g.
UNKNOWN: MS Defender API 503 Service Unavailable after 3 attempts: GET ….
Microsoft Defender API Setup
- Register Application in Microsoft Entra ID (Azure AD) → App registrations → New registration
- Grant API Permissions (see below) → API permissions → Add a permission, always as Application permissions (not delegated), then Grant admin consent for the tenant
- Create Authentication (Secret or Certificate) → Certificates & secrets
- Note Credentials (Client ID, Tenant ID, Secret/Certificate)
Required API permissions
All permissions are Application permissions, read-only, and need admin consent.
WindowsDefenderATP (APIs my organization uses → WindowsDefenderATP) — every command:
| Permission | Used by |
|---|---|
Machine.Read.All |
all commands (machine lookup), onboarding, lastseen, machines, detail, incident-detail (machines) |
Vulnerability.Read.All |
vulnerabilities, products |
Alert.Read.All |
alerts, incidents, incident-detail |
Microsoft Graph (Microsoft APIs → Microsoft Graph) — incident-detail only:
| Permission | Used by |
|---|---|
SecurityIncident.Read.All |
incident-detail: incident header (classification, assignee, priority, tags, portal link) and evidence verdicts / remediation status |
ThreatHunting.Read.All |
incident-detail: device timeline from Advanced Hunting (the attack story) |
Without the Graph permissions incident-detail still works from the WindowsDefenderATP alerts
API, with neither incident header nor timeline; the report says what is missing.
Optional — WindowsDefenderATP, only for the per-alert "related" entities incident-detail
reads when Graph is unavailable (Graph evidence already carries them): File.Read.All,
Ip.Read.All, URL.Read.All, User.Read.All. Missing ones show as unavailable (403).
Check what a token carries (the roles claim) after granting consent; new permissions can
take a few minutes to reach freshly issued tokens.
🔧 Command Line Options
| Option | Description | Example |
|---|---|---|
-c, --config |
Configuration file path | -c /custom/path/config.ini |
-m, --machineId |
Machine ID (GUID) | -m "12345678-1234-1234-1234-123456789abc" |
-d, --computerDnsName |
Computer DNS Name (FQDN) | -d "server.domain.com" |
-W, --warning |
Warning threshold | -W 10 |
-C, --critical |
Critical threshold | -C 100 |
-v, --verbose |
Verbosity level | -v, -vv, -vvv |
--version |
Show version | --version |
🏢 Nagios Integration
Command Definitions
# Microsoft Defender Commands
define command {
command_name check_defender_onboarding
command_line $USER1$/check_msdefender/bin/check_msdefender onboarding -d $HOSTALIAS$
}
define command {
command_name check_defender_lastseen
command_line $USER1$/check_msdefender/bin/check_msdefender lastseen -d $HOSTALIAS$ -W 7 -C 30
}
define command {
command_name check_defender_vulnerabilities
command_line $USER1$/check_msdefender/bin/check_msdefender vulnerabilities -d $HOSTALIAS$ -W 10 -C 100
}
define command {
command_name check_defender_products
command_line $USER1$/check_msdefender/bin/check_msdefender products -d $HOSTALIAS$ -W 5 -C 1
}
define command {
command_name check_defender_alerts
command_line $USER1$/check_msdefender/bin/check_msdefender alerts -d $HOSTALIAS$ -W 1 -C 5
}
Service Definitions
# Microsoft Defender Services
define service {
use generic-service
service_description DEFENDER_ONBOARDING
check_command check_defender_onboarding
hostgroup_name msdefender
}
define service {
use generic-service
service_description DEFENDER_LASTSEEN
check_command check_defender_lastseen
hostgroup_name msdefender
}
define service {
use generic-service
service_description DEFENDER_VULNERABILITIES
check_command check_defender_vulnerabilities
hostgroup_name msdefender
}
define service {
use generic-service
service_description DEFENDER_PRODUCTS
check_command check_defender_products
hostgroup_name msdefender
}
define service {
use generic-service
service_description DEFENDER_ALERTS
check_command check_defender_alerts
hostgroup_name msdefender
}
🏗️ Architecture
This plugin follows clean architecture principles with clear separation of concerns:
check_msdefender/
├── 📁 cli/ # Command-line interface
│ ├── commands/ # Individual command handlers
│ │ ├── onboarding.py # Onboarding status command
│ │ ├── lastseen.py # Last seen command
│ │ ├── vulnerabilities.py # Vulnerabilities command
│ │ ├── products.py # Products CVE monitoring command
│ │ ├── alerts.py # Alerts monitoring command
│ │ ├── machines.py # List machines command
│ │ └── detail.py # Machine detail command
│ ├── decorators.py # Common CLI decorators
│ └── handlers.py # CLI handlers
├── 📁 core/ # Core business logic
│ ├── auth.py # Authentication management
│ ├── config.py # Configuration handling
│ ├── defender.py # Defender API client
│ ├── exceptions.py # Custom exceptions
│ ├── nagios.py # Nagios plugin framework
│ └── logging_config.py # Logging configuration
├── 📁 services/ # Business services
│ ├── onboarding_service.py # Onboarding business logic
│ ├── lastseen_service.py # Last seen business logic
│ ├── vulnerabilities_service.py # Vulnerability business logic
│ ├── products_service.py # Products CVE monitoring business logic
│ ├── alerts_service.py # Alerts monitoring business logic
│ ├── machines_service.py # Machines business logic
│ ├── detail_service.py # Detail business logic
│ └── models.py # Data models
└── 📁 tests/ # Comprehensive test suite
├── unit/ # Unit tests
├── integration/ # Integration tests
└── fixtures/ # Test fixtures
Key Design Principles
- 🎯 Single Responsibility - Each module has one clear purpose
- 🔌 Dependency Injection - Easy testing and mocking
- 🧪 Testable - Comprehensive test coverage
- 📈 Extensible - Easy to add new commands and features
- 🔒 Secure - No secrets in code, proper credential handling
🧪 Development
Development Setup
# Clone repository
git clone https://github.com/lduchosal/check_msdefender.git
cd check_msdefender
# Create development environment
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
# Install in development mode
pip install -e .
Code Quality Tools
# Format code
black check_msdefender/
# Lint code
flake8 check_msdefender/
# Type checking
mypy check_msdefender/
# Run tests
pytest tests/ -v --cov=check_msdefender
Building & Publishing
# Build package
python -m build
# Test installation
pip install dist/*.whl
# Publish to PyPI
python -m twine upload dist/*
Task tracking (kenboard)
Work is tracked on kenboard with the ken CLI (.venv/bin/ken, auth from the
gitignored .ken). Task flow: todo → doing → review → done; only the user asks
for done.
ken list --who Claude --status todo --json # pull assigned work
ken show <id> --json # read full task
ken add "MODULE / Titre" --desc-file body.md --who Claude --status todo
ken move <id> --to doing|review
Titles must not contain < or >: the board rejects them with a bare
HTTP 422 Validation error (write 1.14.2+, not >= 1.14.2).
Closing ceremony
When a task is finished, the user asks for it in these words — « ken done, ken tldr, commit, groom, wiki, publish » (or just « cloture »). The steps, in order:
| Step | What it means |
|---|---|
| ken done | ken done <id>. This is the one moment the rule « never move to done yourself » is lifted: the user is asking for it. If real leftovers remain, open a follow-up task for them rather than leaving the finished one open. |
| ken tldr | Rewrite the task description with a TL;DR on top (problem → action), then the detail below: what was done, which commits / released version, what was found, what is explicitly not done. The board is the audit trail — commit messages alone are not enough. Use --desc-file, never --desc "…\n…" (the \n stays literal and wrecks the markdown). |
| commit | Everything still pending in the working tree (git status), as a conventional commit referencing the task (fix(scope): … #<id>). Often a no-op because the work was committed as it went; say so rather than staying silent. |
| groom | ken wiki groom <id> <section> (sections from ARCHITECTURE.md: cli, core, services, quality). ken wiki groom with no arguments lists what is still unclassified — the pre-flight. Only classified tasks reach the wiki. |
| wiki | ken wiki sync exports the classified tasks to wiki/ (versioned), then commit it as docs(wiki): export kenboard wiki after closing #<id>. ken wiki build renders wiki-html/ locally (gitignored). |
| publish | ./publish.sh: pull --rebase, full quality gate, integration tests, SonarCloud gate, version bump, PyPI upload, chore: release version X.Y.Z commit, tag and push. Needs a clean tree — hence commit and wiki first. |
ken done <id>
ken update <id> --desc-file /tmp/ken-<id>.md # TL;DR + detail
git status # nothing left behind?
ken wiki groom <id> <section>
ken wiki sync && git add wiki && git commit -m "docs(wiki): export kenboard wiki after closing #<id>"
./publish.sh # release to PyPI, tag, push
After publish.sh, check that msal is still >= 1.37 in .venv: pdm update
re-locks it to an older version.
🔍 Output Examples
Successful Check
DEFENDER OK - Onboarding status: 0 (Onboarded) | onboarding=0;1;2;0;2
Warning State
DEFENDER WARNING - Last seen: 10 days ago | lastseen=10;7;30;0;
Critical State
DEFENDER CRITICAL - Vulnerability score: 150 (1 Critical, 5 High) | vulnerabilities=150;10;100;0;
Alerts Warning
DEFENDER WARNING - Unresolved alerts for machine.domain.com | alerts=2;1;5;0;
Unresolved alerts for machine.domain.com
2025-09-14T10:22:14.12Z - Suspicious activity detected (New high)
2025-09-14T12:00:00.00Z - Malware detection (InProgress medium)
🔧 Troubleshooting
Common Issues
| Issue | Solution |
|---|---|
| Authentication Errors | Verify Azure app permissions and credentials |
| Network Connectivity | Check firewall rules for Microsoft endpoints |
| Import Errors | Ensure all dependencies are installed |
| Configuration Issues | Validate config file syntax and paths |
Debug Mode
Enable verbose logging for detailed troubleshooting:
# Maximum verbosity
check_msdefender vulnerabilities -d machine.domain.tld -vvv
# Check specific configuration
check_msdefender onboarding -c /path/to/config.ini -d machine.domain.tld -vv
Required Network Access
Ensure connectivity to:
login.microsoftonline.comapi.securitycenter.microsoft.comapi-eu.securitycenter.microsoft.comapi-eu3.securitycenter.microsoft.comapi-uk.securitycenter.microsoft.com
📊 Exit Codes
| Code | Status | Description |
|---|---|---|
0 |
OK | Value within acceptable range |
1 |
WARNING | Value exceeds warning threshold |
2 |
CRITICAL | Value exceeds critical threshold |
3 |
UNKNOWN | Error occurred during execution |
🤝 Contributing
We welcome contributions! Here's how to get started:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Development Guidelines
- Follow PEP 8 style guide
- Add tests for new features
- Update documentation as needed
- Ensure all tests pass before submitting
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🙏 Acknowledgments
- Built with nagiosplugin framework
- Uses Azure Identity SDK for authentication
- Powered by Click for CLI interface
⭐ Star this repository if you find it useful!
💖 Sponsor
If this project helps you, consider supporting its development:
Metadata
Release files for check-msdefender 1.4.30
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| check_msdefender-1.4.30.tar.gz | 96.4 kB | Without provenance | Details for check_msdefender-1.4.30.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| check_msdefender-1.4.30-py3-none-any.whl | Python 3 | none | any | Details for check_msdefender-1.4.30-py3-none-any.whl |
Total release size: 169.9 kB
Release files / check_msdefender-1.4.30.tar.gz
| Download URL | check_msdefender-1.4.30.tar.gz |
|---|---|
| Size | 96.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
5cf01d407d57f0089e202d3042c65848cb4041dd051c6fd3f6141d86ef500d84
|
|
BLAKE2b-256 checksum How to use checksums |
9646507c4d6f6ce8fc02ebfdcf23207944e1ca87b5cc01d2173ffaa3108a7359
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
pdm/2.29.5 CPython/3.13.17 Linux/7.0.0-1017-azure
|
Release files / check_msdefender-1.4.30-py3-none-any.whl
| Download URL | check_msdefender-1.4.30-py3-none-any.whl |
|---|---|
| Size | 73.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
837deed4db381a7d4c9c944a7dd0960b996c9654fe5c637bc11c34b9da8a685a
|
|
BLAKE2b-256 checksum How to use checksums |
0e962893849db135a084c543c14d13ea13212d81da6023a45229e356f8b82020
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
pdm/2.29.5 CPython/3.13.17 Linux/7.0.0-1017-azure
|
Security for check-msdefender 1.4.30
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.