Skip to content

Commit

Permalink
main: Protect /info from external access
Browse files Browse the repository at this point in the history
Only accesses from localhost (considering reverse-proxied requests) are
allowed.
  • Loading branch information
matheusd committed Mar 22, 2024
1 parent 818a0a9 commit 50a4360
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
6 changes: 6 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ func indexHandler(w http.ResponseWriter, req *http.Request) {

func newInfoHandler(server *server.Server) func(w http.ResponseWriter, req *http.Request) {
return func(w http.ResponseWriter, req *http.Request) {
if !isReqFromLocalhost(req) {
w.WriteHeader(http.StatusForbidden)
log.Warnf("Forbidden request for info from %s", requestAddr(req))
return
}

info, err := server.FetchManagedChannels(req.Context())
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
Expand Down
48 changes: 48 additions & 0 deletions util.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,59 @@
package main

import (
"net"
"net/http"
"strings"

"github.com/gorilla/mux"
)

func requestAddr(req *http.Request) string {
res := req.RemoteAddr
for _, header := range []string{"X-Forwarded-For", "X-Real-IP"} {
if values, ok := req.Header[header]; ok {
for _, value := range values {
res += strings.TrimSpace(value)
}
}
}

return res
}

// isReqFromLocalhost checks if the request came from localhost. It checks the
// X-Forwarded-For and X-Real-IP headers first and then falls back to the
// RemoteAddr if necessary.
func isReqFromLocalhost(req *http.Request) bool {
// Function to check if an IP from a given string is a loopback address.
// It splits the host and port if necessary and checks the IP.
isLoopback := func(addr string) bool {
ip := net.ParseIP(addr)
return ip != nil && ip.IsLoopback()
}

// Check X-Forwarded-For and X-Real-IP headers for the original client IP
for _, header := range []string{"X-Forwarded-For", "X-Real-IP"} {
if values, ok := req.Header[header]; ok {
for _, value := range values {
for _, ipStr := range strings.Split(value, ",") {
ipStr = strings.TrimSpace(ipStr)
if isLoopback(ipStr) {
return true
}
}
}
}
}

// If the headers are not present, fall back to the RemoteAddr.
host, _, err := net.SplitHostPort(req.RemoteAddr)
if err != nil {
host = req.RemoteAddr
}
return isLoopback(host)
}

func logRouterConfig(r *mux.Router) {
err := r.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
pathTemplate, err := route.GetPathTemplate()
Expand Down

0 comments on commit 50a4360

Please sign in to comment.