From 164c6b3441f0b109a4adda87edd0c6c49cdc935f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?= Date: Fri, 18 Dec 2020 21:32:23 +0100 Subject: [PATCH] Bug hunting; Detect array index out of bounds for multi dimensional arrays also --- lib/bughuntingchecks.cpp | 11 ++++++++--- test/testbughuntingchecks.cpp | 9 +++++++++ 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/lib/bughuntingchecks.cpp b/lib/bughuntingchecks.cpp index adb8c1e59..8ee572d79 100644 --- a/lib/bughuntingchecks.cpp +++ b/lib/bughuntingchecks.cpp @@ -46,16 +46,21 @@ static void arrayIndex(const Token *tok, const ExprEngine::Value &value, ExprEng { if (!Token::simpleMatch(tok->astParent(), "[")) return; + int nr = 0; const Token *buf = tok->astParent()->astOperand1(); - if (!buf || !buf->variable() || !buf->variable()->isArray()) + while (Token::simpleMatch(buf, "[")) { + ++nr; + buf = buf->astOperand1(); + } + if (!buf || !buf->variable() || !buf->variable()->isArray() || buf == buf->variable()->nameToken()) // TODO return; const Token *index = tok->astParent()->astOperand2(); if (tok != index) // TODO return; - if (buf->variable()->dimensions().size() == 1 && buf->variable()->dimensions()[0].known) { - const MathLib::bigint bufSize = buf->variable()->dimensions()[0].num; + if (buf->variable()->dimensions().size() > nr && buf->variable()->dimensions()[nr].known) { + const MathLib::bigint bufSize = buf->variable()->dimensions()[nr].num; if (value.isGreaterThan(dataBase, bufSize - 1)) { const bool bailout = (value.type == ExprEngine::ValueType::BailoutValue); dataBase->reportError(tok, diff --git a/test/testbughuntingchecks.cpp b/test/testbughuntingchecks.cpp index c5c4635c9..5dcdef71b 100644 --- a/test/testbughuntingchecks.cpp +++ b/test/testbughuntingchecks.cpp @@ -41,6 +41,7 @@ private: TEST_CASE(arrayIndexOutOfBounds3); TEST_CASE(arrayIndexOutOfBounds4); TEST_CASE(arrayIndexOutOfBounds5); + TEST_CASE(arrayIndexOutOfBoundsDim1); TEST_CASE(bufferOverflowMemCmp1); TEST_CASE(bufferOverflowMemCmp2); TEST_CASE(bufferOverflowStrcpy1); @@ -153,6 +154,14 @@ private: errout.str()); } + void arrayIndexOutOfBoundsDim1() { // itc test case + check("void overrun_st_008 () {\n" + " int buf[5][6];\n" + " buf[5][5] = 1;\n" + "}"); + ASSERT_EQUALS("[test.cpp:3]: (error) Array index out of bounds, cannot determine that 5 is less than 5\n", errout.str()); + } + void bufferOverflowMemCmp1() { // CVE-2020-24265 check("void foo(const char *pktdata, int datalen) {\n"