package waf import ( "bytes" "encoding/json" "errors" "fmt" "io" "net/http" "net/netip" "strings" "time" "sneak.berlin/go/smallwebwaf/internal/bans" "sneak.berlin/go/smallwebwaf/internal/config" "sneak.berlin/go/smallwebwaf/internal/ratelimit" "sneak.berlin/go/smallwebwaf/internal/state" ) // banBodyMaxBytes is the most of the body of a request to add a ban that // is read; its three fields need far less. const banBodyMaxBytes = 4 << 10 // permanent is how the log line and the ban endpoint name a ban that // never ends. const permanent = "permanent" var ( errNotBanToAdd = errors.New( "the body is not a JSON object of netblock, duration and reason") errNotNetblock = errors.New( "is not an address or a netblock, such as 203.0.113.9 or 203.0.113.0/24", ) errMappedNetblock = errors.New( "is IPv4-mapped: give the IPv4 netblock, such as 203.0.113.0/24") errZone = errors.New("has a zone, which a netblock cannot have") errNotDuration = errors.New( "is not a duration above zero, such as 1h or 7d, or permanent") errNotAddress = errors.New("is not an address, such as 203.0.113.9") ) // handleHealth answers GET wafprotocol.HealthPath. func handleHealth() http.HandlerFunc { return func(w http.ResponseWriter, _ *http.Request) { // Set here rather than left to Go's server, which would set it only // after the log line has taken the response's headers. w.Header().Set("Content-Type", "text/plain; charset=utf-8") _, _ = io.WriteString(w, "ok\n") } } // handleListBans answers GET BansPath with every ban held. func (h *handler) handleListBans() http.HandlerFunc { return func(w http.ResponseWriter, _ *http.Request) { h.answerBans(w, h.ledger.Snapshot()) } } // banToAdd is the body of POST BansPath. type banToAdd struct { // Netblock is a netblock, or a client's address, which stands for the // netblock a ban on that client covers. Netblock string `json:"netblock"` // Duration is how long the ban lasts, as a setting gives a duration, // or permanent. Duration string `json:"duration"` Reason string `json:"reason"` } // handleAddBan answers POST BansPath: it bans the netblock the body names, // as an admin, from now for the duration the body gives, with its reason, // and answers with that ban. func (h *handler) handleAddBan() http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { toAdd, err := readBanToAdd(r) var ( netblock netip.Prefix expires time.Time now = h.now() ) if err == nil { netblock, err = h.parseBanNetblock(toAdd.Netblock) } if err == nil { expires, err = expiry(toAdd.Duration, now) } if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } ban := h.ledger.BanForAdmin(netblock, now, expires, toAdd.Reason) h.answerBans(w, []bans.Ban{ban}) } } // readBanToAdd reads the body of POST BansPath: a JSON object with // nothing but whitespace after it, in at most banBodyMaxBytes. func readBanToAdd(r *http.Request) (banToAdd, error) { data, err := io.ReadAll( http.MaxBytesReader(nil, r.Body, banBodyMaxBytes), ) if err != nil { return banToAdd{}, fmt.Errorf("%w: %w", errNotBanToAdd, err) } var toAdd banToAdd decoder := json.NewDecoder(bytes.NewReader(data)) decoder.DisallowUnknownFields() err = decoder.Decode(&toAdd) if err != nil { return banToAdd{}, fmt.Errorf("%w: %w", errNotBanToAdd, err) } // Token returns io.EOF only when nothing but whitespace is left. _, err = decoder.Token() if !errors.Is(err, io.EOF) { return banToAdd{}, fmt.Errorf( "%w: more follows the object", errNotBanToAdd, ) } return toAdd, nil } // parseBanNetblock reads value, a netblock such as 203.0.113.0/24, or a // client's address, which stands for the netblock a ban on that client // covers. An IPv4-mapped netblock, such as ::ffff:203.0.113.0/120, is // refused, since a client's address is looked up as IPv4 and a ban on it // would refuse nothing, and so is a value with a zone. func (h *handler) parseBanNetblock(value string) (netip.Prefix, error) { netblock, err := netip.ParsePrefix(value) if err == nil { if netblock.Addr().Is4In6() { return netip.Prefix{}, fmt.Errorf( "netblock %q %w", value, errMappedNetblock, ) } return netblock, nil } // ParsePrefix refuses a zone, but ParseAddr reads the /48 of // 2001:db8::1%x/48 as part of the zone. addr, err := netip.ParseAddr(value) if err != nil { return netip.Prefix{}, fmt.Errorf( "netblock %q %w", value, errNotNetblock, ) } if addr.Zone() != "" { return netip.Prefix{}, fmt.Errorf("netblock %q %w", value, errZone) } return banNetblock( h.config.BanScopeV4Prefix, h.config.IPv6GroupPrefix, addr, ), nil } // expiry returns when a ban made at now for duration ends: duration // later, for a duration as a setting gives one, or zero for permanent. func expiry(duration string, now time.Time) (time.Time, error) { if duration == permanent { return time.Time{}, nil } length, err := config.ParseDurationNotOff(duration) if err != nil { return time.Time{}, fmt.Errorf( "duration %q %w", duration, errNotDuration, ) } return now.Add(length), nil } // handleLiftBans answers DELETE BansPath/: it lifts every ban // active on a netblock the client's address is in, and answers with those // bans, or with 404 when none is active. func (h *handler) handleLiftBans() http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { client, err := pathAddress(r.URL.Path, BansPath+"/") if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } lifted := h.ledger.Lift(client, h.now()) if len(lifted) == 0 { http.Error( w, "no ban is active on "+client.String(), http.StatusNotFound, ) return } h.answerBans(w, lifted) } } // clientAnswer is the answer to GET ClientsPath: the client the // address is, as clients.json holds it, or null when the table of // clients does not hold it, and the bans on each netblock the address is // in, as bans.json lists them. type clientAnswer struct { Client *ratelimit.Client `json:"client"` Bans []state.BanEntry `json:"bans"` } // handleShowClient answers GET ClientsPath with what waf knows of the // client: its counters, its history, which holds its country as last looked // up and its offences, and its bans with their notes. func (h *handler) handleShowClient() http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { addr, err := pathAddress(r.URL.Path, ClientsPath) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } answer := clientAnswer{ Bans: state.BanEntries(h.ledger.Covering(addr)), } client, seen := h.limiter.Client( clientGroup(h.config.IPv6GroupPrefix, addr), ) if seen { answer.Client = &client } h.answerJSON(w, answer) } } // pathAddress reads the client's address that follows prefix in path. func pathAddress(path, prefix string) (netip.Addr, error) { value := strings.TrimPrefix(path, prefix) addr, err := netip.ParseAddr(value) if err != nil { return netip.Addr{}, fmt.Errorf("%q %w", value, errNotAddress) } return addr.Unmap(), nil } // answerBans answers with held under bans, as bans.json lists them. func (h *handler) answerBans(w http.ResponseWriter, held []bans.Ban) { h.answerJSON(w, struct { Bans []state.BanEntry `json:"bans"` }{state.BanEntries(held)}) } // answerJSON answers with value as indented JSON. func (h *handler) answerJSON(w http.ResponseWriter, value any) { body, err := json.MarshalIndent(value, "", " ") if err != nil { h.processLog.Error( "encoding an answer failed", "error", err.Error(), ) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") _, _ = w.Write(append(body, '\n')) }