Skip to content

Commit

Permalink
Add a flag to only do BasicAuth once per IP
Browse files Browse the repository at this point in the history
  • Loading branch information
ntnj committed Sep 18, 2024
1 parent 399eab5 commit 760ee81
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 10 deletions.
10 changes: 0 additions & 10 deletions .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
@@ -1,16 +1,6 @@
{
"name": "Go:tunwg",
"image": "mcr.microsoft.com/devcontainers/go",
"mounts": [
"type=volume,source=vscode_dev_home,target=/home/vscode"
],
"customizations": {
"vscode": {
"extensions": [
"golang.go"
]
}
},
// To run wireshark for debugging
"capAdd": ["NET_ADMIN"]
}
13 changes: 13 additions & 0 deletions tunwg/tunwg.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (

var forwardFlag = flag.String("forward", "", "hosts to forward")
var limitFlag = flag.String("limit", "", "username password in htpasswd format. bcrypt and plain text are supported")
var limitOncePerIPFlag = flag.Duration("limit_once_on_ip", 0, "Only ask for basic auth once per ip per duration")
var portFlag = flag.Uint("p", 0, "port to forward")

func main() {
Expand Down Expand Up @@ -82,6 +83,7 @@ func main() {
if validator != nil {
rp.Transport = &roundTripper{
validator: validator,
ipValid: make(map[string]time.Time),
}
}
srv := &http.Server{
Expand All @@ -98,9 +100,17 @@ func main() {

type roundTripper struct {
validator func(username, password string) bool
ipValid map[string]time.Time
}

func (r *roundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
ip := req.Header.Get("X-Forwarded-For")
if ip != "" && *limitOncePerIPFlag != 0 {
pass, ok := r.ipValid[ip]
if ok && time.Now().Before(pass.Add(*limitOncePerIPFlag)) {
return http.DefaultTransport.RoundTrip(req)
}
}
user, pass, ok := req.BasicAuth()
if !ok || !r.validator(user, pass) {
return &http.Response{
Expand All @@ -112,6 +122,9 @@ func (r *roundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
Request: req,
}, nil
}
if ip != "" && *limitOncePerIPFlag != 0 {
r.ipValid[ip] = time.Now()
}
return http.DefaultTransport.RoundTrip(req)
}

Expand Down

0 comments on commit 760ee81

Please sign in to comment.