Sobes.tech
Junior — Middle

What methods can be used to protect against cross-site scripting (XSS)?

sobes.tech AI

Answer from AI

Several main methods are used to protect against cross-site scripting (XSS):

  • Output escaping: All data displayed in HTML should be properly escaped so that special characters (e.g., <, >, &) are not interpreted as code.
  • Using Content Security Policy (CSP): CSP allows restricting sources of scripts and other resources, reducing the risk of executing malicious code.
  • Validation and filtering of input data: Check and sanitize user input by removing or encoding potentially dangerous characters.
  • Using secure templating engines: In Go, for example, the html/template package automatically escapes data when inserted into HTML.

Example in Go using html/template:

package main

import (
    "html/template"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    tmpl := template.Must(template.New("page").Parse(`<html><body>User input: {{.}}</body></html>`))
    userInput := r.URL.Query().Get("input")
    tmpl.Execute(w, userInput) // automatically escapes
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

Thus, even if a user enters malicious script, it will be displayed as text and not executed.