auth_proxy.go 4.6 KB

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