auth_proxy.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. package middleware
  2. import (
  3. "errors"
  4. "fmt"
  5. "strings"
  6. "time"
  7. "github.com/grafana/grafana/pkg/bus"
  8. "github.com/grafana/grafana/pkg/log"
  9. "github.com/grafana/grafana/pkg/login"
  10. m "github.com/grafana/grafana/pkg/models"
  11. "github.com/grafana/grafana/pkg/setting"
  12. )
  13. func initContextWithAuthProxy(ctx *Context) bool {
  14. if !setting.AuthProxyEnabled {
  15. return false
  16. }
  17. proxyHeaderValue := ctx.Req.Header.Get(setting.AuthProxyHeaderName)
  18. if len(proxyHeaderValue) == 0 {
  19. return false
  20. }
  21. // if auth proxy ip(s) defined, check if request comes from one of those
  22. if err := checkAuthenticationProxy(ctx, proxyHeaderValue); err != nil {
  23. ctx.Handle(407, "Proxy authentication required", err)
  24. return true
  25. }
  26. query := getSignedInUserQueryForProxyAuth(proxyHeaderValue)
  27. if err := bus.Dispatch(query); err != nil {
  28. if err != m.ErrUserNotFound {
  29. ctx.Handle(500, "Failed to find user specified in auth proxy header", err)
  30. return true
  31. }
  32. if setting.AuthProxyAutoSignUp {
  33. cmd := getCreateUserCommandForProxyAuth(proxyHeaderValue)
  34. if setting.LdapEnabled {
  35. cmd.SkipOrgSetup = true
  36. }
  37. if err := bus.Dispatch(cmd); err != nil {
  38. ctx.Handle(500, "Failed to create user specified in auth proxy header", err)
  39. return true
  40. }
  41. query = &m.GetSignedInUserQuery{UserId: cmd.Result.Id}
  42. if err := bus.Dispatch(query); err != nil {
  43. ctx.Handle(500, "Failed find user after creation", err)
  44. return true
  45. }
  46. } else {
  47. return false
  48. }
  49. }
  50. // initialize session
  51. if err := ctx.Session.Start(ctx); err != nil {
  52. log.Error(3, "Failed to start session", err)
  53. return false
  54. }
  55. // Make sure that we cannot share a session between different users!
  56. if getRequestUserId(ctx) > 0 && getRequestUserId(ctx) != query.Result.UserId {
  57. // remove session
  58. if err := ctx.Session.Destory(ctx); err != nil {
  59. log.Error(3, "Failed to destory session, err")
  60. }
  61. // initialize a new session
  62. if err := ctx.Session.Start(ctx); err != nil {
  63. log.Error(3, "Failed to start session", err)
  64. }
  65. }
  66. // When ldap is enabled, sync userinfo and org roles
  67. if err := syncGrafanaUserWithLdapUser(ctx, query); err != nil {
  68. if err == login.ErrInvalidCredentials {
  69. ctx.Handle(500, "Unable to authenticate user", err)
  70. return false
  71. }
  72. ctx.Handle(500, "Failed to sync user", err)
  73. return false
  74. }
  75. ctx.SignedInUser = query.Result
  76. ctx.IsSignedIn = true
  77. ctx.Session.Set(SESS_KEY_USERID, ctx.UserId)
  78. return true
  79. }
  80. var syncGrafanaUserWithLdapUser = func(ctx *Context, query *m.GetSignedInUserQuery) error {
  81. if setting.LdapEnabled {
  82. expireEpoch := time.Now().Add(time.Duration(-setting.AuthProxyLdapSyncTtl) * time.Minute).Unix()
  83. var lastLdapSync int64
  84. if lastLdapSyncInSession := ctx.Session.Get(SESS_KEY_LASTLDAPSYNC); lastLdapSyncInSession != nil {
  85. lastLdapSync = lastLdapSyncInSession.(int64)
  86. }
  87. if lastLdapSync < expireEpoch {
  88. ldapCfg := login.LdapCfg
  89. for _, server := range ldapCfg.Servers {
  90. auther := login.NewLdapAuthenticator(server)
  91. if err := auther.SyncSignedInUser(query.Result); err != nil {
  92. return err
  93. }
  94. }
  95. ctx.Session.Set(SESS_KEY_LASTLDAPSYNC, time.Now().Unix())
  96. }
  97. }
  98. return nil
  99. }
  100. func checkAuthenticationProxy(ctx *Context, proxyHeaderValue string) error {
  101. if len(strings.TrimSpace(setting.AuthProxyWhitelist)) > 0 {
  102. proxies := strings.Split(setting.AuthProxyWhitelist, ",")
  103. remoteAddrSplit := strings.Split(ctx.Req.RemoteAddr, ":")
  104. sourceIP := remoteAddrSplit[0]
  105. found := false
  106. for _, proxyIP := range proxies {
  107. if sourceIP == strings.TrimSpace(proxyIP) {
  108. found = true
  109. break
  110. }
  111. }
  112. if !found {
  113. msg := fmt.Sprintf("Request for user (%s) is not from the authentication proxy", proxyHeaderValue)
  114. err := errors.New(msg)
  115. return err
  116. }
  117. }
  118. return nil
  119. }
  120. func getSignedInUserQueryForProxyAuth(headerVal string) *m.GetSignedInUserQuery {
  121. query := m.GetSignedInUserQuery{}
  122. if setting.AuthProxyHeaderProperty == "username" {
  123. query.Login = headerVal
  124. } else if setting.AuthProxyHeaderProperty == "email" {
  125. query.Email = headerVal
  126. } else {
  127. panic("Auth proxy header property invalid")
  128. }
  129. return &query
  130. }
  131. func getCreateUserCommandForProxyAuth(headerVal string) *m.CreateUserCommand {
  132. cmd := m.CreateUserCommand{}
  133. if setting.AuthProxyHeaderProperty == "username" {
  134. cmd.Login = headerVal
  135. cmd.Email = headerVal
  136. } else if setting.AuthProxyHeaderProperty == "email" {
  137. cmd.Email = headerVal
  138. cmd.Login = headerVal
  139. } else {
  140. panic("Auth proxy header property invalid")
  141. }
  142. return &cmd
  143. }