auth_proxy.go 7.2 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/models"
  12. "github.com/grafana/grafana/pkg/services/ldap"
  13. "github.com/grafana/grafana/pkg/services/multildap"
  14. "github.com/grafana/grafana/pkg/setting"
  15. "github.com/grafana/grafana/pkg/util"
  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. upsert := &models.UpsertUserCommand{
  173. ReqContext: auth.ctx,
  174. SignupAllowed: auth.LDAPAllowSignup,
  175. ExternalUser: extUser,
  176. }
  177. err = bus.Dispatch(upsert)
  178. if err != nil {
  179. return 0, newError(err.Error(), nil)
  180. }
  181. return upsert.Result.Id, nil
  182. }
  183. // LoginViaHeader logs in user from the header only
  184. // TODO: refactor - cyclomatic complexity should be much lower
  185. func (auth *AuthProxy) LoginViaHeader() (int64, error) {
  186. extUser := &models.ExternalUserInfo{
  187. AuthModule: "authproxy",
  188. AuthId: auth.header,
  189. }
  190. if auth.headerType == "username" {
  191. extUser.Login = auth.header
  192. // only set Email if it can be parsed as an email address
  193. emailAddr, emailErr := mail.ParseAddress(auth.header)
  194. if emailErr == nil {
  195. extUser.Email = emailAddr.Address
  196. }
  197. } else if auth.headerType == "email" {
  198. extUser.Email = auth.header
  199. extUser.Login = auth.header
  200. } else {
  201. return 0, newError("Auth proxy header property invalid", nil)
  202. }
  203. for _, field := range []string{"Name", "Email", "Login", "Groups"} {
  204. if auth.headers[field] == "" {
  205. continue
  206. }
  207. if val := auth.ctx.Req.Header.Get(auth.headers[field]); val != "" {
  208. if field == "Groups" {
  209. extUser.Groups = util.SplitString(val)
  210. } else {
  211. reflect.ValueOf(extUser).Elem().FieldByName(field).SetString(val)
  212. }
  213. }
  214. }
  215. upsert := &models.UpsertUserCommand{
  216. ReqContext: auth.ctx,
  217. SignupAllowed: setting.AuthProxyAutoSignUp,
  218. ExternalUser: extUser,
  219. }
  220. err := bus.Dispatch(upsert)
  221. if err != nil {
  222. return 0, err
  223. }
  224. return upsert.Result.Id, nil
  225. }
  226. // GetSignedUser get full signed user info
  227. func (auth *AuthProxy) GetSignedUser(userID int64) (*models.SignedInUser, *Error) {
  228. query := &models.GetSignedInUserQuery{
  229. OrgId: auth.orgID,
  230. UserId: userID,
  231. }
  232. if err := bus.Dispatch(query); err != nil {
  233. return nil, newError(err.Error(), nil)
  234. }
  235. return query.Result, nil
  236. }
  237. // Remember user in cache
  238. func (auth *AuthProxy) Remember(id int64) *Error {
  239. key := auth.getKey()
  240. // Check if user already in cache
  241. userID, _ := auth.store.Get(key)
  242. if userID != nil {
  243. return nil
  244. }
  245. expiration := time.Duration(auth.cacheTTL) * time.Minute
  246. err := auth.store.Set(key, id, expiration)
  247. if err != nil {
  248. return newError(err.Error(), nil)
  249. }
  250. return nil
  251. }
  252. // coerceProxyAddress gets network of the presented CIDR notation
  253. func coerceProxyAddress(proxyAddr string) (*net.IPNet, error) {
  254. proxyAddr = strings.TrimSpace(proxyAddr)
  255. if !strings.Contains(proxyAddr, "/") {
  256. proxyAddr = strings.Join([]string{proxyAddr, "32"}, "/")
  257. }
  258. _, network, err := net.ParseCIDR(proxyAddr)
  259. return network, err
  260. }