Skip to content

add random timeout on deny #77

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion geoblock.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"io"
"io/fs"
"log"
"math/rand"
"net"
"net/http"
"os"
Expand Down Expand Up @@ -55,6 +56,7 @@ type Config struct {
HTTPStatusCodeDeniedRequest int `yaml:"httpStatusCodeDeniedRequest"`
LogFilePath string `yaml:"logFilePath"`
RedirectURLIfDenied string `yaml:"redirectUrlIfDenied"`
DelayOnDenyMs int `yaml:"delayOnDenyMs"`
}

type ipEntry struct {
Expand Down Expand Up @@ -94,6 +96,7 @@ type GeoBlock struct {
logFile *os.File
redirectURLIfDenied string
name string
delayOnDenyMs int
}

// New created a new GeoBlock plugin.
Expand Down Expand Up @@ -178,6 +181,7 @@ func New(ctx context.Context, next http.Handler, config *Config, name string) (h
logFile: logFile,
redirectURLIfDenied: config.RedirectURLIfDenied,
name: name,
delayOnDenyMs: config.DelayOnDenyMs,
}, nil
}

Expand All @@ -202,7 +206,12 @@ func (a *GeoBlock) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
rw.WriteHeader(http.StatusFound)
return
}

// Introduce a delay before responding (with +-50%)
if a.delayOnDenyMs > 0 {
randomFactor := 0.5 + rand.Float64() // between 0.5 and 1.5
randomDelay := time.Duration(float64(a.delayOnDenyMs) * randomFactor)
time.Sleep(time.Duration(randomDelay) * time.Millisecond)
}
rw.WriteHeader(a.httpStatusCodeDeniedRequest)
return
}
Expand Down
5 changes: 5 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,7 @@ my-GeoBlock:
unknownCountryApiResponse: "nil"
blackListMode: false
addCountryHeader: false
delayOnDenyMs: 2000
countries:
- AF # Afghanistan
- AL # Albania
Expand Down Expand Up @@ -526,3 +527,7 @@ Basically tells GeoBlock to only allow/deny a request based on the first IP addr
### Define a custom log file `redirectUrlIfDenied`

Allows returning a HTTP 301 status code, which indicates that the requested resource has been moved. The URL which can be specified is used to redirect the client to. So instead of "blocking" the client, the client will be redirected to the configured URL.

### Define a custom delay on requests `delayOnDenyMs`

Add a +-50% random delay for deny requests. This is useful to limit spam from forbidden IPs.