This guide is for IT administrators who deploy Al-Khandaq (الخندق) to several Windows, Ubuntu or macOS machines, often on slow or intermittent networks. It describes version 1.0. Where a feature is designed but not yet built, the guide says so.
Al-Khandaq is free for personal and home use, with every fix included. No key and no account are needed. Organisations that want organisation features (for example signed compliance reports) can ask for an organisation key at info@akhundbaba.af. See section 11.
Downloads: www.al-khandaq.com/download.
Related documents:
| Topic | Document |
|---|---|
| Using the app | User guide |
| Every connection Al-Khandaq makes | Privacy |
| Reporting a vulnerability, supported versions | Security policy |
| What changed in each version | Changelog |
| Accessibility | Accessibility statement |
| Licence terms | End-user licence agreement |
The Group Policy template ships with the release files (section 3.1). The full policy key reference, the SIEM event reference and an example macOS configuration profile are available from info@akhundbaba.af.
1. Architecture and trust model
1.1 Components
| Component | Runs as | Purpose |
|---|---|---|
khandaq-agent |
Windows: service Khandaq ("Al-Khandaq Security Posture Agent"), LocalSystem. Linux: khandaq-agent.service, root. macOS: launchd daemon org.alkhandaq.agent, root. |
Runs every check on its own schedule, keeps the merged report and history, hosts fixes (actions) and real-time monitors, serves the local IPC endpoint, sends webhook alerts. |
khandaq-app |
The signed-in user | Tauri desktop app. Shows what the agent reports. Asks the agent to plan and apply fixes. |
khandaq-tray |
The signed-in user | Windows: tray icon and toasts. Linux: tray icon (StatusNotifierItem, where the desktop shows one) with the same menu, and desktop notifications. macOS: no separate tray; the app itself shows the menu-bar icon and alerts. |
khandaq (CLI) |
Whoever runs it | scan and list run checks in the CLI's own process. actions and licence talk to the agent. |
khandaq-fleet |
Separate server | Fleet console. Preview in 1.0. The agent does not report to it. See section 14. |
The agent is the only privileged process. The app, tray and CLI hold no privileges of their own; they send one JSON request per connection over a local endpoint and show the answer:
| Windows | Linux and macOS | |
|---|---|---|
| Endpoint | named pipe \\.\pipe\khandaq |
Unix socket /run/khandaq/khandaq.sock (macOS: /private/var/run/khandaq/khandaq.sock) |
| Who can connect | SYSTEM, Administrators, and interactive users (IU, read/write data only). Remote clients are rejected. |
root and members of group khandaq (socket mode 0660, group khandaq) |
| Client checks the server | The pipe's server PID must be the Khandaq service's PID |
The socket's peer must be uid 0 |
Limits on the endpoint: requests up to 64 KiB, 10 s read and write deadlines, at most 64 connections at once and 8 per account, with 8 slots kept for administrators.
If another process already holds the endpoint name, the agent keeps scanning,
retries the endpoint with back-off (up to 60 s between tries), and reports a
High Fail agent.ipc.endpoint ("Another program holds the agent's connection
point ...").
1.2 Who can do what
| Request | Any user who can connect | Local administrator |
|---|---|---|
| Read status, latest report, events, audit log, acceptances, insights | yes | yes |
Ask for a scan (scan_now) |
yes | yes |
| List actions, plan an action (read-only) | yes | yes |
Apply a plan (apply_action), cancel a run |
no | yes |
| Accept or withdraw acceptance of a finding | no | yes |
Install an organisation key (install_licence) |
no | yes |
"Local administrator" means:
- Windows: the client process's token holds an enabled BUILTIN\Administrators group. A non-elevated (UAC-filtered) token of an administrator does not count. In the app, a non-elevated user is asked for UAC approval; the app relaunches itself elevated to approve.
- Linux: uid 0, or a member of group
khandaq-admin(members also needkhandaqto open the socket). In the app, akhandaq-adminmember is approved straight away, with no password prompt; anyone else gets a polkit (pkexec) prompt for an administrator's password. - macOS: uid 0, or a member of group
khandaq-admin(andkhandaq). In the app, anyone else gets the standard macOS administrator password dialog.
Everyone else gets the error Approving changes needs an administrator.
The agent records the verified account (DOMAIN\user, or the Linux user name)
as the approver. Whatever name the client sends is replaced.
Development exception: when the agent itself is not elevated
(khandaq-agent run --console as a normal user), a client running as the same
account may also approve. Actions then run with that account's own rights. An
elevated agent or the service never allows this.
1.3 Plan, approve, apply
Every change to the machine is an action and follows the same path:
- Plan. The agent runs the action's read-only plan step and stores the plan under a random 128-bit id (32 lowercase hex digits). The client gets the id, the plan and its expiry. Plans expire after 10 minutes. At most 256 plans are kept; the oldest is dropped beyond that.
- Approve and apply. An administrator sends the plan id. The agent accepts only an id it issued, not expired, and each id works once. The client cannot change the plan's arguments: the agent applies the stored plan.
- Audit. The agent writes an
audit_logrow (state = running) before anything changes, then runs the action on its own thread. One run per action at a time. When it ends, the row is completed with the outcome and the verified approver. Runs still markedrunningwhen the agent stopped are closed as failed at the next start. - Rescan. Every check whose latest findings point at the action is run again.
Finished runs can be queried for one hour. Cancelling stops a run between items.
Any user can create plans. The agent records who planned each one
(planned_by) and rate-limits what standard users may ask for. An
administrator should apply only plans they planned or reviewed themselves.
No automatic fixes ship. The automatic-policy hook exists in the agent, but no policy is registered, so nothing is applied without an administrator.
1.4 No licence gate on fixes
Al-Khandaq is free for personal and home use. No action, profile, automatic policy or rollback needs a licence: with no key at all the agent plans and runs every fix. What a fix needs is the administrator approval described above, and nothing else.
A licence key only unlocks organisation features (section 11). One exists in
this version: signing a compliance report (org.reports). Asked for without a
key that grants it, the agent answers This is an organisation feature and needs an Al-Khandaq organisation key; the unsigned report stays free.
2. System requirements
| Supported | |
|---|---|
| Windows | Windows 10, Windows 11, Windows Server 2019 and later; x64 only |
| Ubuntu | 22.04, 24.04, 26.04; amd64 only. The .deb needs glibc 2.34 or later. |
| Fedora / RHEL | .rpm x86_64 is built, but has not been tested on Fedora or RHEL |
| macOS | macOS 11 Big Sur and later; Apple silicon and Intel (one universal package) |
| Requirement | Detail |
|---|---|
| Installer rights | Administrator (Windows and macOS) or root via sudo (Linux) |
| macOS permissions | Full Disk Access for khandaq-agent, for complete malware scans (section 5a.3) |
| Windows runtime | None extra for the agent, tray and CLI (static CRT, no VC++ redistributable). The desktop app needs the WebView2 Runtime, which Windows Server 2019/2022 do not have by default. |
Linux runtime (khandaq) |
libc6, adduser, passwd; systemd recommended. These are normally present, so the server package installs without network access. |
Linux runtime (khandaq-desktop) |
libwebkit2gtk-4.1-0, libgtk-3-0t64 or libgtk-3-0, libayatana-appindicator3-1 or libappindicator3-1. apt may need to download these. |
| Memory | About 58–66 MB resident was measured for the agent on Linux. No formal sizing exists. |
| Network | None required. See section 2.1. |
2.1 Network use
The agent works offline. Checks that need a feed use a cached copy, or report an Error when they cannot get one; an Error is never turned into a Pass.
The complete list of outbound connections, what each one sends, whether it is on by default and the setting that controls it is Every connection Al-Khandaq makes; the app shows the same list under Settings → Privacy. Nothing that sends data about the computer is on by default. The main ones for planning a firewall:
| Destination | Used by | When |
|---|---|---|
www.cisa.gov (KEV catalogue) |
sw.vuln.kev (Windows) |
At most once a day; a stale cached copy is used when the download fails |
api.osv.dev |
sw.vuln.osv (Linux) |
Only when allowed ("Send my program list", off by default) and the content bundle has no current Ubuntu data |
api.github.com, github.com |
av.rules.update (YARA Forge) |
When the rule pack is updated |
| Windows Update / WSUS | os.update.refresh monitor |
2 minutes after the agent starts, then at most every 6 hours; skipped on metered connections |
| winget / apt / snap sources | update checks and update actions | During checks and approved installs |
| Your webhook URL | webhook alerts | Only if configured |
downloads.al-khandaq.com (or [update] mirror) |
self-update and the content channel | 2 minutes after start, then every check_hours (default 6); packages only when installing |
Set a proxy with [network] proxy in agent.toml (section 10.1).
3. Before you deploy
3.1 Release files
Download the files from
www.al-khandaq.com/download. Each
version's files are also listed under
https://downloads.al-khandaq.com/releases/<ver>/ (for example
https://downloads.al-khandaq.com/releases/1.0.0/).
| File | Contents |
|---|---|
AlKhandaq-<ver>-x64.msi |
Windows installer (WiX). Use this for managed deployment. |
AlKhandaq-<ver>-x64-setup.exe |
Inno Setup alternative to the MSI, where published |
AlKhandaq-<ver>-admx.zip |
Group Policy template (ADMX, with English, Dari and Pashto ADML) |
AlKhandaq-<ver>-windows-x64.cdx.json |
CycloneDX 1.5 SBOM for the Windows package |
SHA256SUMS-windows.txt |
SHA-256 of the installer and the SBOM |
SHA256SUMS-*.txt.sig |
Ed25519 signature of a sums file |
khandaq_<ver>-1_amd64.deb |
Agent, CLI, tray notifier |
khandaq-desktop_<ver>-1_amd64.deb |
Desktop app; depends on the exact same khandaq version |
khandaq-<ver>-1.x86_64.rpm, khandaq-desktop-...rpm |
Fedora/RHEL packages (untested) |
khandaq-<ver>-linux-x86_64.cdx.json |
CycloneDX SBOM for the Linux packages |
SHA256SUMS-linux.txt |
SHA-256 of the packages, SBOM and install.sh |
install.sh |
Installs the .deb files next to it |
Al-Khandaq-<ver>.pkg |
macOS installer: app, agent and CLI. Developer ID signed and notarised. |
Al-Khandaq-Agent-<ver>.pkg |
macOS agent and CLI only, without the app, for managed Macs |
SHA256SUMS-macos.txt, SHA256SUMS-macos-agent.txt |
SHA-256 of the macOS packages |
3.2 Verify checksums
Windows (PowerShell):
Get-FileHash -Algorithm SHA256 .\AlKhandaq-1.0.0-x64.msi
Get-Content .\SHA256SUMS-windows.txt
The two values must match (the file lists lowercase hex).
Linux:
sha256sum -c --ignore-missing SHA256SUMS-linux.txt
macOS:
shasum -a 256 -c SHA256SUMS-macos.txt
install.sh checks each .deb against SHA256SUMS-linux.txt itself and
stops on a mismatch or an unlisted file. It only warns if the sums file is
missing.
When a release ships SHA256SUMS-*.txt.sig, check the sums file's origin
first, with the published key
release-files.pub:
khandaq-licence verify-file --keys release-files.pub SHA256SUMS-windows.txt
It prints OK: ... signed by key <id> or exits 1. Without a .sig the sums
only detect a damaged copy. The download page shows the same steps.
3.3 SBOM
The SBOM merges the components of everything that ships (agent, CLI, tray,
app) under one Al-Khandaq application component, without build-only
dependencies. Local build paths are rewritten to file:///build/.... Import
it into your inventory or vulnerability tool next to the installer.
3.4 Code signing
| Platform | Signing in 1.0 |
|---|---|
| macOS | The app, the agent and both .pkg installers are signed with an Apple Developer ID and notarised by Apple. Gatekeeper opens them without a warning. |
| Windows | The MSI and its programs are not code-signed yet; Authenticode signing is on its way. |
| Linux | .deb and .rpm packages are not GPG-signed. |
Until the Windows packages are signed:
- Windows SmartScreen shows "Windows protected your PC ... Unknown publisher" for a downloaded MSI or exe ("More info > Run anyway").
- Smart App Control blocks unsigned apps. WDAC or AppLocker publisher rules and some EDR products block or flag them; allow the installer by hash.
- You cannot tell a patched copy from the real one by signature. Compare SHA-256 values with the signed sums file (section 3.2).
Separately, every self-update and content bundle is checked against Al-Khandaq's own signing keys before it is installed (section 7.3).
4. Installing on Windows
4.1 What the MSI does
| Item | Detail |
|---|---|
| Install folder | C:\Program Files\Al-Khandaq\, fixed (no folder choice): khandaq-agent.exe, khandaq-app.exe, khandaq-tray.exe, LICENSE.txt, agent.toml, and bin\khandaq.exe. bin\ is appended to the system PATH. |
| Service | Khandaq, LocalSystem, automatic start, command khandaq-agent.exe service run. Restarts 60 s after each failure; the failure count resets after one day. Service SID type unrestricted. Started at the end of install. |
| Data folder | Created by the agent, never by setup. Before the service starts, setup runs khandaq-agent.exe service prepare-data as SYSTEM (custom action PrepareDataFolder). See section 9. |
| Config | agent.toml (commented template) next to the agent, owner Administrators, SYSTEM and Administrators only. Never overwritten by upgrades, never removed by uninstall. |
| Tray | HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run, value KhandaqTray: starts for every user at logon. |
| Start menu | "Al-Khandaq" opens the app. |
| Add/Remove Programs | Entry under HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Al-Khandaq, publisher Akhund Baba. The built-in MSI entry is hidden (ARPSYSTEMCOMPONENT) so the uninstall can show the keep-or-delete-data page. MSI product-code detection (Intune, Win32_Product) still works. |
| UpgradeCode | B6535E8F-15E8-437E-9663-9361F2004ECE (never changes) |
4.2 MSI public properties
All are optional and marked Secure.
| Property | Effect |
|---|---|
LICENCE_KEY |
Writes [licence] / key="..." to agent.toml. Hidden: not written to the MSI log. The registry records only LicenceKeyProvided=1 under HKLM\SOFTWARE\Akhund Baba\Al-Khandaq. An upgrade with a new key replaces the old one; one without it keeps the old one. |
FLEET_URL |
https URL of a fleet server; writes [fleet] / server_url. Also stored as FleetUrl in the registry. Nothing uses it yet (section 14). |
ENROLL_TOKEN |
Written as enroll_token only together with FLEET_URL. Hidden. The registry records only FleetTokenProvided=1. |
FLEET_FINGERPRINT |
Written as fingerprint only together with FLEET_URL. |
PURGE_DATA=1 |
On uninstall, also delete everything Al-Khandaq keeps on the computer except the licence ledger: %ProgramData%\Al-Khandaq (history, audit log, logs, quarantine), agent.toml, HKLM\SOFTWARE\Akhund Baba\Al-Khandaq and the uninstalling user's %LOCALAPPDATA% folders (section 19.1). Default: keep. Never applies to the removal of the old version during an upgrade. |
WIXUI_EXITDIALOGOPTIONALCHECKBOX=1 |
Pre-ticks "Open Al-Khandaq" on the Finish page. Has no effect with /qn. |
Fleet values are written once and kept across upgrades. To change an existing
fleet URL, edit agent.toml.
4.3 Silent install
msiexec /i AlKhandaq-1.0.0-x64.msi /qn /l*v C:\Windows\Temp\khandaq-install.log
msiexec /i AlKhandaq-1.0.0-x64.msi /qn LICENCE_KEY=KQL1....
Exit codes are the standard Windows Installer ones: 0 success, 3010 success
with restart needed (not expected), 1603 fatal error (read the /l*v log).
Installing an older version over a newer one is refused with "A newer version
of Al-Khandaq is already installed." A failed prepare-data step fails the
install and rolls it back (section 18.2).
The MSI deploys as an Intune line-of-business app (device context) or through
GPO software installation (with a transform .mst for properties). A
transform holds property values, including a licence key, in clear text;
restrict the share.
4.3a Features and silent-install matrix
The MSI has three features; the Inno setup has the same as components.
| Feature (MSI) | Component (Inno) | Contains | Needs |
|---|---|---|---|
Agent |
agent |
Service, khandaq CLI, agent.toml, Event Log source. Always installed. |
|
Tray |
tray |
Tray icon and notifications, started for every user at logon | a desktop session |
App |
app |
Desktop app, Start menu shortcut, alkhandaq: links |
Microsoft Edge WebView2 |
Servers, Server Core and RDS / Citrix hosts usually want the agent only: no WebView2, and no tray process in every user session. The agent then reports through the CLI, the Event Log, syslog and the webhook (section 13).
| Goal | MSI | Inno setup |
|---|---|---|
| Everything (default) | msiexec /i AlKhandaq.msi /qn |
setup.exe /VERYSILENT /SUPPRESSMSGBOXES /NORESTART |
| Agent only (servers, RDS) | msiexec /i AlKhandaq.msi /qn ADDLOCAL=Agent |
setup.exe /VERYSILENT /SUPPRESSMSGBOXES /NORESTART /TYPE=agent |
| Agent and tray, no app | msiexec /i AlKhandaq.msi /qn ADDLOCAL=Agent,Tray |
... /COMPONENTS="agent,tray" |
| Add the app to an agent-only machine | msiexec /i AlKhandaq.msi /qn ADDLOCAL=App |
... /COMPONENTS="agent,tray,app" |
| Remove tray and app, keep the agent | msiexec /i AlKhandaq.msi /qn REMOVE=Tray,App |
... /TYPE=agent |
| Agent only with a licence and SIEM settings | msiexec /i AlKhandaq.msi /qn ADDLOCAL=Agent LICENCE_KEY=KQL1.... then policy (section 10.4) |
... /TYPE=agent /LICENCE_KEY=KQL1.... |
| Upgrade, keeping the installed features | msiexec /i AlKhandaq-new.msi /qn |
setup.exe /VERYSILENT ... (remembers the choice) |
| Uninstall, keep data | msiexec /x AlKhandaq.msi /qn |
unins000.exe /VERYSILENT |
| Uninstall and delete data | msiexec /x AlKhandaq.msi /qn PURGE_DATA=1 |
unins000.exe /VERYSILENT /PURGEDATA=1 |
Feature and component names are fixed; deployment scripts can rely on them.
ADDLOCAL lists what to have installed after this run in addition to what is
already there, so ADDLOCAL=App on an agent-only machine adds the app and
keeps the agent. With ADDLOCAL=Agent the setup does not start a tray, and
the Finish page never offers to open the app.
4.4 Inno Setup fallback
Use the MSI for anything managed. The Inno setup.exe behaves the same, with
these differences:
AlKhandaq-1.0.0-x64-setup.exe /VERYSILENT /SUPPRESSMSGBOXES /NORESTART /LICENCE_KEY=KQL1....
"C:\Program Files\Al-Khandaq\unins000.exe" /VERYSILENT /PURGEDATA=1
/LICENCE_KEY=is used only whenagent.tomlhas no[licence]section yet. Renew with the app orkhandaq licence install./FLEET_URL=writes a[fleet]section only whenagent.tomlhas none yet; otherwise it is ignored (a second section would make the file invalid, section 10.1). To change fleet settings later, edit the file./FLEET_URL=,/ENROLL_TOKEN=and/FLEET_FINGERPRINT=are all ignored if any of them contains a quote, backslash or control character; setup logs this.- If
prepare-datafails, setup shows the agent's message, installs nothing, and starts the old service again. - The purge switch is
/PURGEDATA=1. An interactive uninstall asks before removing anything; the default answer is No. It deletes the same as the MSI'sPURGE_DATA=1.
5. Installing on Ubuntu (and Fedora/RHEL)
5.1 Install
sudo ./install.sh # khandaq, plus khandaq-desktop on a desktop
sudo ./install.sh --server # khandaq only
sudo apt install ./khandaq_1.0.0-1_amd64.deb ./khandaq-desktop_1.0.0-1_amd64.deb
install.sh must run as root and needs apt. It picks the newest
khandaq_*.deb next to it, adds khandaq-desktop when a display manager is
enabled or XDG_CURRENT_DESKTOP is set (unless --server), verifies
checksums, and runs apt-get install -y. It never downloads Al-Khandaq
itself; apt fetches only Ubuntu's dependency packages. Run it with sudo,
not from a root shell, so the package can see who you are.
For unattended installs use apt-get install -y ./khandaq_<ver>-1_amd64.deb
(and the desktop package where wanted).
5.2 What the khandaq package does
| Item | Detail |
|---|---|
| Files | /usr/bin/khandaq-agent, /usr/bin/khandaq, /usr/bin/khandaq-tray; /usr/lib/systemd/system/khandaq-agent.service; /etc/khandaq/agent.toml (conffile, mode 0600); /etc/xdg/autostart/khandaq-tray.desktop (conffile); icons |
| Groups | Creates system groups khandaq (may read status) and khandaq-admin (may also approve fixes) |
| Sudo user | Adds $SUDO_USER to both groups and says so. Without SUDO_USER (root shell, automation) it prints the usermod command instead. Group changes need a new login. |
| Service | First install: systemctl enable --now khandaq-agent.service. Upgrade: try-restart, so an administrator's systemctl disable stays. Without systemd it prints how to run the agent by hand. |
| Override warning | If /etc/systemd/system/khandaq-agent.service exists (from khandaq-agent service install), postinst warns that it overrides the packaged unit. |
khandaq-desktop adds /usr/bin/khandaq-app, the al-khandaq.desktop
launcher and the polkit policy af.akhundbaba.khandaq.policy (when present at
build time).
Grant access to other users:
sudo usermod -aG khandaq USER # status, notifications, app
sudo usermod -aG khandaq,khandaq-admin USER # also approve fixes
5.3 The systemd unit
The unit runs the agent as root with Type=simple, Restart=on-failure,
RestartSec=60 and TimeoutStopSec=90. systemd creates
/var/lib/khandaq, /var/log/khandaq and /var/cache/khandaq (mode 0750),
/run/khandaq (0755) and /etc/khandaq (0755), with UMask=0027.
Hardening: NoNewPrivileges, ProtectSystem=strict, ProtectKernelTunables,
ProtectControlGroups, ProtectClock, ProtectHostname, RestrictRealtime,
RestrictNamespaces=net ipc (for the scan worker), RestrictSUIDSGID,
LockPersonality, SystemCallArchitectures=native,
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6 AF_NETLINK.
The agent's file system is read-only except:
| Writable | Why |
|---|---|
/var/lib/khandaq, /var/lib/khandaq-licence, /var/log/khandaq, /var/cache/khandaq, /run/khandaq, /etc/khandaq |
Its own state (database, audit key, quarantine), the licence ledger's system copy, logs, feed cache, IPC socket and agent.toml (the *Directory= settings) |
/etc/sysctl.d |
The Linux hardening profile's 60-khandaq-*.conf drop-ins |
/home, /root, /tmp, /var/tmp, /srv, /opt, /media, /mnt, /run/media |
Quarantine and restore: removing a flagged file needs write access to its folder, and these are where downloads and droppers land |
Malware found elsewhere (/usr, /etc) is reported and its processes are
stopped, but the file stays (quarantine fails with "read-only file
system"). Approved package installs and removals (apt-get, dpkg,
apt-mark, flatpak) do not run inside the unit: with
KHANDAQ_UNIT_SANDBOX=1 (set by the unit) the agent hands them to PID 1 as
systemd-run --wait --pipe transient units named khandaq-change-*, which
run with an ordinary root environment. PrivateTmp, ProtectHome,
PrivateDevices, ProtectKernelModules, ProtectKernelLogs,
MemoryDenyWriteExecute and a capability bounding set are left out on
purpose; the unit file explains each.
5.4 RPM
The .rpm does the same in %post (groupadd -r, $SUDO_USER,
systemctl enable --now on first install). RPM has no purge: data stays after
dnf remove.
5a. Installing on macOS
5a.1 Install
Open Al-Khandaq-<ver>.pkg and follow the installer, or from a terminal:
sudo installer -pkg Al-Khandaq-1.0.0.pkg -target /
For managed Macs, deploy Al-Khandaq-Agent-<ver>.pkg through your MDM. It
installs the agent and the CLI without the app or its login item, like the
MSI's ADDLOCAL=Agent. Both packages are signed and notarised, so an MDM can
install them silently. To upgrade, install the newer package over the old one;
agent.toml and the data folder are kept.
5a.2 What the package does
| Item | Detail |
|---|---|
| App | /Applications/Al-Khandaq.app (full package only): window, menu-bar icon and alerts |
| Agent | /usr/local/libexec/al-khandaq/ (khandaq-agent, khandaq-scan-worker, uninstall.sh), a folder only root can change |
| CLI | /usr/local/bin/khandaq, and a khandaq-agent link to the agent |
| Service | launchd daemon /Library/LaunchDaemons/org.alkhandaq.agent.plist (label org.alkhandaq.agent), runs as root from boot. Check it with sudo launchctl print system/org.alkhandaq.agent. |
| Login item | /Library/LaunchAgents/org.alkhandaq.app.plist starts the app at every login (full package only). The installer also starts it at once for the person signed in. |
| Config | /etc/khandaq/agent.toml, written only when none exists. It is mode 0644; if you add secrets (webhook, licence key), run sudo chmod 600 /etc/khandaq/agent.toml. |
| Groups | Creates khandaq (may read status) and khandaq-admin (may also approve fixes). The person signed in at install joins khandaq; if they are a macOS administrator, also khandaq-admin. |
| Data | /Library/Application Support/Al-Khandaq (database, state, quarantine, cache); logs in /Library/Logs/Al-Khandaq |
| Socket | /private/var/run/khandaq/khandaq.sock |
Grant access to other users:
sudo dseditgroup -o edit -a USER -t user khandaq # status, notifications, app
sudo dseditgroup -o edit -a USER -t user khandaq-admin # also approve fixes
Restart the agent with sudo khandaq-agent service stop and then
sudo khandaq-agent service start.
5a.3 Full Disk Access
Without Full Disk Access, macOS hides Desktop, Downloads and Documents (and
the Time Machine backup list) from the agent, so malware scans cannot read
them. The check os.privacy.full_disk_access warns until it is granted.
- By hand: System Settings > Privacy & Security > Full Disk Access, add
/usr/local/libexec/al-khandaq/khandaq-agent(press Cmd-Shift-G to type the path), then restart the agent (section 5a.2). - With an MDM: deploy a Privacy Preferences Policy Control (PPPC) payload
that allows
SystemPolicyAllFilesfor/usr/local/libexec/al-khandaq/khandaq-agent. Read the code requirement for the payload withcodesign -dr - /usr/local/libexec/al-khandaq/khandaq-agent.
5a.4 Policy on macOS
Organisation policy (section 10.4) works as on Linux, with files in
/etc/khandaq/policy.d/. An MDM can also deliver it as a configuration
profile with payload type org.alkhandaq.agent: macOS writes the keys to
/Library/Managed Preferences/org.alkhandaq.agent.plist, and the agent reads
them with the same sections and keys as the policy files. The profile wins key
by key over the files. An example profile is available from
info@akhundbaba.af.
To remove Al-Khandaq from a Mac, see section 19.3.
6. Licence at install time
Personal and home use needs no key: skip this section. Organisations that have an organisation key (section 11; ask at info@akhundbaba.af) can install it with the product:
| Platform | How |
|---|---|
| MSI | LICENCE_KEY=KQL1.... |
| Inno | /LICENCE_KEY=KQL1.... (first install only) |
| Linux | After the package: sudo khandaq licence install example.lic, or add [licence] to /etc/khandaq/agent.toml and sudo systemctl restart khandaq-agent |
| macOS | After the package: sudo khandaq licence install example.lic, or add [licence] to /etc/khandaq/agent.toml and restart the agent (section 5a.2) |
| Any, later | khandaq licence install <file or key> from an elevated prompt or as root / khandaq-admin; or the app, Settings > Licence |
Prefer passing a .lic file to khandaq licence install over the key on the
command line, which can end up in shell history.
7. Clean install and upgrade
7.1 Upgrading 1.x
- MSI: a higher
major.minor.patchremoves the old version (stopping and deleting the service), installs the new one and starts the service.agent.tomland the data folder are kept. Same-version reinstalls are allowed. - Inno: stops the service, prepares the data folder, replaces files, starts the service.
- apt:
apt install ./khandaq_<new>.deb; postinst restarts the agent only if it was running. - macOS: install the newer
.pkgover the old one.agent.tomland the data folder are kept.
A kept data folder is reused only if it passes the ownership rules in
section 9. On Windows that means its .khandaq-install-id marker must match
the id in the registry.
7.2 Pre-release builds
Pre-release (pilot) builds: uninstall them and do a clean install of 1.0.
7.3 Self-update
Al-Khandaq can update itself from its signed release channel. Settings live
in [update] in agent.toml; every key is optional:
[update]
enabled = true # false: never self-update (content still updates)
mode = "notify" # "notify", "security" or "auto"; see below
channel = "stable"
url = "https://downloads.al-khandaq.com/al-khandaq"
mirror = '\\fileserver\khandaq-mirror' # optional: https, http, folder or UNC path
content = true # the daily signed content bundle
check_hours = 6 # how often both channels are checked (1-168)
health_timeout_secs = 600 # the new version must heartbeat within this (60-3600), or it is rolled back
publisher = "Akhund Baba" # Windows only: required Authenticode signer (subject CN)
| Key | Default | Notes |
|---|---|---|
enabled |
true |
false: never self-update. The content bundle still updates while content = true. |
mode |
unset | "notify": show the update and ask. "security": security releases install in the maintenance window, others ask. "auto": every release installs in the window. Unset: "security" at home, "notify" when the computer is managed (Group Policy, Intune, policy.d, or a [fleet] section). |
channel |
"stable" |
Letters, digits and dashes |
url |
"https://downloads.al-khandaq.com/al-khandaq" |
The release and content channel. Must be https://. |
mirror |
none | A local mirror for both channels: https://, http://, or a folder or UNC path with the same layout. Everything is still signature-checked. |
content |
true |
The daily signed content bundle (section 12.1) |
check_hours |
6 |
1 to 168 |
health_timeout_secs |
600 |
60 to 3600 |
publisher |
none | Windows only: an extra check on the Authenticode signer's subject CN. The certificate itself is pinned in the build. |
Early macOS 1.0.0 installs. Macs that installed one of the first 1.0.0
packages have a retired update address built in, so they do not find updates.
Add the current address to /etc/khandaq/agent.toml and restart the agent
(section 5a.2). If the file already has an [update] section, add the url
line to it rather than a second section. The setting is harmless on any other
machine.
[update]
url = "https://downloads.al-khandaq.com/al-khandaq"
- The "Update Al-Khandaq" card (Settings) shows the available version and
its notes, with Install now and Install tonight (administrators).
khandaq self-update [status|check|install [--tonight]|cancel]does the same from a shell. - Installs wait for the maintenance window and honour the metered and battery rules of the update settings; "Install now" does not wait.
- A new version that does not heartbeat within
health_timeout_secsis replaced by the previous package automatically. - Every step is in the audit log (
agent.update.*) and History. - Managed by Intune, GPO, an MDM, WSUS-like tooling or an apt repository: set
enabled = falseand keep deploying packages as before.
8. File and data locations
macOS locations are listed in section 5a.2 and section 19.3.
8.1 Windows
| What | Path |
|---|---|
| Programs | C:\Program Files\Al-Khandaq\ (khandaq-agent.exe, khandaq-app.exe, khandaq-tray.exe, LICENSE.txt); C:\Program Files\Al-Khandaq\bin\khandaq.exe (on PATH) |
| Config | C:\Program Files\Al-Khandaq\agent.toml |
| Data root | %ProgramData%\Al-Khandaq (fallback C:\ProgramData\Al-Khandaq) |
| Ownership marker | %ProgramData%\Al-Khandaq\.khandaq-install-id |
| Database | %ProgramData%\Al-Khandaq\khandaq.db (history, events, audit log, acceptances, drift baselines, profile journal) |
| Latest report | %ProgramData%\Al-Khandaq\state\latest.json |
| Installed licence | %ProgramData%\Al-Khandaq\state\licence.key |
| Licence ledger, data copy | %ProgramData%\Al-Khandaq\state\licence-ledger.json |
| Logs | %ProgramData%\Al-Khandaq\logs\agent.YYYY-MM-DD.log |
| Feed cache | %ProgramData%\Al-Khandaq\cache |
| Quarantine | %ProgramData%\Al-Khandaq\quarantine |
| Malware-scan settings | %ProgramData%\Al-Khandaq\av.json (optional) |
| Rule pack | %ProgramData%\Al-Khandaq\rules\ (yara-rules-core.yar, manifest.json, attribution.json) |
| Scan logs | %ProgramData%\Al-Khandaq\scans\ (<time>-<kind>.jsonl per on-demand scan, detections.json) |
| Moved-aside folders | %ProgramData%\Al-Khandaq.untrusted-<random> |
| Install id | Registry key HKLM\SOFTWARE\Akhund Baba\Al-Khandaq\InstallId (default value), owner SYSTEM, SYSTEM-only DACL |
| Installer records | HKLM\SOFTWARE\Akhund Baba\Al-Khandaq: FleetUrl, FleetTokenProvided, FleetFingerprint, LicenceKeyProvided |
| Licence ledger, system copy | HKLM\SOFTWARE\Akhund Baba\Al-Khandaq Licence, value Ledger |
| Start refusals | Application event log, source Khandaq |
| Per user | %LOCALAPPDATA%\Al-Khandaq\ (tray-state.json, last-report.html) |
8.2 Linux
| What | Path |
|---|---|
| Programs | /usr/bin/khandaq-agent, /usr/bin/khandaq, /usr/bin/khandaq-tray, /usr/bin/khandaq-app (desktop package) |
| Unit | /usr/lib/systemd/system/khandaq-agent.service (package); /etc/systemd/system/khandaq-agent.service if written by khandaq-agent service install (overrides the packaged one) |
| Config | /etc/khandaq/agent.toml (root, 0600, conffile) |
| State root | /var/lib/khandaq (khandaq.db, state/latest.json, state/licence.key, state/licence-ledger.json, quarantine/, av.json, rules/, scans/) |
| Logs | /var/log/khandaq/agent.YYYY-MM-DD.log, and the journal (journalctl -u khandaq-agent) |
| Feed cache | /var/cache/khandaq |
| Socket | /run/khandaq/khandaq.sock |
| Moved-aside folders | /var/lib/khandaq.untrusted-<random> (likewise for the log and cache folders) |
| Licence ledger, system copy | /var/lib/khandaq-licence/ledger.json |
| Hardening profile files | /etc/sysctl.d/60-khandaq-<setting>.conf |
| polkit policy | /usr/share/polkit-1/actions/af.akhundbaba.khandaq.policy |
| Tray autostart | /etc/xdg/autostart/khandaq-tray.desktop; per user $XDG_CONFIG_HOME/autostart/khandaq-tray.desktop if the user ran khandaq-tray --install-autostart |
| Per user | $XDG_STATE_HOME/khandaq (default ~/.local/state/khandaq): logs/, tray-state.json, last-report.html, notifier.lock |
8.3 Permissions
| Object | Windows | Linux |
|---|---|---|
| Data folder and everything in it | Owner SYSTEM (Administrators when not running as SYSTEM); protected DACL: SYSTEM and Administrators full control; no access for users | root:root; directories 0750; files without group-write or other access |
agent.toml |
Owner Administrators; SYSTEM and Administrators full control only | root, 0600 |
| IPC endpoint | Pipe DACL: SYSTEM, Administrators and owner full; interactive users read/write data only | Socket 0660 root:khandaq in /run/khandaq (0755, root) |
Users need nothing on disk. The tray and app get everything through IPC.
9. Data folder ownership rules
The service writes to its data folder as SYSTEM or root and trusts what it
finds there later. Ordinary users can create folders in %ProgramData%, so
the agent never trusts a folder it did not create. Before its first write or
log line, an elevated agent (the service, or service prepare-data):
Checks the parents. It refuses to run if a parent folder is a link or reparse point, or (Linux) is not owned by root, or is world-writable without the sticky bit.
Settles the folder name. It keeps the existing folder only if it can prove it is its own:
- Windows: a real folder (not a link) owned by SYSTEM or Administrators,
holding the
.khandaq-install-idmarker (a plain file with one link, owned by SYSTEM or Administrators) whose content matches the 256-bit id in the SYSTEM-only registry key...\Al-Khandaq\InstallId. - Linux: a real directory owned by root that neither group nor others can write.
Anything else (a link, a file, someone else's folder, an administrators' folder without a matching marker) is renamed to
<folder>.untrusted-<random>, untouched. A fresh folder is created with the locked-down permissions already in place, then marked. If something reappears at the name between steps, the agent looks again, up to 8 times, then refuses ("... kept being re-created by someone else while it was secured; refusing to use it").- Windows: a real folder (not a link) owned by SYSTEM or Administrators,
holding the
Cleans the tree. It moves aside every link, every entry owned by anyone other than SYSTEM/Administrators (root), and every file with more than one name (hard link) into one more
.untrusted-<random>folder.Resets permissions on what is left (section 8.3).
Creates
state,logs,cacheandquarantinerelative to the verified folder handle and writes logs andlatest.jsonthrough those handles, never by path.
If the folder is held open. When a process has the folder (or something inside it) open so that it cannot be renamed, the agent does not take it over. It refuses to start:
Data folder is held open by another process (PID 1234): C:\ProgramData\Al-Khandaq
was not created by this agent and cannot be moved aside while it is open (...).
Refusing to start rather than use it; end that process and start the agent again.
The PID can be "PID unknown". The message goes to the Application event log
(source Khandaq) on Windows, to the journal on Linux, and to the MSI log or
the Inno message box during setup. See section 18.2.
Moved-aside folders are never deleted automatically, and PURGE_DATA
does not remove them. They may contain content planted by another user. Look
at them as an administrator, then delete them.
Files you add. An administrator may create av.json in the data folder.
On Windows, make sure Administrators own it, or the next agent start moves it
aside as "owned by someone else":
icacls "%ProgramData%\Al-Khandaq\av.json" /setowner *S-1-5-32-544
Do not hard-link files into the data folder.
10. Configuration
10.1 agent.toml
| Platform | Path |
|---|---|
| Windows | agent.toml next to khandaq-agent.exe, normally C:\Program Files\Al-Khandaq\agent.toml |
| Linux and macOS | /etc/khandaq/agent.toml |
khandaq-agent run --console --config FILE overrides the path for console
runs only.
Rules:
- Every section is optional. A missing or empty file means defaults.
- The agent reads the file once, at start. Restart after editing:
Restart-Service Khandaq,sudo systemctl restart khandaq-agent, or on macOSsudo khandaq-agent service stopthensudo khandaq-agent service start. - Unknown sections and unknown keys are errors. An invalid or unreadable
file is ignored as a whole: no webhook, no proxy, no licence from this
file. The agent logs "agent.toml is not used; running on defaults" and
reports the finding
agent.config.invalid(Fail, with the reason in itsproblemevidence) until the file is fixed and the service restarted. It shows on the Overview, inkhandaq reportand in webhook alerts. - The
[update]section (self-update and the content channel) is described in section 7.3. - The file can hold secrets. Keep it readable by administrators only.
There are eight sections. Organisation policy (section 10.4) is laid over this file key by key.
[webhook] (off unless url is set)
| Key | Type | Default | Notes |
|---|---|---|---|
url |
string | none (required in the section) | Must start with https://. http:// only with allow_http = true (the Authorization header and alerts then travel in clear text). |
authorization |
string | none | Sent verbatim as the Authorization header |
timeout_secs |
integer | 10 |
Clamped to 1–120 |
secret |
string | none | HMAC-SHA256 key, at least 16 characters: every POST is signed (X-Khandaq-Signature, section 13) |
allow_http |
bool | false |
Accept a plain http:// URL (test networks only) |
[syslog] (off unless server is set)
| Key | Type | Default | Notes |
|---|---|---|---|
server |
string | none (required in the section) | host, host:port or [v6]:port |
transport |
string | udp |
udp (port 514), tcp (514) or tls (6514) |
facility |
integer | 13 |
RFC 5424 facility 0–23 |
fingerprint |
string | none | TLS only: SHA-256 (hex) of a self-signed collector certificate to trust |
[event_log] (Windows)
| Key | Type | Default | Notes |
|---|---|---|---|
enabled |
bool | true |
Write security events to the Al-Khandaq event log |
[licence]
| Key | Type | Default | Notes |
|---|---|---|---|
key |
string | none (required in the section) | A licence key KQL1..... Checked at agent start. |
[fleet] (accepted and validated; not used in 1.0)
| Key | Type | Default | Notes |
|---|---|---|---|
server_url |
string | none (required in the section) | Must start with https:// |
enroll_token |
string | none | Enrollment token kqe_... |
fingerprint |
string | none | SHA-256 (hex) of a self-signed server certificate to pin |
[network]
| Key | Type | Default | Notes |
|---|---|---|---|
proxy |
string | none | http://host:port, https://..., socks5://... (names resolved locally), socks5h://... (names resolved by the proxy) or socks4://...; user:password@ allowed. Every HTTP request of the agent (webhook, KEV feed, ClamAV and rule downloads, fleet) goes through it. Feed downloads are HTTPS only: a redirect to http:// is refused. |
no_proxy |
string | none | Comma-separated hosts or .domain suffixes that bypass the proxy |
The agent exports these as HTTPS_PROXY, HTTP_PROXY and NO_PROXY to its
own process at start, which every HTTP client in it reads, and so do the
tools it runs (winget, PowerShell). Without proxy, those variables from the
service's own environment apply.
[retention]
| Key | Default | Minimum | What |
|---|---|---|---|
history_days |
90 |
1 | Scan history (runs, findings) |
event_days |
30 |
1 | Monitor events |
event_rows |
10000 |
100 | At most this many monitor events |
audit_days |
0 |
0 | Action audit log; 0 keeps it for ever |
db_max_mb |
512 |
16 | khandaq.db ceiling (section 15) |
log_days |
14 |
1 | Daily log files kept |
log_file_mb |
50 |
1 | One day's log stops growing at this size; a line says so |
[schedule]
| Key | Default | What |
|---|---|---|
boot_delay_secs |
5–10 min, random | After a boot, the first scan waits this long from boot (0: at once, at most 3600). An agent started later (install, upgrade, restart) scans at once. Scan now always runs at once. |
low_priority |
true |
Scans run in background mode with EcoQoS on Windows (not while a fix or update runs), and at nice 10 with idle I/O priority on Linux. |
defer_on_battery |
true |
On battery, the heavy checks (av.scan, sw.inventory, sw.vuln, sw.updates, sw.winget, os.update) wait for mains power, retrying every 30 minutes, at most a day after their last run. Manual scans are never deferred. |
Check intervals use the wall clock: after a suspend, overdue checks run on waking, and a clock set back moves every due time back with it.
[security]
| Key | Default | What |
|---|---|---|
scan_worker |
"require" |
Where scanned files are parsed: "require" a sandboxed khandaq-scan-worker process only (when none can start, files are reported as not scanned, never parsed in the agent, and the High finding av.worker.status says "Scanning is paused"); "prefer" the worker and fall back to the agent (logged, a warning finding) when none starts; "off" in the agent. See section 21.2. |
Example:
[webhook]
url = "https://hooks.example.com/khandaq"
authorization = "Bearer change-me"
timeout_secs = 10
[licence]
key = "KQL1...."
[network]
proxy = "http://proxy.corp.example:3128"
no_proxy = "localhost,.corp.example"
[retention]
audit_days = 730
db_max_mb = 256
[privacy]
share_remote_party = false # default
# nvd_lookups = false # unset: the choice made in the app; set: it locks that choice
# redact_identifiers = true # unset: the choice made in the app; set: it locks that choice
[privacy] nvd_lookups: sw.vuln.apps sends the names and versions of
installed programs to NVD, and the CVE ids found to FIRST EPSS, only when this
is true or someone allowed it in the app (first-run notice or Settings,
Privacy). Until then it uses the signed content bundle only. A bundle younger
than 14 days is used even when lookups are allowed (NVD is then not asked at
all; EPSS is asked only for CVEs the bundle's CSV lacks). An older bundle is
still used, and the scan summary warns "Vulnerability data is N days old" with
how to get new data. With no bundle at all it reports Error, "This check is
off", rather than a clean result. A one-off khandaq scan without the agent never sends the list.
[privacy] redact_identifiers: SIEM and syslog events, Event Log entries,
webhook alerts, evidence reports and SARIF/CSV exports lose user-profile paths,
account names and the host name (<user>, <host>). khandaq report --redact
does the same for one export.
[privacy] share_remote_party: an incoming TeamViewer/AnyDesk session is
shown to the person at this computer with who connected (name, ID) and which
local account took it. By default none of that leaves the machine: SIEM and
syslog events, webhook alerts, evidence reports and SARIF/CSV exports say "N
incoming sessions in the last 30 days, the last on true to
include the remote party and the account in those.
Standard users can run khandaq report --format html|pdf|csv (unsigned): they
get a limited report of their own and system-wide items, with approver names and
the licensee left out. --sign and the full report need an administrator.
10.2 Malware-scan settings: av.json
Malware-scan settings are not in agent.toml. They live in av.json in the
data folder (%ProgramData%\Al-Khandaq\av.json, /var/lib/khandaq/av.json, or
on macOS /Library/Application Support/Al-Khandaq/av.json).
The file is optional; a missing or invalid file means defaults (an invalid one
is logged). Keys may be given individually.
| Key | Default | Meaning |
|---|---|---|
max_file_size_mb |
64 |
Larger files are skipped and counted |
realtime_max_mb_per_sec |
32 |
The file watch reads at most this much file content a second; 0 = no limit. A burst is worked off later, not dropped |
realtime_max_files_per_sec |
200 |
The file watch scans at most this many files a second; 0 = no limit |
realtime_rescan_cooldown_secs |
600 |
A file that keeps changing is scanned again at most this often (every 30 s for programs and scripts); its last version is always scanned. 0 = every change |
schedule.quiet_hours |
{"start": 23, "end": 6} |
Local hours when a scheduled scan does not start, even an overdue one. May cross midnight; null = none |
schedule.defer_fullscreen |
true |
A scheduled scan waits while a signed-in person runs a full-screen app or game (reported by the tray), for at most 7 days past its interval |
scan_timeout_secs |
10 |
YARA-X time limit per file (minimum 1) |
block_exec |
false |
Linux, root only: deny execution of files matching Critical rules through fanotify. Off by default: a blocked file cannot run at all, so test it on representative machines first. |
block_exec_budget_ms |
250 |
Time budget per block decision, clamped to 20–5000; past it the file is allowed |
allow_copyleft_rules |
false |
Load GPL/AGPL/LGPL and share-alike (CC BY-SA) rule sets from the downloaded pack. Malpedia is CC BY-SA from YARA Forge 20261108 |
allow_noncommercial_rules |
false |
Load non-commercial-only rule sets (for example CC BY-NC). Keep off: organisational use counts as commercial. |
allow_unspecified_rules |
false |
Load rule sets with no licence or a custom one. Off, only licences known to be permissive are loaded. |
auto_install_rules |
true |
When no content bundle or rule pack is present and content updates are on, the agent downloads the pinned YARA Forge core pack from GitHub at its next update check. It verifies the SHA-256 and sends nothing about the computer. |
extra_watch_folders |
[] |
Folders the file watch covers in addition to the quick-scan folders |
Example:
{ "max_file_size_mb": 128, "extra_watch_folders": ["D:\\Shares\\Incoming"] }
On Windows, real-time scanning is post-write scanning only. Microsoft
Defender is what blocks files. Only Linux fanotify with block_exec blocks
before a file runs.
10.3 What is not configurable
- Schedules. Each check has an interval compiled into the product
(minimum 60 s); organisation policy can replace it per check prefix
(
checks.intervals, section 10.4) or turn checks off (checks.disabled). The agent runs every check at start, then each check again after its interval. Checks due within 30 s of each other run in one batch. "Scan now" makes every check due; repeat requests within 30 s are ignored. - Logging level: environment variable
KHANDAQ_LOG(same syntax asRUST_LOG, defaultinfo). For the Windows service set it in theEnvironmentmulti-string value ofHKLM\SYSTEM\CurrentControlSet\Services\Khandaq; on Linux in a systemd drop-in (systemctl edit khandaq-agent, thenEnvironment=KHANDAQ_LOG=debug).
10.4 Organisation policy
Group Policy (the ADMX template in the release files, section 3.1), Intune,
Linux and macOS policy files (/etc/khandaq/policy.d/*.toml) and macOS
configuration profiles (section 5a.4) can set update policy, malware scanning
response and schedule, notification level, proxy, webhook and syslog,
retention, check selection and intervals, and self-update. Policy wins over
agent.toml, which wins over the app's settings; the app shows managed
controls locked. Policy settings are not behind a licence key. For the full
key list and Intune OMA-URI examples, write to
info@akhundbaba.af.
11. Licensing
11.1 What a key controls
Personal and home use is free and needs no key and no account: scans, reports, every fix, profile and rollback. An organisation key adds organisation features on top; it never unlocks protection. To get one, write to info@akhundbaba.af.
Nothing phones home: a key is checked on the machine, so air-gapped networks work. The rest of this section is for administrators who install organisation keys.
| Feature flag | Unlocks | In this version |
|---|---|---|
org.fleet |
Fleet enrolment and management | Flag only; not wired yet |
org.reports |
Signed compliance reports (khandaq report --sign, "Sign it" in the app) |
Enforced |
org.policy |
Central hardening policy | Flag only; not built yet |
org.mirror |
Offline update mirror tooling | Flag only; not built yet. Importing .kqrelease and .kqbundle files and [update] mirror work without a key |
Managed settings from Group Policy, Intune, policy.d or a macOS
configuration profile (section 10.4) are not behind a key.
| Key state | Scans, fixes, profiles, rollback | Organisation features |
|---|---|---|
missing (no key) |
yes | no |
valid |
yes | those the key carries (status.licence.org_features) |
grace (up to 7 days after expiry) |
yes | yes, with a notice |
expired, invalid, other_machine, not_yet_valid |
yes | no |
clock_back (trial keys only, section 11.5) |
yes | no, until the clock is right |
Fixes always need an administrator's approval (section 1); a key neither replaces nor adds to that.
11.2 Key format
KQL1.<base64url(JSON payload)>.<base64url(Ed25519 signature)>
The payload holds id, licensee, issued, expires, features (the
flags above), and optionally machine and valid_days. A .lic file holds
the same key plus # comment lines; whitespace and line breaks are ignored.
Al-Khandaq accepts only keys signed by Akhund Baba's licence key, which is
built into the product. Keys are issued offline by Akhund Baba; ask at
info@akhundbaba.af.
Keys issued before 2026-11-12 carry features: ["fix"]. They still
verify, and grant all four organisation features for their period. A key with
no features grants none. The format itself did not change.
11.3 Key kinds
| Kind | Behaviour | Use for |
|---|---|---|
| Fixed dates | Valid from issued to expires |
Organisations |
Trial (valid_days, start at install) |
Runs valid_days from the first install on each computer, never past expires. expires - valid_days is the last day it can be installed. A key installed after that day is expired, with no grace. |
Time-limited organisation trials |
Machine-bound (machine) |
Works on one computer only. Elsewhere: other_machine. |
Individually managed machines |
Any machine (no machine) |
Works on any computer; a trial gets its own period on each | One key for a whole rollout (for example in LICENCE_KEY) |
Machine code. Read it with khandaq licence (or khandaq licence --json,
field machine_code) or in the app under Settings > Licence. It is a hash of
MachineGuid (Windows), /etc/machine-id (Linux) or the hardware UUID
(IOPlatformUUID, macOS). It changes when those
change (for example an OS reinstall). Cloned images that share a machine id
share a machine code, so reset /etc/machine-id in Linux templates. For
machine-bound keys: install the agent, collect the codes, have the keys
issued, then install them with khandaq licence install.
11.4 Where the agent looks
state/licence.keyin the data folder, written bykhandaq licence installor the app.[licence] keyinagent.toml, written by the installers or by hand.
When both verify, the agent uses the one that is usable now and runs longest.
khandaq licence install takes effect at once; an agent.toml change needs
an agent restart.
11.5 Expiry, grace and the clock
- Organisation features keep working for 7 days after expiry, then stop. Scans and fixes are never affected.
- Trial keys only: while one is loaded, the agent records the latest time it
has seen (written at most hourly). If the clock is later more than 2 days
behind that mark, the state is
clock_backand the organisation features wait until the clock is right again. Installing a key never lowers the mark. - With no key, or with a fixed-date key, the clock is not recorded or
compared, and the state is never
clock_back.
11.6 The anti-reinstall ledger (trial keys only)
The ledger stores the latest time seen and, for each trial key, when it was first installed on this machine. It is kept twice and merged (latest time, earliest install):
| Copy | Location | Removed by |
|---|---|---|
| Data copy | state/licence-ledger.json in the data folder |
PURGE_DATA=1, /PURGEDATA=1, apt purge |
| System copy, Windows | HKLM\SOFTWARE\Akhund Baba\Al-Khandaq Licence, value Ledger |
Nothing. No installer writes or removes it. |
| System copy, Linux and macOS | /var/lib/khandaq-licence/ledger.json |
Nothing. It is not part of the package. |
So uninstalling and reinstalling, even with data deletion, does not restart a trial. This is by design.
A computer that never had a trial key has no ledger: the agent writes one only while a trial key is loaded. The ledger can only hold back organisation features, never a fix.
Support case: if a machine's clock was set far ahead by mistake while a trial
key was installed, the state stays clock_back. Clear it by deleting both
ledger copies and restarting the agent. That also forgets activations, so do
it only on a machine you trust.
11.7 Not available
No revocation list (a key stops at its expiry; keep periods short) and no renewal through the fleet server. Fleet, central policy and the mirror tool are not built yet; their flags exist so keys issued now can carry them.
12. Malware-scan rules and updates
| Rules | Source | How they arrive |
|---|---|---|
| Starter rules | Bundled with the product | Compiled in; always active |
| YARA Forge core pack | YARAHQ/yara-forge, release 20261108, asset yara-forge-rules-core.zip |
Action av.rules.update, approved by an administrator |
av.rules.update:
- downloads over HTTPS from
api.github.comandgithub.com(OS trust store); - checks the zip's SHA-256 against both GitHub's published digest and the value pinned in the binary;
- test-compiles the rules with YARA-X, then installs them atomically into
rules\with a manifest and an attribution index; - needs an administrator to approve, but no licence (section 1.4).
Licence filtering happens when the rules load, per av.json, so changing
allow_copyleft_rules or allow_noncommercial_rules needs no new download.
The pinned release is part of the binary. A newer rule pack arrives only with
a newer Al-Khandaq build. The check av.rules.status (every 6 hours) warns:
- when only starter rules are active, with the update as its fix;
- when the installed pack is not the one this build pins, with the update as its fix;
- when the pinned pack is more than 45 days old, counted from its release
date (the tag,
YYYYMMDD), not from when it was installed. This warning says "Update Al-Khandaq to get newer rules" and has no fix button, because running the update again would install the same pack.
Offline networks. Import a signed content bundle with khandaq feeds import <file.kqbundle> and a release with khandaq self-update import <file.kqrelease>, or point [update] mirror at a share or folder (sections
7.3 and 12.1).
Run the action from the CLI:
khandaq actions plan av.rules.update
khandaq actions apply <plan_id>
12.1 The signed content channel
Rules and lists normally come from a signed content bundle: our own
extra rules plus the licence-filtered YARA Forge set (each rule with its
author, source and licence), CC0 IOC lists (SSL Blacklist, Feodo Tracker,
SHA-256 lists), and KEV, EPSS and OSV snapshots. The agent checks it with
the self-update ([update] content = true), verifies the content key, every
file's hash, test-compiles the rules, and swaps the bundle in atomically. The
previous bundle is kept.
The public Mac deployment checks
https://downloads.al-khandaq.com/al-khandaq. Cloudflare renews signed freshness
records daily; this does not publish new rules or change the content bundle's
issue date. New content is currently published by the operator using the offline
content key. Publish fresh content at least weekly, before the rules-age warning.
The initial bundle contains YARA rules, KEV, EPSS and LOLDrivers data. IOC,
Sigma and OSV coverage depends on the installed bundle and built-in datasets;
the Protection screen lists the actual files and dates.
- Protection screen: bundle version, age, origin, files and licences, Roll back content.
khandaq feedsshows the same;khandaq feeds rollbackgoes back one bundle.- Air-gapped: copy a
.kqbundlefile and runkhandaq feeds import <file>as an administrator, or point[update] mirrorat a share that holds the channel folders. av.rules.statuswarns when the bundle is more than 7 days old. Without a bundle, "Update malware scanning rules" (av.rules.update) installs the pinned YARA Forge release as before.
12.2 Behaviour protection: detect versus prevent
| Layer | Prevents (before it runs or writes) | Detects and reacts (after) |
|---|---|---|
| Microsoft Defender (Windows) | Known malware at open/execute, Controlled folder access, ASR rules | Its own detections (shown by av.defender.detections) |
av.realtime.exec (Linux, opt-in) |
Files matching Critical rules, at execute | |
av.realtime.files, scheduled scans |
Files after they are written | |
av.behaviour |
Nothing: no driver, so no hook can stop a call | Processes, file changes, DNS and connections as they happen; ransomware is frozen within about a second of the verdict and then stopped and quarantined |
The behaviour layer accepts that a few files may be encrypted before the
verdict (the simulator loses 12-19 of 60). Keep Defender's Controlled
folder access on where you can: the detection's Turn on Controlled
folder access button and the av.behaviour remedy offer it.
What runs where
- Windows: the agent service opens an ETW session named
Al-Khandaq Behaviour(needs administrator rights; stop it withlogman stop "Al-Khandaq Behaviour" -etsif an agent crashed and you want it gone, the agent also stops a leftover one at start). If Sysmon is installed, itsMicrosoft-Windows-Sysmon/Operationalchannel is read too and process starts come from it (full command lines of short-lived programs,OriginalFileName, LSASS access). Turn on Sysmon (av.sysmon.enable) enables the built-in Windows Sysmon feature where it exists and installs a small Al-Khandaq configuration for it; sysmon-modular (MIT) is a fuller alternative. Without Sysmon, a program that exits within about a second may be seen without its command line. - Linux: proc connector and fanotify need root (the service has it);
without them the agent polls
/procand sees renames without the writing process. eBPF is not used. - macOS: without Apple's Endpoint Security entitlement the agent polls the
process list and watches the home folders with FSEvents. File events have
no process, so ransomware is reported but cannot be frozen. The full path
is the
com.apple.developer.endpoint-security.cliententitlement (granted by Apple on request), shipped as a system extension with Full Disk Access: it givesNOTIFY_EXEC,NOTIFY_RENAME,NOTIFY_WRITEwith the acting process andAUTH_*events that can block.
Rules and attribution. Bundled Sigma rules from SigmaHQ are used under
the Detection Rule License 1.1; their authors are shown with every detection
(Protection screen, notification text, SIEM rule_author and
rule_license).
Content bundles may add or replace rules (role sigma); each rule must name
an author and a licence, and copyleft or non-commercial rules are refused.
Tuning. Learning mode (Protection, or av.behaviour_learning_days)
makes heuristic ransomware verdicts alert-only for that many days after
behaviour protection first starts; canary hits and backup deletion act from
day one. A false alarm: False alarm on the detection resumes what was
frozen and adds the program to behaviour.allow_programs. Detections are
kept in behaviour.json (newest 200) and the monitor's state in
behaviour-status.json, both in the AV data folder.
Overhead. The ETW callback filters system folders, the agent's own files and pid 4 before decoding paths and forwards at most one write per process and file every two seconds. Measured: 0.23 % of one core at idle.
13. Webhook alerts
With [webhook] url set, the agent POSTs JSON in two cases.
After a scan batch, when the verdict is worse than the previous batch's,
or when a check reports a Fail it did not report in its previous run. Both
comparisons use the history database, so restarts do not repeat alerts. The
very first scan alerts unless it is Safe. Warnings alone never alert. Verdict
order, best to worst: safe, incomplete, at_risk, critical.
{
"source": "khandaq-agent",
"agent_version": "1.0.0",
"host": "web-01",
"platform": "Ubuntu 24.04.3 LTS",
"timestamp": "2026-11-02T10:00:00Z",
"verdict": "critical",
"previous_verdict": "at_risk",
"verdict_worsened": true,
"score": {"value": 42, "verdict": "critical", "failed": 3, "warnings": 2, "passed": 20, "unknown": 1, "accepted": 0},
"new_failures": [{"check_id": "...", "severity": "high", "status": "fail", "summary": "..."}],
"text": "Al-Khandaq on web-01: Critical (42/100). New failure: ..."
}
previous_verdict is null on the first scan.
For a monitor event with status Fail:
{
"source": "khandaq-agent",
"agent_version": "1.0.0",
"kind": "event",
"host": "web-01",
"platform": "...",
"timestamp": "...",
"event": { "check_id": "...", "domain": "...", "severity": "...", "status": "fail", "summary": "...", "evidence": {}, "...": "..." },
"text": "Al-Khandaq on web-01: <summary>"
}
text lets Slack- and Mattermost-style incoming webhooks show the alert as it
is.
Delivery: https only unless allow_http = true; with secret set every POST is signed (X-Khandaq-Signature, HMAC-SHA256
over <timestamp>.<body>); alerts are queued in state/webhook-queue and
retried with backoff (30 s to 1 h) across restarts, at most 1000 alerts or 7
days. Redirects are not followed, so the Authorization header never goes to
another host. TLS uses rustls with the OS certificate store. Drift events are
not sent to the webhook. Host names and finding text are not escaped for chat
markup.
The same events, and more (fixes, detections, tamper, configuration), go to
the Windows Event Log and to syslog ([event_log] and [syslog], section
10.1). khandaq-agent siem-test sends one test event to each.
14. Fleet console
The fleet console (khandaq-fleet) is a preview in 1.0. The agent does
not enroll or report to it: the fleet client is not wired into the agent. The
[fleet] section and the FLEET_URL / ENROLL_TOKEN / FLEET_FINGERPRINT
MSI properties are accepted and stored, but nothing reads them. Leave the
[fleet] settings empty for now; fleet management will arrive in a later
version.
To see many machines today, use the webhook (section 13) or collect
khandaq-agent status / latest.json with your own tooling.
15. Logs, audit log, history and retention
| Record | Where | Retention |
|---|---|---|
| Agent log | logs\agent.YYYY-MM-DD.log (Windows data folder) or /var/log/khandaq/ plus the journal. The date is UTC. |
Newest log_days (14) files, each at most log_file_mb (50 MB) |
| Crash records | crash-YYYYMMDDTHHMMSSZ-n.txt next to the logs: version, thread, message, location, backtrace, image base |
Newest 20 |
| Start refusals | Windows Application event log, source Khandaq; Linux journal |
OS policy |
Scan history (runs, findings tables in khandaq.db) |
Data folder | history_days (90), and the size ceiling |
Monitor events (events) |
khandaq.db |
event_days (30), at most event_rows (10,000), and the size ceiling |
Audit log (audit_log) |
khandaq.db |
Kept for ever unless audit_days is set; never touched by the size ceiling |
Acceptances (acceptances) |
khandaq.db |
Until withdrawn |
Drift baselines (baselines) |
khandaq.db |
One per check, replaced |
Hardening profile journal (profile_runs) |
khandaq.db |
Not pruned |
| Latest report | state/latest.json |
Replaced after every batch |
| On-demand scan logs | scans\*.jsonl (every file scanned and its SHA-256) |
Not pruned |
| Quarantine | quarantine\ |
Until restored or deleted through an action |
| Tray state | per user | Overwritten |
Each audit_log row holds run_id, action_id, approved_by (verified
account), the full plan, state, status, started_at, finished_at and
the outcome. Ways to read it:
- the app, History section (last 100 entries);
- the IPC request
{"cmd":"audit_log","limit":N}(default 50, at most 1,000); - as an administrator, with any SQLite client on a copy of
khandaq.db.
Tamper evidence. Since schema 4 every audit record is also a row of a
hash chain (audit_chain): action runs starting (with the verified
planner) and finishing, licence installs, service starts and stops
(including whether the previous run stopped cleanly), agent.toml changes,
and changes to the Windows service's permissions. Each row's SHA-256 covers
the previous row's hash. Every 16 rows, and at every start and stop, the
agent signs the head with a per-install Ed25519 key (state/audit-key.bin:
DPAPI machine scope on Windows, a root-only 0600 file on Linux) and mirrors
it to state/audit-head.json and the agent log. Retention removes whole
prefixes of the chain and keeps a signed checkpoint at the cut as the
anchor, so the rest still verifies; nothing is pruned while the chain does
not verify.
khandaq audit verify # exit code 1 when anything was altered
khandaq audit verify --json # the AuditVerification object
The finding agent.audit.integrity (High) appears in every report while
the trail does not verify; the agent re-checks every hour. See section 21
for what this does and does not catch.
If khandaq.db cannot be opened, the agent logs an error and keeps events,
audit log and acceptances in memory only until it restarts. Watch for
"agent database unavailable" in the log.
Schema version and upgrades. khandaq.db carries its schema version in
SQLite's PRAGMA user_version (1.0.0 writes 4). At
start the agent applies the missing steps, each in one transaction with its
version bump, and logs "khandaq.db migrated: ..."; a crash during an upgrade
leaves the old or the new version, never a half. A file from a newer agent (a
downgrade) is used as it is. khandaq status and the diagnostics bundle show
the version.
Size ceiling. The file uses incremental auto-vacuum. After every scan, when it
uses more than db_max_mb, the oldest scan runs go first (the newest 10
always stay), then the oldest monitor events, and the freed space goes back
to the disk. The audit log, acceptances, baselines and profile runs are never
deleted for space.
16. Hardening profiles and rollback
Three profiles of reversible settings: basic ⊂ recommended ⊂ strict.
Windows settings are registry DWORDs under HKLM; Linux settings are sysctl
integers (written to /proc/sys and to /etc/sysctl.d/60-khandaq-<setting>.conf).
strict settings carry compatibility warnings (old NAS/SMB devices, NTLM-only
apps, USB storage, containers and debuggers). The plan lists every setting
it will change before you approve it.
| Action | Arguments | Needs |
|---|---|---|
expert.profile.apply |
profile=basic|recommended|strict |
Administrator |
expert.profile.rollback |
run=<profile run id> |
Administrator |
Apply:
khandaq actions plan expert.profile.apply profile=recommended --json
khandaq actions apply <plan_id>
The plan lists only settings that differ from the profile, with from → to.
The agent adds the setting list and a fresh profile run id to the plan's
arguments (plan.args.run in the JSON); keep that id. At apply time the agent
re-reads and journals the prior values, then writes.
Roll back:
khandaq actions plan expert.profile.rollback run=<profile run id>
khandaq actions apply <plan_id>
Rollback restores each value from the agent's own journal, or deletes it if it was absent before. A run rolls back once. The app's Expert > Hardening tab lists profile runs and offers the same rollback.
Profile settings stay on the machine after Al-Khandaq is uninstalled. Roll back before uninstalling if you want the previous values.
Not in the profiles: ASR rules, Office macro policy, LSA protection, PowerShell 2.0 removal, BitLocker.
17. Scripting with the CLI
17.1 khandaq scan
khandaq scan # problems only
khandaq scan -v # everything
khandaq scan --json # full report as JSON on stdout
khandaq scan --domain os --json # hardware | os | software | network (repeatable)
khandaq scan --only os.defender # check ids starting with this prefix
khandaq scan --json --timings # timings table on stderr
khandaq scan --format sarif # SARIF 2.1.0 (code-scanning dashboards)
khandaq scan --format csv # one row per finding
khandaq scan --since old.json # only new and resolved problems
khandaq list [--frameworks] # every check; [admin] marks admin-only checks
khandaq list --json # the catalogue: id, title, domain, severity, interval, frameworks
Exit codes of scan:
| Code | Meaning |
|---|---|
| 0 | Safe |
| 1 | At risk |
| 2 | Critical |
| 3 | Incomplete (an important check could not run) |
A command-line usage error (unknown option, missing argument) exits with 64
in every khandaq command, so it never looks like a verdict. --help and
--version exit 0.
--json (same as --format json) prints the report document
khandaq.report/1: schema, product_version, install_id (null for a
one-off scan), hostname, then the report. Its JSON Schema is
khandaq.report-1.schema.json. Adding fields keeps /1;
removing or changing one makes it /2. The report itself has
started_at, duration_ms, elevated, platform,
runs (per check: check_id, title, duration_ms, findings) and score
(value, verdict, failed, warnings, passed, unknown, accepted).
Each finding has check_id, domain, severity (info … critical),
status (pass, warn, fail, error, not_applicable), summary,
evidence, remediation, fix, references, observed_at.
khandaq scan runs the checks in its own process, with the rights of whoever
runs it. It is not the agent's report:
- Run without elevation, admin-only checks are skipped with reason
not_elevated, and the verdict becomes Incomplete. - It does not apply acceptances; the agent does.
- It does not use the agent's background Windows Update refresh.
For the agent's own report (as SYSTEM or root, with acceptances), use:
"C:\Program Files\Al-Khandaq\khandaq-agent.exe" status # Windows (not on PATH)
khandaq-agent status # Linux and macOS, root or group khandaq
It prints {"ok":true,"protocol":2,"data":{...}}. data holds
agent_version, scanning, report, new_problems, monitors,
running_actions and licence. Exit code 0 if the agent answered, 1
otherwise. khandaq-agent scan-now asks for a scan.
Running khandaq scan unelevated on Windows can create
%ProgramData%\Al-Khandaq\cache as that user (the agent moves such content
aside). Prefer khandaq report for collection.
--since FILE compares with an earlier report (a saved --json output,
or a copy of state/latest.json): it prints the problems (Fail or Warn) that
are new and the ones that are gone, or with --json a khandaq.diff/1
document (since, now, new, resolved, unchanged, score_before,
score_now). It exits 0 when nothing new went wrong and 1 when something did.
SARIF: one rule per check, one result per Fail, Warn or Error finding
(error for failed high and critical findings, warning for other problems,
note for checks that could not run). Posture findings have no source file,
so each result names the host as its logical location; the fingerprint
khandaq/v1 is check, subject and summary. CSV: hostname, check_id, domain, severity, status, summary, subject, remediation, observed_at, every
finding; cells that start with = + - @ get a leading ' so spreadsheets do
not run them.
17.1a Agent commands (automation)
These read and change the running agent over its local API. Every one takes
--json; the JSON is the API's data.
khandaq status [--json] # version, scan in progress, score, licence, monitors, DB schema
khandaq report [--format ...] [--since F] # the agent's merged report (exit code as for scan)
khandaq scan-now [--only PREFIX] [--wait] [--timeout 900] [--format ...]
khandaq events [--limit 100] [--json] # monitor events, newest first
khandaq audit [--limit 100] [--json] # finished action runs: who approved what, result
khandaq accept CHECK [--subject S] [--note N] [--review-on YYYY-MM-DD] # administrators
khandaq unaccept CHECK [--subject S] # administrators
khandaq acceptances [--json]
khandaq insights [--json] # fix-first order, frameworks, E8, role, drift, triage
khandaq updates [--json] # pending updates per source
khandaq diag [--out FILE] # diagnostics bundle (administrators)
khandaq report --format pdf|html|csv [--sign] [--out FILE] # compliance evidence report
khandaq verify-report FILE [--key-id ID] # check a signed evidence report (exit 1 if not)
khandaq-agent siem-test [--config FILE] # one test event to Event Log, syslog and webhook
Compliance evidence report. khandaq report --format pdf --sign writes
AlKhandaq-evidence-<host>-<time>.pdf and <file>.sig.json in the current
folder (--out for another name). It holds the host, report time, score and
verdict, every finding with its CIS Controls v8 IG1, NIST CSF 2.0, ISO/IEC
27001:2022, Cyber Essentials, Essential Eight and ATT&CK references, accepted
risks with approver and expiry, fixes from the audit log, framework coverage
and the agent version. --format html is one self-contained file;
--format csv is one table with a record column (summary, finding,
control, accepted_risk, fix). The app's History screen has the same
export. The agent signs with its own Ed25519 key (state\evidence-key.p8,
SYSTEM/root only); khandaq status shows its id (evidence_key_id). Record
that id per machine; an auditor runs khandaq verify-report FILE --key-id ID,
which fails on any change to the file or its details. The PDF uses the
standard Latin fonts: text in other scripts shows as ? there (use HTML or
the signed JSON for Dari/Pashto host names).
scan-now --wait returns once the agent has published a newer report and
prints it like report. report is the agent's view (as SYSTEM or root, with
acceptances), unlike scan. Errors print error: ... on stderr and exit 1.
17.2 khandaq actions
khandaq actions list # actions the agent can run here
khandaq actions plan <action_id> [KEY=VALUE ...] # read-only; prints the plan id
khandaq actions apply <plan_id> # administrator; waits and prints progress
khandaq actions status <run_id>
khandaq actions cancel <run_id> # administrator
Add --json to any of them for the agent's JSON answer. Exit codes: 0 on
success; 1 on an error (no agent, refused, unknown or expired plan) and when
apply or status reports a finished run that did not succeed. status on a
run still running exits 0.
Example: install security updates only, unattended, on Linux as root:
plan=$(khandaq actions plan os.update.install security_only=true --json | jq -r .plan_id)
khandaq actions apply "$plan" --json
plan --json returns plan_id, expires_at and plan (action_id, args,
summary, items, reboot_may_be_required, warnings, planned_at). An
empty items list means nothing to do. Apply within 10 minutes; each plan id
works once.
Useful arguments:
| Action | Arguments |
|---|---|
os.update.install |
only (comma-separated KB numbers, Windows Update ids or apt package names), security_only=true |
sw.package.upgrade |
package (comma-separated winget ids or snap names) |
expert.profile.apply |
profile |
expert.profile.rollback |
run |
khandaq actions list shows each action's id, whether it needs an elevated
agent, and whether it is reversible. Windows Update installs never restart the
machine; the outcome says when a restart is needed.
How updates install
- One update run installs at a time (Windows Update and winget, or apt and snap, never at once); a second approved run waits as queued.
- Planning reads the lists already on the machine and never searches Windows Update online; the plan says how old the list is. Installing does one online search, then downloads and installs all planned updates as one batch.
- Windows Update: software updates only (
IsInstalled=0 and IsHidden=0 and Type='Software' and BrowseOnly=0), no feature upgrades. With a restart pending, only updates that never need a restart install. On machines managed by WSUS, Windows Update for Business or an MDM (Intune), nothing is installed and the Updates screen says who manages them. - winget:
--source winget, exact id and the planned--version, exit codes mapped (restart-required counts as installed). The service updates machine-wide installs; the app updates each person's own installs in their session and records them in History assw.package.upgrade.user. - apt:
dpkg --configure -afirst, then oneinstall --only-upgradetransaction that waits up to 10 minutes for the dpkg lock and keeps automatic-install marks. snap: through snapd, respectingsnap refresh --hold. - Update runs are saved in
state/update-runs.json: after a restart a cut-off run is closed with what it finished, and a queued run starts again.
Update settings (state/updates.json)
Edited from Updates > When updates install (administrator approval), or by hand while the agent is stopped:
{
"security": "automatic",
"other": "ask",
"window": { "start": "02:00", "end": "05:00" },
"defer_days": 7,
"on_metered": false,
"on_battery": false,
"restart": { "mode": "ask", "never_between": { "start": "08:00", "end": "18:00" }, "deadline_days": 7 },
"ignored": { "winget:Git.Git": "2.56.0.4" },
"pinned": ["winget:Docker.DockerDesktop"]
}
Automatic installs are approved as policy:updates. Nothing installs
automatically until security or other is automatic. Restarts are
scheduled (30 minutes' warning) only when restart.mode is automatic or the
deadline has passed, and never inside never_between.
17.3 khandaq licence
khandaq licence [--json] # free use, donation address, key state, features, expiry, machine code
khandaq licence install <file.lic | KQL1....>
Exit code 0 with no key (free use) and with a usable key; 1 when an installed
key cannot be used (expired, damaged, another machine, clock). With --json,
org_features lists the organisation features usable now.
18. Troubleshooting
18.1 The service does not start
Windows:
Get-Service Khandaq,sc.exe qc Khandaq, and the Application event log (sourceKhandaq). Linux:systemctl status khandaq-agentandjournalctl -u khandaq-agent. macOS:sudo launchctl print system/org.alkhandaq.agentand the logs in/Library/Logs/Al-Khandaq.Look for a data-folder refusal (18.2) or an unsafe parent folder ("refusing to use ...: its parent ... is a link, not owned by an administrator, or writable by anyone").
Run the data-folder step by hand from an elevated prompt or as root. It prints what it repaired or why it refuses:
"C:\Program Files\Al-Khandaq\khandaq-agent.exe" service prepare-data sudo khandaq-agent service prepare-dataThe Windows service restarts itself 60 s after each failure (the failure count resets after a day); systemd restarts it 60 s after a failure.
18.2 The data folder is held
Message: Data folder is held open by another process (PID ...).
- Find the process. On Windows, Resource Monitor (
resmon.exe) > CPU > Associated Handles, search forAl-Khandaq. On Linux,fuser -vorlsof +D /var/lib/khandaq. - End it, or sign out its user, or restart the machine, then start the service or rerun setup.
- During MSI install the step fails and the install rolls back (1603); during an upgrade the machine stays on the old version. Inno restarts the old service.
- The agent never takes over a held folder. Any process, including a standard user's, can block install or start this way for as long as it holds the folder. This fails safe: nothing is written into the folder.
18.3 Windows Update is slow: Error, not Pass
os.update.pending searches Windows Update offline with a 45 s limit (23 s
was measured on a busy machine), while it lists winget at the same time. When
Windows Update is busy or hangs, the finding is an Error ("did not finish
within 45 s"), never a Pass, and it costs no points. Two consequences:
- The score can look better than it is, because a pending security update is not counted while the search fails.
os.update.pendingis Medium severity, so its Error does not make the verdict Incomplete. A machine whose Windows Update hangs can still show Safe with its updates unchecked.
The agent refreshes the Windows Update list online in the background
(os.update.refresh, 2 minutes after start, then every 6 hours). A list not
refreshed for more than 3 days gives a Warn. A cached list older than 3 days
is not served. winget can also take most of its 35 s limit on a cold cache, so
the first scan of the day on a slow link can show an Error for winget.
18.4 Elevated and non-elevated results differ
| Source | Rights | Acceptances | Typical difference |
|---|---|---|---|
App, tray, khandaq-agent status |
Agent (SYSTEM / root) | Applied | Full coverage; adds "N user profiles not checked (signed out)" warnings |
khandaq scan in an elevated prompt / sudo |
Administrator / root | Not applied | Close to the agent, minus acceptances and the agent's cached Windows Update list |
khandaq scan unelevated |
The user | Not applied | Admin-only checks give Error not_elevated; verdict Incomplete (exit 3) |
Use the agent's report for decisions.
18.5 Clients cannot reach the agent
- "cannot reach the agent on ...": the service is not running, or (Linux, macOS) the
user is not in group
khandaq(log in again afterusermod). Al-Khandaq can't verify the agent: the endpoint is served by a process that is not theKhandaqservice (Windows) or not root (Linux, macOS). Find and stop that process. The agent reports this asagent.ipc.endpoint.Approving changes needs an administrator: approve from an elevated prompt, as root, or as akhandaq-adminmember.This is an organisation feature and needs an Al-Khandaq organisation key: a signed report (or another organisation feature) was asked for without a key that grants it. Section 11. Fixes never give this answer.
18.6 Settings are ignored
The agent ignores an invalid agent.toml completely and raises the finding
agent.config.invalid, whose problem evidence names the error (also in the
log: "agent.toml is not used"). Common causes: a typo in a section or key
name, a duplicate [fleet] or [licence] section (section 4.4), an http://
fleet URL, a retention value below its minimum.
18.7 Collect diagnostics for support
One zip with what support needs, from any of:
- the app: Settings → Background service → Collect diagnostics (asks for an administrator, saves into Downloads and shows the file);
khandaq diag [--out FILE](administrator, through the running agent);khandaq-agent diag [--out FILE] [--data-dir DIR] [--config FILE], run as administrator or root. It reads the data folder directly, so it also works when the agent does not start. Without elevation it collects what it can and lists the rest underproblemsinmanifest.json.
Contents: manifest.json (bundle schema khandaq.diagnostics/1, versions,
OS, host name, paths, khandaq.db schema version, size and row counts),
config/agent.toml with secrets replaced (authorization, licence key,
enrolment token, proxy credentials, webhook URL path), state/latest.json and
the update state, the newest three daily logs (last 4 MB each) and all crash
records with licence keys and tokens redacted, system/service.txt (service
configuration and state), system/acl.txt (data folder permissions) and
system/status.json (the agent's status, when it runs). The licence key and
the licence ledger are never included. Host, user names and paths are: tell
the user before they send it.
19. Uninstall and what remains
19.1 Windows
msiexec /x AlKhandaq-1.0.0-x64.msi /qn (keeps data)
msiexec /x AlKhandaq-1.0.0-x64.msi /qn PURGE_DATA=1 (deletes all settings and data)
msiexec /x {ProductCode} /qn
msiexec /x {ProductCode} /qn QUARANTINE_ACTION=restore (keep is the default; also delete)
"C:\Program Files\Al-Khandaq\unins000.exe" /VERYSILENT /QUARANTINE=restore (Inno setup)
From Settings > Apps, the uninstall asks what to do with quarantined files (keep, the default; restore all; delete all), warns when there are any, and shows an unticked "Also delete all settings and data, including the quarantine folder" box. A silent uninstall keeps them.
Kept files stay in %ProgramData%\Al-Khandaq\quarantine. Reinstalling brings
them back into the app. Restore all applies the checks of a single restore: it
never replaces a file and needs the original folder to exist, and whatever cannot
go back stays in quarantine and is logged. The ticked box removes the folder, so
it also removes kept files and any that could not be restored.
Repair. Settings > Apps > Al-Khandaq > Modify opens the wizard with Repair;
or run msiexec /fa {ProductCode}. Running the same setup.exe again repairs an
Inno install. Settings and data are kept.
Always removed: the service, the program files, the PATH entry, the
KhandaqTray Run value, the Start menu shortcut, the Add/Remove Programs
entry.
| Item | Default uninstall | With the box ticked or PURGE_DATA=1 |
|---|---|---|
C:\Program Files\Al-Khandaq\agent.toml (settings, licence key, secrets) |
Kept, so a reinstall keeps them | Deleted (khandaq-agent service purge, as SYSTEM) |
%ProgramData%\Al-Khandaq (history, audit log, logs, quarantine, data copy of the licence ledger) |
Kept | Deleted |
HKLM\SOFTWARE\Akhund Baba\Al-Khandaq (InstallId key; FleetUrl, FleetTokenProvided, FleetFingerprint, LicenceKeyProvided) |
Kept: InstallId lets a reinstall trust the kept data folder |
Deleted (service purge) |
%LOCALAPPDATA%\Al-Khandaq and %LOCALAPPDATA%\org.alkhandaq.app (tray state, the app's WebView2 cache) |
Kept | Deleted for every profile (service purge, as SYSTEM; a profile with a link in AppData\Local is skipped and logged) |
HKLM\SOFTWARE\Akhund Baba\Al-Khandaq Licence (Ledger) |
Kept | Kept, by design: stops a reinstall from restarting a licence |
HKLM\SOFTWARE\Akhund Baba\Al-Khandaq Updates (Trust) |
Kept | Kept, by design: the update trust ledger stops a reinstall from accepting an older, rolled-back update |
%ProgramData%\Al-Khandaq.untrusted-* |
Kept | Kept: may hold content planted by another user (section 9) |
| Security changes made by fixes and hardening profiles (registry values, firewall rules and profiles, Defender settings) | Kept | Kept on purpose: uninstalling a security tool should not weaken the machine. To reverse them, use Undo on each fix or roll back each profile run before uninstalling; afterwards nothing can undo them |
Any HKCU KhandaqTray value from khandaq-tray --install-autostart |
Kept | Kept |
Quarantined files cannot be restored after a purge, unless restore was chosen in the same uninstall.
A failed purge step is written to the MSI log and does not stop the
uninstall. To do it by hand before uninstalling, stop the service and run
"C:\Program Files\Al-Khandaq\khandaq-agent.exe" service purge from an
elevated prompt.
Installing the same version again (a rebuilt MSI) replaces the installed copy instead of adding a second one.
19.2 Linux
sudo apt remove khandaq-desktop khandaq # stops and disables the agent; keeps data and agent.toml
sudo apt purge khandaq # also deletes /var/lib/khandaq, /var/log/khandaq,
# /var/cache/khandaq, /run/khandaq, agent.toml and
# each person's app files in their home folder
Removal also stops every session's tray and app. Quarantined files survive
both commands unless you choose otherwise, because after a purge no agent is
left to restore them. To decide at removal time, set the action (keep,
restore or delete) on a removal that still has the agent installed:
sudo env KHANDAQ_QUARANTINE_ACTION=restore apt purge khandaq
KHANDAQ_QUARANTINE_ACTION=delete also works when purging a package that was
already removed. restore does not, because the agent is gone by then.
| Remains after purge | Why |
|---|---|
/var/lib/khandaq/quarantine, if it holds files and the action was not delete |
Files may be someone's only copy; reinstall to restore them, or sudo rm -rf /var/lib/khandaq |
/etc/khandaq/policy.d/* |
The organisation's policy, not the product's. dpkg warns that /etc/khandaq is not empty |
Groups khandaq, khandaq-admin |
Files elsewhere may use them: sudo groupdel khandaq-admin; sudo groupdel khandaq |
/var/lib/khandaq-licence/ledger.json |
By design (not part of the package) |
/var/lib/khandaq-update/trust.json |
By design: the update trust ledger stops a reinstall from accepting an older, rolled-back update |
/var/lib/khandaq.untrusted-* and similar |
Never removed automatically |
/etc/sysctl.d/60-khandaq-*.conf and the live sysctl values |
Roll back profiles before removing |
/etc/systemd/system/khandaq-agent.service |
Only if created by khandaq-agent service install; remove it and run systemctl daemon-reload |
Per-user files in a non-default place (XDG_STATE_HOME, XDG_CONFIG_HOME) |
Root cannot see a person's environment |
dnf remove (RPM) stops the agent, tray and app but never deletes data. RPM
has no purge. To handle quarantined files, run sudo systemctl stop khandaq-agent and then sudo khandaq-agent service restore-quarantine (or
delete-quarantine) before dnf remove. To delete the data afterwards,
delete the three folders named in its message.
19.3 macOS
sudo /usr/local/libexec/al-khandaq/uninstall.sh # removes the programs; keeps data and agent.toml
sudo /usr/local/libexec/al-khandaq/uninstall.sh --purge # also deletes data, logs, agent.toml and each person's app files
With quarantined files present and a terminal attached, the script asks
whether to keep, restore or delete them. --quarantine=keep|restore|delete
answers in advance for scripted removal; with no terminal and no option, it
keeps them. As on Linux, --purge leaves quarantined files in place unless
the action is delete.
If a step fails, the script says what failed, exits non-zero and keeps itself and the agent so you can run it again.
Remains after --purge |
Why |
|---|---|
/Library/Application Support/Al-Khandaq/quarantine, if it holds files and the action was not delete |
Files may be someone's only copy |
/var/lib/khandaq-licence/ledger.json |
By design |
/etc/khandaq/policy.d/* |
The organisation's policy |
Groups khandaq, khandaq-admin |
sudo dseditgroup -o delete khandaq-admin; sudo dseditgroup -o delete khandaq |
| Settings changed by fixes and profiles | Undo or roll back before removing |
20. Known limitations
Limitations of version 1.0 that matter to an administrator:
| Severity | Limitation |
|---|---|
| Medium | Hidden accounts are not reported. Accounts hidden from the sign-in screen (Winlogon\SpecialAccounts\UserList = 0) are left out of the "profiles not checked" warning, and no check reports hidden accounts. A hidden account's Run keys go unread while coverage looks complete. Hiding an account needs administrator rights. |
| Medium | An Error on os.update.pending can still give Safe (section 18.3). |
| Medium (fails safe) | Any user process holding the data folder, a junction at its name, or a file inside it blocks install, upgrade or service start (section 18.2). The message often says "PID unknown". |
| Low | An unelevated khandaq scan on Windows can create %ProgramData%\Al-Khandaq\cache as the user; a later elevated CLI scan may trust a planted feed file there. The agent itself moves such content aside. |
| Low | A Windows Update list cached more than 3 days ago turns a "security updates waiting" High Fail into a Medium Warn. |
| Low | The same problem can be counted more than once (AutoPlay, winget updates, TeamViewer, SMB). |
Other limits an administrator should know:
- Any user can create action plans (the plan records who made it). Apply only plans you made or reviewed.
- An acceptance on a check that names no item covers every finding from that check, and is not tied to the finding's state.
- The audit log is pruned only when
[retention] audit_daysis set, and only when the trail verifies. - Windows real-time scanning is post-write only; Defender blocks.
- On Windows a file restored from quarantine takes its folder's permissions; the original owner is recorded but not set back.
- Interactive uninstallers cannot show a window from the service session, so
sw.remote.uninstallrefuses those and points to Settings > Apps. - Self-update is on by default (section 7.3). To distribute new MSI /
.debversions with your own tooling instead, set[update] enabled = falseormode = "notify", or use the policy. - On macOS, behaviour protection polls the process list and watches home folders with FSEvents; ransomware is reported but cannot be frozen (section 12.2). Malware scans need Full Disk Access (section 5a.3).
- As with any security tool, test on representative machines before a wide rollout.
21. Security architecture
This section is for the people who must decide whether to trust the agent on their machines. It says what the agent defends against, where the trust boundaries are, and, as plainly as we can, what it only detects.
21.1 Threat model
| Adversary | Can | Goal against Al-Khandaq |
|---|---|---|
| Malicious file (download, email attachment, USB) | Reach the scanner with crafted bytes: archives, PE files, Office documents, disk images | Exploit a parser running with SYSTEM/root rights |
| Hostile feed or network position | Serve a crafted KEV/OSV feed or rule pack, or tamper in transit | Make the agent parse attacker bytes, or blind it |
| Ordinary local user (shared PC) | Use the IPC pipe/socket, write their own registry hive and profile | Read other users' privacy evidence; get changes approved; hide a finding; exhaust the agent |
| Local administrator or malware running as SYSTEM/root | Everything the OS allows | Stop the agent quietly, rewrite its records, replace its binaries |
The last row cannot be prevented by any user-mode agent; the goal there is that it is not silent.
21.2 Trust boundaries
untrusted bytes ──► khandaq-scan-worker (AppContainer / nobody+seccomp, no network)
│ framed pipe, size-limited, versioned
▼
local users ──────► IPC pipe/socket ──► khandaq-agent (SYSTEM / root)
(identity from the OS: │
token / SO_PEERCRED) ├─► actions (after approval, audited)
├─► khandaq.db + signed hash chain
└─► systemd-run (Linux package changes)
- Scanned content → worker. YARA-X (rule conditions and its PE/.NET
modules) and the archive and container unpacker (zip, OOXML, 7z, CAB,
ISO 9660, OLE/VBA, OneNote) run in
khandaq-scan-worker, never in the agent. The agent opens and reads the file, hashes it, applies exclusions, the verdict cache and known-bad lists, asks the OS for the Authenticode signer, talks to clamd, and makes the verdict; the worker only returns rule matches and member hashes.- Windows: an AppContainer with no capabilities (no network, low integrity, no access to user or system files beyond what every app package may read), in a job object (one process, 2 GiB, killed with the agent, UI restrictions), with child process creation disabled.
- Linux: its own network and IPC namespace (when the agent is root),
user
nobody,no_new_privs, no core dumps,RLIMIT_FSIZE=0, and a seccomp filter that refuses sockets, exec, fork (threads only), ptrace, mounts, namespaces, module loading, BPF and opening files for writing. - macOS: user
nobody, with a Seatbelt sandbox profile that allows no network, no file writes, no new processes and no Mach services. A worker that cannot enable the sandbox stops before it is given any rules. - It reads nothing from disk: the compiled rules arrive once over the pipe, then one file per request. Frames carry a magic, a protocol version and a length checked against a per-kind limit before anything is read. A result is bounded (match count, string lengths, hash format) before the agent uses it.
- A worker that crashes, hangs past its deadline (four times the YARA-X timeout plus one second per 8 MB, at most 10 minutes) or breaks the protocol is killed. Only that item fails, and it counts as "unconfirmed", never clean; the next item starts a new worker.
[security] scan_workerinagent.toml:require(default on every platform: fail closed; when no worker can start, the items are reported as not scanned, nothing is parsed in the agent, a History entry is written and the High findingav.worker.status"Scanning is paused: the safe scanner could not start" is raised, which the tray and app announce; a new start is tried after a minute and by the check every hour),prefer(explicit administrator choice: fall back to in-agent scanning, with a log warning, a counter in the AV state and a warning finding) oroff.- Measured overhead (debug build, 440 files, own rules): about 110 ms to start a worker (once per scan thread; workers are pooled), and no per-file cost above noise. Release builds were not measured.
- Feeds and rule packs. The YARA Forge pack is checked against a
SHA-256 pinned in the binary before it is unzipped or compiled; future
content bundles are signed (self-update channel). The CISA KEV and OSV
feeds come over TLS from the vendor and are parsed by
serde_jsonin the agent with size limits; these, like every other parser of untrusted text (sshd_config, sudoers, PAM, registry values, winget tables, quarantine sidecars, IPC requests), have fuzz targets that run in continuous integration. - IPC. The pipe/socket identity comes from the OS (Windows token of the
client process, Linux
SO_PEERCRED), never from the request. Changes need an enabled Administrators group (or root /khandaq-admin). Every plan records its verified planner (shown at approval and chained into the audit trail), so nobody approves a plan believing they made it. A caller who is not an administrator sees system-wide findings and their own per-user items only: privacy events (camera, microphone, location), per-user apps, extensions and settings, and per-user update lists of another person are filtered out ofstatus, events, insights and pending updates. Request size, deadlines and per-account connection caps stop one user locking others out. - Approved changes. Actions run only after approval, each with an
audit row written before anything changes. On Linux the agent's own
file system is read-only apart from its folders (section 5.3); package
installs leave the unit through
systemd-run.
21.3 What the agent detects, and what it prevents
| Event | Prevented? | Detected, and how |
|---|---|---|
| A parser bug triggered by a malicious file | Contained: it runs in the worker sandbox | The item fails; the worker failure is logged and counted |
| A non-admin reads another user's privacy evidence over IPC | Yes (filtered) | |
| A non-admin approves a change | Yes (needs an enabled admin token / root) | Refusals are logged |
Someone edits, deletes or reorders audit records in khandaq.db without the key |
No | Yes: khandaq audit verify, finding agent.audit.integrity |
| The database is restored from an older copy or emptied | No | Yes, against state/audit-head.json and the log |
| An agent binary is replaced or patched | No | Yes at the next start: agent.self.integrity (Critical), against the signed khandaq-binaries.sha256 |
| The install folder becomes writable by non-admins | No | Yes: agent.self.integrity |
| The service DACL is loosened so others can stop or reconfigure it | Repaired at start and hourly | Yes: service.dacl.changed in the audit trail, agent.service.protection |
| An administrator stops the service | No (Windows cannot stop an administrator) | Yes: service.stopped in the trail; after 5 minutes the tray shows "Protection is not running" with a critical notification; the next start records whether the stop was clean |
| The agent is killed or crashes | No | Yes: the next start records "ended without a clean stop"; the tray alert as above |
| SYSTEM/root malware rewrites everything consistently (reads the key, re-signs the chain, replaces the binary and its manifest) | No | Only from outside the machine: forward the agent log or the Event Log to a SIEM and compare the checkpoint hashes it saw (audit checkpoint signed lines) |
Rows written after the newest checkpoint are chained but not yet signed; a truncation of those rows is caught only through the head file and the log.
21.4 Limits, stated plainly
- No Protected Process Light, ELAM or tamper protection. Running the agent as a protected process needs an Early Launch Anti-Malware driver signed by Microsoft, which in turn needs membership of the Microsoft Virus Initiative (MVI). Al-Khandaq has neither. An administrator, or malware with administrator or SYSTEM rights, can stop, debug or modify the agent; Al-Khandaq detects and reports this (above), it does not prevent it. The same holds for root on Linux and macOS.
- No kernel component. Real-time file scanning on Windows is post-write (ReadDirectoryChangesW), not a minifilter; Linux can block execution with fanotify (opt-in, root).
- The audit key lives on the machine. DPAPI machine scope and the data folder's DACL keep other users from it, not an administrator. Keep logs off the machine if you need evidence that survives an administrator.
- Unsigned feeds. KEV and OSV are trusted as served by CISA and osv.dev over TLS; a compromise of those services is out of scope.
- Windows service DACL. BUILTIN\Administrators keep full control on purpose: denying them would only make them take ownership first.
- Fuzzing has run only briefly; the targets run for a minute each in continuous integration.