Skip to content

Commit

Permalink
add flag for trusted proxies
Browse files Browse the repository at this point in the history
if you run ipecho behind a reverse proxy, you need to add the IP of
that reverse proxy as seen by ipecho with the -trusted-proxies flag:

ipecho -proxy="10.0.0.1"
  • Loading branch information
lgrn committed Mar 14, 2024
1 parent e197403 commit abd9260
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 5 deletions.
20 changes: 19 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,29 @@ This will compile to the binary file `ipecho`.
Port 80 requires root permissions, so you need to run the binary as root. For example:

```
sudo ./ipecho
# ./ipecho
```

Logging is done to STDOUT.

If you expect a reverse proxy to contact this application with headers
that indicate the actual origin IP, such as `X-Real-IP` or
`X-Forwarded-For`, you must indicate with a flag what the IP of this
reverse proxy will be to mark it as trusted.

For example, if ipecho runs on `10.0.0.20` and a reverse proxy on
`10.0.0.1`, on the node that runs ipecho you would run:

```
# ./ipecho -proxy='10.0.0.1'
```

This flag can be specified multiple times to trust multiple proxies:

```
# ./ipecho -proxy='10.0.0.1' -proxy='10.0.0.2' (...)
```

## Step 3: Examples

```
Expand Down
30 changes: 26 additions & 4 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,18 +1,41 @@
package main

import (
"flag"
"fmt"
"log"
"net/http"
"strings"

"github.com/gin-gonic/gin"
)

type stringSlice []string

func (i *stringSlice) String() string {
return strings.Join(*i, ",")
}

func (i *stringSlice) Set(value string) error {
*i = append(*i, value)
return nil
}

func main() {
var trustedProxies stringSlice
flag.Var(&trustedProxies, "proxy", "IP address of reverse proxy that will contact us, and we trust to provide correct headers (this flag can be repeated)")
flag.Parse()

gin.SetMode(gin.ReleaseMode)
r := gin.Default()
// do not trust proxies to provide "real ip" via header
r.SetTrustedProxies(nil)

if len(trustedProxies) > 0 {
if err := r.SetTrustedProxies(trustedProxies); err != nil {
log.Fatalf("Tried and failed to set trusted proxies: %v", err)
}
} else {
r.SetTrustedProxies(nil)
}

r.GET("/json", func(c *gin.Context) {
// c.Request.Header returns []string, use 'strings' to convert to string
Expand All @@ -24,8 +47,7 @@ func main() {
})

r.GET("/", func(c *gin.Context) {
ip := c.ClientIP() + "\n"
c.String(http.StatusOK, ip)
c.String(http.StatusOK, c.ClientIP()+"\n")
})

r.NoRoute(func(c *gin.Context) {
Expand Down

0 comments on commit abd9260

Please sign in to comment.