command_shield library
command_shield — security-first command-line analysis.
Parse, normalize, classify, analyse and policy-validate shell commands into ALLOW / REVIEW / DENY decisions without ever executing them. Designed for AI agents, remote executors, CI/CD systems and sandboxed runners that need an explainable, deterministic verdict before a command runs.
The typical entry point is CommandShield:
import 'package:command_shield/command_shield.dart';
void main() {
final shield = CommandShield();
final result = shield.validate('git status', syntax: CommandSyntax.bash);
print(result.decision); // CommandDecision.allow
}
Important. Command validation reduces risk but is not a substitute for sandboxing, containers, least privilege or process isolation. Treat it as one defence-in-depth layer, never the only one.
Classes
- Analyzer
- Orchestrates the post-parse stages of the pipeline: normalization → capability detection → effect classification → security analysis, producing a single CommandAnalysis.
- ArchiveKnowledge
- Knowledge about archive and bundling tools.
- ArgPredicate
- Matches according to an arbitrary test function — the escape hatch for logic that the declarative matchers cannot express.
- ArgRegex
- Matches when any argument matches pattern.
- ArgumentMatch
- A predicate over the argument tokens of an invocation, used by ArgumentRule to decide whether the rule applies.
- ArgumentPatternPolicy
- Rejects commands whose arguments match a forbidden regular expression.
- ArgumentRule
- A rule that attributes capabilities (and an optional elevated risk) when match applies to the invocation's arguments.
- BashParser
- The GNU Bourne-Again Shell parser.
- CapabilityDetector
- Detects the CommandCapabilitys exercised by a parsed command tree.
- CommandAnalysis
- The complete, immutable result of analysing a command.
- CommandChain
- A chain of commands joined by a single ChainOperator.
- CommandFamilies
- Shared helpers for recognising command families inside detectors.
- CommandInvocation
- A single command invocation: an executable plus its arguments.
- CommandKnowledge
- All knowledge the base holds about a single command (executable).
- CommandKnowledgeBase
- A plugin-composed knowledge base mapping commands (and their sub-commands and arguments) to the CommandCapabilitys they exercise and a SecurityLevel risk hint.
- CommandKnowledgePlugin
- A self-contained unit of command knowledge.
- CommandKnowledgeResult
- The full result of analysing a single command invocation against the command knowledge base.
- CommandNode
- The root of the typed command abstract-syntax tree (AST).
- CommandParser
- Base class for all command parsers.
- CommandPolicy
- A composable validation rule that turns a CommandAnalysis into a CommandResult.
- CommandResult
- The outcome of validating a command against a policy.
- CommandScript
- A script: an ordered sequence of top-level commands, typically separated by newlines.
- CommandShield
- The high-level entry point of the package.
- CommandSubstitution
-
A command substitution:
$(...)or back-tick`...`whose output is substituted into the surrounding command. - CommandSubstitutionDetector
-
Detects command substitution:
$(...)and back-tick`...`. - CompressionKnowledge
- Knowledge about single-stream compressors and zip tools.
- ContainerKnowledge
- Knowledge about container engines and orchestration tools.
- CryptoKnowledge
- Knowledge about encryption, signing and encoding tools.
- DangerousCharacterPolicy
- Rejects commands whose raw text contains shell control characters/sequences.
- DangerousOperatorDetector
-
Detects shell control operators in the raw command:
;,&&,||,|,>,>>,<,<<. - DartFlutterKnowledge
- Knowledge about the Dart and Flutter command-line tools.
- DatabaseKnowledge
- Knowledge about database clients and dump/restore tools.
- DestructiveCommandDetector
-
Detects destructive deletion commands (
rm,rmdir,del,erase,shred,unlink, ...), escalating severity based on flags and targets. - EditorKnowledge
- Knowledge about interactive text editors.
- EffectClassifier
- Maps a set of CommandCapabilitys to a set of CommandEffects.
- EnvExpansionDetector
-
Detects environment-variable expansion:
$HOME,${HOME},%USERPROFILE%and$env:USERPROFILE. - EnvironmentKnowledge
- Knowledge about environment-variable utilities.
- EnvironmentVariableExpansionPolicy
-
Flags commands that expand environment variables (
$HOME,${HOME},%USERPROFILE%,$env:USERPROFILE). - EnvironmentVariableReference
-
A reference to an environment variable, e.g.
$HOME,${HOME},%USERPROFILE%or$env:USERPROFILE. - ExactFlag
- Matches when any argument is exactly equal to one of flags.
- ExecutableAllowListPolicy
- Permits only commands whose every (normalized) executable is on an explicit allow-list. Any other executable yields onViolation (default CommandDecision.deny).
- ExecutableBlockListPolicy
- Rejects commands that invoke any executable on a block-list.
- FilesystemKnowledge
- Knowledge about filesystem inspection and manipulation commands.
- GenericParser
- The safest parser: pure tokenization with no interpretation of shell metacharacters.
- GitKnowledge
-
Knowledge about the
gitversion-control tool and its sub-commands. - HashKnowledge
- Knowledge about checksum and digest tools.
- KnowledgeMatch
- A mutable accumulator passed to declarative rules and KnowledgeRefiner hooks while a command is being analysed.
- KnowledgeRiskDetector
- Surfaces the risk hints carried by the CommandKnowledgeBase as security findings.
- LengthLimitPolicy
- Flags commands whose raw length exceeds maxLength characters.
- ListKnowledgePlugin
- A CommandKnowledgePlugin backed by a fixed list of entries, so callers can register ad-hoc knowledge without declaring a class.
- NetworkKnowledge
- Knowledge about network clients, transfer tools and cloud CLIs.
- NormalizationRule
- A single, named rule that maps a raw executable name to a canonical form.
- Normalizer
- Normalizes executable names to a canonical form so downstream stages can reason about commands regardless of how they were written.
- PackageManagerKnowledge
- Knowledge about software package managers.
- ParseDiagnostic
- A single diagnostic produced while parsing a command line.
- ParseResult
- The outcome of parsing a raw command string with a CommandSyntax.
- ParserFactory
- Resolves the CommandParser for a given CommandSyntax.
- PathTraversalDetector
-
Detects path-traversal sequences (
../,..\) in command arguments. - PathTraversalPolicy
-
Flags commands that contain path-traversal sequences (
../,..\). - Pipeline
-
A pipeline of commands connected by
|, where each command's standard output is fed to the next command's standard input. - PolicySet
- A composite policy that evaluates several policies and merges their results into a single, most-restrictive CommandResult.
- PosixParser
- The POSIX shell parser (the portable subset shared with bash).
- PowerShellParser
- Parser for Microsoft PowerShell.
- PrefixFlag
- Matches when any argument equals, or starts with, one of prefixes.
- PrivilegeEscalationDetector
-
Detects privilege-escalation commands:
sudo,su,runas,doas,pkexec. - ProcessKnowledge
- Knowledge about process inspection and control commands.
- QuoteAwareSplitter
- A lightweight, quote- and escape-aware word splitter shared by the parsers.
- RedirectionNode
-
An I/O redirection such as
> out.txt,>> log,< in.txtor2> err. - RemoteExecDetector
- Detects the "download and execute" anti-pattern, where content fetched from the network is piped directly into a shell or interpreter.
- RiskThresholdPolicy
- Maps the analysis's overall SecurityLevel to a CommandDecision using two thresholds.
- SecurityAnalyzer
- Runs the full suite of security detectors and aggregates their findings.
- SecurityContext
- Immutable input shared by all SecurityDetectors.
- SecurityDetector
- A single security detector. Implementations are pure and deterministic and must never execute anything.
- SecurityFinding
- A single, explainable security observation about a command.
- SecurityReport
- The result of running every SecurityDetector over a command.
- ShellExecutionDetector
-
Detects invocations that execute an arbitrary command string supplied as an
argument:
bash -c,sh -c,cmd /c,powershell -Command, etc. - ShellExecutionPolicy
-
Flags inline shell execution (
bash -c,sh -c,cmd /c,powershell -Command,-EncodedCommand). - ShellKnowledge
- Knowledge about shells, language interpreters/build tools, and the wrapper commands that re-dispatch to another command in their arguments.
- ShellParser
- Shared implementation for POSIX/Bash-family shells.
- SubcommandRule
- A rule that attributes capabilities (and an optional elevated risk) when the first non-flag argument — the "sub-command" — is one of names.
- SystemConfigKnowledge
- Knowledge about commands that change system or security configuration.
- TokenPresent
- Matches when any of tokens appears anywhere in the arguments.
- WindowsCmdParser
-
Parser for the Windows Command Prompt (
cmd.exe) batch syntax. - WindowsKnowledge
-
Knowledge about Windows-specific commands:
cmdbuiltins, PowerShell cmdlets and system tools. - WrapperSpec
-
Describes how a wrapper command (such as
sudoorenv) locates the command it ultimately executes within its own arguments.
Enums
- ChainOperator
- The operator that joins the commands of a CommandChain.
- CommandCapability
- A discrete capability a command may exercise.
- CommandDecision
- The final verdict produced by the policy engine for a command.
- CommandEffect
- A human-readable, high-level summary of what a command does.
- CommandPlatform
- The operating systems on which a command is commonly available.
- CommandSyntax
- The command-line syntax a raw command string is written in.
- DiagnosticSeverity
- The severity of a ParseDiagnostic.
- KnowledgeCategory
- The broad domain a command belongs to.
- RedirectionType
- The kind of I/O redirection described by a RedirectionNode.
- SecurityLevel
- The severity of a security concern, from least to most dangerous.
Extensions
- CommandDecisionCombine on CommandDecision
- Ordering helpers for CommandDecision.
- SecurityLevelComparison on SecurityLevel
- Ordering helpers for SecurityLevel.
Constants
-
defaultKnowledgePlugins
→ const List<
CommandKnowledgePlugin> -
The built-in plugins composed by
CommandKnowledgeBasewhen no explicit set is supplied (or whenincludeDefaultsis left enabled).
Properties
- aliasRule → NormalizationRule
-
Maps known executable aliases to a canonical command name.
final
-
defaultNormalizationRules
→ List<
NormalizationRule> -
The built-in, ordered normalization rules used by Normalizer.standard.
final
- stripDirectoryRule → NormalizationRule
-
Removes any leading directory component from an executable path.
final
- stripWindowsExtensionRule → NormalizationRule
-
Strips common Windows executable/script extensions.
final
- versionSuffixRule → NormalizationRule
-
Collapses versioned interpreter names to their base name.
final
Functions
-
buildDefaultPolicy(
) → PolicySet -
Builds the default PolicySet used by
CommandShieldwhen no custom policy is supplied.
Typedefs
-
KnowledgeRefiner
= void Function(List<
String> args, KnowledgeMatch match) -
An optional Dart hook for command logic that the declarative rules cannot
express. It receives the invocation
argsand mutatesmatchdirectly.