Skip to content

Instantly share code, notes, and snippets.

@saga420
Created August 28, 2022 10:07
Show Gist options
  • Select an option

  • Save saga420/034c45075f6d28c0eb56903cf10f5767 to your computer and use it in GitHub Desktop.

Select an option

Save saga420/034c45075f6d28c0eb56903cf10f5767 to your computer and use it in GitHub Desktop.
package main
import (
"github.com/gin-gonic/gin"
"net"
"net/http"
"os/exec"
)
var privateNetworks []*net.IPNet
func init() {
for _, cidr := range []string{
// RFC 1918: private IPv4 networks
"10.0.0.0/8",
"172.16.0.0/12",
"192.168.0.0/16",
// RFC 4193: IPv6 ULAs
"fc00::/7",
// RFC 6598: reserved prefix for CGNAT
"100.64.0.0/10",
} {
_, subnet, _ := net.ParseCIDR(cidr)
privateNetworks = append(privateNetworks, subnet)
}
}
// IsPrivateAddress returns whether an IP address belongs to the LAN.
func IsPrivateAddress(ip net.IP) bool {
for _, network := range privateNetworks {
if network.Contains(ip) {
return true
}
}
return false
}
func main() {
r := gin.Default()
r.GET("/a", func(c *gin.Context) {
ip := net.ParseIP(c.RemoteIP())
if IsPrivateAddress(ip) == true {
c.JSON(http.StatusOK, gin.H{
"e": "private",
})
return
}
s, e := exec.Command("/usr/sbin/ufw", "allow", "from", ip.String(), "to", "any").Output()
if e != nil {
c.JSON(http.StatusOK, gin.H{
"ri": e.Error(),
})
return
}
c.JSON(http.StatusOK, gin.H{
"ri": ip.String(),
"s": string(s),
"ci": c.ClientIP(),
})
return
})
r.GET("/d", func(c *gin.Context) {
ip := net.ParseIP(c.RemoteIP())
if IsPrivateAddress(ip) == true {
c.JSON(http.StatusOK, gin.H{
"e": "private",
})
return
}
exec.Command("/usr/sbin/ufw", "--force", "reset").Output()
exec.Command("/usr/sbin/ufw", "allow", "80").Output()
exec.Command("/usr/sbin/ufw", "allow", "22").Output()
exec.Command("/usr/sbin/ufw", "--force", "enable").Output()
c.JSON(http.StatusOK, gin.H{
"ri": ip.String(),
"ci": c.ClientIP(),
})
return
})
r.Run(":80")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment