auth_proxy.go 7.0 KB

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