Security skill · Find and fix
Secure review: Go.
Review Go code (HTTP services, gRPC, CLIs, workers) for language-specific security flaws such as command and path injection, unchecked errors that skip security decisions, goroutine data races on shared state, unsafe TLS and HTTP client defaults, weak randomness, template misuse, and vulnerable modules, then fix and verify with tests and the race detector. Use when auditing or reviewing a Go codebase or pull request.
Facts
- Category
- Find and fix
- License
- MIT
- Tags
- Code review
- Version
- 1.0.0
- Last updated
- 2026-12-02
- Folder
secure-review-go/- MCP resource
skill://secure-review-go/SKILL.md- Files
- SKILL.md
- LICENSE
- references/go-patterns.md
Original Saasment content. Saasment is in early access; this skill does not require joining it.
Install via MCP or as files
Connect your client to https://www.saasment.com/api/mcp (see client setup) and call get_skill:
{
"name": "get_skill",
"arguments": {
"slug": "secure-review-go"
}
}Or download the .zip and unpack it into your agent's skills directory:
Terminal, from your project root (user-level: ~/.cursor/skills)
mkdir -p .cursor/skills
curl -fsSL https://www.saasment.com/ai-security/skills/secure-review-go/download.zip -o /tmp/secure-review-go.zip
unzip -o /tmp/secure-review-go.zip -d .cursor/skills
# result: .cursor/skills/secure-review-go/SKILL.mdReview SKILL.md before enabling a skill. Skills are instructions your agent will follow.
SKILL.md
--- name: secure-review-go description: Review Go code (HTTP services, gRPC, CLIs, workers) for language-specific security flaws such as command and path injection, unchecked errors that skip security decisions, goroutine data races on shared state, unsafe TLS and HTTP client defaults, weak randomness, template misuse, and vulnerable modules, then fix and verify with tests and the race detector. Use when auditing or reviewing a Go codebase or pull request. license: MIT metadata: author: Saasment version: "1.0.0" category: both tags: "code-review" --- # Secure review: Go (find and fix) License: MIT. Copyright (c) 2026 Saasment. Source: https://www.saasment.com/ai-security/skills/secure-review-go Go is memory safe and has a strong standard library, so most real findings come from a different set of mistakes: ignored errors that make a security decision succeed by default, shared state touched by several goroutines, HTTP servers and clients left on permissive defaults, string-built commands and paths, and `math/rand` used where randomness must be unpredictable. This skill covers the Go-specific pass; run it together with `secure-code-review-checklist`. ## When to use - You audit a Go service, CLI, operator, or library. - A pull request adds handlers, middleware, concurrency, file or process handling, or TLS configuration. - A tool such as `govulncheck` or a static analyzer reported findings that need triage. ## Safe by default - Review only code you own or are authorized to review. Run tests and probes only locally or in a test environment with synthetic data. - Do not run `go generate`, `go run`, or build scripts from an unfamiliar repository on a machine with credentials. Read them first. - Keep probes harmless: unique marker strings, temporary directories, local listeners only. - Do not point scanners or load at systems you are not authorized to test. ## Procedure 1. **Inventory.** List modules (`go.mod`), Go version, `main` packages, HTTP routers and middleware chains, background workers, and which packages handle untrusted input. 2. **Find ignored errors on security paths.** Search for `_ =` and bare calls whose error is dropped near authentication, authorization, parsing, signature checks, and file operations. A dropped error in `if err == nil` logic that defaults to "allowed" is a finding (patterns in `references/go-patterns.md`). 3. **Check request handling.** Every handler runs through authentication and authorization middleware, request bodies are bounded with `http.MaxBytesReader`, JSON decoding uses a typed struct (consider `DisallowUnknownFields`), and URL, header, and form values are validated before use. 4. **Check processes and paths.** `exec.Command` with `sh -c` and interpolated input, user input in `filepath.Join` or `os.Open` without a containment check, archive extraction without validating entry names (see `input-validation-deserialization-review`). 5. **Check concurrency.** Maps and slices written by several goroutines without a mutex or channel, shared caches of per-user data, request-scoped values stored in globals, and `time-of-check to time-of-use` gaps around permissions or balances. 6. **Check network defaults.** `http.Server` without read, write, and header timeouts; `http.Client` without a timeout; `InsecureSkipVerify: true`; TLS minimum version unset; redirects followed to internal addresses (see `ssrf-find-and-fix`). 7. **Check randomness and secrets.** `math/rand` for tokens, IDs, or keys (use `crypto/rand`), non-constant-time comparison of secrets (use `crypto/subtle`), secrets in logs or error strings. 8. **Check templates.** `text/template` used to render HTML, and `template.HTML`, `template.JS`, or `template.URL` conversions applied to user data. 9. **Check modules.** Run `govulncheck ./...`, review `replace` directives and pseudo-versions, and keep `go.sum` committed (see `dependency-cve-triage-and-patch`). 10. **Fix and add tests.** Handle every error explicitly with deny-by-default, add timeouts and body limits, use argument-list `exec.Command`, guard shared state, and add a test per fix. ## Verification - Confirm a data race: run the relevant tests with `go test -race ./...` and show the race report; after the fix the same command is clean. Add a test that exercises the shared state from several goroutines. - Confirm an ignored-error bug with a test that forces the dependency to return an error (a fake that fails) and asserts the request is denied, not allowed. - Confirm body limits and timeouts by sending an oversized body to a local test server and asserting a 413 or a closed connection, and by checking the server struct has non-zero timeouts. - Confirm command and path fixes with inputs containing spaces, `;`, and `../`; assert they are rejected or passed as one literal argument. - Re-run `govulncheck ./...`, `go vet ./...`, and the linter set your project uses, and compare with the baseline. ## Reporting Table: id, package and file, bug class, reachable by whom, fix, test. Note the Go and module versions reviewed and the `govulncheck` result. ## References - Go security documentation: https://go.dev/doc/security/ - Go vulnerability management and `govulncheck`: https://go.dev/doc/security/vuln/ - Go race detector: https://go.dev/doc/articles/race_detector - `crypto/rand` package: https://pkg.go.dev/crypto/rand - Companion skills: `secure-code-review-checklist`, `input-validation-deserialization-review`, `ssrf-find-and-fix`.
Helper files
LICENSE
MIT License Copyright (c) 2026 Saasment Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
references/go-patterns.md
# Go risky patterns
License: MIT. Copyright (c) 2026 Saasment.
Search leads only. Confirm that untrusted data or a concurrent path reaches each hit.
## Search commands
```bash
# Dropped errors and shell invocation
rg -n '^\s*_\s*(,\s*_)?\s*[:=]+|exec\.Command\(\s*"(sh|bash)"' --glob '*.go'
# Weak randomness, disabled TLS verification, missing timeouts
rg -n '"math/rand"|InsecureSkipVerify|http\.ListenAndServe\(|&http\.Client\{\}|http\.DefaultClient' --glob '*.go'
# Template escape hatches
rg -n 'template\.(HTML|JS|URL)\(|"text/template"' --glob '*.go'
# Path handling
rg -n 'filepath\.Join\(|os\.(Open|ReadFile|Create)\(|http\.ServeFile|http\.Dir\(' --glob '*.go'
# Tools
govulncheck ./...
go vet ./...
go test -race ./...
```
## Errors that decide security
```go
// Risky: a failed lookup leaves ok == false, but the error path falls through to "allow"
user, err := store.Find(ctx, id)
if err != nil {
log.Printf("lookup failed: %v", err)
}
if user.Role == "admin" { // user may be nil or zero value here
allow()
}
// Safer: deny by default
user, err := store.Find(ctx, id)
if err != nil || user == nil {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
```
## Server and client defaults
```go
// Risky: no timeouts, no body limit
http.ListenAndServe(":8080", mux)
resp, err := http.Get(userURL)
// Safer
srv := &http.Server{
Addr: ":8080",
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 15 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 60 * time.Second,
}
client := &http.Client{Timeout: 10 * time.Second}
func handler(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 1<<20)
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
// decode into a typed struct, then validate fields
}
```
## Commands, paths, randomness
```go
// Risky
exec.Command("sh", "-c", "convert "+name+" out.png")
os.ReadFile(filepath.Join(base, name))
token := fmt.Sprint(rand.Int63()) // math/rand
// Safer
exec.CommandContext(ctx, "convert", validatedName, "out.png")
full := filepath.Join(base, filepath.Clean("/"+name))
if !strings.HasPrefix(full, filepath.Clean(base)+string(os.PathSeparator)) { /* reject */ }
buf := make([]byte, 32)
_, err := rand.Read(buf) // crypto/rand
```
## Shared state
```go
// Risky: concurrent map writes can crash or corrupt data
var cache = map[string]Session{}
// Safer: guard with a mutex (or use a type designed for concurrent use)
type SessionCache struct {
mu sync.RWMutex
m map[string]Session
}
```
Related
Companion skills
Questions
How do I install the Secure review: Go skill?
Download https://www.saasment.com/ai-security/skills/secure-review-go/download.zip and unzip it into your agent's skills directory (for example .cursor/skills, .claude/skills, .agents/skills, or .github/skills) so that secure-review-go/SKILL.md exists. Or connect to https://www.saasment.com/api/mcp and call the get_skill tool with the slug secure-review-go.
What license is the Secure review: Go skill under?
It is original Saasment content under the MIT license, stated in the SKILL.md frontmatter and in the LICENSE file in the skill folder.
Is it safe to run this skill?
A skill is a set of instructions your agent follows, so read SKILL.md first. It tells the agent to test only systems you own or are authorized to test, to use test environments and synthetic data, and to avoid destructive probes. Downloading it does not run any code on your machine.