You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

146 lines
3.2 KiB

  1. package security
  2. import (
  3. "errors"
  4. "fmt"
  5. "net"
  6. "net/http"
  7. "strings"
  8. "time"
  9. "github.com/chrislusf/weed-fs/go/glog"
  10. "github.com/dgrijalva/jwt-go"
  11. )
  12. var (
  13. ErrUnauthorized = errors.New("unauthorized token")
  14. )
  15. /*
  16. Guard is to ensure data access security.
  17. There are 2 ways to check access:
  18. 1. white list. It's checking request ip address.
  19. 2. JSON Web Token(JWT) generated from secretKey.
  20. The jwt can come from:
  21. 1. url parameter jwt=...
  22. 2. request header "Authorization"
  23. 3. cookie with the name "jwt"
  24. The white list is checked first because it is easy.
  25. Then the JWT is checked.
  26. The Guard will also check these claims if provided:
  27. 1. "exp" Expiration Time
  28. 2. "nbf" Not Before
  29. Generating JWT:
  30. 1. use HS256 to sign
  31. 2. optionally set "exp", "nbf" fields, in Unix time,
  32. the number of seconds elapsed since January 1, 1970 UTC.
  33. Referenced:
  34. https://github.com/pkieltyka/jwtauth/blob/master/jwtauth.go
  35. */
  36. type Guard struct {
  37. whiteList []string
  38. secretKey string
  39. isActive bool
  40. }
  41. func NewGuard(whiteList []string, secretKey string) *Guard {
  42. g := &Guard{whiteList: whiteList, secretKey: secretKey}
  43. g.isActive = len(g.whiteList) != 0 || len(g.secretKey) != 0
  44. return g
  45. }
  46. func (g *Guard) Secure(f func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request) {
  47. if !g.isActive {
  48. //if no security needed, just skip all checkings
  49. return f
  50. }
  51. return func(w http.ResponseWriter, r *http.Request) {
  52. if err := g.doCheck(w, r); err != nil {
  53. w.WriteHeader(http.StatusUnauthorized)
  54. return
  55. }
  56. f(w, r)
  57. }
  58. }
  59. func (g *Guard) NewToken() (tokenString string, err error) {
  60. m := make(map[string]interface{})
  61. m["exp"] = time.Now().Unix() + 10
  62. return g.Encode(m)
  63. }
  64. func (g *Guard) Encode(claims map[string]interface{}) (tokenString string, err error) {
  65. if !g.isActive {
  66. return "", nil
  67. }
  68. t := jwt.New(jwt.GetSigningMethod("HS256"))
  69. t.Claims = claims
  70. return t.SignedString(g.secretKey)
  71. }
  72. func (g *Guard) Decode(tokenString string) (token *jwt.Token, err error) {
  73. return jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
  74. return g.secretKey, nil
  75. })
  76. }
  77. func (g *Guard) doCheck(w http.ResponseWriter, r *http.Request) error {
  78. if len(g.whiteList) != 0 {
  79. host, _, err := net.SplitHostPort(r.RemoteAddr)
  80. if err == nil {
  81. for _, ip := range g.whiteList {
  82. if ip == host {
  83. return nil
  84. }
  85. }
  86. }
  87. }
  88. if len(g.secretKey) != 0 {
  89. // Get token from query params
  90. tokenStr := r.URL.Query().Get("jwt")
  91. // Get token from authorization header
  92. if tokenStr == "" {
  93. bearer := r.Header.Get("Authorization")
  94. if len(bearer) > 7 && strings.ToUpper(bearer[0:6]) == "BEARER" {
  95. tokenStr = bearer[7:]
  96. }
  97. }
  98. // Get token from cookie
  99. if tokenStr == "" {
  100. cookie, err := r.Cookie("jwt")
  101. if err == nil {
  102. tokenStr = cookie.Value
  103. }
  104. }
  105. if tokenStr == "" {
  106. return ErrUnauthorized
  107. }
  108. // Verify the token
  109. token, err := g.Decode(tokenStr)
  110. if err != nil {
  111. glog.V(1).Infof("Token verification error from %s: %v", r.RemoteAddr, err)
  112. return ErrUnauthorized
  113. }
  114. if !token.Valid {
  115. glog.V(1).Infof("Token invliad from %s: %v", r.RemoteAddr, tokenStr)
  116. return ErrUnauthorized
  117. }
  118. }
  119. glog.V(1).Infof("No permission from %s", r.RemoteAddr)
  120. return fmt.Errorf("No write permisson from %s", r.RemoteAddr)
  121. }