Skip to content

[C++] Taint analysis does not appear to handle aliasing #18151

@JustusAdam

Description

@JustusAdam

Taint analysis appears to loose taint whenever assignments to pointer aliases are involved.

This first example is very simple but the flow from source to sink is not found. It appears to me as though there is no alias analysis being performed if this simple case doesn’t work?

__attribute__((noinline)) int source()
{
    return 2;
}

__attribute__((noinline)) int target(int source)
{
    return source;
}

void test_values() {
    int *a = new int[1];
    int *b = a;
    a[0] = source();
    target(b[0]);
    target(a[0]);
}

This is the output I get from this example. Only the flow via a is detected.

|     source     | source_line |        sink        | sink_line |
+----------------+-------------+--------------------+-----------+
| call to source |          14 | access to array    |        16 |

I had wondered if maybe an alias analysis is only performed to resolve dynamic dispatch, but in this simple case it has the same problem. Only the first flow is found, not the second one

int a_function()
{
    return source();
}

int b_function()
{
    return 0;
}

int test_dispatch()
{
    int (*fptr)();

    fptr = a_function;

    target(fptr());

    int (*fptr2)();
    int (**fptr2_ptr)() = &fptr2;
    fptr2 = b_function;
    *fptr2_ptr = a_function;

    target(fptr2());

    return 0;
}

This is the output. (The line numbers are off by 10, because I’ve omitted defining source and target again).

|     source     | source_line |        sink        | sink_line |
+----------------+-------------+--------------------+-----------+
| call to source |          13 | call to expression |        27 |

The query I run in all of these cases is the following

import cpp
import semmle.code.cpp.dataflow.new.TaintTracking

module SourceSinkCallConfig implements DataFlow::ConfigSig {
  predicate isSource(DataFlow::Node source) {
    source.asExpr().(Call).getTarget().getName() = "source"
  }

  predicate isSink(DataFlow::Node sink) {
    exists(Call call |
      call.getTarget().getName() = "target" and
      call.getArgument(0) = sink.asExpr()
    )
  }
}

module SourceSinkCallTaint = TaintTracking::Global<SourceSinkCallConfig>;

from DataFlow::Node source, DataFlow::Node sink, int source_line, int sink_line
where
  SourceSinkCallTaint::flow(source, sink) and
  source_line = source.getLocation().getStartLine() and
  sink_line = sink.getLocation().getStartLine()
select source, source_line, sink, sink_line

CodeQL version: 2.19.3

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions