auth_proxy.go 4.6 KB

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