Prevent SQL and command injection
Prevent SQL and command injection
Keep instructions separate from data. A SQL driver can bind a value to a placeholder rather than treating it as query syntax. The placeholder style depends on the database driver. Use fixed query text and bind values; allowlist any dynamic identifiers or sort directions because ordinary placeholders do not represent SQL identifiers.
package main
import ( "context" "database/sql" "fmt")
func lookup(ctx context.Context, db *sql.DB, name string) (string, error) { var label string e := db.QueryRowContext(ctx, "SELECT label FROM items WHERE name = ?", name).Scan(&label) return label, e}func main() { fmt.Println("query function compiled")}The lookup function illustrates a query for a driver using question-mark placeholders. The example only compiles the function; it does not connect to a database. Handle sql.ErrNoRows separately from infrastructure errors and avoid logging bound values. Integration tests with the actual driver are required.
Expected output:
query function compiledBuild a fixed argument list
package main
import ( "errors" "fmt")
func taskArgs(label string) ([]string, error) { if label != "blue" && label != "green" { return nil, errors.New("unsupported label") } return []string{"--label", label}, nil}func main() { a, e := taskArgs("blue") fmt.Println(a, e == nil) _, e = taskArgs("other") fmt.Println(e != nil)}When invoking a trusted program, pass separate arguments to exec.CommandContext, not a constructed shell command. Here only the argument list is built, never executed. Separate arguments do not prevent dangerous options or unsafe behavior in the called program; validate allowed values, use a trusted executable path, limit runtime and output, and review its option semantics. Windows argument rules may differ.
Expected output:
[--label blue] truetrueTry it locally
Check that green is accepted and an empty label is rejected.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Security engineering 02: Prevent SQL and command injection
Check the lesson objective before moving on.
What should a SQL placeholder represent here?
Why validate arguments even without a shell?