Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

Database query built from user-controlled sources

ID: go/sql-injectionKind: path-problemSecurity severity: 8.8Severity: errorPrecision: highTags:   - security   - external/cwe/cwe-089Query suites:   - go-code-scanning.qls   - go-security-extended.qls   - go-security-and-quality.qls

Click to see the query in the CodeQL repository

If a database query (such as an SQL or NoSQL query) is built from user-provided data without sufficient sanitization, a malicious user may be able to run commands that exfiltrate, tamper with, or destroy data stored in the database.

Recommendation

Most database connector libraries offer a way of safely embedding untrusted data into a query by means of query parameters or prepared statements. Use these features rather than building queries by string concatenation.

Example

In the following example, assume the functionhandler is an HTTP request handler in a web application, whose parameterreq contains the request object:

packagemainimport("database/sql""fmt""net/http")funchandler(db*sql.DB,req*http.Request){q:=fmt.Sprintf("SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='%s' ORDER BY PRICE",req.URL.Query()["category"])db.Query(q)}

The handler constructs an SQL query involving user input taken from the request object unsafely usingfmt.Sprintf to embed a request parameter directly into the query stringq. The parameter may include quote characters, allowing a malicious user to terminate the string literal into which the parameter is embedded and add arbitrary SQL code after it.

Instead, the untrusted query parameter should be safely embedded using placeholder parameters:

packagemainimport("database/sql""net/http")funchandlerGood(db*sql.DB,req*http.Request){q:="SELECT ITEM,PRICE FROM PRODUCT WHERE ITEM_CATEGORY='?' ORDER BY PRICE"db.Query(q,req.URL.Query()["category"])}

References


[8]ページ先頭

©2009-2025 Movatter.jp