Application security
suggest changeGo is memory safe: no buffer overflows, no use-after-free, no format string bugs. That removes a whole class of vulnerabilities that plague C and C++ programs. It doesn't remove the bugs that come from trusting input: SQL injection, cross-site scripting, command injection, path traversal, forged cookies, leaked secrets.
The standard library has good defenses for all of them, as long as you use the right package and the right function. This article goes through the most common vulnerabilities in Go applications and shows the safe way to write the code.
The rule behind almost every section: never mix untrusted data into code. Code is SQL text, HTML, shell command lines and file paths. Data is what the user sent you. Keep them separate and let the library do the encoding.
SQL injection
Building a query with string concatenation lets the input change the meaning of the query:
package main
import (
"database/sql"
"fmt"
"log"
_ "modernc.org/sqlite"
)
func main() {
db, err := sql.Open("sqlite", ":memory:")
if err != nil {
log.Fatal(err)
}
defer db.Close()
db.Exec(`CREATE TABLE users (name TEXT, email TEXT)`)
db.Exec(`INSERT INTO users VALUES ('alice', 'alice@example.com'), ('bob', 'bob@example.com')`)
input := "nobody' OR '1'='1"
// WRONG: user input becomes part of the SQL text
query := "SELECT name, email FROM users WHERE name = '" + input + "'"
fmt.Println("unsafe:", count(db, query))
// RIGHT: input is sent separately as a parameter
fmt.Println("safe: ", count(db, "SELECT name, email FROM users WHERE name = ?", input))
}
func count(db *sql.DB, query string, args ...any) int {
rows, err := db.Query(query, args...)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
n := 0
for rows.Next() {
n++
}
return n
}
unsafe: 2
safe: 0
The unsafe query became WHERE name = 'nobody' OR '1'='1', which matches every row. With a placeholder, the driver sends the value separately from the SQL text, so it's always treated as a string, no matter what characters it contains.
Every method of database/sql that runs SQL (Query, QueryRow, Exec, their Context variants and prepared statements) accepts arguments. Use them. Never build SQL with fmt.Sprintf or +. The placeholder syntax depends on the driver: ? for SQLite and MySQL, $1, $2 for PostgreSQL.
Placeholders work only for values. Table names, column names and keywords like ASC can't be parameters. When they come from user input, for example a "sort by" option, map the input to a fixed set of identifiers:
// column names can't be parameters, so map user input to known identifiers
var sortColumns = map[string]string{
"name": "name",
"joined": "created_at",
}
func listUsers(db *sql.DB, sortBy string) ([]string, error) {
col, ok := sortColumns[sortBy]
if !ok {
return nil, fmt.Errorf("invalid sort column %q", sortBy)
}
rows, err := db.Query("SELECT name FROM users ORDER BY " + col)
if err != nil {
return nil, err
}
defer rows.Close()
var names []string
for rows.Next() {
var n string
if err := rows.Scan(&n); err != nil {
return nil, err
}
names = append(names, n)
}
return names, rows.Err()
}
func main() {
// ... open db and insert ('carol', 1), ('alice', 3), ('bob', 2)
fmt.Println(listUsers(db, "name"))
fmt.Println(listUsers(db, "joined"))
fmt.Println(listUsers(db, "name; DROP TABLE users"))
}
[alice bob carol] <nil>
[carol bob alice] <nil>
[] invalid sort column "name; DROP TABLE users"
The string concatenated into the query always comes from the map, never from the user. See SQL for more on database/sql.
Cross-site scripting (XSS)
If a web page includes user input without escaping it, an attacker can inject JavaScript that runs in other users' browsers. text/template does no escaping at all. html/template has the same API but understands HTML and escapes every value based on where it appears:
package main
import (
"html/template"
"os"
ttemplate "text/template"
)
const page = `<p>Hello, {{.Name}}</p>
<a href="{{.URL}}">profile</a>
<script>var user = {{.Name}};</script>
`
type data struct {
Name string
URL string
}
func main() {
d := data{
Name: `<script>alert("pwned")</script>`,
URL: `javascript:alert(1)`,
}
// WRONG: text/template does no escaping
ttemplate.Must(ttemplate.New("t").Parse(page)).Execute(os.Stdout, d)
os.Stdout.WriteString("---\n")
// RIGHT: html/template escapes based on context
template.Must(template.New("h").Parse(page)).Execute(os.Stdout, d)
}
<p>Hello, <script>alert("pwned")</script></p>
<a href="javascript:alert(1)">profile</a>
<script>var user = <script>alert("pwned")</script>;</script>
---
<p>Hello, <script>alert("pwned")</script></p>
<a href="#ZgotmplZ">profile</a>
<script>var user = "\u003cscript\u003ealert(\"pwned\")\u003c/script\u003e";</script>
html/template applied three different escapings to the same kind of value:
- in HTML text,
<and"became HTML entities - in the
hrefattribute, thejavascript:URL was replaced by#ZgotmplZ, a marker that means "unsafe value removed" - inside
<script>, the value became a properly quoted JavaScript string
Rules for staying safe:
- always use
html/templatefor HTML. A good habit is to never importtext/templatein a web server package - don't convert user input to
template.HTML,template.JSortemplate.URL. These types tell the template "this is already safe" and turn escaping off. Use them only for content you produced yourself (see HTML templates) - don't build HTML with
fmt.Fprintf(w, "<p>%s</p>", name). If you must write HTML by hand, escape withhtml.EscapeString - set a
Content-Security-Policyheader (shown later) as a second line of defense
Command injection
os/exec doesn't use a shell. Each argument is passed to the program as-is, so characters like ;, |, $() and backticks have no special meaning. The vulnerability appears when you add a shell yourself:
package main
import (
"fmt"
"os/exec"
)
func main() {
filename := "notes.txt; echo HACKED"
// WRONG: the shell interprets ; and runs a second command
out, _ := exec.Command("sh", "-c", "echo "+filename).CombinedOutput()
fmt.Printf("shell: %q\n", out)
// RIGHT: arguments are passed directly to the program, no shell involved
out, _ = exec.Command("echo", filename).CombinedOutput()
fmt.Printf("direct: %q\n", out)
// an argument that starts with - can still be read as an option;
// use -- to end option parsing when the program supports it
out, _ = exec.Command("ls", "--", "-la").CombinedOutput()
fmt.Printf("dashes: %q\n", out)
}
shell: "notes.txt\nHACKED\n"
direct: "notes.txt; echo HACKED\n"
dashes: "ls: cannot access '-la': No such file or directory\n"
(Output from Linux.)
Avoid sh -c, bash -c and cmd /c with user input. If you need pipes or redirection, wire them up in Go with cmd.Stdin, cmd.Stdout and io.Pipe. Also never let the user choose the program itself: exec.Command(userInput) is remote code execution. See os/exec pitfalls for other traps.
Path traversal
When a file name comes from a request, ../../etc/passwd lets the attacker read files outside the directory you meant to serve. filepath.Join(dir, name) doesn't protect you: it happily cleans .. and walks up.
There are two tools in the standard library:
filepath.IsLocal(name)(Go 1.20) reports whether a path stays inside the directory it's evaluated in: not absolute, no..escaping upward, not a reserved name likeNULon Windowsos.Root(Go 1.24) opens a directory and confines every operation on it, including symbolic links that point outside
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
dir, _ := os.MkdirTemp("", "uploads")
defer os.RemoveAll(dir)
os.WriteFile(filepath.Join(dir, "report.txt"), []byte("quarterly numbers"), 0o644)
names := []string{"report.txt", "../../etc/passwd", "./report.txt", "/etc/passwd"}
fmt.Println("filepath.IsLocal:")
for _, name := range names {
fmt.Printf(" %-20s %v\n", name, filepath.IsLocal(name))
}
// os.Root confines every operation to one directory
root, err := os.OpenRoot(dir)
if err != nil {
panic(err)
}
defer root.Close()
fmt.Println("os.Root:")
for _, name := range names {
data, err := root.ReadFile(name)
if err != nil {
fmt.Printf(" %-20s error: %v\n", name, err)
continue
}
fmt.Printf(" %-20s %q\n", name, data)
}
}
filepath.IsLocal:
report.txt true
../../etc/passwd false
./report.txt true
/etc/passwd false
os.Root:
report.txt "quarterly numbers"
../../etc/passwd error: openat ../../etc/passwd: path escapes from parent
./report.txt "quarterly numbers"
/etc/passwd error: openat /etc/passwd: path escapes from parent
IsLocal is a purely lexical check, so it can't see a symlink inside the directory that points to /etc. os.Root checks every path component as it opens it, which also closes the race where a directory is swapped for a symlink between the check and the open. Prefer os.Root for anything that touches user-chosen paths, such as uploads or extracting archives. os.Root has Open, Create, OpenFile, Mkdir, Remove, Stat, ReadFile, WriteFile and more, and root.FS() returns an fs.FS.
For serving static files, http.FileServer(http.Dir(dir)) and http.FileServerFS already reject ... Be careful with http.ServeFile(w, r, path): it trusts the path you give it.
Secure random values
Session IDs, password reset tokens, API keys, CSRF tokens and encryption keys must be unpredictable. Generate them with crypto/rand, never with math/rand or math/rand/v2:
package main
import (
"crypto/rand"
"encoding/hex"
"fmt"
)
func main() {
// a random string with 128 bits of entropy, base32 encoded
fmt.Println(rand.Text())
// raw random bytes, e.g. for a key
key := make([]byte, 32)
rand.Read(key) // never returns an error since Go 1.24; crashes the program if the OS fails
fmt.Println(hex.EncodeToString(key))
}
4WTYVIB5TUBXOH7AUT666W5JHR
36fbd3534500c7aa8ae036a28f3f43ff166b28b637f455a88c24564ace3bf45b
rand.Text (Go 1.24) is the simplest way to make a token. See Random numbers for random strings from a custom alphabet and other uses.
Constant-time comparison and signed values
Comparing a secret with == or bytes.Equal stops at the first mismatching byte. An attacker who can measure response times can, in principle, guess a token one byte at a time. Use crypto/subtle.ConstantTimeCompare for secrets and hmac.Equal for MACs.
To give a client data that it must not modify, like a user ID in a cookie, sign it with HMAC:
package main
import (
"crypto/hmac"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"errors"
"fmt"
"strings"
)
var secretKey = []byte("load-me-from-a-secret-store-32-bytes!")
func sign(value string) string {
mac := hmac.New(sha256.New, secretKey)
mac.Write([]byte(value))
sig := base64.RawURLEncoding.EncodeToString(mac.Sum(nil))
return value + "." + sig
}
func verify(signed string) (string, error) {
value, sig, ok := strings.Cut(signed, ".")
if !ok {
return "", errors.New("malformed")
}
got, err := base64.RawURLEncoding.DecodeString(sig)
if err != nil {
return "", errors.New("malformed signature")
}
mac := hmac.New(sha256.New, secretKey)
mac.Write([]byte(value))
if !hmac.Equal(got, mac.Sum(nil)) { // constant-time comparison
return "", errors.New("invalid signature")
}
return value, nil
}
func checkAPIKey(given, expected string) bool {
return subtle.ConstantTimeCompare([]byte(given), []byte(expected)) == 1
}
func main() {
cookie := sign("user=alice")
fmt.Println(cookie)
fmt.Println(verify(cookie))
tampered := strings.Replace(cookie, "alice", "admin", 1)
fmt.Println(verify(tampered))
fmt.Println(checkAPIKey("s3cret", "s3cret"), checkAPIKey("s3cres", "s3cret"))
}
user=alice.QNgayJs6Jed4L5Gf_vyM15LIMFT7dfYr8b6Uzq_KLfU
user=alice <nil>
invalid signature
true false
Signing prevents tampering but the value is still readable by the client. If it must also be secret, encrypt it with an AEAD such as AES-GCM (see Encryption and decryption with AES GCM). A signed value is valid forever unless you include an expiry time in it and check it. For tokens with standard claims, see JWT Authorization.
Don't invent your own cryptography. Use crypto/hmac, crypto/cipher AEADs, crypto/ed25519 and other high-level standard library packages, and avoid MD5 and SHA-1 for anything security related.
Storing passwords
Never store passwords in plain text, encrypted, or hashed with a fast hash like SHA-256. Use a slow, salted password hashing function: bcrypt (golang.org/x/crypto/bcrypt), scrypt or Argon2id (golang.org/x/crypto/argon2). These are deliberately expensive so that a stolen database can't be brute forced quickly. Compare with the library's verify function, which is constant time. The details deserve their own article: see Password hashing.
Hardening an HTTP server
A Go web server needs a few things that the defaults don't give you:
- timeouts.
http.ListenAndServeand a zerohttp.Serverhave no timeouts, so a client that sends headers one byte per minute (Slowloris) holds a connection and a goroutine forever - body size limit. Without
http.MaxBytesReader, a client can send a multi-gigabyte body that your JSON decoder tries to read into memory - strict input parsing. Reject unknown fields and validate lengths and ranges
- security headers telling the browser to restrict what the page can do
- CSRF protection for state-changing requests made from other sites
package main
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"time"
)
const maxBody = 1 << 20 // 1 MB
func securityHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h := w.Header()
h.Set("Content-Security-Policy", "default-src 'self'")
h.Set("X-Content-Type-Options", "nosniff")
h.Set("X-Frame-Options", "DENY")
h.Set("Referrer-Policy", "strict-origin-when-cross-origin")
h.Set("Strict-Transport-Security", "max-age=63072000; includeSubDomains")
next.ServeHTTP(w, r)
})
}
type comment struct {
Text string `json:"text"`
}
func handleComment(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, maxBody)
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
var c comment
if err := dec.Decode(&c); err != nil {
var tooBig *http.MaxBytesError
if errors.As(err, &tooBig) {
http.Error(w, "request too large", http.StatusRequestEntityTooLarge)
return
}
// don't echo internal details back to the client
http.Error(w, "bad request", http.StatusBadRequest)
return
}
if len(c.Text) == 0 || len(c.Text) > 1000 {
http.Error(w, "text must be 1-1000 bytes", http.StatusBadRequest)
return
}
fmt.Fprintln(w, "saved")
}
func newServer() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("POST /comments", handleComment)
// rejects cross-origin state-changing requests (CSRF), Go 1.25+
csrf := http.NewCrossOriginProtection()
return securityHeaders(csrf.Handler(mux))
}
func main() {
// in production, use http.Server with timeouts:
_ = &http.Server{
Addr: ":443",
Handler: newServer(),
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 120 * time.Second,
MaxHeaderBytes: 64 << 10,
}
ts := httptest.NewServer(newServer())
defer ts.Close()
send := func(name, body string, hdr map[string]string) {
req, _ := http.NewRequest("POST", ts.URL+"/comments", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
for k, v := range hdr {
req.Header.Set(k, v)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Println(name, err)
return
}
defer resp.Body.Close()
b, _ := io.ReadAll(resp.Body)
fmt.Printf("%-13s %d %s", name, resp.StatusCode, b)
}
send("ok", `{"text":"hi"}`, nil)
send("unknown field", `{"text":"hi","admin":true}`, nil)
send("too large", `{"text":"`+strings.Repeat("a", maxBody)+`"}`, nil)
send("cross-site", `{"text":"hi"}`, map[string]string{"Sec-Fetch-Site": "cross-site"})
send("same-origin", `{"text":"hi"}`, map[string]string{"Sec-Fetch-Site": "same-origin"})
}
ok 200 saved
unknown field 400 bad request
too large 413 request too large
cross-site 403 cross-origin request detected from Sec-Fetch-Site header
same-origin 200 saved
http.CrossOriginProtection (Go 1.25) uses the Sec-Fetch-Site and Origin headers that all modern browsers send to reject POST, PUT, PATCH and DELETE requests coming from another site. It replaces CSRF tokens for most applications. Use AddTrustedOrigin to allow specific other origins. GET, HEAD and OPTIONS are always allowed, so never change state in a GET handler.
Other points:
- error messages sent to the client should be generic. Log the details on the server, don't return
err.Error(), stack traces or SQL errors to the user - add a recovery middleware so one panic doesn't leak a stack trace.
net/httprecovers panics per request, but it logs and closes the connection rather than returning a clean 500 - rate limit login and other expensive endpoints, for example with
golang.org/x/time/rate - configure CORS narrowly.
Access-Control-Allow-Origin: *combined with credentials is a mistake (see CORS Middleware) - when your server fetches URLs given by users (webhooks, image previews), it can be tricked into reaching internal services (SSRF). Allow only expected hosts and block private IP ranges with a custom
net.Dialer.Controlfunction
See HTTP server middleware for how to structure such wrappers.
Secure cookies
Session cookies should be inaccessible to JavaScript, sent only over HTTPS, and not sent on cross-site requests:
package main
import (
"crypto/rand"
"fmt"
"net/http"
"time"
)
func main() {
c := &http.Cookie{
Name: "__Host-session", // __Host- prefix: Secure, Path=/, no Domain
Value: rand.Text(),
Path: "/",
Expires: time.Date(2026, 11, 17, 0, 0, 0, 0, time.UTC),
Secure: true, // only sent over HTTPS
HttpOnly: true, // not readable from JavaScript
SameSite: http.SameSiteLaxMode, // not sent on cross-site POSTs
}
fmt.Println(c.String())
}
__Host-session=ZUDKI2YFSAIAVIHYAZIK47HFOC; Path=/; Expires=Tue, 17 Nov 2026 00:00:00 GMT; HttpOnly; Secure; SameSite=Lax
In a handler, call http.SetCookie(w, c). Store the session ID in the cookie and the session data on the server. Generate a new session ID after login to prevent session fixation, and delete the server-side session on logout. See Cookies.
TLS
Serve everything over HTTPS. Go's crypto/tls has secure defaults: TLS 1.2 is the minimum version, only modern cipher suites are enabled, and post-quantum key exchange is on by default. You rarely need to change anything beyond the minimum version:
package main
import (
"crypto/tls"
"log"
"net/http"
"time"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello over TLS\n"))
})
srv := &http.Server{
Addr: ":8443",
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
TLSConfig: &tls.Config{
MinVersion: tls.VersionTLS12, // the default since Go 1.22; TLS13 if all clients support it
},
}
// redirect plain HTTP to HTTPS
go http.ListenAndServe(":8080", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "https://"+r.Host+r.URL.RequestURI(), http.StatusMovedPermanently)
}))
log.Fatal(srv.ListenAndServeTLS("cert.pem", "key.pem"))
}
golang.org/x/crypto/acme/autocert gets free certificates from Let's Encrypt automatically. See Create an HTTPS server for generating a certificate for local testing.
Never set InsecureSkipVerify: true in a client outside of tests. It disables certificate checking and makes the connection open to man-in-the-middle attacks. To trust a private CA, add it to tls.Config.RootCAs instead.
Keeping secrets out of code and logs
Don't hard-code passwords, API keys or signing keys in source code. They end up in git history and in every copy of the binary (strings will find them). Read them from environment variables, files mounted by your deployment system, or a secret manager.
Secrets also leak through logs. Give them a type that refuses to print itself. log/slog calls LogValue and the fmt package calls String:
package main
import (
"log/slog"
"os"
)
// Secret is a string that never shows up in logs
type Secret string
func (Secret) LogValue() slog.Value { return slog.StringValue("[REDACTED]") }
func (Secret) String() string { return "[REDACTED]" }
type DBConfig struct {
Host string
User string
Password Secret
}
func main() {
cfg := DBConfig{Host: "db.internal", User: "app", Password: Secret(os.Getenv("DB_PASSWORD"))}
if cfg.Password == "" {
cfg.Password = "hunter2"
}
logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey {
return slog.Attr{} // drop time for reproducible output
}
return a
},
}))
logger.Info("connecting", "host", cfg.Host, "user", cfg.User, "password", cfg.Password)
logger.Info("config", "cfg", cfg)
}
level=INFO msg=connecting host=db.internal user=app password=[REDACTED]
level=INFO msg=config cfg="{Host:db.internal User:app Password:[REDACTED]}"
Use string(cfg.Password) at the one place that really needs the value. Also avoid logging whole HTTP requests: Authorization headers, cookies and query strings with tokens are secrets too.
Tools: govulncheck, vet, fuzzing
govulncheck checks your code and dependencies against the Go vulnerability database. Unlike tools that just compare version numbers, it analyzes the call graph and reports only vulnerabilities in functions your code actually calls:
$ go run golang.org/x/vuln/cmd/govulncheck@latest ./...
...
Vulnerability #12: GO-2026-6599
Reset context tracking on consecutive template expressions in html/template
More info: https://pkg.go.dev/vuln/GO-2026-6599
Standard library
Found in: html/template@go1.27
Fixed in: html/template@go1.27.2
Example traces found:
#1: xss/main.go:29:54: xss.main calls template.Template.Execute
Your code is affected by 12 vulnerabilities from the Go standard library.
This is real output for the examples in this article built with Go 1.27.0: many fixes land in the standard library, so the most effective security measure is often upgrading to the latest Go patch release. Run govulncheck in CI.
Other useful tools:
go vetcatches some suspicious code, like format string mismatches- the race detector (
go test -race) finds data races, which can corrupt security checks under load gosecandstaticcheckflag common security mistakes such as SQL built with string formatting, weak crypto and missing timeouts- fuzzing (
go test -fuzz) feeds random inputs to your parsers and finds panics and infinite loops that an attacker could trigger go.sumverifies that dependency downloads haven't been tampered with. Keep the dependency list short and review what you add
Summary
| vulnerability | defense |
|---|---|
| SQL injection | query parameters (?, $1); allowlist for identifiers |
| XSS | html/template; no template.HTML on user input; CSP header |
| command injection | exec.Command(prog, args...), no sh -c |
| path traversal | os.Root, filepath.IsLocal |
| predictable tokens | crypto/rand, rand.Text() |
| timing attacks | subtle.ConstantTimeCompare, hmac.Equal |
| tampered cookies | HMAC signature or AEAD encryption |
| stolen password database | bcrypt / Argon2id |
| Slowloris, huge bodies | http.Server timeouts, http.MaxBytesReader |
| CSRF | http.CrossOriginProtection, SameSite cookies |
| eavesdropping | TLS, Secure cookies, HSTS |
| leaked secrets | env vars or secret store, redacting LogValue / String |
| vulnerable dependencies | govulncheck, stay on the latest Go release |
- treat everything from the network, files and environment as untrusted
- keep data out of code: parameters for SQL, contextual escaping for HTML, argument lists for commands
- prefer standard library primitives over hand-written security code
- fail closed: reject input you don't understand and return generic errors