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.

196 lines
4.5 KiB

5 years ago
5 years ago
5 years ago
10 years ago
5 years ago
5 years ago
10 years ago
10 years ago
9 years ago
9 years ago
10 years ago
9 years ago
10 years ago
5 years ago
  1. package security
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "net"
  7. "net/http"
  8. "strings"
  9. "github.com/valyala/fasthttp"
  10. "github.com/chrislusf/seaweedfs/weed/glog"
  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. SigningKey SigningKey
  39. ExpiresAfterSec int
  40. ReadSigningKey SigningKey
  41. ReadExpiresAfterSec int
  42. isWriteActive bool
  43. }
  44. func NewGuard(whiteList []string, signingKey string, expiresAfterSec int, readSigningKey string, readExpiresAfterSec int) *Guard {
  45. g := &Guard{
  46. whiteList: whiteList,
  47. SigningKey: SigningKey(signingKey),
  48. ExpiresAfterSec: expiresAfterSec,
  49. ReadSigningKey: SigningKey(readSigningKey),
  50. ReadExpiresAfterSec: readExpiresAfterSec,
  51. }
  52. g.isWriteActive = len(g.whiteList) != 0 || len(g.SigningKey) != 0
  53. return g
  54. }
  55. func (g *Guard) OldWhiteList(f func(w http.ResponseWriter, r *http.Request)) func(w http.ResponseWriter, r *http.Request) {
  56. if !g.isWriteActive {
  57. //if no security needed, just skip all checking
  58. return f
  59. }
  60. return func(w http.ResponseWriter, r *http.Request) {
  61. if err := g.checkWhiteList(w, r); err != nil {
  62. w.WriteHeader(http.StatusUnauthorized)
  63. return
  64. }
  65. f(w, r)
  66. }
  67. }
  68. func (g *Guard) WhiteList(f func(ctx *fasthttp.RequestCtx)) func(ctx *fasthttp.RequestCtx) {
  69. if !g.isWriteActive {
  70. //if no security needed, just skip all checking
  71. return f
  72. }
  73. return func(ctx *fasthttp.RequestCtx) {
  74. if err := g.fastCheckWhiteList(ctx); err != nil {
  75. ctx.SetStatusCode(http.StatusUnauthorized)
  76. return
  77. }
  78. f(ctx)
  79. }
  80. }
  81. func GetActualRemoteHost(r *http.Request) (host string, err error) {
  82. host = r.Header.Get("HTTP_X_FORWARDED_FOR")
  83. if host == "" {
  84. host = r.Header.Get("X-FORWARDED-FOR")
  85. }
  86. if strings.Contains(host, ",") {
  87. host = host[0:strings.Index(host, ",")]
  88. }
  89. if host == "" {
  90. host, _, err = net.SplitHostPort(r.RemoteAddr)
  91. }
  92. return
  93. }
  94. func FastGetActualRemoteHost(ctx *fasthttp.RequestCtx) (theHost string, err error) {
  95. host := ctx.Request.Header.Peek("HTTP_X_FORWARDED_FOR")
  96. if host == nil {
  97. host = ctx.Request.Header.Peek("X-FORWARDED-FOR")
  98. }
  99. commaIndex := bytes.IndexByte(host, ',')
  100. if commaIndex >= 0 {
  101. host = host[0:commaIndex]
  102. }
  103. if host == nil {
  104. shost, _, serr := net.SplitHostPort(ctx.RemoteAddr().String())
  105. return shost, serr
  106. }
  107. return string(host), nil
  108. }
  109. func (g *Guard) checkWhiteList(w http.ResponseWriter, r *http.Request) error {
  110. if len(g.whiteList) == 0 {
  111. return nil
  112. }
  113. host, err := GetActualRemoteHost(r)
  114. if err == nil {
  115. for _, ip := range g.whiteList {
  116. // If the whitelist entry contains a "/" it
  117. // is a CIDR range, and we should check the
  118. // remote host is within it
  119. if strings.Contains(ip, "/") {
  120. _, cidrnet, err := net.ParseCIDR(ip)
  121. if err != nil {
  122. panic(err)
  123. }
  124. remote := net.ParseIP(host)
  125. if cidrnet.Contains(remote) {
  126. return nil
  127. }
  128. }
  129. //
  130. // Otherwise we're looking for a literal match.
  131. //
  132. if ip == host {
  133. return nil
  134. }
  135. }
  136. }
  137. glog.V(0).Infof("Not in whitelist: %s", r.RemoteAddr)
  138. return fmt.Errorf("Not in whitelis: %s", r.RemoteAddr)
  139. }
  140. func (g *Guard) fastCheckWhiteList(ctx *fasthttp.RequestCtx) error {
  141. if len(g.whiteList) == 0 {
  142. return nil
  143. }
  144. host, err := FastGetActualRemoteHost(ctx)
  145. if err == nil {
  146. for _, ip := range g.whiteList {
  147. // If the whitelist entry contains a "/" it
  148. // is a CIDR range, and we should check the
  149. // remote host is within it
  150. if strings.Contains(ip, "/") {
  151. _, cidrnet, err := net.ParseCIDR(ip)
  152. if err != nil {
  153. panic(err)
  154. }
  155. remote := net.ParseIP(host)
  156. if cidrnet.Contains(remote) {
  157. return nil
  158. }
  159. }
  160. //
  161. // Otherwise we're looking for a literal match.
  162. //
  163. if ip == host {
  164. return nil
  165. }
  166. }
  167. }
  168. glog.V(0).Infof("Not in whitelist: %s", ctx.RemoteAddr())
  169. return fmt.Errorf("Not in whitelis: %s", ctx.RemoteAddr())
  170. }