diff --git a/powershell/ql/src/queries/security/cwe-494/DownloadWithoutIntegrityCheck.qhelp b/powershell/ql/src/queries/security/cwe-494/DownloadWithoutIntegrityCheck.qhelp
index 9af562220470..433696cc589e 100644
--- a/powershell/ql/src/queries/security/cwe-494/DownloadWithoutIntegrityCheck.qhelp
+++ b/powershell/ql/src/queries/security/cwe-494/DownloadWithoutIntegrityCheck.qhelp
@@ -6,15 +6,29 @@
- Downloading an artifact (such as an executable, installer, archive, or script) and then
- using it without verifying its integrity allows an attacker who can tamper with the artifact
- to execute arbitrary code on the machine. Even when the artifact is retrieved from a trusted
- source such as GitHub over HTTPS, the contents can still be replaced through a compromised
- account, a malicious release asset, a poisoned cache or mirror, or a man-in-the-middle attack.
+ An attacker who can influence a downloaded executable, installer, module, assembly, or script
+ can execute code when that artifact is run or loaded without effective verification.
+ This query requires both an insecure or explicitly modeled remotely controlled origin and
+ a downstream code-execution or code-loading operation.
- Without an integrity check, there is no guarantee that the bytes that were downloaded are the
- bytes that were intended, so the downloaded artifact must not be trusted.
+ Plain HTTP downloads are analyzed under an on-path-attacker threat model. Remote-input
+ models can also identify downloads whose entire URL comes from an inbound request.
+ Ordinary function parameters, environment variables, and generic HTTPS download responses
+ are not automatically considered attacker controlled.
+
+
+ Fixed HTTPS origins, download-only and extraction-only operations, and ordinary configuration
+ retrieval are outside this query's strict scope. These exclusions are not proof that the
+ corresponding operations are safe. Hostname substrings and build, test, or dependency paths
+ are not used to establish severity or trust.
+
+
+ The query tracks modeled file copies, moves, renames, file reads and writes, and archive members
+ constructed below an extraction directory. File lifecycle and verification paths are evaluated
+ within a control-flow scope; custom filesystem wrappers and runtime-computed paths may not be
+ resolved. Findings identify high-impact candidates, not a guarantee of high severity in every
+ deployment.
@@ -27,12 +41,27 @@
value; otherwise, discard it and fail. Where available, prefer verifying a digital signature of
the artifact in addition to, or instead of, a plain hash comparison.
+
+ Computing or logging a hash is not an integrity check by itself. Compare the complete digest
+ against a trusted expected value, and ensure that a mismatch stops execution before the artifact
+ is installed, loaded, extracted, or run. An optional check, a swallowed exception, or a check
+ performed only after the artifact has been used does not provide this protection.
+
+
+ Signature verification must also establish the intended publisher. For Authenticode, check
+ that the signature is valid and that the signer certificate matches a trusted pinned
+ certificate thumbprint. Modeled native checks include GPG with a fixed
+ --assert-signer fingerprint and Cosign blob verification with fixed certificate
+ identity and OIDC issuer. The native verifier's successful exit code must be enforced before
+ use; merely invoking a signature tool or inspecting its output does not verify the artifact.
+ A constant path to a public-key file alone does not establish that the key is trusted.
+
- In the following example, an executable is downloaded from GitHub and then run directly. Because
- the artifact is never verified, a tampered download is executed without detection.
+ In the following example, an executable is downloaded over HTTP and then run directly.
+ An on-path attacker can replace the executable, which is never verified.
@@ -57,6 +86,14 @@
Microsoft Learn:
Get-FileHash.
+
+ GnuPG:
+ GPG configuration options.
+
+
+ Sigstore:
+ Verifying signatures.
+
diff --git a/powershell/ql/src/queries/security/cwe-494/DownloadWithoutIntegrityCheck.ql b/powershell/ql/src/queries/security/cwe-494/DownloadWithoutIntegrityCheck.ql
index f9c1d98aeab4..ba0c9ab38534 100644
--- a/powershell/ql/src/queries/security/cwe-494/DownloadWithoutIntegrityCheck.ql
+++ b/powershell/ql/src/queries/security/cwe-494/DownloadWithoutIntegrityCheck.ql
@@ -1,6 +1,6 @@
/**
- * @name Unvalidated Artifact Download
- * @description Download of artifact without integrity check.
+ * @name Execution of an attacker-influenced download without verification
+ * @description Code from an insecure or attacker-controlled download is executed without an effective integrity or publisher check.
* @kind problem
* @problem.severity warning
* @security-severity 7.5
@@ -14,132 +14,1063 @@
import powershell
import semmle.code.powershell.dataflow.DataFlow
import semmle.code.powershell.dataflow.TaintTracking
+import semmle.code.powershell.controlflow.ControlFlowGraph
+import semmle.code.powershell.controlflow.CfgNodes
+import semmle.code.powershell.dataflow.flowsources.Remote
-/** Holds if `s` looks like a URL pointing at a trusted artifact host. */
-bindingset[s]
-predicate isTrustedArtifactHost(string s) {
- s.matches([
- "%github%",
- "%gitlab%",
- "%bitbucket%",
- "%sourceforge%",
- "%powershellgallery%",
- "%nuget%",
- "%npmjs%",
- "%pypi%",
- "%repo1.maven%",
- "%repo.maven.apache%",
- "%blob.core.windows%",
- "%amazonaws%",
- "%googleapis%",
- "%azure%",
- "%visualstudio%",
- "%jfrog%",
- "%artifactory%"
- ])
-}
-
-/** A data-flow node that is tainted by a string constant looking like an artifact URL. */
-class ArtifactUrl extends DataFlow::Node {
- ArtifactUrl() {
- exists(DataFlow::Node source, string s |
- TaintTracking::localTaint(source, this) and
- s =
- [
- source.asExpr().getValue().asString(),
- source.asExpr().getExpr().(ExpandableStringExpr).getUnexpandedValue()
- ].toLowerCase() and
- isTrustedArtifactHost(s) and
- // Exclude API metadata endpoints (e.g. api.github.com/.../releases/latest),
- // which return JSON metadata rather than a downloadable artifact.
- not s.matches(["%api.github.com%", "%api.bitbucket.org%"])
- )
- }
+/** Gets a cmdlet's named argument, or its positional argument when not named. */
+bindingset[name, position]
+DataFlow::Node getArgument(DataFlow::CallNode call, string name, int position) {
+ result = call.getNamedArgument(name)
+ or
+ not call.hasNamedArgument(name) and
+ result = call.getPositionalArgument(position)
}
-/**
- * A call that downloads an artifact from a trusted host.
- *
- * This covers cmdlets and their aliases (`Invoke-WebRequest`/`iwr`,
- * `Invoke-RestMethod`/`irm`, `Start-BitsTransfer`), native download tools
- * (`curl`, `wget`, `azcopy`, `aria2c`) and the .NET `WebClient`/`HttpClient`
- * download methods. The URL may be passed as a named argument (e.g. `-Uri`,
- * `-Source`), positionally, or as a method argument.
- */
-class DownloadCall extends DataFlow::CallNode {
- ArtifactUrl url;
+/** Gets a pipeline argument without confusing it with the command's ordinary arguments. */
+DataFlow::Node getPipelineInput(DataFlow::CallNode call) {
+ result.asExpr() = call.getCallNode().getPipelineArgument()
+}
+/** Holds if `node` has an explicitly known .NET receiver type. */
+bindingset[type]
+predicate hasType(DataFlow::Node node, string type) {
+ exists(DataFlow::ObjectCreationNode creation |
+ (
+ creation.getLowerCaseConstructedTypeName() = type.toLowerCase()
+ or
+ creation.getQualifier().asExpr().getExpr().(TypeNameExpr).getPossiblyQualifiedName() =
+ type.toLowerCase()
+ ) and
+ DataFlow::localFlow(creation, node)
+ )
+ or
+ exists(DataFlow::Node parameter |
+ parameter.asParameter().getAnAttribute().(TypeConstraint).getName().toLowerCase() =
+ type.toLowerCase() and
+ DataFlow::localFlow(parameter, node)
+ )
+}
+
+predicate isDotNetDownload(DataFlow::CallNode call) {
+ call.getAName() =
+ [
+ "DownloadFile", "DownloadFileAsync", "DownloadFileTaskAsync", "DownloadData",
+ "DownloadDataAsync", "DownloadDataTaskAsync", "DownloadString", "DownloadStringAsync",
+ "DownloadStringTaskAsync", "GetStringAsync", "GetByteArrayAsync", "GetStreamAsync"
+ ]
+}
+
+/** A download, with URL and destination roles modeled separately. */
+class DownloadCall extends DataFlow::CallNode {
DownloadCall() {
this.getAName() =
[
- // cmdlets and aliases
- "Invoke-WebRequest", "iwr", "Invoke-RestMethod", "irm", "Start-BitsTransfer",
- // native command-line download tools
- "curl", "curl.exe", "wget", "wget.exe", "azcopy", "azcopy.exe", "aria2c", "aria2c.exe",
- // .NET WebClient / HttpClient download methods
- "DownloadFile", "DownloadFileAsync", "DownloadFileTaskAsync", "DownloadData",
- "DownloadDataAsync", "DownloadDataTaskAsync", "DownloadString", "DownloadStringAsync",
- "GetByteArrayAsync", "GetStreamAsync"
- ] and
- url = this.getAnArgument()
- }
-
- /**
- * Gets the argument that names the file the artifact is written to, if any.
- * Downloads that consume the response inline (e.g. `irm ... | iex`) have no
- * such argument.
- */
+ "Invoke-WebRequest", "iwr", "Invoke-RestMethod", "irm", "curl", "wget",
+ "Start-BitsTransfer", "curl.exe", "wget.exe", "azcopy", "azcopy.exe", "aria2c", "aria2c.exe"
+ ]
+ or
+ isDotNetDownload(this) and
+ hasType(this.getQualifier(),
+ ["System.Net.WebClient", "Net.WebClient", "System.Net.Http.HttpClient", "Net.Http.HttpClient"])
+ }
+
+ DataFlow::Node getUrl() {
+ this.getAName() = ["Invoke-WebRequest", "iwr", "Invoke-RestMethod", "irm", "curl", "wget"] and
+ result = getArgument(this, "uri", 0)
+ or
+ this.getAName() = "Start-BitsTransfer" and
+ result = getArgument(this, "source", 0)
+ or
+ this.getAName() = ["curl.exe", "wget.exe", "aria2c", "aria2c.exe"] and
+ result = [this.getNamedArgument("url"), this.getPositionalArgument(0)]
+ or
+ this.getAName() = ["azcopy", "azcopy.exe"] and
+ this.getPositionalArgument(0).asExpr().getValue().asString().toLowerCase() = "copy" and
+ result = this.getPositionalArgument(1)
+ or
+ this.asExpr().getExpr() instanceof InvokeMemberExpr and
+ result = this.getArgument(0)
+ }
+
DataFlow::Node getOutFileArg() {
- result =
- this.getNamedArgument([
- "outfile", "destination", "outputfile", "outpath", "literalpath", "path", "o"
- ])
+ this.getAName() = ["Invoke-WebRequest", "iwr", "Invoke-RestMethod", "irm", "curl", "wget"] and
+ result = this.getNamedArgument("outfile")
+ or
+ this.getAName() = "Start-BitsTransfer" and
+ result = getArgument(this, "destination", 1)
+ or
+ this.getAName() = ["curl.exe", "wget.exe", "aria2c", "aria2c.exe"] and
+ result = this.getNamedArgument(["o", "output"])
+ or
+ this.getAName() = ["azcopy", "azcopy.exe"] and
+ result = this.getPositionalArgument(2)
or
- // WebClient.DownloadFile(url, destinationFile): the destination is the 2nd argument.
this.getAName() = ["DownloadFile", "DownloadFileAsync", "DownloadFileTaskAsync"] and
result = this.getArgument(1)
}
+
+ /** Gets returned content; an ordinary file download's status output is not its body. */
+ DataFlow::Node getContent() {
+ not exists(this.getOutFileArg()) and
+ not this.getAName() =
+ ["Start-BitsTransfer", "wget.exe", "azcopy", "azcopy.exe", "aria2c", "aria2c.exe"] and
+ result = this
+ }
}
-/**
- * A call that verifies the integrity of a file, by computing/comparing a hash
- * or by checking a signature.
- */
-class IntegrityCheck extends DataFlow::CallNode {
- IntegrityCheck() {
+/** Holds if an entire expression is known to start with the insecure HTTP scheme. */
+predicate hasHttpPrefix(Expr expr) {
+ [
+ expr.getValue().asString(),
+ expr.(ExpandableStringExpr).getUnexpandedValue()
+ ].toLowerCase().matches("http://%")
+ or
+ expr instanceof AddExpr and
+ hasHttpPrefix(expr.(AddExpr).getLeft())
+}
+
+/** Explicit inbound request data, not an arbitrary parameter or environment variable. */
+class RequestUrlInput extends DataFlow::Node {
+ RequestUrlInput() {
+ exists(IndexExpr index, MemberExpr query, DataFlow::Node receiver, DataFlow::Node collection |
+ query.memberNameMatches("QueryString") and
+ receiver.asExpr().getExpr() = query.getQualifier() and
+ hasType(receiver, ["System.Net.HttpListenerRequest", "Net.HttpListenerRequest"]) and
+ collection.asExpr().getExpr() = query and
+ DataFlow::localFlow(collection, any(DataFlow::Node n | n.asExpr().getExpr() = index.getBase())) and
+ this.asExpr().getExpr() = index
+ )
+ }
+}
+
+module HttpOriginConf implements DataFlow::ConfigSig {
+ predicate isSource(DataFlow::Node source) { hasHttpPrefix(source.asExpr().getExpr()) }
+
+ predicate isSink(DataFlow::Node sink) { sink = any(DownloadCall d).getUrl() }
+}
+
+module HttpOriginFlow = DataFlow::Global;
+
+module RemoteOriginConf implements DataFlow::ConfigSig {
+ predicate isSource(DataFlow::Node source) {
+ source instanceof RequestUrlInput
+ or
+ source instanceof RemoteFlowSource and
+ // Generic download responses do not establish control by a less-trusted caller.
+ not source instanceof DownloadCall and
+ not isDotNetDownload(source.(DataFlow::CallNode))
+ }
+
+ predicate isSink(DataFlow::Node sink) { sink = any(DownloadCall d).getUrl() }
+}
+
+module RemoteOriginFlow = DataFlow::Global;
+
+/** A call that computes a hash, rather than verifying a signature. */
+class HashCheck extends DataFlow::CallNode {
+ HashCheck() {
+ this.getAName() = ["Get-FileHash", "gfh", "certutil", "certutil.exe", "ComputeHash"]
+ }
+
+ /** Gets the path of the file whose contents are hashed. */
+ DataFlow::Node getHashedFile() {
+ this.getAName() = ["Get-FileHash", "gfh"] and
+ result = [this.getNamedArgument(["path", "literalpath"]), this.getPositionalArgument(0)]
+ or
+ this.getAName() = ["certutil", "certutil.exe"] and
+ result = this.getNamedArgument("hashfile")
+ or
+ this.getAName() = "ComputeHash" and
+ not exists(this.getArgument(1)) and
+ exists(DataFlow::CallNode read |
+ read.getAName() = ["ReadAllBytes", "OpenRead"] and
+ DataFlow::localFlow(read, this.getArgument(0)) and
+ result = read.getArgument(0)
+ )
+ }
+
+ /** Gets the computed digest, excluding unrelated properties of a hash object. */
+ DataFlow::Node getDigest() {
+ this.getAName() = ["Get-FileHash", "gfh"] and
+ exists(MemberExpr member, DataFlow::Node qualifier |
+ member.memberNameMatches("Hash") and
+ qualifier.asExpr().getExpr() = member.getQualifier() and
+ DataFlow::localFlow(this, qualifier) and
+ result.asExpr().getExpr() = member
+ )
+ or
+ this.getAName() = ["certutil", "certutil.exe", "ComputeHash"] and
+ result = this
+ }
+}
+
+/** Holds if a static method is invoked on the given .NET type. */
+bindingset[type]
+predicate isStaticCall(DataFlow::CallNode call, string type) {
+ call.getQualifier().asExpr().getExpr().(TypeNameExpr).getPossiblyQualifiedName() =
+ type.toLowerCase()
+}
+
+/** Gets a cmdlet's source file, without accepting unrelated arguments as files. */
+DataFlow::Node getFileArgument(DataFlow::CallNode call) {
+ result = call.getNamedArgument("literalpath")
+ or
+ not call.hasNamedArgument("literalpath") and
+ result = getArgument(call, "path", 0)
+}
+
+/** A read of file contents, not a use of the path string as file contents. */
+class FileRead extends DataFlow::CallNode {
+ FileRead() {
+ this.getAName() = ["Get-Content", "gc", "cat", "type"]
+ or
+ this.getAName() = ["ReadAllBytes", "ReadAllText", "OpenRead"] and
+ isStaticCall(this, ["System.IO.File", "IO.File"])
+ }
+
+ DataFlow::Node getFile() {
+ this.asExpr().getExpr() instanceof InvokeMemberExpr and result = this.getArgument(0)
+ or
+ not this.asExpr().getExpr() instanceof InvokeMemberExpr and result = getFileArgument(this)
+ or
+ // Unknown switch binding currently attaches a following positional path to -Raw.
+ this.getAName() = ["Get-Content", "gc", "cat", "type"] and
+ not exists(getFileArgument(this)) and
+ result = this.getNamedArgument("raw")
+ }
+}
+
+/** A file-preserving copy, move, or rename. */
+class FileTransfer extends DataFlow::CallNode {
+ FileTransfer() {
this.getAName() =
[
- "Get-FileHash", "gfh", // hash a file
- "certutil", "certutil.exe", // certutil -hashfile SHA256
- "ComputeHash", // [SHA256]::Create().ComputeHash(...)
- "Get-AuthenticodeSignature", "Test-FileCatalog", // signature / catalog checks
- "cosign", "cosign.exe", "gpg", "gpg.exe" // external signature verification
+ "Copy-Item", "cp", "copy", "cpi", "Move-Item", "mv", "move", "mi", "Rename-Item", "ren",
+ "rni"
]
}
- /** Gets an argument referring to the file whose integrity is being checked. */
- DataFlow::Node getFile() { result = this.getAnArgument() }
+ DataFlow::Node getInput() { result = getFileArgument(this) }
+
+ DataFlow::Node getOutput() {
+ not this.getAName() = ["Rename-Item", "ren", "rni"] and
+ result = getArgument(this, "destination", 1)
+ or
+ this.hasNamedArgument("passthru") and
+ exists(MemberExpr member, DataFlow::Node receiver |
+ member.memberNameMatches("FullName") and
+ receiver.asExpr().getExpr() = member.getQualifier() and
+ DataFlow::localFlow(this, receiver) and
+ result.asExpr().getExpr() = member
+ )
+ }
+
+ predicate removesInput() {
+ this.getAName() = ["Move-Item", "mv", "move", "mi", "Rename-Item", "ren", "rni"]
+ }
+}
+
+/** An overwrite of a file with content from an expression or pipeline. */
+class FileWrite extends DataFlow::CallNode {
+ FileWrite() {
+ this.getAName() = ["Set-Content", "sc"]
+ or
+ this.getAName() = "Out-File" and not this.hasNamedArgument("append")
+ or
+ this.getAName() = ["WriteAllBytes", "WriteAllText"] and
+ isStaticCall(this, ["System.IO.File", "IO.File"])
+ }
+
+ DataFlow::Node getFile() {
+ this.getAName() = ["Set-Content", "sc"] and result = getFileArgument(this)
+ or
+ this.getAName() = "Out-File" and result = getArgument(this, "filepath", 0)
+ or
+ this.asExpr().getExpr() instanceof InvokeMemberExpr and result = this.getArgument(0)
+ }
+
+ DataFlow::Node getContent() {
+ this.getAName() = ["Set-Content", "sc"] and
+ result = [getArgument(this, "value", 1), getPipelineInput(this)]
+ or
+ this.getAName() = "Out-File" and
+ result = [this.getNamedArgument("inputobject"), getPipelineInput(this)]
+ or
+ this.asExpr().getExpr() instanceof InvokeMemberExpr and result = this.getArgument(1)
+ }
+}
+
+/** An extraction operation. Extraction alone is deliberately not an execution sink. */
+class ArchiveExtraction extends DataFlow::CallNode {
+ ArchiveExtraction() {
+ this.getAName() = "Expand-Archive"
+ or
+ this.getAName() = "ExtractToDirectory" and
+ isStaticCall(this, ["System.IO.Compression.ZipFile", "IO.Compression.ZipFile"])
+ }
+
+ DataFlow::Node getFile() {
+ this.getAName() = "Expand-Archive" and result = getFileArgument(this)
+ or
+ this.getAName() = "ExtractToDirectory" and result = this.getArgument(0)
+ }
+
+ DataFlow::Node getDirectory() {
+ this.getAName() = "Expand-Archive" and result = getArgument(this, "destinationpath", 1)
+ or
+ this.getAName() = "ExtractToDirectory" and result = this.getArgument(1)
+ }
+}
+
+/** A path constructed under a directory using a fixed, non-traversing relative name. */
+class ChildPath extends DataFlow::CallNode {
+ ChildPath() {
+ this.getAName() = "Join-Path"
+ or
+ this.getAName() = "Combine" and isStaticCall(this, ["System.IO.Path", "IO.Path"])
+ }
+
+ DataFlow::Node getDirectory() {
+ this.getAName() = "Join-Path" and result = getArgument(this, "path", 0)
+ or
+ this.getAName() = "Combine" and result = this.getArgument(0)
+ }
+
+ DataFlow::Node getChild() {
+ this.getAName() = "Join-Path" and
+ not this.hasNamedArgument("additionalchildpath") and
+ not exists(this.getPositionalArgument(2)) and
+ result = getArgument(this, "childpath", 1)
+ or
+ this.getAName() = "Combine" and
+ not exists(this.getArgument(2)) and
+ result = this.getArgument(1)
+ }
+
+ predicate isRelative() {
+ exists(string child |
+ child = this.getChild().asExpr().getValue().asString() and
+ child != "" and
+ not child.matches(["/%", "\\%", "%:%", "%..%"])
+ )
+ }
+}
+
+/** A use that executes downloaded code, rather than merely retrieving or unpacking it. */
+predicate isExecutablePath(DataFlow::Node node) {
+ exists(DataFlow::Node literal, string path |
+ DataFlow::localFlow(literal, node) and
+ path =
+ [
+ literal.asExpr().getValue().asString(),
+ literal.asExpr().getExpr().(ExpandableStringExpr).getUnexpandedValue()
+ ].toLowerCase() and
+ path.matches(["%.exe", "%.com", "%.cmd", "%.bat", "%.msi"])
+ )
+ or
+ exists(ChildPath path | DataFlow::localFlow(path, node) and isExecutablePath(path.getChild()))
+}
+
+class CodeExecution extends DataFlow::CallNode {
+ CodeExecution() {
+ this instanceof DataFlow::CallOperatorNode or
+ this instanceof DataFlow::DotSourcingOperatorNode or
+ this.getAName() =
+ [
+ "Import-Module", "ipmo", "Start-Process", "saps", "start", "Add-Type", "LoadFrom",
+ "LoadFile", "powershell", "powershell.exe", "pwsh", "pwsh.exe", "msiexec", "msiexec.exe",
+ "Invoke-Expression", "iex", "Load"
+ ]
+ }
+
+ DataFlow::Node getFile() {
+ this instanceof DataFlow::CallOperatorNode and
+ result = this.(DataFlow::CallOperatorNode).getCommand()
+ or
+ this instanceof DataFlow::DotSourcingOperatorNode and
+ result = this.(DataFlow::DotSourcingOperatorNode).getCommand()
+ or
+ this.getAName() = ["Import-Module", "ipmo"] and result = getArgument(this, "name", 0)
+ or
+ this.getAName() = ["Start-Process", "saps", "start"] and
+ result = getArgument(this, "filepath", 0) and
+ isExecutablePath(result)
+ or
+ this.getAName() = "Add-Type" and result = this.getNamedArgument(["path", "literalpath"])
+ or
+ this.getAName() = ["LoadFrom", "LoadFile"] and
+ isStaticCall(this, ["System.Reflection.Assembly", "Reflection.Assembly"]) and
+ result = this.getArgument(0)
+ or
+ this.getAName() = ["powershell", "powershell.exe", "pwsh", "pwsh.exe"] and
+ result = this.getNamedArgument("file")
+ or
+ this.getAName() = ["msiexec", "msiexec.exe"] and
+ exists(int i |
+ this.getPositionalArgument(i).asExpr().getValue().asString().toLowerCase() =
+ ["/i", "/package"] and
+ result = this.getPositionalArgument(i + 1)
+ )
+ or
+ this.getAName() = ["Start-Process", "saps", "start"] and
+ exists(DataFlow::Node arguments, ArrayLiteral array, string host, string option, int i |
+ hasFixedValue(getArgument(this, "filepath", 0), host) and
+ DataFlow::localFlow(arguments, getArgument(this, "argumentlist", 1)) and
+ arguments.asExpr().getExpr() = array and
+ option = array.getExpr(i).getValue().asString().toLowerCase() and
+ (
+ host.toLowerCase() = ["msiexec", "msiexec.exe"] and option = ["/i", "/package"]
+ or
+ host.toLowerCase() = ["powershell", "powershell.exe", "pwsh", "pwsh.exe"] and
+ option = "-file"
+ ) and
+ result.asExpr().getExpr() = array.getExpr(i + 1)
+ )
+ }
+
+ DataFlow::Node getContent() {
+ this.getAName() = ["Invoke-Expression", "iex"] and
+ result = [getArgument(this, "command", 0), getPipelineInput(this)]
+ or
+ this.getAName() = "Load" and
+ isStaticCall(this, ["System.Reflection.Assembly", "Reflection.Assembly"]) and
+ result = this.getArgument(0)
+ or
+ this instanceof DataFlow::CallOperatorNode and
+ result = this.(DataFlow::CallOperatorNode).getCommand() and
+ exists(DataFlow::CallNode create |
+ create.getAName() = "Create" and
+ isStaticCall(create, ["System.Management.Automation.ScriptBlock", "ScriptBlock"]) and
+ DataFlow::localFlow(create, result)
+ )
+ }
+}
+
+module FileConf implements DataFlow::ConfigSig {
+ predicate isSource(DataFlow::Node source) {
+ source = any(DownloadCall d).getOutFileArg() or
+ source = any(FileTransfer t).getOutput() or
+ source = any(FileWrite w).getFile() or
+ source = any(ArchiveExtraction e).getDirectory() or
+ source instanceof ChildPath
+ }
+
+ predicate isSink(DataFlow::Node sink) {
+ sink = any(DataFlow::CallNode c).getAnArgument() or
+ sink = any(CodeExecution c).getFile() or
+ sink = any(FileTransfer t).getOutput() or
+ sink = any(ChildPath p).getDirectory()
+ }
+}
+
+// File names retain their value; arbitrary string taint is not file identity.
+module FileFlow = DataFlow::Global;
+
+predicate sameFile(DataFlow::Node file, DataFlow::Node other) {
+ DataFlow::localFlow(file, other)
+ or
+ FileFlow::flow(file, other)
+ or
+ exists(string path |
+ path = file.asExpr().getValue().asString() and
+ path != "" and
+ path = other.asExpr().getValue().asString() and
+ file.asExpr().getScope() = other.asExpr().getScope()
+ )
+ or
+ exists(ChildPath first, ChildPath second, string child |
+ first.isRelative() and
+ second.isRelative() and
+ DataFlow::localFlow(first, file) and
+ DataFlow::localFlow(second, other) and
+ hasFixedValue(first.getChild(), child) and
+ hasFixedValue(second.getChild(), child) and
+ (
+ sameFile(first.getDirectory(), second.getDirectory())
+ or
+ sameFile(second.getDirectory(), first.getDirectory())
+ )
+ )
+}
+
+predicate archiveMember(DataFlow::Node directory, DataFlow::Node member) {
+ exists(ChildPath path |
+ path.isRelative() and
+ member = path and
+ (sameFile(directory, path.getDirectory()) or archiveMember(directory, path.getDirectory()))
+ )
+}
+
+/** Holds if `first` dominates and is evaluated before `second`. */
+predicate precedes(CfgNode first, CfgNode second) {
+ first.getBasicBlock().strictlyDominates(second.getBasicBlock())
+ or
+ exists(int i, int j |
+ first = first.getBasicBlock().getNode(i) and
+ second = first.getBasicBlock().getNode(j) and
+ i < j
+ )
+}
+
+/** Holds if `expected` is a fixed, complete hexadecimal digest. */
+predicate isExpectedDigest(DataFlow::Node expected) {
+ exists(DataFlow::LocalSourceNode constant | DataFlow::localFlow(constant, expected)) and
+ forall(DataFlow::LocalSourceNode constant | DataFlow::localFlow(constant, expected) |
+ exists(string digest |
+ digest = constant.asExpr().getValue().asString() and
+ digest.regexpMatch("[0-9a-fA-F]+") and
+ digest.length() = [32, 40, 64, 96, 128]
+ )
+ )
+}
+
+/** A value-preserving step or a lossless conversion of a digest to hexadecimal text. */
+predicate digestStep(DataFlow::Node input, DataFlow::Node output) {
+ DataFlow::localFlowStep(input, output)
+ or
+ exists(DataFlow::CallNode format, TypeNameExpr type |
+ format.getQualifier().asExpr().getExpr() = type and
+ (
+ type.getPossiblyQualifiedName() = ["System.BitConverter", "BitConverter"].toLowerCase() and
+ format.getAName() = "ToString"
+ or
+ type.getPossiblyQualifiedName() = ["System.Convert", "Convert"].toLowerCase() and
+ format.getAName() = "ToHexString"
+ ) and
+ input = format.getArgument(0) and
+ not exists(format.getArgument(1)) and
+ output = format
+ )
+ or
+ exists(DataFlow::CallNode format |
+ input = format.getQualifier() and
+ output = format and
+ (
+ format.getAName() = "Replace" and
+ format.getArgument(0).asExpr().getValue().asString() = "-" and
+ format.getArgument(1).asExpr().getValue().asString() = ""
+ or
+ format.getAName() = ["ToLower", "ToUpper", "ToLowerInvariant", "ToUpperInvariant"] and
+ not exists(format.getAnArgument())
+ )
+ )
+}
+
+/** A control-flow step that does not continue past an uncaught throw or exit. */
+predicate continuingStep(CfgNode node, CfgNode next) {
+ next = node.getASuccessor() and
+ // The CFG currently propagates the normal completion of a throw's operand.
+ not exists(Stmt abort |
+ (abort instanceof ThrowStmt or abort instanceof ExitStmt or abort instanceof ReturnStmt) and
+ node.getAstNode().getParent*() = abort and
+ not next.getAstNode().getParent*() = abort and
+ not abort.getParent+() instanceof TryStmt and
+ not exists(TrapStmt trap | abort.getParent+() = trap.getParent())
+ )
+}
+
+/** Holds if the entire compared value is derived from this digest, not a bypass value. */
+predicate isDigestValue(DataFlow::Node digest, DataFlow::Node actual) {
+ digestStep*(digest, actual) and
+ forall(DataFlow::LocalSourceNode origin | DataFlow::localFlow(origin, actual) |
+ digestStep*(digest, origin)
+ )
+}
+
+/** Facts established by a Boolean expression, independently of short-circuit CFG support. */
+predicate conditionImplies(Expr condition, boolean outcome, Expr tested, boolean required) {
+ condition = tested and required = [true, false] and outcome = required
+ or
+ conditionImplies(condition.(ParenExpr).getExpr(), outcome, tested, required)
+ or
+ exists(boolean inner |
+ (
+ outcome = true and inner = false
+ or
+ outcome = false and inner = true
+ ) and
+ conditionImplies(condition.(NotExpr).getOperand(), inner, tested, required)
+ )
+ or
+ outcome = true and
+ conditionImplies(condition.(LogicalAndExpr).getAnOperand(), true, tested, required)
+ or
+ outcome = false and
+ conditionImplies(condition.(LogicalOrExpr).getAnOperand(), false, tested, required)
+}
+
+predicate hashGuard(HashCheck check, ExprCfgNode guard, BooleanSuccessor success) {
+ exists(ComparisonExpr comparison, DataFlow::Node actual, DataFlow::Node expected |
+ actual.asExpr().getExpr() = comparison.getAnOperand() and
+ expected.asExpr().getExpr() = comparison.getAnOperand() and
+ actual != expected and
+ isDigestValue(check.getDigest(), actual) and
+ isExpectedDigest(expected) and
+ conditionImplies(guard.getExpr(), success.getValue(), comparison, equalityMatchesOn(comparison)) and
+ precedes(check.getCfgNode(), guard)
+ )
+}
+
+/** Gets a property read from a particular value, including through local aliases. */
+bindingset[name]
+DataFlow::Node getProperty(DataFlow::Node value, string name) {
+ exists(MemberExpr member, DataFlow::Node receiver |
+ member.memberNameMatches(name) and
+ receiver.asExpr().getExpr() = member.getQualifier() and
+ DataFlow::localFlow(value, receiver) and
+ result.asExpr().getExpr() = member
+ )
+}
+
+predicate hasFixedValue(DataFlow::Node value, string expected) {
+ exists(DataFlow::LocalSourceNode origin |
+ DataFlow::localFlow(origin, value) and expected = origin.asExpr().getValue().asString()
+ ) and
+ forall(DataFlow::LocalSourceNode origin | DataFlow::localFlow(origin, value) |
+ origin.asExpr().getValue().asString() = expected
+ )
+}
+
+boolean equalityMatchesOn(ComparisonExpr comparison) {
+ (comparison instanceof EqExpr or comparison instanceof CEqExpr) and
+ result = true
+ or
+ (comparison instanceof NeExpr or comparison instanceof CNeExpr) and
+ result = false
}
-module Conf implements DataFlow::ConfigSig {
- predicate isSource(DataFlow::Node source) { source = any(DownloadCall c).getOutFileArg() }
+/** A comparison of a particular value against an exact fixed string. */
+predicate stringGuard(
+ DataFlow::Node value, string expected, ExprCfgNode guard, BooleanSuccessor success
+) {
+ exists(ComparisonExpr comparison, DataFlow::Node actual, DataFlow::Node other |
+ actual.asExpr().getExpr() = comparison.getAnOperand() and
+ other.asExpr().getExpr() = comparison.getAnOperand() and
+ actual != other and
+ isDigestValue(value, actual) and
+ hasFixedValue(other, expected) and
+ guard.getExpr() = comparison and
+ success.getValue() = equalityMatchesOn(comparison)
+ )
+}
+
+/** Holds if reaching `target` requires passing this guard's successful branch. */
+predicate requiresSuccess(ExprCfgNode guard, BooleanSuccessor success, CfgNode target) {
+ precedes(guard, target) and
+ exists(guard.getASuccessor(success)) and
+ not exists(CfgNode failure |
+ failure = guard.getASuccessor(success.getDual()) and continuingStep*(failure, target)
+ )
+}
+
+/** A signature must establish both validity and the expected publisher's certificate. */
+predicate authenticodeGuard(DataFlow::CallNode check, ExprCfgNode guard, BooleanSuccessor success) {
+ check.getAName() = "Get-AuthenticodeSignature" and
+ exists(
+ ExprCfgNode status, ExprCfgNode signer, BooleanSuccessor statusOk, BooleanSuccessor signerOk,
+ DataFlow::Node fingerprint, ComparisonExpr comparison
+ |
+ stringGuard(getProperty(check, "Status"), "Valid", status, statusOk) and
+ fingerprint = getProperty(getProperty(check, "SignerCertificate"), "Thumbprint") and
+ signer.getExpr() = comparison and
+ exists(DataFlow::Node actual, DataFlow::Node expected |
+ actual.asExpr().getExpr() = comparison.getAnOperand() and
+ expected.asExpr().getExpr() = comparison.getAnOperand() and
+ actual != expected and
+ isDigestValue(fingerprint, actual) and
+ isExpectedDigest(expected)
+ ) and
+ signerOk.getValue() = equalityMatchesOn(comparison) and
+ precedes(check.getCfgNode(), status) and
+ precedes(check.getCfgNode(), signer) and
+ (
+ requiresSuccess(status, statusOk, signer) and guard = signer and success = signerOk
+ or
+ requiresSuccess(signer, signerOk, status) and guard = status and success = statusOk
+ or
+ conditionImplies(guard.getExpr(), success.getValue(), status.getExpr(), statusOk.getValue()) and
+ conditionImplies(guard.getExpr(), success.getValue(), signer.getExpr(), signerOk.getValue())
+ )
+ )
+}
- predicate isSink(DataFlow::Node sink) { sink = any(IntegrityCheck c).getFile() }
+/** Gets the value of a native command's long option, not a PowerShell parameter. */
+bindingset[name]
+DataFlow::Node getNativeOption(DataFlow::CallNode call, string name) {
+ not call.getPositionalArgument(_).asExpr().getValue().asString().matches("--" + name + "=%") and
+ (
+ result = call.getNamedArgument("-" + name) and
+ not call.getPositionalArgument(_).asExpr().getValue().asString() = "--" + name
+ or
+ not call.hasNamedArgument("-" + name) and
+ exists(int i |
+ i =
+ unique(int index |
+ call.getPositionalArgument(index).asExpr().getValue().asString() = "--" + name
+ |
+ index
+ ) and
+ result = call.getPositionalArgument(i + 1)
+ )
+ )
+}
+
+bindingset[name]
+predicate hasNativeOption(DataFlow::CallNode call, string name) {
+ call.hasNamedArgument("-" + name)
+ or
+ call.getPositionalArgument(_).asExpr().getValue().asString() = "--" + name
+ or
+ call.getPositionalArgument(_).asExpr().getValue().asString().matches("--" + name + "=%")
+}
+
+/** Gets an operand, excluding long options and their following values. */
+bindingset[position]
+DataFlow::Node getNativeOperand(DataFlow::CallNode call, int position) {
+ result =
+ rank[position + 1](DataFlow::Node operand, int i |
+ operand = call.getPositionalArgument(i) and
+ not operand.asExpr().getValue().asString().matches("--%") and
+ not call.getPositionalArgument(i - 1).asExpr().getValue().asString().matches("--%")
+ |
+ operand order by i
+ )
}
-module Flow = TaintTracking::Global;
+/** Native verification policies that establish the expected signer, not just any valid signature. */
+class NativeSignatureCheck extends DataFlow::CallNode {
+ NativeSignatureCheck() { this.getAName() = ["gpg", "gpg.exe", "cosign", "cosign.exe"] }
+
+ DataFlow::Node getFile() {
+ this.getAName() = ["gpg", "gpg.exe"] and
+ exists(string fingerprint |
+ hasFixedValue(getNativeOption(this, "assert-signer"), fingerprint) and
+ fingerprint.regexpMatch("[0-9a-fA-F]+") and
+ fingerprint.length() = [40, 64]
+ ) and
+ exists(getNativeOption(this, "verify")) and
+ not exists(getNativeOperand(this, 1)) and
+ (
+ result = getNativeOperand(this, 0)
+ or
+ not exists(getNativeOperand(this, 0)) and result = getNativeOption(this, "verify")
+ )
+ or
+ this.getAName() = ["cosign", "cosign.exe"] and
+ getNativeOperand(this, 0).asExpr().getValue().asString() = "verify-blob" and
+ not exists(getNativeOperand(this, 2)) and
+ exists(string identity, string issuer |
+ hasFixedValue(getNativeOption(this, "certificate-identity"), identity) and
+ identity != "" and
+ hasFixedValue(getNativeOption(this, "certificate-oidc-issuer"), issuer) and
+ issuer.matches("https://%")
+ ) and
+ not hasNativeOption(this,
+ [
+ "key", "trusted-root", "certificate-chain", "ca-roots", "ca-intermediates",
+ "insecure-ignore-sct", "insecure-ignore-tlog", "certificate-identity-regexp",
+ "certificate-oidc-issuer-regexp"
+ ]) and
+ result = getNativeOperand(this, 1)
+ }
+}
+
+/** Only an unmodified exit code from this verifier can establish successful verification. */
+predicate nativeSignatureGuard(
+ NativeSignatureCheck check, ExprCfgNode guard, BooleanSuccessor success
+) {
+ exists(ComparisonExpr comparison, Expr actual, Expr zero |
+ actual = comparison.getAnOperand() and
+ zero = comparison.getAnOperand() and
+ actual != zero and
+ actual.(AutomaticVariable).getLowerCaseName() = "lastexitcode" and
+ zero.getValue().asInt() = 0 and
+ conditionImplies(guard.getExpr(), success.getValue(), comparison, equalityMatchesOn(comparison)) and
+ precedes(check.getCfgNode(), guard) and
+ not exists(DataFlow::CallNode intervening |
+ intervening != check and
+ continuingStep+(check.getCfgNode(), intervening.getCfgNode()) and
+ continuingStep+(intervening.getCfgNode(), guard)
+ )
+ )
+}
+
+/** An overwrite or removal stops tracking the previous downloaded file version. */
+predicate overwritesFile(DataFlow::Node file, CfgNode node) {
+ exists(DownloadCall download |
+ node = download.getCfgNode() and sameFile(file, download.getOutFileArg())
+ )
+ or
+ exists(FileWrite write | node = write.getCfgNode() and sameFile(file, write.getFile()))
+ or
+ exists(FileTransfer transfer |
+ node = transfer.getCfgNode() and
+ (
+ transfer.removesInput() and sameFile(file, transfer.getInput())
+ or
+ sameFile(file, transfer.getOutput())
+ )
+ )
+ or
+ exists(DataFlow::CallNode remove |
+ node = remove.getCfgNode() and
+ (
+ remove.getAName() = ["Remove-Item", "ri", "rm", "del"] and
+ sameFile(file, getFileArgument(remove))
+ or
+ // Relative path identity cannot be assumed across a working-directory change.
+ remove.getAName() = ["Set-Location", "cd", "chdir", "sl", "Push-Location", "Pop-Location"]
+ )
+ )
+}
+
+predicate producedFile(DataFlow::CallNode producer, DataFlow::Node file) {
+ file = producer.(DownloadCall).getOutFileArg() or
+ file = producer.(FileTransfer).getOutput() or
+ file = producer.(FileWrite).getFile() or
+ file = producer.(FileRead).getFile() or
+ archiveMember(producer.(ArchiveExtraction).getDirectory(), file)
+}
+
+/** Reaches a node from a specific producer while the same file version is present. */
+predicate producedFileReaches(DataFlow::CallNode producer, DataFlow::Node file, CfgNode target) {
+ producedFile(producer, file) and continuingStep(producer.getCfgNode(), target)
+ or
+ exists(CfgNode node |
+ producedFileReaches(producer, file, node) and
+ not overwritesFile(file, node) and
+ continuingStep(node, target)
+ )
+}
+
+/** A check of an unchanged original also validates the copy made from it. */
+predicate checksProducedFile(
+ DataFlow::CallNode producer, DataFlow::Node file, DataFlow::Node checked, CfgNode check
+) {
+ sameFile(file, checked) and producedFileReaches(producer, file, check)
+ or
+ exists(FileTransfer copy |
+ producer = copy and
+ not copy.removesInput() and
+ file = copy.getOutput() and
+ sameFile(copy.getInput(), checked) and
+ precedes(copy.getCfgNode(), check) and
+ not exists(CfgNode changed |
+ overwritesFile(copy.getInput(), changed) and
+ continuingStep+(copy.getCfgNode(), changed) and
+ continuingStep*(changed, check)
+ )
+ )
+}
+
+/** Only this file version, checked after it was produced, can validate a path. */
+predicate fileVerificationEdge(
+ DataFlow::CallNode producer, DataFlow::Node file, CfgNode guard, CfgNode next
+) {
+ exists(HashCheck check, ExprCfgNode condition, BooleanSuccessor success |
+ checksProducedFile(producer, file, check.getHashedFile(), check.getHashedFile().asExpr()) and
+ hashGuard(check, condition, success) and
+ guard = condition and
+ next = condition.getASuccessor(success) and
+ not next = condition.getASuccessor(success.getDual())
+ )
+ or
+ exists(DataFlow::CallNode check, ExprCfgNode condition, BooleanSuccessor success |
+ authenticodeGuard(check, condition, success) and
+ checksProducedFile(producer, file, getArgument(check, "filepath", 0), check.getCfgNode()) and
+ guard = condition and
+ next = condition.getASuccessor(success) and
+ not next = condition.getASuccessor(success.getDual())
+ )
+ or
+ exists(NativeSignatureCheck check, ExprCfgNode condition, BooleanSuccessor success |
+ checksProducedFile(producer, file, check.getFile(), check.getCfgNode()) and
+ nativeSignatureGuard(check, condition, success) and
+ guard = condition and
+ next = condition.getASuccessor(success) and
+ not next = condition.getASuccessor(success.getDual())
+ )
+}
+
+/** An existential path to a particular use, excluding only successful verification edges. */
+predicate unverifiedFileReachable(DataFlow::CallNode producer, DataFlow::Node file, CfgNode target) {
+ producedFile(producer, file) and continuingStep(producer.getCfgNode(), target)
+ or
+ exists(CfgNode node |
+ unverifiedFileReachable(producer, file, node) and
+ not overwritesFile(file, node) and
+ continuingStep(node, target) and
+ not fileVerificationEdge(producer, file, node, target)
+ )
+}
+
+predicate unverifiedFileUse(
+ DataFlow::CallNode producer, DataFlow::Node file, DataFlow::CallNode use, DataFlow::Node input
+) {
+ sameFile(file, input) and
+ unverifiedFileReachable(producer, file, use.getCfgNode())
+}
+
+/** Extra content steps represent bytes/text, never a path string becoming its file's bytes. */
+predicate contentStep(DataFlow::Node input, DataFlow::Node output) {
+ output = getProperty(input, ["Content", "Result"])
+ or
+ exists(DataFlow::CallNode decode |
+ decode.getAName() = "GetString" and
+ decode
+ .getQualifier()
+ .asExpr()
+ .getExpr()
+ .(MemberExpr)
+ .getQualifier()
+ .(TypeNameExpr)
+ .getPossiblyQualifiedName() = ["System.Text.Encoding", "Text.Encoding"].toLowerCase() and
+ input = decode.getArgument(0) and
+ output = decode
+ )
+ or
+ exists(DataFlow::CallNode create |
+ create.getAName() = "Create" and
+ isStaticCall(create, ["System.Management.Automation.ScriptBlock", "ScriptBlock"]) and
+ input = create.getArgument(0) and
+ output = create
+ )
+}
+
+module ContentConf implements DataFlow::ConfigSig {
+ predicate isSource(DataFlow::Node source) {
+ source = any(DownloadCall d).getContent() or source instanceof FileRead
+ }
+
+ predicate isSink(DataFlow::Node sink) {
+ sink = any(CodeExecution use).getContent() or
+ sink = any(FileWrite write).getContent() or
+ sink = any(HashCheck check).getArgument(0)
+ }
+
+ predicate isAdditionalFlowStep(DataFlow::Node input, DataFlow::Node output) {
+ contentStep(input, output)
+ }
+}
+
+module ContentFlow = TaintTracking::Global;
+
+predicate unverifiedContentReachable(
+ DataFlow::CallNode producer, DataFlow::Node content, CfgNode target
+) {
+ (
+ content = producer.(DownloadCall).getContent()
+ or
+ producer instanceof FileRead and content = producer
+ ) and
+ continuingStep(producer.getCfgNode(), target)
+ or
+ exists(CfgNode node |
+ unverifiedContentReachable(producer, content, node) and
+ continuingStep(node, target) and
+ not (
+ producer instanceof FileRead and
+ fileVerificationEdge(producer, producer.(FileRead).getFile(), node, target)
+ ) and
+ not exists(HashCheck check, ExprCfgNode guard, BooleanSuccessor success |
+ check.getAName() = "ComputeHash" and
+ not exists(check.getArgument(1)) and
+ DataFlow::localFlow(content, check.getArgument(0)) and
+ hashGuard(check, guard, success) and
+ node = guard and
+ target = guard.getASuccessor(success) and
+ not target = guard.getASuccessor(success.getDual())
+ )
+ )
+}
+
+predicate unverifiedContentUse(
+ DataFlow::CallNode producer, DataFlow::Node content, DataFlow::CallNode use, DataFlow::Node input
+) {
+ ContentFlow::flow(content, input) and
+ unverifiedContentReachable(producer, content, use.getCfgNode())
+}
+
+predicate pinnedHttpsUrl(DownloadCall download) {
+ exists(
+ ComparisonExpr comparison, ExprCfgNode guard, BooleanSuccessor success, DataFlow::Node actual,
+ DataFlow::Node expected, string url
+ |
+ actual.asExpr().getExpr() = comparison.getAnOperand() and
+ expected.asExpr().getExpr() = comparison.getAnOperand() and
+ actual != expected and
+ DataFlow::localFlow(actual, download.getUrl()) and
+ hasFixedValue(expected, url) and
+ url.toLowerCase().matches("https://%") and
+ conditionImplies(guard.getExpr(), success.getValue(), comparison, equalityMatchesOn(comparison)) and
+ requiresSuccess(guard, success, download.getCfgNode())
+ )
+}
+
+/** The strict query needs evidence of a weaker trust boundary than a fixed HTTPS origin. */
+string getOriginReason(DownloadCall download) {
+ not pinnedHttpsUrl(download) and
+ (
+ HttpOriginFlow::flow(_, download.getUrl()) and result = "over unencrypted HTTP"
+ or
+ not HttpOriginFlow::flow(_, download.getUrl()) and
+ RemoteOriginFlow::flow(_, download.getUrl()) and
+ result = "from a remotely controlled URL"
+ )
+}
+
+/** An unverified materialized file, preserving content through modeled filesystem operations. */
+predicate unverifiedFile(DownloadCall download, DataFlow::CallNode producer, DataFlow::Node file) {
+ exists(getOriginReason(download)) and
+ producer = download and
+ file = download.getOutFileArg()
+ or
+ exists(FileTransfer transfer, DataFlow::CallNode previous, DataFlow::Node source |
+ unverifiedFile(download, previous, source) and
+ unverifiedFileUse(previous, source, transfer, transfer.getInput()) and
+ producer = transfer and
+ file = transfer.getOutput()
+ )
+ or
+ exists(ArchiveExtraction extract, DataFlow::CallNode previous, DataFlow::Node archive |
+ unverifiedFile(download, previous, archive) and
+ unverifiedFileUse(previous, archive, extract, extract.getFile()) and
+ producer = extract and
+ archiveMember(extract.getDirectory(), file)
+ )
+ or
+ exists(FileWrite write, DataFlow::CallNode previous, DataFlow::Node content |
+ unverifiedContent(download, previous, content) and
+ unverifiedContentUse(previous, content, write, write.getContent()) and
+ producer = write and
+ file = write.getFile()
+ )
+}
-/** Holds if the downloaded file `out` flows to an integrity check. */
-predicate isVerified(DataFlow::Node out) {
- exists(Flow::PathNode source |
- source.getNode() = out and
- source.isSource()
+predicate unverifiedContent(
+ DownloadCall download, DataFlow::CallNode producer, DataFlow::Node content
+) {
+ exists(getOriginReason(download)) and
+ producer = download and
+ content = download.getContent()
+ or
+ exists(FileRead read, DataFlow::CallNode previous, DataFlow::Node file |
+ unverifiedFile(download, previous, file) and
+ unverifiedFileUse(previous, file, read, read.getFile()) and
+ producer = read and
+ content = read
)
}
-from DownloadCall call, DataFlow::Node out
+from DownloadCall download, CodeExecution use, DataFlow::CallNode producer, DataFlow::Node artifact
where
- out = call.getOutFileArg() and
- not isVerified(out)
-select call,
- "This downloads an artifact without verifying its integrity (e.g. a hash or signature check)."
+ unverifiedFile(download, producer, artifact) and
+ unverifiedFileUse(producer, artifact, use, use.getFile())
+ or
+ unverifiedContent(download, producer, artifact) and
+ unverifiedContentUse(producer, artifact, use, use.getContent())
+select download,
+ "This download " + getOriginReason(download) +
+ " reaches $@ without an effective integrity or expected-publisher check.", use,
+ "code execution or loading"
diff --git a/powershell/ql/src/queries/security/cwe-494/examples/powershell/DownloadWithoutIntegrityCheckBad.ps1 b/powershell/ql/src/queries/security/cwe-494/examples/powershell/DownloadWithoutIntegrityCheckBad.ps1
index d406ad64c79d..11661eb19dd3 100644
--- a/powershell/ql/src/queries/security/cwe-494/examples/powershell/DownloadWithoutIntegrityCheckBad.ps1
+++ b/powershell/ql/src/queries/security/cwe-494/examples/powershell/DownloadWithoutIntegrityCheckBad.ps1
@@ -1,8 +1,6 @@
-# BAD: An artifact is downloaded from GitHub and then executed without
-# verifying that its contents match a known-good hash. If the release asset is
-# replaced (for example, through a compromised account, a tampered mirror, or a
-# man-in-the-middle attack), arbitrary code runs on the machine.
-$uri = "https://github.com/example/project/releases/download/v1.2.3/installer.exe"
+# BAD: An HTTP download is executed without verification. An on-path attacker
+# can replace the downloaded executable.
+$uri = "http://downloads.example.com/installer.exe"
$outFile = Join-Path $env:TEMP "installer.exe"
Invoke-WebRequest -Uri $uri -OutFile $outFile
diff --git a/powershell/ql/src/queries/security/cwe-494/examples/powershell/DownloadWithoutIntegrityCheckGood.ps1 b/powershell/ql/src/queries/security/cwe-494/examples/powershell/DownloadWithoutIntegrityCheckGood.ps1
index fa7646ec2815..91d539378a00 100644
--- a/powershell/ql/src/queries/security/cwe-494/examples/powershell/DownloadWithoutIntegrityCheckGood.ps1
+++ b/powershell/ql/src/queries/security/cwe-494/examples/powershell/DownloadWithoutIntegrityCheckGood.ps1
@@ -1,8 +1,8 @@
-# GOOD: The artifact is downloaded from GitHub and its SHA-256 hash is compared
+# GOOD: The artifact's SHA-256 hash is compared
# against the expected value (published by the author through a trusted channel,
# such as the signed release notes) before it is used. The artifact is only
# executed once its integrity has been confirmed.
-$uri = "https://github.com/example/project/releases/download/v1.2.3/installer.exe"
+$uri = "http://downloads.example.com/installer.exe"
$outFile = Join-Path $env:TEMP "installer.exe"
$expectedHash = "8c954cd9b6c8f8180a05f1de66ee555f0c44b4c6738120785d827521bb8d54df"
diff --git a/powershell/ql/test/query-tests/security/cwe-494/DownloadWithoutIntegrityCheck.expected b/powershell/ql/test/query-tests/security/cwe-494/DownloadWithoutIntegrityCheck.expected
index e44db9cf3629..a82527783b45 100644
--- a/powershell/ql/test/query-tests/security/cwe-494/DownloadWithoutIntegrityCheck.expected
+++ b/powershell/ql/test/query-tests/security/cwe-494/DownloadWithoutIntegrityCheck.expected
@@ -1,7 +1,61 @@
-| test.ps1:22:3:22:47 | Call to invoke-webrequest | This downloads an artifact without verifying its integrity (e.g. a hash or signature check). |
-| test.ps1:40:3:40:103 | Call to invoke-webrequest | This downloads an artifact without verifying its integrity (e.g. a hash or signature check). |
-| test.ps1:45:3:45:89 | Call to iwr | This downloads an artifact without verifying its integrity (e.g. a hash or signature check). |
-| test.ps1:66:3:66:95 | Call to downloadfile | This downloads an artifact without verifying its integrity (e.g. a hash or signature check). |
-| test.ps1:71:3:71:118 | Call to downloadfile | This downloads an artifact without verifying its integrity (e.g. a hash or signature check). |
-| test.ps1:76:3:76:116 | Call to start-bitstransfer | This downloads an artifact without verifying its integrity (e.g. a hash or signature check). |
-| test.ps1:81:3:81:91 | Call to curl | This downloads an artifact without verifying its integrity (e.g. a hash or signature check). |
+| test.ps1:22:3:22:47 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:23:3:23:12 | Call to | code execution or loading |
+| test.ps1:42:3:42:102 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:43:3:43:12 | Call to | code execution or loading |
+| test.ps1:48:3:48:88 | Call to iwr | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:49:3:49:12 | Call to | code execution or loading |
+| test.ps1:54:8:54:100 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:55:3:55:30 | Call to invoke-expression | code execution or loading |
+| test.ps1:60:3:60:74 | Call to irm | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:60:78:60:94 | Call to invoke-expression | code execution or loading |
+| test.ps1:70:3:70:94 | Call to downloadfile | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:71:3:71:12 | Call to | code execution or loading |
+| test.ps1:76:3:76:117 | Call to downloadfile | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:77:3:77:12 | Call to | code execution or loading |
+| test.ps1:82:3:82:115 | Call to start-bitstransfer | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:83:3:83:12 | Call to | code execution or loading |
+| test.ps1:88:3:88:61 | Call to curl.exe | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:89:3:89:12 | Call to | code execution or loading |
+| test.ps1:98:3:98:61 | Call to azcopy | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:99:3:99:12 | Call to | code execution or loading |
+| test.ps1:140:3:140:47 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:143:3:143:12 | Call to | code execution or loading |
+| test.ps1:149:3:149:47 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:151:3:151:12 | Call to | code execution or loading |
+| test.ps1:176:3:176:102 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:178:3:178:12 | Call to | code execution or loading |
+| test.ps1:182:3:182:102 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:187:3:187:12 | Call to | code execution or loading |
+| test.ps1:191:3:191:102 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:196:3:196:12 | Call to | code execution or loading |
+| test.ps1:200:3:200:102 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:201:3:201:12 | Call to | code execution or loading |
+| test.ps1:207:3:207:102 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:210:3:210:12 | Call to | code execution or loading |
+| test.ps1:214:3:214:102 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:217:3:217:12 | Call to | code execution or loading |
+| test.ps1:221:3:221:102 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:224:3:224:12 | Call to | code execution or loading |
+| test.ps1:228:3:228:102 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:235:3:235:12 | Call to | code execution or loading |
+| test.ps1:241:3:241:102 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:242:3:242:12 | Call to | code execution or loading |
+| test.ps1:246:3:246:102 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:248:3:248:12 | Call to | code execution or loading |
+| test.ps1:252:3:252:102 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:255:3:255:12 | Call to | code execution or loading |
+| test.ps1:276:3:276:102 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:277:3:277:12 | Call to | code execution or loading |
+| test.ps1:283:3:283:102 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:286:3:286:12 | Call to | code execution or loading |
+| test.ps1:290:3:290:102 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:296:3:296:12 | Call to | code execution or loading |
+| test.ps1:301:3:301:102 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:305:3:305:12 | Call to | code execution or loading |
+| test.ps1:325:3:325:102 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:330:3:330:12 | Call to | code execution or loading |
+| test.ps1:335:3:335:102 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:338:3:338:12 | Call to | code execution or loading |
+| test.ps1:360:3:360:42 | Call to invoke-webrequest | This download from a remotely controlled URL reaches $@ without an effective integrity or expected-publisher check. | test.ps1:361:3:361:12 | Call to | code execution or loading |
+| test.ps1:383:3:383:85 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:384:3:384:12 | Call to | code execution or loading |
+| test.ps1:402:3:402:105 | Call to invoke-restmethod | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:403:3:403:12 | Call to | code execution or loading |
+| test.ps1:407:3:407:103 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:408:3:408:12 | Call to | code execution or loading |
+| test.ps1:413:3:413:73 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:414:3:414:31 | Call to start-process | code execution or loading |
+| test.ps1:419:3:419:73 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:420:3:420:31 | Call to start-process | code execution or loading |
+| test.ps1:443:3:443:76 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:444:3:444:65 | Call to start-process | code execution or loading |
+| test.ps1:453:3:453:80 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:454:3:454:68 | Call to start-process | code execution or loading |
+| test.ps1:458:3:458:76 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:459:3:459:29 | Call to msiexec.exe | code execution or loading |
+| test.ps1:468:3:468:80 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:469:31:469:47 | Call to invoke-expression | code execution or loading |
+| test.ps1:473:11:473:70 | Call to invoke-restmethod | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:475:3:475:12 | Call to | code execution or loading |
+| test.ps1:479:3:479:79 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:480:3:480:50 | Call to loadfrom | code execution or loading |
+| test.ps1:485:12:485:74 | Call to downloaddata | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:486:3:486:44 | Call to load | code execution or loading |
+| test.ps1:490:3:490:76 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:492:3:492:10 | Call to | code execution or loading |
+| test.ps1:502:3:502:76 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:504:3:504:21 | Call to | code execution or loading |
+| test.ps1:508:3:508:76 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:513:3:513:9 | Call to | code execution or loading |
+| test.ps1:525:3:525:76 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:530:3:530:9 | Call to | code execution or loading |
+| test.ps1:539:3:539:72 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:542:3:542:8 | Call to | code execution or loading |
+| test.ps1:562:3:562:72 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:566:3:566:36 | Call to | code execution or loading |
+| test.ps1:587:3:587:85 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:588:3:588:17 | Call to install.ps1 | code execution or loading |
+| test.ps1:614:3:614:76 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:615:3:615:12 | Call to | code execution or loading |
+| test.ps1:647:3:647:76 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:651:3:651:12 | Call to | code execution or loading |
+| test.ps1:669:3:669:76 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:672:3:672:12 | Call to | code execution or loading |
+| test.ps1:676:3:676:76 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:679:3:679:12 | Call to | code execution or loading |
+| test.ps1:683:3:683:76 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:687:3:687:12 | Call to | code execution or loading |
+| test.ps1:691:3:691:76 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:695:3:695:12 | Call to | code execution or loading |
+| test.ps1:699:3:699:76 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:702:3:702:12 | Call to | code execution or loading |
+| test.ps1:706:3:706:76 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:709:3:709:12 | Call to | code execution or loading |
+| test.ps1:714:13:714:78 | Call to getstringasync | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:715:3:715:36 | Call to | code execution or loading |
+| test.ps1:741:3:741:76 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:746:3:746:12 | Call to | code execution or loading |
+| test.ps1:750:3:750:76 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:753:3:753:12 | Call to | code execution or loading |
+| test.ps1:766:3:766:76 | Call to invoke-webrequest | This download over unencrypted HTTP reaches $@ without an effective integrity or expected-publisher check. | test.ps1:771:3:771:12 | Call to | code execution or loading |
diff --git a/powershell/ql/test/query-tests/security/cwe-494/test.ps1 b/powershell/ql/test/query-tests/security/cwe-494/test.ps1
index df443d37aeb0..f0401b939967 100644
--- a/powershell/ql/test/query-tests/security/cwe-494/test.ps1
+++ b/powershell/ql/test/query-tests/security/cwe-494/test.ps1
@@ -1,7 +1,7 @@
-# CWE-494 - Download of a GitHub release artifact without an integrity check.
+# CWE-494 - Execution of an insecure or attacker-controlled download.
#
-# Each function below is one download idiom. It documents, as inline
-# expectations, which idioms the query catches and which it still misses:
+# A finding requires both a modeled untrusted origin and code execution/loading.
+# Download-only, extraction-only, and fixed HTTPS origins are outside this scope.
#
# # $ Alert -> the query reports here (expected true positive)
# # $ MISSING: Alert -> the query SHOULD report here but does not yet
@@ -17,84 +17,92 @@
# ---------------------------------------------------------------------------
function Iwr_NamedUri_OutFile($outFile) {
- # BAD - baseline; download from github with no hash check.
- $uri = "https://github.com/example/project/releases/download/v1.2.3/installer.exe"
+ # BAD - an on-path attacker can replace the executable.
+ $uri = "http://github.com/example/project/releases/download/v1.2.3/installer.exe"
Invoke-WebRequest -Uri $uri -OutFile $outFile # $ Alert
+ & $outFile
}
function Iwr_NamedUri_OutFile_Hashed($outFile) {
- # GOOD - Get-FileHash barrier on the downloaded file (correctly NOT flagged).
- $uri = "https://github.com/example/project/releases/download/v1.2.3/installer.exe"
+ # GOOD - mismatch terminates before the downloaded artifact can be used.
+ $uri = "http://github.com/example/project/releases/download/v1.2.3/installer.exe"
$expected = "8c954cd9b6c8f8180a05f1de66ee555f0c44b4c6738120785d827521bb8d54df"
Invoke-WebRequest -Uri $uri -OutFile $outFile
$actual = (Get-FileHash -Path $outFile -Algorithm SHA256).Hash
if ($actual -ne $expected) { Remove-Item $outFile -Force; throw "hash mismatch" }
+ & $outFile
}
# ---------------------------------------------------------------------------
-# MISSING: argument-shape variants of Invoke-WebRequest / Invoke-RestMethod.
+# Argument-shape variants of Invoke-WebRequest / Invoke-RestMethod.
# ---------------------------------------------------------------------------
function Iwr_PositionalUri($outFile) {
# BAD - URL passed positionally, not as -Uri.
- Invoke-WebRequest "https://github.com/example/project/releases/download/v1/app.exe" -OutFile $outFile # $ Alert
+ Invoke-WebRequest "http://github.com/example/project/releases/download/v1/app.exe" -OutFile $outFile # $ Alert
+ & $outFile
}
function Iwr_Alias_Positional($outFile) {
# BAD - iwr alias + positional URL.
- iwr "https://github.com/example/project/releases/download/v1/app.zip" -OutFile $outFile # $ Alert
+ iwr "http://github.com/example/project/releases/download/v1/app.exe" -OutFile $outFile # $ Alert
+ & $outFile
}
function Iwr_NoOutFile_PipedToIex() {
# BAD - no -OutFile; content executed inline.
- $r = Invoke-WebRequest -Uri "https://github.com/example/project/releases/download/v1/bootstrap.ps1" # $ MISSING: Alert
+ $r = Invoke-WebRequest -Uri "http://github.com/example/project/releases/download/v1/bootstrap.ps1" # $ Alert
Invoke-Expression $r.Content
}
function Irm_NoOutFile() {
# BAD - Invoke-RestMethod returns content, no -OutFile.
- irm "https://github.com/example/project/releases/download/v1/install.ps1" | Invoke-Expression # $ MISSING: Alert
+ irm "http://github.com/example/project/releases/download/v1/install.ps1" | Invoke-Expression # $ Alert
}
# ---------------------------------------------------------------------------
-# MISSING: download sinks that are not in the cmdlet name list at all.
+# Other modeled download APIs.
# ---------------------------------------------------------------------------
function WebClient_DownloadFile($outFile) {
# BAD - System.Net.WebClient.DownloadFile.
$wc = New-Object System.Net.WebClient
- $wc.DownloadFile("https://github.com/example/project/releases/download/v1/app.exe", $outFile) # $ Alert
+ $wc.DownloadFile("http://github.com/example/project/releases/download/v1/app.exe", $outFile) # $ Alert
+ & $outFile
}
function WebClient_Inline($outFile) {
# BAD - inline (New-Object Net.WebClient).DownloadFile(...).
- (New-Object Net.WebClient).DownloadFile("https://github.com/example/project/releases/download/v1/app.exe", $outFile) # $ Alert
+ (New-Object Net.WebClient).DownloadFile("http://github.com/example/project/releases/download/v1/app.exe", $outFile) # $ Alert
+ & $outFile
}
function Bits_Transfer($outFile) {
# BAD - Start-BitsTransfer.
- Start-BitsTransfer -Source "https://github.com/example/project/releases/download/v1/app.exe" -Destination $outFile # $ Alert
+ Start-BitsTransfer -Source "http://github.com/example/project/releases/download/v1/app.exe" -Destination $outFile # $ Alert
+ & $outFile
}
function Curl_Native($outFile) {
- # BAD - native curl with -o.
- curl -sL "https://github.com/example/project/releases/download/v1/app.tar.gz" -o $outFile # $ Alert
+ # BAD - native curl with an explicit destination.
+ curl.exe "http://downloads.example.com/app.exe" -o $outFile # $ Alert
+ & $outFile
}
function Wget_Native() {
- # BAD - native wget piped to tar (no output file at all).
- wget "https://github.com/example/project/releases/download/v1/app.tar.gz" # $ MISSING: Alert
+ # No execution: merely retrieving an archive is not enough.
+ wget "http://downloads.example.com/app.tar.gz"
}
function AzCopy($outFile) {
- # BAD - azcopy / aria2c.
- azcopy copy "https://github.com/Azure/azure-storage-azcopy/releases/download/v10.31.0/azcopy.zip" $outFile # $ MISSING: Alert
+ azcopy copy "http://downloads.example.com/app.exe" $outFile # $ Alert
+ & $outFile
}
function Wrapper_Function($outFile) {
- # BAD - custom download wrapper; the real Invoke-WebRequest lives in a
- # dot-sourced helper.
- Download-File "https://github.com/example/project/releases/download/v1/app.exe" $outFile # $ MISSING: Alert
+ # An undefined helper is not evidence that a download takes place.
+ Download-File "http://downloads.example.com/app.exe" $outFile
+ & $outFile
}
# ---------------------------------------------------------------------------
@@ -102,47 +110,49 @@ function Wrapper_Function($outFile) {
# ---------------------------------------------------------------------------
function Verified_With_CertUtil($outFile) {
- # GOOD - certutil hash verification (now recognised as an integrity barrier).
- $uri = "https://github.com/example/project/releases/download/v1/app.exe"
+ # GOOD - certutil computes a hash and mismatch terminates the script.
+ $uri = "http://github.com/example/project/releases/download/v1/app.exe"
Invoke-WebRequest -Uri $uri -OutFile $outFile
$h = certutil -hashfile $outFile SHA256
- if ($h -notmatch "ABC123") { throw "hash mismatch" }
+ if ($h -ne "8c954cd9b6c8f8180a05f1de66ee555f0c44b4c6738120785d827521bb8d54df") { throw "hash mismatch" }
+ & $outFile
}
# ---------------------------------------------------------------------------
-# TRUE NEGATIVES: these must NOT be flagged. Either the download is verified,
-# or it is not a trusted-host artifact download at all. No inline expectation
-# means "no alert expected here".
+# Verification and excluded origin/use patterns.
# ---------------------------------------------------------------------------
function Verified_With_ComputeHash($outFile) {
# GOOD - hash computed via [SHA256]::Create().ComputeHash over the bytes read
# from the downloaded file, then compared.
- $uri = "https://github.com/example/project/releases/download/v1/app.exe"
+ $uri = "http://github.com/example/project/releases/download/v1/app.exe"
Invoke-WebRequest -Uri $uri -OutFile $outFile
$sha = [System.Security.Cryptography.SHA256]::Create()
$bytes = [System.IO.File]::ReadAllBytes($outFile)
$hash = [System.BitConverter]::ToString($sha.ComputeHash($bytes)).Replace("-", "")
- if ($hash -ne "ABC123") { throw "hash mismatch" }
+ if ($hash -ne "8c954cd9b6c8f8180a05f1de66ee555f0c44b4c6738120785d827521bb8d54df") { throw "hash mismatch" }
+ & $outFile
}
function Verified_With_Signature($outFile) {
- # GOOD - Authenticode signature check on the downloaded file.
- $uri = "https://github.com/example/project/releases/download/v1/app.exe"
- Invoke-WebRequest -Uri $uri -OutFile $outFile
+ # Status alone does not establish the intended publisher.
+ $uri = "http://github.com/example/project/releases/download/v1/app.exe"
+ Invoke-WebRequest -Uri $uri -OutFile $outFile # $ Alert
$sig = Get-AuthenticodeSignature -FilePath $outFile
if ($sig.Status -ne "Valid") { throw "bad signature" }
+ & $outFile
}
function Verified_With_Cosign($outFile) {
- # GOOD - external signature verification via cosign.
- $uri = "https://github.com/example/project/releases/download/v1/app.tar.gz"
- Invoke-WebRequest -Uri $uri -OutFile $outFile
+ # Merely invoking a verifier does not enforce its result.
+ $uri = "http://github.com/example/project/releases/download/v1/app.exe"
+ Invoke-WebRequest -Uri $uri -OutFile $outFile # $ Alert
cosign verify-blob --signature "$outFile.sig" $outFile
+ & $outFile
}
function NonArtifact_Host($outFile) {
- # GOOD - download from a host that is not a recognised artifact host.
+ # A fixed HTTPS origin with no code execution is outside the strict scope.
Invoke-WebRequest -Uri "https://example.com/data/report.json" -OutFile $outFile
}
@@ -154,6 +164,609 @@ function GitHub_Api_DataOnly() {
}
function Local_Copy($outFile) {
- # GOOD - copying a local file; no network download, no trusted-host URL.
+ # GOOD - copying a local file; no network download.
Copy-Item -Path "C:\artifacts\app.exe" -Destination $outFile
}
+
+# ---------------------------------------------------------------------------
+# Hashing is only verification when a complete expected digest is enforced.
+# ---------------------------------------------------------------------------
+
+function Hash_Ignored($outFile) {
+ Invoke-WebRequest "http://github.com/example/project/releases/download/v1/app.exe" -OutFile $outFile # $ Alert
+ Get-FileHash -Path $outFile -Algorithm SHA256
+ & $outFile
+}
+
+function Hash_Mismatch_OnlyLogged($outFile) {
+ Invoke-WebRequest "http://github.com/example/project/releases/download/v1/app.exe" -OutFile $outFile # $ Alert
+ $hash = (Get-FileHash -Path $outFile).Hash
+ if ($hash -ne "8c954cd9b6c8f8180a05f1de66ee555f0c44b4c6738120785d827521bb8d54df") {
+ Write-Error "hash mismatch"
+ }
+ & $outFile
+}
+
+function Hash_Conditional($outFile, $verify) {
+ Invoke-WebRequest "http://github.com/example/project/releases/download/v1/app.exe" -OutFile $outFile # $ Alert
+ if ($verify) {
+ $hash = (Get-FileHash -Path $outFile).Hash
+ if ($hash -ne "8c954cd9b6c8f8180a05f1de66ee555f0c44b4c6738120785d827521bb8d54df") { throw "hash mismatch" }
+ }
+ & $outFile
+}
+
+function Hash_AfterUse($outFile) {
+ Invoke-WebRequest "http://github.com/example/project/releases/download/v1/app.exe" -OutFile $outFile # $ Alert
+ & $outFile
+ $hash = (Get-FileHash -Path $outFile).Hash
+ if ($hash -ne "8c954cd9b6c8f8180a05f1de66ee555f0c44b4c6738120785d827521bb8d54df") { throw "hash mismatch" }
+}
+
+function Hash_WrongFile($outFile) {
+ Invoke-WebRequest "http://github.com/example/project/releases/download/v1/app.exe" -OutFile $outFile # $ Alert
+ $hash = (Get-FileHash -Path "$outFile.sig").Hash
+ if ($hash -ne "8c954cd9b6c8f8180a05f1de66ee555f0c44b4c6738120785d827521bb8d54df") { throw "hash mismatch" }
+ & $outFile
+}
+
+function Hash_WrongProperty($outFile) {
+ Invoke-WebRequest "http://github.com/example/project/releases/download/v1/app.exe" -OutFile $outFile # $ Alert
+ $algorithm = (Get-FileHash -Path $outFile).Algorithm
+ if ($algorithm -ne "SHA256") { throw "unexpected algorithm" }
+ & $outFile
+}
+
+function Hash_SelfComparison($outFile) {
+ Invoke-WebRequest "http://github.com/example/project/releases/download/v1/app.exe" -OutFile $outFile # $ Alert
+ $hash = (Get-FileHash -Path $outFile).Hash
+ if ($hash -ne $hash) { throw "hash mismatch" }
+ & $outFile
+}
+
+function Hash_Mismatch_Caught($outFile) {
+ Invoke-WebRequest "http://github.com/example/project/releases/download/v1/app.exe" -OutFile $outFile # $ Alert
+ try {
+ $hash = (Get-FileHash -Path $outFile).Hash
+ if ($hash -ne "8c954cd9b6c8f8180a05f1de66ee555f0c44b4c6738120785d827521bb8d54df") { throw "hash mismatch" }
+ } catch {
+ Write-Warning "Continuing despite hash failure"
+ }
+ & $outFile
+}
+
+function Hash_BeforeDownload($outFile) {
+ $hash = (Get-FileHash -Path $outFile).Hash
+ if ($hash -ne "8c954cd9b6c8f8180a05f1de66ee555f0c44b4c6738120785d827521bb8d54df") { throw "hash mismatch" }
+ Invoke-WebRequest "http://github.com/example/project/releases/download/v1/app.exe" -OutFile $outFile # $ Alert
+ & $outFile
+}
+
+function CertUtil_NotHashing($outFile) {
+ Invoke-WebRequest "http://github.com/example/project/releases/download/v1/app.exe" -OutFile $outFile # $ Alert
+ certutil -encode $outFile "$outFile.b64"
+ & $outFile
+}
+
+function ComputeHash_Ignored($outFile) {
+ Invoke-WebRequest "http://github.com/example/project/releases/download/v1/app.exe" -OutFile $outFile # $ Alert
+ $sha = [System.Security.Cryptography.SHA256]::Create()
+ $sha.ComputeHash([System.IO.File]::ReadAllBytes($outFile))
+ & $outFile
+}
+
+function Hash_Valid_Alias_ReversedOperands($outFile) {
+ iwr "http://github.com/example/project/releases/download/v1/app.exe" -OutFile $outFile
+ $hash = (gfh -LiteralPath $outFile).Hash
+ if ("8c954cd9b6c8f8180a05f1de66ee555f0c44b4c6738120785d827521bb8d54df" -cne $hash) { throw "hash mismatch" }
+ & $outFile
+}
+
+function Hash_Valid_EqualityElse($outFile) {
+ Invoke-WebRequest "http://github.com/example/project/releases/download/v1/app.exe" -OutFile $outFile
+ $hash = (Get-FileHash $outFile).Hash
+ if ($hash -eq "8c954cd9b6c8f8180a05f1de66ee555f0c44b4c6738120785d827521bb8d54df") {
+ & $outFile
+ } else {
+ throw "hash mismatch"
+ }
+}
+
+function Hash_AfterCallOperatorUse($outFile) {
+ Invoke-WebRequest "http://github.com/example/project/releases/download/v1/app.exe" -OutFile $outFile # $ Alert
+ & $outFile
+ $hash = (Get-FileHash -Path $outFile).Hash
+ if ($hash -ne "8c954cd9b6c8f8180a05f1de66ee555f0c44b4c6738120785d827521bb8d54df") { throw "hash mismatch" }
+}
+
+function Hash_PartialDigest($outFile) {
+ Invoke-WebRequest "http://github.com/example/project/releases/download/v1/app.exe" -OutFile $outFile # $ Alert
+ $hash = (Get-FileHash -Path $outFile).Hash.Substring(0, 6)
+ if ($hash -ne "8c954c") { throw "hash mismatch" }
+ & $outFile
+}
+
+function Hash_UntrustedExpected($outFile, $expected, $usePinnedHash) {
+ Invoke-WebRequest "http://github.com/example/project/releases/download/v1/app.exe" -OutFile $outFile # $ Alert
+ if ($usePinnedHash) {
+ $expected = "8c954cd9b6c8f8180a05f1de66ee555f0c44b4c6738120785d827521bb8d54df"
+ }
+ $hash = (Get-FileHash -Path $outFile).Hash
+ if ($hash -ne $expected) { throw "hash mismatch" }
+ & $outFile
+}
+
+function ComputeHash_StaleBytes($outFile) {
+ $bytes = [System.IO.File]::ReadAllBytes($outFile)
+ Invoke-WebRequest "http://github.com/example/project/releases/download/v1/app.exe" -OutFile $outFile # $ Alert
+ $sha = [System.Security.Cryptography.SHA256]::Create()
+ $hash = [System.Convert]::ToHexString($sha.ComputeHash($bytes))
+ if ($hash -ne "8c954cd9b6c8f8180a05f1de66ee555f0c44b4c6738120785d827521bb8d54df") { throw "hash mismatch" }
+ & $outFile
+}
+
+function Hash_Valid_BeforeUse($outFile) {
+ Invoke-WebRequest "http://github.com/example/project/releases/download/v1/app.exe" -OutFile $outFile
+ Write-Verbose "Downloaded $outFile"
+ $hash = (Get-FileHash -Path $outFile).Hash.ToLowerInvariant()
+ if ($hash -ne "8c954cd9b6c8f8180a05f1de66ee555f0c44b4c6738120785d827521bb8d54df") { exit 1 }
+ & $outFile
+}
+
+function ComputeHash_Valid_HexString($outFile) {
+ Invoke-WebRequest "http://github.com/example/project/releases/download/v1/app.exe" -OutFile $outFile
+ $sha = [System.Security.Cryptography.SHA256]::Create()
+ $hash = [System.Convert]::ToHexString($sha.ComputeHash([System.IO.File]::ReadAllBytes($outFile)))
+ if ($hash -ne "8c954cd9b6c8f8180a05f1de66ee555f0c44b4c6738120785d827521bb8d54df") { throw "hash mismatch" }
+ & $outFile
+}
+
+function ComputeHash_PartialBuffer($outFile) {
+ Invoke-WebRequest "http://github.com/example/project/releases/download/v1/app.exe" -OutFile $outFile # $ Alert
+ $bytes = [System.IO.File]::ReadAllBytes($outFile)
+ $sha = [System.Security.Cryptography.SHA256]::Create()
+ $hash = [System.Convert]::ToHexString($sha.ComputeHash($bytes, 0, 100))
+ if ($hash -ne "8c954cd9b6c8f8180a05f1de66ee555f0c44b4c6738120785d827521bb8d54df") { throw "hash mismatch" }
+ & $outFile
+}
+
+function Hash_Mismatch_Trapped($outFile) {
+ trap { continue }
+ Invoke-WebRequest "http://github.com/example/project/releases/download/v1/app.exe" -OutFile $outFile # $ Alert
+ $hash = (Get-FileHash -Path $outFile).Hash
+ if ($hash -ne "8c954cd9b6c8f8180a05f1de66ee555f0c44b4c6738120785d827521bb8d54df") { throw "hash mismatch" }
+ & $outFile
+}
+
+# Strict origin and execution requirements.
+
+function FixedHttps_Executed($outFile) {
+ Invoke-WebRequest "https://downloads.example.com/app.exe" -OutFile $outFile
+ & $outFile
+}
+
+function UnknownUrl_Executed($url, $outFile) {
+ Invoke-WebRequest $url -OutFile $outFile
+ & $outFile
+}
+
+function EnvironmentUrl_Executed($outFile) {
+ Invoke-WebRequest $env:INSTALLER_URL -OutFile $outFile
+ & $outFile
+}
+
+function RequestUrl_Executed([System.Net.HttpListenerRequest]$request, $outFile) {
+ $url = $request.QueryString["download"]
+ Invoke-WebRequest $url -OutFile $outFile # $ Alert
+ & $outFile
+}
+
+function RequestUrl_PinnedHttps([System.Net.HttpListenerRequest]$request, $outFile) {
+ $url = $request.QueryString["download"]
+ if ($url -ne "https://downloads.example.com/app.exe") { throw "unexpected URL" }
+ Invoke-WebRequest $url -OutFile $outFile
+ & $outFile
+}
+
+function RequestUrl_OnlyInQuery([System.Net.HttpListenerRequest]$request, $outFile) {
+ $tracking = $request.QueryString["tracking"]
+ Invoke-WebRequest "https://downloads.example.com/app.exe?tracking=$tracking" -OutFile $outFile
+ & $outFile
+}
+
+function Http_InQueryOnly($outFile) {
+ Invoke-WebRequest "https://downloads.example.com/app.exe?mirror=http://elsewhere.example.com" -OutFile $outFile
+ & $outFile
+}
+
+function Http_Interpolated($version, $outFile) {
+ Invoke-WebRequest "HTTP://downloads.example.com/$version/app.exe" -OutFile $outFile # $ Alert
+ & $outFile
+}
+
+function Http_DownloadOnly($outFile) {
+ Invoke-WebRequest "http://downloads.example.com/app.exe" -OutFile $outFile
+}
+
+function Http_ConfigOnly($outFile) {
+ Invoke-RestMethod "http://app.scm.azurewebsites.net/api/vfs/site/wwwroot/Config.js" -OutFile $outFile
+ Get-Content $outFile
+}
+
+function Https_KuduExecutable($outFile) {
+ Invoke-RestMethod "https://app.scm.azurewebsites.net/api/vfs/site/wwwroot/install.ps1" -OutFile $outFile
+ & $outFile
+}
+
+function Http_KuduExecutable($outFile) {
+ Invoke-RestMethod "http://app.scm.azurewebsites.net/api/vfs/site/wwwroot/install.ps1" -OutFile $outFile # $ Alert
+ & $outFile
+}
+
+function Http_ApiExecutable($outFile) {
+ Invoke-WebRequest "http://api.github.com/repos/example/project/releases/assets/123" -OutFile $outFile # $ Alert
+ & $outFile
+}
+
+function StartProcess_Executable() {
+ $file = "downloaded.exe"
+ Invoke-WebRequest "http://downloads.example.com/app.exe" -OutFile $file # $ Alert
+ Start-Process -FilePath $file
+}
+
+function StartProcess_ExecutableChildPath() {
+ $file = Join-Path $env:TEMP "downloaded.exe"
+ Invoke-WebRequest "http://downloads.example.com/app.exe" -OutFile $file # $ Alert
+ Start-Process -FilePath $file
+}
+
+function StartProcess_VerifiedChildPath() {
+ $file = Join-Path $env:TEMP "downloaded.exe"
+ Invoke-WebRequest "http://downloads.example.com/app.exe" -OutFile $file
+ $hash = (Get-FileHash $file).Hash
+ if ($hash -ne "8c954cd9b6c8f8180a05f1de66ee555f0c44b4c6738120785d827521bb8d54df") { throw "hash mismatch" }
+ Start-Process -FilePath $file
+}
+
+function StartProcess_DataAssociation() {
+ $file = "report.json"
+ Invoke-WebRequest "http://downloads.example.com/report.json" -OutFile $file
+ Start-Process -FilePath $file
+}
+
+function StartProcess_UnrelatedArgument($outFile) {
+ Invoke-WebRequest "http://downloads.example.com/report.json" -OutFile $outFile
+ Start-Process "notepad.exe" -ArgumentList $outFile
+}
+
+function StartProcess_InstallerPackage($outFile) {
+ Invoke-WebRequest "http://downloads.example.com/app.msi" -OutFile $outFile # $ Alert
+ Start-Process "msiexec.exe" -ArgumentList "/i", $outFile, "/qn"
+}
+
+function StartProcess_InstallerLog($outFile) {
+ Invoke-WebRequest "http://downloads.example.com/app.msi" -OutFile $outFile
+ Start-Process "msiexec.exe" -ArgumentList "/i", "local.msi", "/log", $outFile
+}
+
+function StartProcess_PowerShellFile($outFile) {
+ Invoke-WebRequest "http://downloads.example.com/install.ps1" -OutFile $outFile # $ Alert
+ Start-Process "pwsh" -ArgumentList "-NoProfile", "-File", $outFile
+}
+
+function Installer_ActualPackage($outFile) {
+ Invoke-WebRequest "http://downloads.example.com/app.msi" -OutFile $outFile # $ Alert
+ msiexec.exe /i $outFile /qn
+}
+
+function Installer_LogFileOnly($outFile) {
+ Invoke-WebRequest "http://downloads.example.com/app.msi" -OutFile $outFile
+ msiexec.exe /i "local.msi" /log $outFile
+}
+
+function ReadThenExecute($outFile) {
+ Invoke-WebRequest "http://downloads.example.com/install.ps1" -OutFile $outFile # $ Alert
+ Get-Content -Raw $outFile | Invoke-Expression
+}
+
+function BodyWrittenThenExecuted($outFile) {
+ $body = Invoke-RestMethod "http://downloads.example.com/install.ps1" # $ Alert
+ $body | Set-Content -Path $outFile
+ . $outFile
+}
+
+function Assembly_Loaded($outFile) {
+ Invoke-WebRequest "http://downloads.example.com/plugin.dll" -OutFile $outFile # $ Alert
+ [System.Reflection.Assembly]::LoadFrom($outFile)
+}
+
+function WebClient_BytesLoaded() {
+ $client = [System.Net.WebClient]::new()
+ $bytes = $client.DownloadData("http://downloads.example.com/plugin.dll") # $ Alert
+ [System.Reflection.Assembly]::Load($bytes)
+}
+
+function MovedThenExecuted($outFile, $moved) {
+ Invoke-WebRequest "http://downloads.example.com/app.exe" -OutFile $outFile # $ Alert
+ Move-Item $outFile -Destination $moved
+ & $moved
+}
+
+function MovedOriginal_NotExecuted($outFile, $moved) {
+ Invoke-WebRequest "http://downloads.example.com/app.exe" -OutFile $outFile
+ Move-Item $outFile -Destination $moved
+ & $outFile
+}
+
+function RenamedThenExecuted($outFile) {
+ Invoke-WebRequest "http://downloads.example.com/app.exe" -OutFile $outFile # $ Alert
+ $renamed = Rename-Item $outFile -NewName "renamed.exe" -PassThru
+ & $renamed.FullName
+}
+
+function CopyNotVerifiedByChangedOriginal($outFile, $copy) {
+ Invoke-WebRequest "http://downloads.example.com/app.exe" -OutFile $outFile # $ Alert
+ Copy-Item $outFile -Destination $copy
+ Set-Content $outFile "trusted replacement"
+ $hash = (Get-FileHash $outFile).Hash
+ if ($hash -ne "8c954cd9b6c8f8180a05f1de66ee555f0c44b4c6738120785d827521bb8d54df") { throw "hash mismatch" }
+ & $copy
+}
+
+function CopyVerifiedByUnchangedOriginal($outFile, $copy) {
+ Invoke-WebRequest "http://downloads.example.com/app.exe" -OutFile $outFile
+ Copy-Item $outFile -Destination $copy
+ $hash = (Get-FileHash $outFile).Hash
+ if ($hash -ne "8c954cd9b6c8f8180a05f1de66ee555f0c44b4c6738120785d827521bb8d54df") { throw "hash mismatch" }
+ & $copy
+}
+
+function CopyNotVerifiedByOptionallyChangedOriginal($outFile, $copy, $replace) {
+ Invoke-WebRequest "http://downloads.example.com/app.exe" -OutFile $outFile # $ Alert
+ Copy-Item $outFile -Destination $copy
+ if ($replace) { Set-Content $outFile "trusted replacement" }
+ $hash = (Get-FileHash $outFile).Hash
+ if ($hash -ne "8c954cd9b6c8f8180a05f1de66ee555f0c44b4c6738120785d827521bb8d54df") { throw "hash mismatch" }
+ & $copy
+}
+
+function Archive_ExtractionOnly($zip, $directory) {
+ Invoke-WebRequest "http://downloads.example.com/app.zip" -OutFile $zip
+ Expand-Archive $zip -DestinationPath $directory
+}
+
+function Archive_ExtractedCodeExecuted($zip, $directory) {
+ Invoke-WebRequest "http://downloads.example.com/app.zip" -OutFile $zip # $ Alert
+ Expand-Archive $zip -DestinationPath $directory
+ $exe = Join-Path $directory "bin\app.exe"
+ & $exe
+}
+
+function Archive_VerifiedBeforeExecution($zip, $directory) {
+ Invoke-WebRequest "http://downloads.example.com/app.zip" -OutFile $zip
+ $hash = (Get-FileHash $zip).Hash
+ if ($hash -ne "8c954cd9b6c8f8180a05f1de66ee555f0c44b4c6738120785d827521bb8d54df") { throw "hash mismatch" }
+ Expand-Archive $zip -DestinationPath $directory
+ & (Join-Path $directory "app.exe")
+}
+
+function Archive_VerifiedMemberWithReconstructedPath($zip, $directory) {
+ Invoke-WebRequest "http://downloads.example.com/app.zip" -OutFile $zip
+ Expand-Archive $zip -DestinationPath $directory
+ $hash = (Get-FileHash (Join-Path $directory "app.exe")).Hash
+ if ($hash -ne "8c954cd9b6c8f8180a05f1de66ee555f0c44b4c6738120785d827521bb8d54df") { throw "hash mismatch" }
+ & (Join-Path $directory "app.exe")
+}
+
+function Archive_DifferentMemberVerified($zip, $directory) {
+ Invoke-WebRequest "http://downloads.example.com/app.zip" -OutFile $zip # $ Alert
+ Expand-Archive $zip -DestinationPath $directory
+ $hash = (Get-FileHash (Join-Path $directory "other.exe")).Hash
+ if ($hash -ne "8c954cd9b6c8f8180a05f1de66ee555f0c44b4c6738120785d827521bb8d54df") { throw "hash mismatch" }
+ & (Join-Path $directory "app.exe")
+}
+
+function FilePathSuffixIsNotDownloadedFile($outFile) {
+ Invoke-WebRequest "http://downloads.example.com/app.exe" -OutFile $outFile
+ & "$outFile.other.exe"
+}
+
+function OverwrittenBeforeExecution($outFile) {
+ Invoke-WebRequest "http://downloads.example.com/install.ps1" -OutFile $outFile
+ Set-Content $outFile "Write-Output 'local code'"
+ & $outFile
+}
+
+function RedownloadedBeforeExecution($outFile) {
+ Invoke-WebRequest "http://downloads.example.com/app.exe" -OutFile $outFile
+ Invoke-WebRequest "https://downloads.example.com/app.exe" -OutFile $outFile
+ & $outFile
+}
+
+function SeparateLiteralFileReferences() {
+ Invoke-WebRequest "http://downloads.example.com/install.ps1" -OutFile "install.ps1" # $ Alert
+ & "install.ps1"
+}
+
+function MutuallyExclusiveDownloadAndUse($condition, $outFile) {
+ if ($condition) {
+ Invoke-WebRequest "http://downloads.example.com/app.exe" -OutFile $outFile
+ } else {
+ & $outFile
+ }
+}
+
+# Verification is a path property, not the presence of a check somewhere in a function.
+
+function BothBranchesVerified($outFile, $condition) {
+ Invoke-WebRequest "http://downloads.example.com/app.exe" -OutFile $outFile
+ if ($condition) {
+ $hash = (Get-FileHash $outFile).Hash
+ if ($hash -ne "8c954cd9b6c8f8180a05f1de66ee555f0c44b4c6738120785d827521bb8d54df") { throw "hash mismatch" }
+ } else {
+ $hash = (Get-FileHash $outFile).Hash
+ if ($hash -ne "8c954cd9b6c8f8180a05f1de66ee555f0c44b4c6738120785d827521bb8d54df") { throw "hash mismatch" }
+ }
+ & $outFile
+}
+
+function OnlyOneUseVerified($outFile) {
+ Invoke-WebRequest "http://downloads.example.com/app.exe" -OutFile $outFile # $ Alert
+ & $outFile
+ $hash = (Get-FileHash $outFile).Hash
+ if ($hash -ne "8c954cd9b6c8f8180a05f1de66ee555f0c44b4c6738120785d827521bb8d54df") { throw "hash mismatch" }
+ & $outFile
+}
+
+function ReadBeforeValidatingSameFile($outFile) {
+ Invoke-WebRequest "http://downloads.example.com/install.ps1" -OutFile $outFile
+ $script = Get-Content -Raw $outFile
+ $hash = (Get-FileHash $outFile).Hash
+ if ($hash -ne "8c954cd9b6c8f8180a05f1de66ee555f0c44b4c6738120785d827521bb8d54df") { throw "hash mismatch" }
+ Invoke-Expression $script
+}
+
+function Signature_ExpectedPublisher($outFile) {
+ Invoke-WebRequest "http://downloads.example.com/app.exe" -OutFile $outFile
+ $sig = Get-AuthenticodeSignature -FilePath $outFile
+ if ($sig.Status -ne "Valid") { throw "bad signature" }
+ if ($sig.SignerCertificate.Thumbprint -ne "0123456789ABCDEF0123456789ABCDEF01234567") { throw "wrong publisher" }
+ & $outFile
+}
+
+function Signature_ExpectedPublisherCombinedGuard($outFile) {
+ Invoke-WebRequest "http://downloads.example.com/app.exe" -OutFile $outFile
+ $sig = Get-AuthenticodeSignature -FilePath $outFile
+ if ($sig.Status -ne "Valid" -or $sig.SignerCertificate.Thumbprint -ne "0123456789ABCDEF0123456789ABCDEF01234567") {
+ throw "invalid or unexpected signer"
+ }
+ & $outFile
+}
+
+function Signature_IgnoredFailure($outFile) {
+ Invoke-WebRequest "http://downloads.example.com/app.exe" -OutFile $outFile # $ Alert
+ $sig = Get-AuthenticodeSignature -FilePath $outFile
+ if ($sig.Status -ne "Valid") { Write-Warning "bad signature" }
+ if ($sig.SignerCertificate.Thumbprint -ne "0123456789ABCDEF0123456789ABCDEF01234567") { Write-Warning "wrong publisher" }
+ & $outFile
+}
+
+function Signature_GpgExpectedSigner($outFile) {
+ Invoke-WebRequest "http://downloads.example.com/app.exe" -OutFile $outFile
+ gpg --assert-signer "0123456789ABCDEF0123456789ABCDEF01234567" --verify "$outFile.sig" $outFile
+ if ($LASTEXITCODE -ne 0) { throw "bad signature" }
+ & $outFile
+}
+
+function Signature_CosignExpectedIdentity($outFile) {
+ Invoke-WebRequest "http://downloads.example.com/app.exe" -OutFile $outFile
+ cosign verify-blob $outFile --bundle "$outFile.sigstore.json" --certificate-identity "release@example.com" --certificate-oidc-issuer "https://accounts.google.com"
+ if ($LASTEXITCODE -ne 0) { throw "bad signature" }
+ & $outFile
+}
+
+function Signature_GpgUnexpectedSigner($outFile) {
+ Invoke-WebRequest "http://downloads.example.com/app.exe" -OutFile $outFile # $ Alert
+ gpg --verify "$outFile.sig" $outFile
+ if ($LASTEXITCODE -ne 0) { throw "bad signature" }
+ & $outFile
+}
+
+function Signature_CosignIgnoredFailure($outFile) {
+ Invoke-WebRequest "http://downloads.example.com/app.exe" -OutFile $outFile # $ Alert
+ cosign verify-blob $outFile --bundle "$outFile.sigstore.json" --certificate-identity "release@example.com" --certificate-oidc-issuer "https://accounts.google.com"
+ if ($LASTEXITCODE -ne 0) { Write-Warning "bad signature" }
+ & $outFile
+}
+
+function Signature_GpgOtherExitCode($outFile) {
+ Invoke-WebRequest "http://downloads.example.com/app.exe" -OutFile $outFile # $ Alert
+ gpg --assert-signer "0123456789ABCDEF0123456789ABCDEF01234567" --verify "$outFile.sig" $outFile
+ cmd.exe /c "exit 0"
+ if ($LASTEXITCODE -ne 0) { throw "bad signature" }
+ & $outFile
+}
+
+function Signature_GpgOverwrittenExitCode($outFile) {
+ Invoke-WebRequest "http://downloads.example.com/app.exe" -OutFile $outFile # $ Alert
+ gpg --assert-signer "0123456789ABCDEF0123456789ABCDEF01234567" --verify "$outFile.sig" $outFile
+ $LASTEXITCODE = 0
+ if ($LASTEXITCODE -ne 0) { throw "bad signature" }
+ & $outFile
+}
+
+function Signature_GpgWrongFile($outFile, $other) {
+ Invoke-WebRequest "http://downloads.example.com/app.exe" -OutFile $outFile # $ Alert
+ gpg --assert-signer "0123456789ABCDEF0123456789ABCDEF01234567" --verify "$other.sig" $other
+ if ($LASTEXITCODE -ne 0) { throw "bad signature" }
+ & $outFile
+}
+
+function Signature_GpgAdditionalSigner($outFile) {
+ Invoke-WebRequest "http://downloads.example.com/app.exe" -OutFile $outFile # $ Alert
+ gpg --assert-signer "0123456789ABCDEF0123456789ABCDEF01234567" "--assert-signer=89ABCDEF0123456789ABCDEF0123456789ABCDEF" --verify "$outFile.sig" $outFile
+ if ($LASTEXITCODE -ne 0) { throw "bad signature" }
+ & $outFile
+}
+
+function HttpClient_ResponseExecuted() {
+ $client = [System.Net.Http.HttpClient]::new()
+ $script = $client.GetStringAsync("http://downloads.example.com/install.ps1").Result # $ Alert
+ & ([ScriptBlock]::Create($script))
+}
+
+function ResponseIsNotCallerControl($outFile) {
+ $client = [System.Net.WebClient]::new()
+ $url = $client.DownloadString("https://downloads.example.com/latest-url")
+ Invoke-WebRequest $url -OutFile $outFile
+ & $outFile
+}
+
+function ReturnedTextIsNotAScriptBlock() {
+ $text = Invoke-RestMethod "http://downloads.example.com/script.txt"
+ # A string passed to & is a command name, not PowerShell source text.
+ & $text
+}
+
+function Hash_CombinedFailClosed($outFile, $otherFailure) {
+ Invoke-WebRequest "http://downloads.example.com/app.exe" -OutFile $outFile
+ $hash = (Get-FileHash $outFile).Hash
+ if ($hash -ne "8c954cd9b6c8f8180a05f1de66ee555f0c44b4c6738120785d827521bb8d54df" -or $otherFailure) {
+ throw "verification failed"
+ }
+ & $outFile
+}
+
+function Hash_CombinedBypass($outFile, $verify) {
+ Invoke-WebRequest "http://downloads.example.com/app.exe" -OutFile $outFile # $ Alert
+ $hash = (Get-FileHash $outFile).Hash
+ if ($hash -ne "8c954cd9b6c8f8180a05f1de66ee555f0c44b4c6738120785d827521bb8d54df" -and $verify) {
+ throw "verification failed"
+ }
+ & $outFile
+}
+
+function Hash_ComparisonWithoutEnforcement($outFile) {
+ Invoke-WebRequest "http://downloads.example.com/app.exe" -OutFile $outFile # $ Alert
+ $hash = (Get-FileHash $outFile).Hash
+ if ($hash -eq "8c954cd9b6c8f8180a05f1de66ee555f0c44b4c6738120785d827521bb8d54df") { }
+ & $outFile
+}
+
+function Hash_NegatedEquality($outFile) {
+ Invoke-WebRequest "http://downloads.example.com/app.exe" -OutFile $outFile
+ $hash = (Get-FileHash $outFile).Hash
+ if (-not ($hash -eq "8c954cd9b6c8f8180a05f1de66ee555f0c44b4c6738120785d827521bb8d54df")) {
+ throw "verification failed"
+ }
+ & $outFile
+}
+
+function Signature_CombinedBypass($outFile) {
+ Invoke-WebRequest "http://downloads.example.com/app.exe" -OutFile $outFile # $ Alert
+ $sig = Get-AuthenticodeSignature -FilePath $outFile
+ if ($sig.Status -ne "Valid" -and $sig.SignerCertificate.Thumbprint -ne "0123456789ABCDEF0123456789ABCDEF01234567") {
+ throw "invalid or unexpected signer"
+ }
+ & $outFile
+}