Go Secure Coding

Secure coding practices for Go applications.


SQL Injection Prevention

1// ❌ Vulnerable
2username := r.FormValue("username")
3query := fmt.Sprintf("SELECT * FROM users WHERE username = '%s'", username)
4db.Query(query)
5
6// βœ… Secure
7username := r.FormValue("username")
8query := "SELECT * FROM users WHERE username = $1"
9db.Query(query, username)

Command Injection Prevention

 1// ❌ Vulnerable
 2filename := r.FormValue("file")
 3cmd := exec.Command("sh", "-c", "cat "+filename)
 4output, _ := cmd.Output()
 5
 6// βœ… Secure
 7filename := r.FormValue("file")
 8if !regexp.MustCompile(`^[a-zA-Z0-9_.-]+$`).MatchString(filename) {
 9    return errors.New("invalid filename")
10}
11cmd := exec.Command("cat", filename)
12output, err := cmd.Output()

XSS Prevention

 1// ❌ Vulnerable
 2func handler(w http.ResponseWriter, r *http.Request) {
 3    query := r.URL.Query().Get("q")
 4    fmt.Fprintf(w, "<h1>Results: %s</h1>", query)
 5}
 6
 7// βœ… Secure: Use html/template
 8import "html/template"
 9
10func handler(w http.ResponseWriter, r *http.Request) {
11    query := r.URL.Query().Get("q")
12    tmpl := template.Must(template.New("search").Parse("<h1>Results: {{.}}</h1>"))
13    tmpl.Execute(w, query)
14}

Secure Password Hashing

1// ❌ Insecure
2import "crypto/md5"
3hash := md5.Sum([]byte(password))
4
5// βœ… Secure
6import "golang.org/x/crypto/bcrypt"
7
8hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
9err = bcrypt.CompareHashAndPassword(hashedPassword, []byte(password))

Secure Random Generation

1// ❌ Insecure
2import "math/rand"
3token := make([]byte, 32)
4rand.Read(token)
5
6// βœ… Secure
7import "crypto/rand"
8token := make([]byte, 32)
9_, err := rand.Read(token)

Related Snippets