Go security pitfalls

From makifbaysal/tasktrooper · View interactive version

Go security pitfalls is an AI agent skill from the GitHub repository makifbaysal/tasktrooper. Use when reviewing Go changes - net/http and Fiber handlers, database/sql and GORM queries, os/exec, filepath and os.Root, html/template, crypto, TLS and SSH clients, JSON binding

How to use this skill

Skill file

Go Security Pitfalls

Overview

Go removes whole classes of bugs (memory safety, implicit shell, unsafe default deserialization), which makes the remaining ones look innocent: a fmt.Sprintf in a query builder, a HasPrefix path check, a template.HTML conversion. Memory-safety findings in pure Go are excluded; unsafe and cgo are the exception.

1. SQL: database/sql, sqlx, GORM (CWE-89)

// ❌
db.QueryContext(ctx, fmt.Sprintf("SELECT * FROM tasks WHERE owner = '%s'", owner))
// ✅
db.QueryContext(ctx, "SELECT * FROM tasks WHERE owner = $1", owner)

GORM accepts raw SQL in more places than people expect:

// ❌ all of these take SQL text
db.Where(fmt.Sprintf("name = '%s'", name)).Find(&users)
db.Order(r.URL.Query().Get("sort")).Find(&users)   // ORDER BY injection
db.First(&user, r.PathValue("id"))                // a string id is used as an inline condition
db.Raw("SELECT … " + filter).Scan(&rows)
// ✅
db.Where("name = ?", name).Find(&users)
db.Order(clause.OrderByColumn{Column: clause.Column{Name: sortCols[key]}}).Find(&users)
db.First(&user, "id = ?", id)

2. Commands: os/exec (CWE-78, CWE-88)

exec.Command never invokes a shell — unless you pass sh -c. With separate args the risk is argument injection:

// ❌ shell
exec.Command("sh", "-c", "git clone "+repoURL).Run()
// ❌ no shell, but repoURL = "--upload-pack=…" is an option
exec.Command("git", "clone", repoURL, dir).Run()
// ✅
exec.Command("git", "clone", "--", repoURL, dir).Run()

Also check cmd.Env built from request data (NODE_OPTIONS, LD_PRELOAD, GIT_SSH_COMMAND — injection-and-dangerous-sinks).

3. Paths: filepath, os.Root (CWE-22)

// ❌ lexical check: a symlink inside base escapes it, and
//    "/srv/data-other/x" passes HasPrefix(p, "/srv/data")
p := filepath.Join(base, name)
if !strings.HasPrefix(p, base) { … }

// ✅ Go 1.24+: lookups confined to the root, symlinks included
root, err := os.OpenRoot(base)
f, err := root.Open(name)
// ✅ older Go: reject anything non-local before joining
if !filepath.IsLocal(name) { return errBadPath }

http.FileServer(http.Dir(dir)) blocks .. but follows symlinks inside dir and serves dotfiles — a finding when dir is the repo root or an upload directory. Archive extraction: check filepath.IsLocal(hdr.Name) per entry.

4. Templates (CWE-79)

5. JSON Binding (CWE-915)

// ❌ the request decodes straight into the domain type, Role and OrgID included
var u domain.User
json.NewDecoder(r.Body).Decode(&u)
// ✅ a request DTO with only client-settable fields, mapped explicitly
var req struct{ Name, Email string }
json.NewDecoder(r.Body).Decode(&req)

encoding/json matches keys case-insensitively and lets the last duplicate win: a gateway or validator that checks "role" misses "ROLE". Relevant only when a different component validates the raw JSON.

6. Crypto and Transport (CWE-295, CWE-338)

7. HTTP Handlers and Middleware

8. unsafe and cgo

unsafe.Pointer arithmetic, unsafe.Slice/unsafe.String over attacker-sized buffers, and C code reached through cgo are memory-unsafe again — trace sizes and lengths from input (native-memory-safety-and-ffi has the bounds, integer and cgo pointer rules).

Common Mistakes

Red Flags

References (names and links only)

Go security best practices · os.Root (Go 1.24) · gosec rules · GORM security · govulncheck

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.