guard.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. package security
  2. import (
  3. "errors"
  4. "fmt"
  5. "net"
  6. "net/http"
  7. "strings"
  8. "github.com/seaweedfs/seaweedfs/weed/glog"
  9. )
  10. var (
  11. ErrUnauthorized = errors.New("unauthorized token")
  12. )
  13. /*
  14. Guard is to ensure data access security.
  15. There are 2 ways to check access:
  16. 1. white list. It's checking request ip address.
  17. 2. JSON Web Token(JWT) generated from secretKey.
  18. The jwt can come from:
  19. 1. url parameter jwt=...
  20. 2. request header "Authorization"
  21. 3. cookie with the name "jwt"
  22. The white list is checked first because it is easy.
  23. Then the JWT is checked.
  24. The Guard will also check these claims if provided:
  25. 1. "exp" Expiration Time
  26. 2. "nbf" Not Before
  27. Generating JWT:
  28. 1. use HS256 to sign
  29. 2. optionally set "exp", "nbf" fields, in Unix time,
  30. the number of seconds elapsed since January 1, 1970 UTC.
  31. Referenced:
  32. https://github.com/pkieltyka/jwtauth/blob/master/jwtauth.go
  33. */
  34. type Guard struct {
  35. whiteListIp map[string]struct{}
  36. whiteListCIDR map[string]*net.IPNet
  37. SigningKey SigningKey
  38. ExpiresAfterSec int
  39. ReadSigningKey SigningKey
  40. ReadExpiresAfterSec int
  41. isWriteActive bool
  42. isEmptyWhiteList bool
  43. }
  44. func NewGuard(whiteList []string, signingKey string, expiresAfterSec int, readSigningKey string, readExpiresAfterSec int) *Guard {
  45. g := &Guard{
  46. SigningKey: SigningKey(signingKey),
  47. ExpiresAfterSec: expiresAfterSec,
  48. ReadSigningKey: SigningKey(readSigningKey),
  49. ReadExpiresAfterSec: readExpiresAfterSec,
  50. }
  51. g.UpdateWhiteList(whiteList)
  52. return g
  53. }
  54. func (g *Guard) WhiteList(f http.HandlerFunc) http.HandlerFunc {
  55. if !g.isWriteActive {
  56. //if no security needed, just skip all checking
  57. return f
  58. }
  59. return func(w http.ResponseWriter, r *http.Request) {
  60. if err := g.checkWhiteList(w, r); err != nil {
  61. w.WriteHeader(http.StatusUnauthorized)
  62. return
  63. }
  64. f(w, r)
  65. }
  66. }
  67. func GetActualRemoteHost(r *http.Request) string {
  68. // For security reasons, only use RemoteAddr to determine the client's IP address.
  69. // Do not trust headers like X-Forwarded-For, as they can be easily spoofed by clients.
  70. host, _, err := net.SplitHostPort(r.RemoteAddr)
  71. if err == nil {
  72. return host
  73. }
  74. // If SplitHostPort fails, it may be because of a missing port.
  75. // We try to parse RemoteAddr as a raw host (IP or hostname).
  76. host = strings.TrimSpace(r.RemoteAddr)
  77. // It might be an IPv6 address without a port, but with brackets.
  78. // e.g. "[::1]"
  79. if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
  80. host = host[1 : len(host)-1]
  81. }
  82. // Return the host (can be IP or hostname, just like headers)
  83. return host
  84. }
  85. func (g *Guard) checkWhiteList(w http.ResponseWriter, r *http.Request) error {
  86. if g.isEmptyWhiteList {
  87. return nil
  88. }
  89. host := GetActualRemoteHost(r)
  90. // Check exact match first (works for both IPs and hostnames)
  91. if _, ok := g.whiteListIp[host]; ok {
  92. return nil
  93. }
  94. // Check CIDR ranges (only for valid IP addresses)
  95. remote := net.ParseIP(host)
  96. if remote != nil {
  97. for _, cidrnet := range g.whiteListCIDR {
  98. // If the whitelist entry contains a "/" it
  99. // is a CIDR range, and we should check the
  100. if cidrnet.Contains(remote) {
  101. return nil
  102. }
  103. }
  104. }
  105. glog.V(0).Infof("Not in whitelist: %s (original RemoteAddr: %s)", host, r.RemoteAddr)
  106. return fmt.Errorf("Not in whitelist: %s", host)
  107. }
  108. func (g *Guard) UpdateWhiteList(whiteList []string) {
  109. whiteListIp := make(map[string]struct{})
  110. whiteListCIDR := make(map[string]*net.IPNet)
  111. for _, ip := range whiteList {
  112. if strings.Contains(ip, "/") {
  113. _, cidrnet, err := net.ParseCIDR(ip)
  114. if err != nil {
  115. glog.Errorf("Parse CIDR %s in whitelist failed: %v", ip, err)
  116. }
  117. whiteListCIDR[ip] = cidrnet
  118. } else {
  119. whiteListIp[ip] = struct{}{}
  120. }
  121. }
  122. g.isEmptyWhiteList = len(whiteListIp) == 0 && len(whiteListCIDR) == 0
  123. g.isWriteActive = !g.isEmptyWhiteList || len(g.SigningKey) != 0
  124. g.whiteListIp = whiteListIp
  125. g.whiteListCIDR = whiteListCIDR
  126. }