Movatterモバイル変換


[0]ホーム

URL:


Avoiding SQL injection risk

You can avoid an SQL injection risk by providing SQL parameter values assqlpackage function arguments. Many functions in thesql package provideparameters for the SQL statement and for values to be used in that statement’sparameters (others provide a parameter for a prepared statement and parameters).

Code in the following example uses the? symbol as a placeholder for theid parameter, which is provided as a function argument:

// Correct format for executing an SQL statement with parameters.rows, err := db.Query("SELECT * FROM user WHERE id = ?", id)

sql package functions that perform database operations create preparedstatements from the arguments you supply. At run time, thesql package turnsthe SQL statement into a prepared statement and sends it along with theparameter, which is separate.

Note: Parameter placeholders vary depending on the DBMS and driveryou’re using. For example,pq driverfor Postgres accepts a placeholder form such as$1 instead of?.

You might be tempted to use a function from thefmt package to assemble theSQL statement as a string with parameters included – like this:

// SECURITY RISK!rows, err := db.Query(fmt.Sprintf("SELECT * FROM user WHERE id = %s", id))

This is not secure! When you do this, Go assembles the entire SQL statement,replacing the%s format verb with the parameter value, before sending thefull statement to the DBMS. This poses anSQL injection risk because thecode’s caller could send an unexpected SQL snippet as theid argument. Thatsnippet could complete the SQL statement in unpredictable ways that aredangerous to your application.

For example, by passing a certain%s value, you might end up with somethinglike the following, which could return all user records in your database:

SELECT * FROM user WHERE id = 1 OR 1=1;
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp