guard.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. package security
  2. import (
  3. "errors"
  4. "fmt"
  5. "net"
  6. "net/http"
  7. "strings"
  8. "github.com/chrislusf/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. whiteList []string
  36. SecretKey Secret
  37. isActive bool
  38. }
  39. func NewGuard(whiteList []string, secretKey string) *Guard {
  40. g := &Guard{whiteList: whiteList, SecretKey: Secret(secretKey)}
  41. g.isActive = len(g.whiteList) != 0 || len(g.SecretKey) != 0
  42. return g
  43. }
  44. func (g *Guard) WhiteList(f func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request) {
  45. if !g.isActive {
  46. //if no security needed, just skip all checkings
  47. return f
  48. }
  49. return func(w http.ResponseWriter, r *http.Request) {
  50. if err := g.checkWhiteList(w, r); err != nil {
  51. w.WriteHeader(http.StatusUnauthorized)
  52. return
  53. }
  54. f(w, r)
  55. }
  56. }
  57. func (g *Guard) Secure(f func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request) {
  58. if !g.isActive {
  59. //if no security needed, just skip all checkings
  60. return f
  61. }
  62. return func(w http.ResponseWriter, r *http.Request) {
  63. if err := g.checkJwt(w, r); err != nil {
  64. w.WriteHeader(http.StatusUnauthorized)
  65. return
  66. }
  67. f(w, r)
  68. }
  69. }
  70. func GetActualRemoteHost(r *http.Request) (host string, err error) {
  71. host = r.Header.Get("HTTP_X_FORWARDED_FOR")
  72. if host == "" {
  73. host = r.Header.Get("X-FORWARDED-FOR")
  74. }
  75. if strings.Contains(host, ",") {
  76. host = host[0:strings.Index(host, ",")]
  77. }
  78. if host == "" {
  79. host, _, err = net.SplitHostPort(r.RemoteAddr)
  80. }
  81. return
  82. }
  83. func (g *Guard) checkWhiteList(w http.ResponseWriter, r *http.Request) error {
  84. if len(g.whiteList) == 0 {
  85. return nil
  86. }
  87. host, err := GetActualRemoteHost(r)
  88. if err == nil {
  89. for _, ip := range g.whiteList {
  90. // If the whitelist entry contains a "/" it
  91. // is a CIDR range, and we should check the
  92. // remote host is within it
  93. if strings.Contains(ip, "/") {
  94. _, cidrnet, err := net.ParseCIDR(ip)
  95. if err != nil {
  96. panic(err)
  97. }
  98. remote := net.ParseIP(host)
  99. if cidrnet.Contains(remote) {
  100. return nil
  101. }
  102. }
  103. //
  104. // Otherwise we're looking for a literal match.
  105. //
  106. if ip == host {
  107. return nil
  108. }
  109. }
  110. }
  111. glog.V(0).Infof("Not in whitelist: %s", r.RemoteAddr)
  112. return fmt.Errorf("Not in whitelis: %s", r.RemoteAddr)
  113. }
  114. func (g *Guard) checkJwt(w http.ResponseWriter, r *http.Request) error {
  115. if g.checkWhiteList(w, r) == nil {
  116. return nil
  117. }
  118. if len(g.SecretKey) == 0 {
  119. return nil
  120. }
  121. tokenStr := GetJwt(r)
  122. if tokenStr == "" {
  123. return ErrUnauthorized
  124. }
  125. // Verify the token
  126. token, err := DecodeJwt(g.SecretKey, tokenStr)
  127. if err != nil {
  128. glog.V(1).Infof("Token verification error from %s: %v", r.RemoteAddr, err)
  129. return ErrUnauthorized
  130. }
  131. if !token.Valid {
  132. glog.V(1).Infof("Token invliad from %s: %v", r.RemoteAddr, tokenStr)
  133. return ErrUnauthorized
  134. }
  135. glog.V(1).Infof("No permission from %s", r.RemoteAddr)
  136. return fmt.Errorf("No write permisson from %s", r.RemoteAddr)
  137. }