SQL injection

SQL injection

Description

Concatenating or formatting a request value into SQL lets that value change the query conditions.

Potential impact

A query may expose other users’ data or bypass access checks. Changes, deletion and service disruption depend on database privileges. Driver settings also determine whether multiple statements can run.

Remediation

  • Use your driver’s placeholders, such as ? or $1, in db.Query, db.QueryRow and db.Exec. Pass values as separate arguments. Use value binding with ORMs and query builders as well.
  • Reject invalid numeric IDs before binding them. Select column names and sort directions from an allow-list defined in code.
  • Grant only the database privileges the application needs. Keep detailed errors in protected logs and return a generic error to the user.

Examples

The examples assume a driver that supports ?. Handle authentication, permission to read the record and response output separately.

Before

go
package main

import (
    "database/sql"
    "net/http"
)

// Before: a handler that concatenates input into SQL
func unsafeUserDetailHandler(db *sql.DB) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        // Read id directly as a query-parameter string
        userID := r.URL.Query().Get("id")

        // Unsafe: build SQL by concatenating user input
        // Example: /user?id=1 OR 1=1 --
        query := "SELECT name, email FROM users WHERE id = " + userID

        row := db.QueryRow(query)
        var name, email string
        if err := row.Scan(&name, &email); err != nil {
            http.Error(w, "error", http.StatusInternalServerError)
            return
        }

        w.Write([]byte(name + " / " + email))
    }
}

After

go
package main

import (
    "database/sql"
    "net/http"
    "strconv"
)

// After: a handler using a parameterized statement
func safeUserDetailHandler(db *sql.DB) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        userIDStr := r.URL.Query().Get("id")

        // 1. Validate the type: reject non-numeric input
        userID, err := strconv.Atoi(userIDStr)
        if err != nil {
            http.Error(w, "invalid id", http.StatusBadRequest)
            return
        }

        // 2. Use a parameterized statement and placeholder
        //   - Bind values to placeholders such as `?` or `$1`
        //     so their string contents cannot change the query structure
        const query = "SELECT name, email FROM users WHERE id = ?"

        row := db.QueryRow(query, userID)
        var name, email string
        if err := row.Scan(&name, &email); err != nil {
            http.Error(w, "not found", http.StatusNotFound)
            return
        }

        w.Write([]byte(name + " / " + email))
    }
}

The revised handler converts the ID with strconv.Atoi and passes it separately to QueryRow. Scan reads only the first row. Return a not-found response for sql.ErrNoRows and handle database failures separately.

References