Skip to content
This repository was archived by the owner on Oct 27, 2021. It is now read-only.

Commit

Permalink
Merge pull request #41 from maltek/signed-shift
Browse files Browse the repository at this point in the history
query for signed shifts
  • Loading branch information
itsacoderepo authored Jan 20, 2021
2 parents 71de5d1 + b099f34 commit bf93c51
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/main/scala/io/joern/scanners/c/SignedLeftShift.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package io.joern.scanners.c

import io.joern.scanners._
import io.shiftleft.codepropertygraph.generated.Operators
import io.shiftleft.console._
import io.shiftleft.semanticcpg.language._

object SignedLeftShift extends QueryBundle {

@q
def signedLeftShift(): Query = Query(
name = "signed-left-shift",
author = Crew.malte,
title = "Signed Shift May Cause Undefined Behavior",
description =
"""
|Signed integer overflow is undefined behavior. Shifts of signed values to the
|left are very prone to overflow.
|""".stripMargin,
score = 2,
docStartLine = sourcecode.Line(),
traversal = { cpg =>
cpg.call
.nameExact(Operators.shiftLeft, Operators.assignmentShiftLeft)
.where(_.argument(1).typ.fullNameExact("int", "long"))
.filterNot(_.argument.isLiteral.size == 2) // assume such constant values produces a correct result
},
docEndLine = sourcecode.Line(),
docFileName = sourcecode.FileName()
)

}
36 changes: 36 additions & 0 deletions src/test/scala/io/joern/scanners/c/SignedLeftShiftTests.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package io.joern.scanners.c

import io.shiftleft.codepropertygraph.generated.nodes
import io.shiftleft.console.scan._
import io.shiftleft.semanticcpg.language._

class SignedLeftShiftTests extends Suite {

override val code =
"""
void bad1(int val) {
val <<= 24;
}
void bad2(int val) {
255 << val;
}
void bad3(int val) {
val << val;
}
void good(unsigned int val) {
255 << 24; // we ignore signed shift with two literals
val <<= 24;
val << val;
}
"""

"find signed left shift" in {
SignedLeftShift.signedLeftShift()(cpg).flatMap(_.evidence).map{
case c: nodes.Call =>
c.method.name
case _ => fail
}.toSet shouldBe Set("bad1", "bad2", "bad3")
}

}

0 comments on commit bf93c51

Please sign in to comment.