Uncontrolled data in SQL query¶
ID: cpp/sql-injection Kind: path-problem Security severity: 8.8 Severity: error Precision: high Tags: - security - external/cwe/cwe-089 Query suites: - cpp-code-scanning.qls - cpp-security-extended.qls - cpp-security-and-quality.qls
Click to see the query in the CodeQL repository
The code passes user input as part of a SQL query without escaping special elements. It generates a SQL query using sprintf
, with the user-supplied data directly passed as an argument to sprintf
. This leaves the code vulnerable to attack by SQL Injection.
Recommendation¶
Use a library routine to escape characters in the user-supplied string before converting it to SQL.
Example¶
intmain(intargc,char**argv){char*userName=argv[2];// BADcharquery1[1000]={0};sprintf(query1,"SELECT UID FROM USERS where name = \"%s\"",userName);runSql(query1);// GOODcharuserNameSql[1000]={0};encodeSqlString(userNameSql,1000,userName);charquery2[1000]={0};sprintf(query2,"SELECT UID FROM USERS where name = \"%s\"",userNameSql);runSql(query2);}
References¶
MSDN Library: SQL Injection.
Common Weakness Enumeration: CWE-89.