auth_proxy.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. package middleware
  2. import (
  3. "fmt"
  4. "net/mail"
  5. "reflect"
  6. "strings"
  7. "time"
  8. "github.com/grafana/grafana/pkg/bus"
  9. "github.com/grafana/grafana/pkg/log"
  10. "github.com/grafana/grafana/pkg/login"
  11. m "github.com/grafana/grafana/pkg/models"
  12. "github.com/grafana/grafana/pkg/services/session"
  13. "github.com/grafana/grafana/pkg/setting"
  14. )
  15. var AUTH_PROXY_SESSION_VAR = "authProxyHeaderValue"
  16. func initContextWithAuthProxy(ctx *m.ReqContext, orgID int64) bool {
  17. if !setting.AuthProxyEnabled {
  18. return false
  19. }
  20. proxyHeaderValue := ctx.Req.Header.Get(setting.AuthProxyHeaderName)
  21. if len(proxyHeaderValue) == 0 {
  22. return false
  23. }
  24. // if auth proxy ip(s) defined, check if request comes from one of those
  25. if err := checkAuthenticationProxy(ctx.RemoteAddr(), proxyHeaderValue); err != nil {
  26. ctx.Handle(407, "Proxy authentication required", err)
  27. return true
  28. }
  29. // initialize session
  30. if err := ctx.Session.Start(ctx.Context); err != nil {
  31. log.Error(3, "Failed to start session", err)
  32. return false
  33. }
  34. query := &m.GetSignedInUserQuery{OrgId: orgID}
  35. // if this session has already been authenticated by authProxy just load the user
  36. sessProxyValue := ctx.Session.Get(AUTH_PROXY_SESSION_VAR)
  37. if sessProxyValue != nil && sessProxyValue.(string) == proxyHeaderValue && getRequestUserId(ctx) > 0 {
  38. // if we're using ldap, sync user periodically
  39. if setting.LdapEnabled {
  40. syncQuery := &m.LoginUserQuery{
  41. ReqContext: ctx,
  42. Username: proxyHeaderValue,
  43. }
  44. if err := syncGrafanaUserWithLdapUser(syncQuery); err != nil {
  45. if err == login.ErrInvalidCredentials {
  46. ctx.Handle(500, "Unable to authenticate user", err)
  47. return false
  48. }
  49. ctx.Handle(500, "Failed to sync user", err)
  50. return false
  51. }
  52. }
  53. query.UserId = getRequestUserId(ctx)
  54. // if we're using ldap, pass authproxy login name to ldap user sync
  55. } else if setting.LdapEnabled {
  56. ctx.Session.Delete(session.SESS_KEY_LASTLDAPSYNC)
  57. syncQuery := &m.LoginUserQuery{
  58. ReqContext: ctx,
  59. Username: proxyHeaderValue,
  60. }
  61. if err := syncGrafanaUserWithLdapUser(syncQuery); err != nil {
  62. if err == login.ErrInvalidCredentials {
  63. ctx.Handle(500, "Unable to authenticate user", err)
  64. return false
  65. }
  66. ctx.Handle(500, "Failed to sync user", err)
  67. return false
  68. }
  69. if syncQuery.User == nil {
  70. ctx.Handle(500, "Failed to sync user", nil)
  71. return false
  72. }
  73. query.UserId = syncQuery.User.Id
  74. // no ldap, just use the info we have
  75. } else {
  76. extUser := &m.ExternalUserInfo{
  77. AuthModule: "authproxy",
  78. AuthId: proxyHeaderValue,
  79. }
  80. if setting.AuthProxyHeaderProperty == "username" {
  81. extUser.Login = proxyHeaderValue
  82. // only set Email if it can be parsed as an email address
  83. emailAddr, emailErr := mail.ParseAddress(proxyHeaderValue)
  84. if emailErr == nil {
  85. extUser.Email = emailAddr.Address
  86. }
  87. } else if setting.AuthProxyHeaderProperty == "email" {
  88. extUser.Email = proxyHeaderValue
  89. extUser.Login = proxyHeaderValue
  90. } else {
  91. ctx.Handle(500, "Auth proxy header property invalid", nil)
  92. return true
  93. }
  94. for _, field := range []string{"Name", "Email", "Login"} {
  95. if setting.AuthProxyHeaders[field] == "" {
  96. continue
  97. }
  98. if val := ctx.Req.Header.Get(setting.AuthProxyHeaders[field]); val != "" {
  99. reflect.ValueOf(extUser).Elem().FieldByName(field).SetString(val)
  100. }
  101. }
  102. // add/update user in grafana
  103. cmd := &m.UpsertUserCommand{
  104. ReqContext: ctx,
  105. ExternalUser: extUser,
  106. SignupAllowed: setting.AuthProxyAutoSignUp,
  107. }
  108. err := bus.Dispatch(cmd)
  109. if err != nil {
  110. ctx.Handle(500, "Failed to login as user specified in auth proxy header", err)
  111. return true
  112. }
  113. query.UserId = cmd.Result.Id
  114. }
  115. if err := bus.Dispatch(query); err != nil {
  116. ctx.Handle(500, "Failed to find user", err)
  117. return true
  118. }
  119. // Make sure that we cannot share a session between different users!
  120. if getRequestUserId(ctx) > 0 && getRequestUserId(ctx) != query.Result.UserId {
  121. // remove session
  122. if err := ctx.Session.Destory(ctx.Context); err != nil {
  123. log.Error(3, "Failed to destroy session, err")
  124. }
  125. // initialize a new session
  126. if err := ctx.Session.Start(ctx.Context); err != nil {
  127. log.Error(3, "Failed to start session", err)
  128. }
  129. }
  130. ctx.Session.Set(AUTH_PROXY_SESSION_VAR, proxyHeaderValue)
  131. ctx.SignedInUser = query.Result
  132. ctx.IsSignedIn = true
  133. ctx.Session.Set(session.SESS_KEY_USERID, ctx.UserId)
  134. return true
  135. }
  136. var syncGrafanaUserWithLdapUser = func(query *m.LoginUserQuery) error {
  137. expireEpoch := time.Now().Add(time.Duration(-setting.AuthProxyLdapSyncTtl) * time.Minute).Unix()
  138. var lastLdapSync int64
  139. if lastLdapSyncInSession := query.ReqContext.Session.Get(session.SESS_KEY_LASTLDAPSYNC); lastLdapSyncInSession != nil {
  140. lastLdapSync = lastLdapSyncInSession.(int64)
  141. }
  142. if lastLdapSync < expireEpoch {
  143. ldapCfg := login.LdapCfg
  144. if len(ldapCfg.Servers) < 1 {
  145. return fmt.Errorf("No LDAP servers available")
  146. }
  147. for _, server := range ldapCfg.Servers {
  148. author := login.NewLdapAuthenticator(server)
  149. if err := author.SyncUser(query); err != nil {
  150. return err
  151. }
  152. }
  153. query.ReqContext.Session.Set(session.SESS_KEY_LASTLDAPSYNC, time.Now().Unix())
  154. }
  155. return nil
  156. }
  157. func checkAuthenticationProxy(remoteAddr string, proxyHeaderValue string) error {
  158. if len(strings.TrimSpace(setting.AuthProxyWhitelist)) == 0 {
  159. return nil
  160. }
  161. // Multiple ip addresses? Right-most IP address is the IP address of the most recent proxy
  162. if strings.Contains(remoteAddr, ",") {
  163. sourceIPs := strings.Split(remoteAddr, ",")
  164. remoteAddr = strings.TrimSpace(sourceIPs[len(sourceIPs)-1])
  165. }
  166. remoteAddr = strings.TrimPrefix(remoteAddr, "[")
  167. remoteAddr = strings.TrimSuffix(remoteAddr, "]")
  168. proxies := strings.Split(setting.AuthProxyWhitelist, ",")
  169. // Compare allowed IP addresses to actual address
  170. for _, proxyIP := range proxies {
  171. if remoteAddr == strings.TrimSpace(proxyIP) {
  172. return nil
  173. }
  174. }
  175. return fmt.Errorf("Request for user (%s) from %s is not from the authentication proxy", proxyHeaderValue, remoteAddr)
  176. }