auth_proxy.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. package authproxy
  2. import (
  3. "fmt"
  4. "net"
  5. "net/mail"
  6. "reflect"
  7. "strings"
  8. "time"
  9. "github.com/grafana/grafana/pkg/bus"
  10. "github.com/grafana/grafana/pkg/infra/remotecache"
  11. "github.com/grafana/grafana/pkg/login"
  12. models "github.com/grafana/grafana/pkg/models"
  13. "github.com/grafana/grafana/pkg/setting"
  14. )
  15. const (
  16. // CachePrefix is a prefix for the cache key
  17. CachePrefix = "auth-proxy-sync-ttl:%s"
  18. )
  19. // AuthProxy struct
  20. type AuthProxy struct {
  21. store *remotecache.RemoteCache
  22. ctx *models.ReqContext
  23. orgID int64
  24. header string
  25. LDAP func(server *login.LdapServerConf) login.ILdapAuther
  26. enabled bool
  27. whitelistIP string
  28. headerType string
  29. headers map[string]string
  30. cacheTTL int
  31. ldapEnabled bool
  32. }
  33. // Error auth proxy specific error
  34. type Error struct {
  35. Message string
  36. DetailsError error
  37. }
  38. // newError creates the Error
  39. func newError(message string, err error) *Error {
  40. return &Error{
  41. Message: message,
  42. DetailsError: err,
  43. }
  44. }
  45. // Error returns a Error error string
  46. func (err *Error) Error() string {
  47. return fmt.Sprintf("%s", err.Message)
  48. }
  49. // Options for the AuthProxy
  50. type Options struct {
  51. Store *remotecache.RemoteCache
  52. Ctx *models.ReqContext
  53. OrgID int64
  54. }
  55. // New instance of the AuthProxy
  56. func New(options *Options) *AuthProxy {
  57. header := options.Ctx.Req.Header.Get(setting.AuthProxyHeaderName)
  58. return &AuthProxy{
  59. store: options.Store,
  60. ctx: options.Ctx,
  61. orgID: options.OrgID,
  62. header: header,
  63. LDAP: login.NewLdapAuthenticator,
  64. enabled: setting.AuthProxyEnabled,
  65. headerType: setting.AuthProxyHeaderProperty,
  66. headers: setting.AuthProxyHeaders,
  67. whitelistIP: setting.AuthProxyWhitelist,
  68. cacheTTL: setting.AuthProxyLdapSyncTtl,
  69. ldapEnabled: setting.LdapEnabled,
  70. }
  71. }
  72. // IsEnabled checks if the proxy auth is enabled
  73. func (auth *AuthProxy) IsEnabled() bool {
  74. // Bail if the setting is not enabled
  75. if auth.enabled == false {
  76. return false
  77. }
  78. return true
  79. }
  80. // HasHeader checks if the we have specified header
  81. func (auth *AuthProxy) HasHeader() bool {
  82. if len(auth.header) == 0 {
  83. return false
  84. }
  85. return true
  86. }
  87. // IsAllowedIP compares presented IP with the whitelist one
  88. func (auth *AuthProxy) IsAllowedIP() (bool, *Error) {
  89. ip := auth.ctx.Req.RemoteAddr
  90. if len(strings.TrimSpace(auth.whitelistIP)) == 0 {
  91. return true, nil
  92. }
  93. proxies := strings.Split(auth.whitelistIP, ",")
  94. var proxyObjs []*net.IPNet
  95. for _, proxy := range proxies {
  96. result, err := coerceProxyAddress(proxy)
  97. if err != nil {
  98. return false, newError("Could not get the network", err)
  99. }
  100. proxyObjs = append(proxyObjs, result)
  101. }
  102. sourceIP, _, _ := net.SplitHostPort(ip)
  103. sourceObj := net.ParseIP(sourceIP)
  104. for _, proxyObj := range proxyObjs {
  105. if proxyObj.Contains(sourceObj) {
  106. return true, nil
  107. }
  108. }
  109. err := fmt.Errorf(
  110. "Request for user (%s) from %s is not from the authentication proxy", auth.header,
  111. sourceIP,
  112. )
  113. return false, newError("Proxy authentication required", err)
  114. }
  115. // InCache checks if we have user in cache
  116. func (auth *AuthProxy) InCache() bool {
  117. userID, _ := auth.GetUserIDViaCache()
  118. if userID == 0 {
  119. return false
  120. }
  121. return true
  122. }
  123. // getKey forms a key for the cache
  124. func (auth *AuthProxy) getKey() string {
  125. return fmt.Sprintf(CachePrefix, auth.header)
  126. }
  127. // GetUserID gets user id with whatever means possible
  128. func (auth *AuthProxy) GetUserID() (int64, *Error) {
  129. if auth.InCache() {
  130. // Error here means absent cache - we don't need to handle that
  131. id, _ := auth.GetUserIDViaCache()
  132. return id, nil
  133. }
  134. if auth.ldapEnabled {
  135. id, err := auth.GetUserIDViaLDAP()
  136. if err == login.ErrInvalidCredentials {
  137. return 0, newError("Proxy authentication required", login.ErrInvalidCredentials)
  138. }
  139. if err != nil {
  140. return 0, newError("Failed to sync user", err)
  141. }
  142. return id, nil
  143. }
  144. id, err := auth.GetUserIDViaHeader()
  145. if err != nil {
  146. return 0, newError("Failed to login as user specified in auth proxy header", err)
  147. }
  148. return id, nil
  149. }
  150. // GetUserIDViaCache gets the user from cache
  151. func (auth *AuthProxy) GetUserIDViaCache() (int64, error) {
  152. var (
  153. cacheKey = auth.getKey()
  154. userID, err = auth.store.Get(cacheKey)
  155. )
  156. if err != nil {
  157. return 0, err
  158. }
  159. return userID.(int64), nil
  160. }
  161. // GetUserIDViaLDAP gets user via LDAP request
  162. func (auth *AuthProxy) GetUserIDViaLDAP() (int64, *Error) {
  163. query := &models.LoginUserQuery{
  164. ReqContext: auth.ctx,
  165. Username: auth.header,
  166. }
  167. ldapCfg := login.LdapCfg
  168. if len(ldapCfg.Servers) < 1 {
  169. return 0, newError("No LDAP servers available", nil)
  170. }
  171. for _, server := range ldapCfg.Servers {
  172. author := auth.LDAP(server)
  173. if err := author.SyncUser(query); err != nil {
  174. return 0, newError(err.Error(), nil)
  175. }
  176. }
  177. return query.User.Id, nil
  178. }
  179. // GetUserIDViaHeader gets user from the header only
  180. func (auth *AuthProxy) GetUserIDViaHeader() (int64, error) {
  181. extUser := &models.ExternalUserInfo{
  182. AuthModule: "authproxy",
  183. AuthId: auth.header,
  184. }
  185. if auth.headerType == "username" {
  186. extUser.Login = auth.header
  187. // only set Email if it can be parsed as an email address
  188. emailAddr, emailErr := mail.ParseAddress(auth.header)
  189. if emailErr == nil {
  190. extUser.Email = emailAddr.Address
  191. }
  192. } else if auth.headerType == "email" {
  193. extUser.Email = auth.header
  194. extUser.Login = auth.header
  195. } else {
  196. return 0, newError("Auth proxy header property invalid", nil)
  197. }
  198. for _, field := range []string{"Name", "Email", "Login"} {
  199. if auth.headers[field] == "" {
  200. continue
  201. }
  202. if val := auth.ctx.Req.Header.Get(auth.headers[field]); val != "" {
  203. reflect.ValueOf(extUser).Elem().FieldByName(field).SetString(val)
  204. }
  205. }
  206. // add/update user in grafana
  207. cmd := &models.UpsertUserCommand{
  208. ReqContext: auth.ctx,
  209. ExternalUser: extUser,
  210. SignupAllowed: setting.AuthProxyAutoSignUp,
  211. }
  212. err := bus.Dispatch(cmd)
  213. if err != nil {
  214. return 0, err
  215. }
  216. return cmd.Result.Id, nil
  217. }
  218. // GetSignedUser get full signed user info
  219. func (auth *AuthProxy) GetSignedUser(userID int64) (*models.SignedInUser, *Error) {
  220. query := &models.GetSignedInUserQuery{
  221. OrgId: auth.orgID,
  222. UserId: userID,
  223. }
  224. if err := bus.Dispatch(query); err != nil {
  225. return nil, newError(err.Error(), nil)
  226. }
  227. return query.Result, nil
  228. }
  229. // Remember user in cache
  230. func (auth *AuthProxy) Remember() *Error {
  231. // Make sure we do not rewrite the expiration time
  232. if auth.InCache() {
  233. return nil
  234. }
  235. var (
  236. key = auth.getKey()
  237. value, _ = auth.GetUserIDViaCache()
  238. expiration = time.Duration(-auth.cacheTTL) * time.Minute
  239. err = auth.store.Set(key, value, expiration)
  240. )
  241. if err != nil {
  242. return newError(err.Error(), nil)
  243. }
  244. return nil
  245. }
  246. // coerceProxyAddress gets network of the presented CIDR notation
  247. func coerceProxyAddress(proxyAddr string) (*net.IPNet, error) {
  248. proxyAddr = strings.TrimSpace(proxyAddr)
  249. if !strings.Contains(proxyAddr, "/") {
  250. proxyAddr = strings.Join([]string{proxyAddr, "32"}, "/")
  251. }
  252. _, network, err := net.ParseCIDR(proxyAddr)
  253. return network, err
  254. }