auth_proxy.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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, orgId int64) 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. query.OrgId = orgId
  28. if err := bus.Dispatch(query); err != nil {
  29. if err != m.ErrUserNotFound {
  30. ctx.Handle(500, "Failed to find user specified in auth proxy header", err)
  31. return true
  32. }
  33. if setting.AuthProxyAutoSignUp {
  34. cmd := getCreateUserCommandForProxyAuth(proxyHeaderValue)
  35. if setting.LdapEnabled {
  36. cmd.SkipOrgSetup = true
  37. }
  38. if err := bus.Dispatch(cmd); err != nil {
  39. ctx.Handle(500, "Failed to create user specified in auth proxy header", err)
  40. return true
  41. }
  42. query = &m.GetSignedInUserQuery{UserId: cmd.Result.Id, OrgId: orgId}
  43. if err := bus.Dispatch(query); err != nil {
  44. ctx.Handle(500, "Failed find user after creation", err)
  45. return true
  46. }
  47. } else {
  48. return false
  49. }
  50. }
  51. // initialize session
  52. if err := ctx.Session.Start(ctx); 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); err != nil {
  60. log.Error(3, "Failed to destroy session, err")
  61. }
  62. // initialize a new session
  63. if err := ctx.Session.Start(ctx); 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(SESS_KEY_USERID, ctx.UserId)
  79. return true
  80. }
  81. var syncGrafanaUserWithLdapUser = func(ctx *Context, query *m.GetSignedInUserQuery) error {
  82. if setting.LdapEnabled {
  83. expireEpoch := time.Now().Add(time.Duration(-setting.AuthProxyLdapSyncTtl) * time.Minute).Unix()
  84. var lastLdapSync int64
  85. if lastLdapSyncInSession := ctx.Session.Get(SESS_KEY_LASTLDAPSYNC); lastLdapSyncInSession != nil {
  86. lastLdapSync = lastLdapSyncInSession.(int64)
  87. }
  88. if lastLdapSync < expireEpoch {
  89. ldapCfg := login.LdapCfg
  90. for _, server := range ldapCfg.Servers {
  91. author := login.NewLdapAuthenticator(server)
  92. if err := author.SyncSignedInUser(query.Result); err != nil {
  93. return err
  94. }
  95. }
  96. ctx.Session.Set(SESS_KEY_LASTLDAPSYNC, time.Now().Unix())
  97. }
  98. }
  99. return nil
  100. }
  101. func checkAuthenticationProxy(ctx *Context, proxyHeaderValue string) error {
  102. if len(strings.TrimSpace(setting.AuthProxyWhitelist)) > 0 {
  103. proxies := strings.Split(setting.AuthProxyWhitelist, ",")
  104. remoteAddrSplit := strings.Split(ctx.Req.RemoteAddr, ":")
  105. sourceIP := remoteAddrSplit[0]
  106. found := false
  107. for _, proxyIP := range proxies {
  108. if sourceIP == strings.TrimSpace(proxyIP) {
  109. found = true
  110. break
  111. }
  112. }
  113. if !found {
  114. msg := fmt.Sprintf("Request for user (%s) is not from the authentication proxy", proxyHeaderValue)
  115. err := errors.New(msg)
  116. return err
  117. }
  118. }
  119. return nil
  120. }
  121. func getSignedInUserQueryForProxyAuth(headerVal string) *m.GetSignedInUserQuery {
  122. query := m.GetSignedInUserQuery{}
  123. if setting.AuthProxyHeaderProperty == "username" {
  124. query.Login = headerVal
  125. } else if setting.AuthProxyHeaderProperty == "email" {
  126. query.Email = headerVal
  127. } else {
  128. panic("Auth proxy header property invalid")
  129. }
  130. return &query
  131. }
  132. func getCreateUserCommandForProxyAuth(headerVal string) *m.CreateUserCommand {
  133. cmd := m.CreateUserCommand{}
  134. if setting.AuthProxyHeaderProperty == "username" {
  135. cmd.Login = headerVal
  136. cmd.Email = headerVal
  137. } else if setting.AuthProxyHeaderProperty == "email" {
  138. cmd.Email = headerVal
  139. cmd.Login = headerVal
  140. } else {
  141. panic("Auth proxy header property invalid")
  142. }
  143. return &cmd
  144. }