Question

I am investigating a possible SQL injection bug in some COBOL code. The code uses host variables to submit the statement to a DB2 database. e.g.

EXEC SQL INSERT INTO TBL (a, b, c) VALUES (:x, :y, :z) END-EXEC

Can anyone tell me if this method would be vulnerable to an SQLi attack or if the way COBOL/DB2 parses the host variables means that it would be impossible to execute?

Every thing I read suggests there are better ways to protect against SQLi but the IBM website does mention using host variables but doesn't explain if it would totally mitigate against the attack.

No correct solution

OTHER TIPS

Static statements with host variables are not susceptible to SQL injection attacks.

Non-parameterized dynamic statements are what you need to worry about... They would look something like so: (my COBOL is rusty)

STRING "INSERT INTO TBL (a,b,c) VALUES ("
         X ", " 
         Y ", "
         Z ")" INTO WSQLSTMT.

EXEC SQL PREPARE MYSTMT FROM :WSQLSTMT END-EXEC.
EXEC SQL EXECUTE MYSTMT END-EXEC.

Note that you could use EXECUTE IMMEDIATE, in place of the two step PREPARE and EXECUTE

In contrast, a parameterized dynamic query looks like:

STRING "INSERT INTO TBL (a,b,c) VALUES (?, ?, ?)" INTO WSQLSTMT.
EXEC SQL PREPARE MYSTMT FROM :WSQLSTMT END-EXEC.
EXEC SQL EXECUTE MYSTMT USING :X, :Y, :Z END-EXEC.

In summary, a static query with host variables like you original posted is SAFE as is a parameterized dynamic query. A non-parameterized query that directly uses the user input to build the SQL statement to execute is NOT SAFE.

The key thing to understand is that the statement must be compiled (PREPARED) in advance before the run-time values of the variables come into play. In you original static statement, the statement is prepared automatically at compile time.

Side note, since a static statement is prepared at compile time, it performs better than a dynamic statement prepared at run time. So it's usually best to use static statements whenever possible.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top