|
| 1 | +// Semmle test case for rule SprintfToSqlQuery.ql (Uncontrolled sprintf for SQL query) |
| 2 | +// Associated with CWE-089: SQL injection. http://cwe.mitre.org/data/definitions/89.html |
| 3 | + |
| 4 | +///// Library routines ///// |
| 5 | + |
| 6 | +typedef unsigned long size_t; |
| 7 | +int snprintf(char *s, size_t n, const char *format, ...); |
| 8 | +void sanitizeString(char *stringOut, size_t len, const char *strIn); |
| 9 | +int mysql_query(int arg1, const char *sqlArg); |
| 10 | +int atoi(const char *nptr); |
| 11 | + |
| 12 | +///// Test code ///// |
| 13 | + |
| 14 | +int main(int argc, char** argv) { |
| 15 | + char *userName = argv[2]; |
| 16 | + int userNumber = atoi(argv[3]); |
| 17 | + |
| 18 | + // a string from the user is injected directly into an SQL query. |
| 19 | + char query1[1000] = {0}; |
| 20 | + snprintf(query1, 1000, "SELECT UID FROM USERS where name = \"%s\"", userName); |
| 21 | + mysql_query(0, query1); // BAD |
| 22 | + |
| 23 | + // the user string is encoded by a library routine. |
| 24 | + char userNameSanitized[1000] = {0}; |
| 25 | + sanitizeString(userNameSanitized, 1000, userName); |
| 26 | + char query2[1000] = {0}; |
| 27 | + snprintf(query2, 1000, "SELECT UID FROM USERS where name = \"%s\"", userNameSanitized); |
| 28 | + mysql_query(0, query2); // GOOD |
| 29 | + |
| 30 | + // an integer from the user is injected into an SQL query. |
| 31 | + char query3[1000] = {0}; |
| 32 | + snprintf(query3, 1000, "SELECT UID FROM USERS where number = \"%i\"", userNumber); |
| 33 | + mysql_query(0, query3); // GOOD |
| 34 | +} |
0 commit comments