Skip to content

Commit

Permalink
Improve help message to clarify support for IP addresses and CIDR blocks
Browse files Browse the repository at this point in the history
- Updated the help message for the --allow-ip flag to clearly indicate that both IP addresses and CIDR blocks are supported.
- Provided examples for better understanding.

Update TrustedProxiesMiddleware to support CIDR blocks

- Before: Checked if client IP starts with any of the trusted proxies.
- After: Parses client IP and trusted proxies as CIDR blocks and checks if client IP is within any of the trusted CIDR ranges.
- Added handling for invalid IP addresses and appending /32 if no subnet mask is specified.
  • Loading branch information
heedaeshin committed Aug 20, 2024
1 parent ecb1dd3 commit 163bae3
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
2 changes: 1 addition & 1 deletion cmd/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,5 +41,5 @@ func init() {
rootCmd.AddCommand(serverCmd)

serverCmd.Flags().StringVarP(&listenPort, "port", "P", "80", "Listen port")
serverCmd.Flags().StringArrayVarP(&allowIP, "allow-ip", "I", []string{}, "ip to allow")
serverCmd.Flags().StringArrayVarP(&allowIP, "allow-ip", "I", []string{}, "IP addresses and CIDR blocks to allow; example: 192.168.0.1 or 0.0.0.0/0, 10.0.0.0/8")
}
17 changes: 15 additions & 2 deletions websrc/serve/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
"fmt"
"html/template"
"io"
"net"
"net/http"
"strings"

Expand Down Expand Up @@ -62,10 +63,22 @@ func (t *TemplateRenderer) Render(w io.Writer, name string, data interface{}, c
func TrustedProxiesMiddleware(trustedProxies []string) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
clientIP := c.RealIP() // Echo gets the real IP of the client
clientIP := net.ParseIP(c.RealIP()) // Parse the real IP of the client

if clientIP == nil {
return echo.NewHTTPError(http.StatusForbidden, "Invalid IP address")
}

for _, proxy := range trustedProxies {
if strings.HasPrefix(clientIP, proxy) {
// Append /32 if no subnet mask is specified
if !strings.Contains(proxy, "/") {
proxy += "/32"
}
_, cidr, err := net.ParseCIDR(proxy)
if err != nil {
continue
}
if cidr.Contains(clientIP) {
// Request is from a trusted proxy
return next(c)
}
Expand Down

0 comments on commit 163bae3

Please sign in to comment.