Uncontrolled data in SQL query¶
ID: cpp/sql-injectionKind: path-problemSecurity severity: 8.8Severity: errorPrecision: highTags: - security - external/cwe/cwe-089Query 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 usingsprintf, with the user-supplied data directly passed as an argument tosprintf. 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.