Files
codeql-workshop-sql-injecti…/src/README.org
2023-08-16 15:04:33 -07:00

3.4 KiB
Raw Blame History

SQL injection example

This directory contains the problematic Java source code. The rest of this README describes

The codeql query is developed in ../session/README.org.

Setup and sample run

The jdbc connector at https://github.com/xerial/sqlite-jdbc, from here is included in the git repository.

  # Use a simple headline prompt 
  PS1='
  \033[32m---- SQL injection demo ----\[\033[33m\033[0m\]
  $?:$ '

  
  # Build
  ./build.sh

  # Prepare db
  ./admin -r
  ./admin -c
  ./admin -s 

  # Add regular user interactively
  ./add-user 2>> users.log
  First User

  # Check
  ./admin -s

  # Add Johnny Droptable 
  ./add-user 2>> users.log
  Johnny'); DROP TABLE users; --

  # And the problem:
  ./admin -s

  # Check the log
  tail users.log

Identify the problem

./add-user is reading from STDIN, and writing to a database; looking at the code in ./AddUser.java leads to

System.console().readLine();

for the read and

conn.createStatement().executeUpdate(query);

for the write.

This problem is thus a dataflow problem; in codeql terminology we have

  • a source at the System.console().readLine();
  • a sink at the conn.createStatement().executeUpdate(query);

We write codeql to identify these two, and then connect them via

  • a dataflow configuration for this problem, the more general taintflow configuration.

Build the codeql database

To get started, build the codeql database (adjust paths to your setup):

  # Build the db with source commit id.
  SRCDIR=$(pwd)
  DB=$SRCDIR/java-sqli-$(cd $SRCDIR && git rev-parse --short HEAD)

  echo $DB
  test -d "$DB" && rm -fR "$DB"
  mkdir -p "$DB"

  cd $SRCDIR && codeql database create --language=java -s . -j 8 -v $DB --command='./build.sh'

  # Check for AddUser in the db
  unzip -v $DB/src.zip | grep AddUser

Then add this database directory to your VS Code DATABASES tab.

(old / optional) Build the codeql database in steps

For larger projects, using a single command to build everything is costly when any part of the build fails.

To build a database in steps, use the following sequence, adjusting paths to your setup:

  # Build the db with source commit id.
  export PATH=$HOME/local/vmsync/codeql250:"$PATH"
  SRCDIR=$HOME/local/codeql-training-material.java-sqli/java/codeql-dataflow-sql-injection
  DB=$SRCDIR/java-sqli-$(cd $SRCDIR && git rev-parse --short HEAD)

  # Check paths
  echo $DB
  echo $SRCDIR

  # Prepare db directory
  test -d "$DB" && rm -fR "$DB"
  mkdir -p "$DB"

  # Run the build
  cd $SRCDIR
  codeql database init --language=java -s . -v $DB
  # Repeat trace-command as needed to cover all targets
  codeql database trace-command -v $DB -- make 
  codeql database finalize -j4 $DB

Then add this database directory to your VS Code DATABASES tab.