From 4a2fd527edea3e40f4891bc89ba4a623a60d1077 Mon Sep 17 00:00:00 2001 From: Mathias Vorreiter Pedersen Date: Fri, 8 Nov 2024 15:01:18 +0000 Subject: [PATCH] PS: Add reads of environment variables as local flow sources. --- .../ql/lib/semmle/code/powershell/Variable.qll | 15 +++++++++++++++ .../semmle/code/powershell/VariableExpression.qll | 9 +++++++++ .../powershell/dataflow/flowsources/Local.qll | 6 ++++++ 3 files changed, 30 insertions(+) diff --git a/powershell/ql/lib/semmle/code/powershell/Variable.qll b/powershell/ql/lib/semmle/code/powershell/Variable.qll index 39ac5bdabb2..f5cb7259e0e 100644 --- a/powershell/ql/lib/semmle/code/powershell/Variable.qll +++ b/powershell/ql/lib/semmle/code/powershell/Variable.qll @@ -273,6 +273,21 @@ class LocalVariable extends AbstractLocalScopeVariable, TLocalVariable { final override Scope getDeclaringScope() { result = scope } } +/** + * A variable of the form `$Env:HOME`. + */ +class EnvVariable extends Variable { + string var; + + EnvVariable() { this.getName() = ["env:", "Env:"] + var } + + /** + * Gets the part of the variable name that represens which environment + * variable. + */ + string getEnvironmentVariable() { result = var } +} + class Parameter extends AbstractLocalScopeVariable, TParameter { ParameterImpl p; diff --git a/powershell/ql/lib/semmle/code/powershell/VariableExpression.qll b/powershell/ql/lib/semmle/code/powershell/VariableExpression.qll index 4259ecd79ea..b07774a2924 100644 --- a/powershell/ql/lib/semmle/code/powershell/VariableExpression.qll +++ b/powershell/ql/lib/semmle/code/powershell/VariableExpression.qll @@ -48,3 +48,12 @@ class VarWriteAccess extends VarAccess { predicate isImplicit() { isImplicitVariableWriteAccess(this) } } + +/** An access to an environment variable such as `$Env:PATH` */ +class EnvVarAccess extends VarAccess { + EnvVarAccess() { super.getVariable() instanceof EnvVariable } + + override EnvVariable getVariable() { result = super.getVariable() } + + string getEnvironmentVariable() { result = this.getVariable().getEnvironmentVariable() } +} diff --git a/powershell/ql/lib/semmle/code/powershell/dataflow/flowsources/Local.qll b/powershell/ql/lib/semmle/code/powershell/dataflow/flowsources/Local.qll index 48f64b17be4..b27d24a051c 100644 --- a/powershell/ql/lib/semmle/code/powershell/dataflow/flowsources/Local.qll +++ b/powershell/ql/lib/semmle/code/powershell/dataflow/flowsources/Local.qll @@ -30,6 +30,12 @@ abstract class EnvironmentVariableSource extends LocalFlowSource { override string getSourceType() { result = "environment variable" } } +private class EnvironmentVariableEnv extends EnvironmentVariableSource { + EnvironmentVariableEnv() { + this.asExpr().getExpr().(VarReadAccess).getVariable() instanceof EnvVariable + } +} + private class ExternalEnvironmentVariableSource extends EnvironmentVariableSource { ExternalEnvironmentVariableSource() { this = ModelOutput::getASourceNode("environment", _).asSource()