Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Command-line argument accessed without checking argument count

## Overview

The C and C++ standards guarantee that `argv[argc]` is a NULL pointer. A program that reads `argv[n]` without first checking that `argc > n` therefore receives NULL (or reads past the end of the argument vector) when it is started with fewer arguments than expected. Passing that pointer on, for example to `fopen` or `strcpy`, dereferences NULL and crashes the program (CWE-476).

The query reports reads of `argv[n]` and `*(argv + n)` in `main` with a constant index `n >= 1` that are not protected by a check of `argc`. An access is considered protected when it is only evaluated on one branch of a condition that reads `argc`, when a preceding `if` statement that reads `argc` leaves the current path (by returning, exiting, or calling a function that may exit), or when `argc` is passed to a function such as `getopt` before the access.

## Recommendation

Check `argc` before reading command-line arguments and print a usage message when too few arguments were supplied.

## Example

The following program passes `argv[1]` to `ProcessImage` without checking `argc`:

```c
int main(int argc, char **argv) {
ProcessImage(argv[1]); // BAD: NULL when run without arguments
return 0;
}
```

The corrected version checks the argument count first:

```c
int main(int argc, char **argv) {
if (argc < 2) {
fprintf(stderr, "usage: %s <file>\n", argv[0]);
return 1;
}
ProcessImage(argv[1]); // GOOD
return 0;
}
```

## References

- Common Weakness Enumeration: [CWE-476: NULL Pointer Dereference](https://cwe.mitre.org/data/definitions/476.html).
- Common Weakness Enumeration: [CWE-20: Improper Input Validation](https://cwe.mitre.org/data/definitions/20.html).
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
/**
* @name Command-line argument accessed without checking argument count
* @description Reading `argv[n]` in `main` without first checking that `argc`
* is greater than `n` reads a NULL pointer (or past the end of
* the argument vector) when the program is started with too few
* arguments.
* @kind problem
* @problem.severity warning
* @security-severity 3.3
* @precision medium
* @id cpp/argv-access-without-argc-check
* @tags security
* reliability
* external/cwe/cwe-476
* external/cwe/cwe-20
*/

import cpp
import semmle.code.cpp.controlflow.Dominance

/** A `main` (or `wmain`) function with `argc` and `argv` parameters. */
class MainFunction extends Function {
MainFunction() {
this.hasGlobalName(["main", "wmain"]) and
this.getNumberOfParameters() >= 2
}

Parameter getArgc() { result = this.getParameter(0) }

Parameter getArgv() { result = this.getParameter(1) }
}

/**
* An access to `argv[index]` in `main` with a constant `index` of at least 1,
* written either as `argv[index]` or as `*(argv + index)`.
*/
class ConstantArgvAccess extends Expr {
MainFunction main;
int index;

ConstantArgvAccess() {
exists(Expr base, Expr offset |
(
base = this.(ArrayExpr).getArrayBase() and
offset = this.(ArrayExpr).getArrayOffset()
or
exists(PointerAddExpr add |
add = this.(PointerDereferenceExpr).getOperand() and
base = add.getLeftOperand() and
offset = add.getRightOperand()
)
) and
base.(VariableAccess).getTarget() = main.getArgv() and
index = offset.getValue().toInt() and
index >= 1
) and
// `&argv[n]` does not read the element.
not this.getParent() instanceof AddressOfExpr and
not this.isUnevaluated()
}

MainFunction getMain() { result = main }

int getIndex() { result = index }
}

/** Holds if `e` is an expression that reads `argc` of `main`. */
predicate isArgcRead(Expr e, MainFunction main) { e.(VariableAccess).getTarget() = main.getArgc() }

/**
* Holds if function `f` (transitively) calls a function that terminates the
* process, such as `exit` or `abort`.
*/
predicate mayTerminate(Function f) {
f.hasGlobalOrStdName([
"exit", "_exit", "_Exit", "abort", "quick_exit", "err", "errx", "verr", "verrx"
])
or
exists(FunctionCall call |
call.getEnclosingFunction() = f and
mayTerminate(call.getTarget())
)
}

/** Holds if statement `s` contains a statement or call that leaves the current path. */
predicate leavesPath(Stmt s) {
exists(Stmt inner | inner.getParentStmt*() = s |
inner instanceof ReturnStmt or
inner instanceof GotoStmt or
inner instanceof BreakStmt or
inner instanceof ContinueStmt
)
or
exists(FunctionCall call | call.getEnclosingStmt().getParentStmt*() = s |
mayTerminate(call.getTarget())
)
or
exists(ThrowExpr t | t.getEnclosingStmt().getParentStmt*() = s)
}

/**
* Holds if `access` is only evaluated on one branch of a condition `cond`,
* for example inside an `if`, loop, `?:` or the right operand of `&&`/`||`.
*
* This is purely syntactic so that it also works when several programs in
* the same database define `main` (whose definitions are then merged).
*/
predicate isConditionallyEvaluated(ConstantArgvAccess access, Expr cond) {
exists(IfStmt s | cond = s.getCondition() | access.getEnclosingStmt().getParentStmt+() = s)
or
exists(Loop l | cond = l.getCondition() |
access.getEnclosingStmt().getParentStmt+() = l.getStmt()
)
Comment thread
felickz marked this conversation as resolved.
Resolved
or
exists(ConditionalExpr c | cond = c.getCondition() |
access.getParent*() = [c.getThen(), c.getElse()]
)
or
exists(BinaryLogicalOperation op | cond = op.getLeftOperand() |
access.getParent*() = op.getRightOperand()
)
}

/**
* Holds if `access` is protected by a check of `argc`: either the access is
* only reached on one branch of a condition that reads `argc`, or a preceding
* `if` statement that reads `argc` leaves the current path (by returning,
* exiting or similar) when the check fails.
*/
predicate isArgcChecked(ConstantArgvAccess access) {
exists(Expr cond, Expr argc |
isConditionallyEvaluated(access, cond) and
isArgcRead(argc, access.getMain()) and
argc.getParent*() = cond and
(
not exists(Loop l | cond = l.getCondition())
or
dominates(argc, access)
)
)
or
exists(IfStmt ifStmt, Expr argc |
isArgcRead(argc, access.getMain()) and
argc.getParent*() = ifStmt.getCondition() and
(leavesPath(ifStmt.getThen()) or leavesPath(ifStmt.getElse())) and
dominates(argc, access)
)
or
// `argc` is validated by a helper, for example `check_args(argc, argv)`, or
// passed to an option parser such as `getopt`.
exists(FunctionCall call, Expr argc |
isArgcRead(argc, access.getMain()) and
argc = call.getAnArgument() and
dominates(call, access)
)
}

from ConstantArgvAccess access
where not isArgcChecked(access)
select access,
"argv[" + access.getIndex() + "] is read without checking that argc is greater than " +
access.getIndex() + "; it is NULL when the program is run with fewer arguments."
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Untrusted divisor without zero check

## Overview

Integer division and remainder by zero is undefined behavior in C and C++ and, on most platforms, terminates the process with a fault such as `SIGFPE`. When the divisor comes from untrusted input (a file, a network socket, an environment variable or the command line) and is not checked against zero, an attacker can crash the program by supplying `0`. This is a denial-of-service vulnerability (CWE-369).

The query tracks untrusted data to the divisor of `/`, `%`, `/=` and `%=` on integer types. Fields read from a structure that was filled as a whole (for example `fread(&img, sizeof(img), 1, fp)`) are treated as untrusted. Any comparison of the divisor, or a truthiness test such as `if (n)`, is treated as validation, and divisors that range analysis shows to be non-zero (such as `(x % 10) + 1`) are not reported.

## Recommendation

Check every divisor that is derived from external input before using it, and reject or handle the zero case explicitly.

## Example

The following example reads an image header from a file and divides by its `height` field without checking it:

```c
struct Image img;
while (fread(&img, sizeof(img), 1, fp) > 0) {
int ratio = img.width / img.height; // BAD: height may be 0
}
```

The corrected version rejects a zero height before the division:

```c
struct Image img;
while (fread(&img, sizeof(img), 1, fp) > 0) {
if (img.height == 0)
continue;
int ratio = img.width / img.height; // GOOD
}
```

## References

- Common Weakness Enumeration: [CWE-369: Divide By Zero](https://cwe.mitre.org/data/definitions/369.html).
- SEI CERT C Coding Standard: [INT33-C. Ensure that division and remainder operations do not result in divide-by-zero errors](https://wiki.sei.cmu.edu/confluence/display/c/INT33-C.+Ensure+that+division+and+remainder+operations+do+not+result+in+divide-by-zero+errors).
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
/**
* @name Untrusted divisor without zero check
* @description Using a value read from a file, socket, environment variable or
* command line as the divisor of an integer division or remainder
* without first checking it against zero allows an attacker to
* crash the program with a divide-by-zero fault.
* @kind path-problem
* @problem.severity warning
* @security-severity 5.3
* @precision medium
* @id cpp/tainted-divisor-without-zero-check
* @tags security
* reliability
* external/cwe/cwe-369
*/

import cpp
import semmle.code.cpp.ir.dataflow.TaintTracking
import semmle.code.cpp.security.FlowSources
import semmle.code.cpp.controlflow.IRGuards
import semmle.code.cpp.rangeanalysis.SimpleRangeAnalysis
import semmle.code.cpp.controlflow.Dominance
import TaintedDivisorFlow::PathGraph

/** Gets the divisor operand of an integer division or remainder operation `op`. */
Expr getIntegerDivisor(Expr op) {
(
result = op.(DivExpr).getRightOperand() or
result = op.(RemExpr).getRightOperand() or
result = op.(AssignDivExpr).getRValue() or
result = op.(AssignRemExpr).getRValue()
) and
op.getUnspecifiedType() instanceof IntegralType
}

/**
* Holds if `divisor` can be shown to be non-zero by range analysis, for
* example `(x % 10) + 1`.
*/
predicate isProvablyNonZero(Expr divisor) {
lowerBound(divisor.getFullyConverted()) > 0 or
upperBound(divisor.getFullyConverted()) < 0
}

/**
* Holds if `g` is a check that validates `e` on the `branch` edge. Any
* comparison of `e`, or a test of `e` for truthiness, is treated as
* validation since the exact non-zero bound is often expressed indirectly
* (for example `if (height <= 0) return;`).
*/
predicate validatesValue(IRGuardCondition g, Expr e, boolean branch) {
exists(ComparisonOperation cmp |
cmp = g.getUnconvertedResultExpression() and
e = cmp.getAnOperand() and
branch = [true, false]
)
or
e = g.getUnconvertedResultExpression() and
not e instanceof ComparisonOperation and
branch = true
or
exists(NotExpr not_ |
not_ = g.getUnconvertedResultExpression() and
e = not_.getOperand() and
branch = false
)
}

/**
* Holds if `fa` accesses field `f` of the aggregate denoted by `base`, either
* directly (`s.f`, `p->f`) or through an explicit dereference (`(*p).f`).
*/
predicate fieldAccessOf(FieldAccess fa, VariableAccess base, Field f) {
f = fa.getTarget() and
(
base = fa.getQualifier()
or
base = fa.getQualifier().(PointerDereferenceExpr).getOperand()
)
}

/**
* Holds if field `f` of variable `v` is assigned by `assign`, which dominates
* the field read `fa` or is itself the assignment's lvalue.
*/
predicate overwrittenBefore(
DataFlow::Node aggregate, VariableAccess base, FieldAccess fa, Field f
) {
exists(Assignment assign, VariableAccess otherBase, FunctionCall write, VariableAccess writeBase |
fieldAccessOf(assign.getLValue(), otherBase, f) and
otherBase.getTarget() = base.getTarget() and
(
aggregate.asIndirectExpr().(VariableAccess).getTarget() = base.getTarget()
or aggregate.asExpr().(VariableAccess).getTarget() = base.getTarget()
) and
write.getTarget().hasGlobalName(["fread", "recv"]) and
writeBase.getParent*() = write.getAnArgument() and
writeBase.getTarget() = base.getTarget() and
dominates(write, assign) and
(dominates(assign, fa) or fa = assign.getLValue())
)
}

/**
* Holds if `fieldRead` reads a field of an aggregate `base` that was written
* as a whole (for example by `fread(&img, ...)` or `recv(s, &hdr, ...)`).
*/
predicate aggregateToFieldStep(DataFlow::Node aggregate, DataFlow::Node fieldRead) {
exists(FieldAccess fa, VariableAccess base, Field f |
fieldRead.asExpr() = fa and
fieldAccessOf(fa, base, f) and
not overwrittenBefore(aggregate, base, fa, f) and
(
aggregate.asIndirectExpr() = base
or
aggregate.asExpr() = base and base.getUnspecifiedType() instanceof Class
)
)
}

module TaintedDivisorConfig implements DataFlow::ConfigSig {
predicate isSource(DataFlow::Node source) { source instanceof FlowSource }

predicate isSink(DataFlow::Node sink) {
exists(Expr divisor |
divisor = getIntegerDivisor(_) and
sink.asExpr() = divisor and
not isProvablyNonZero(divisor)
)
}

predicate isBarrier(DataFlow::Node node) {
node = DataFlow::BarrierGuard<validatesValue/3>::getABarrierNode()
}
Comment thread
felickz marked this conversation as resolved.
Resolved

predicate isAdditionalFlowStep(DataFlow::Node n1, DataFlow::Node n2) {
aggregateToFieldStep(n1, n2)
}
}

module TaintedDivisorFlow = TaintTracking::Global<TaintedDivisorConfig>;

from
TaintedDivisorFlow::PathNode source, TaintedDivisorFlow::PathNode sink, Expr op,
FlowSource flowSource
where
TaintedDivisorFlow::flowPath(source, sink) and
sink.getNode().asExpr() = getIntegerDivisor(op) and
flowSource = source.getNode()
select sink.getNode(), source, sink,
"This divisor depends on $@ and is not checked against zero before the $@.", flowSource,
flowSource.getSourceType(), op, "division"
Loading
Loading