auth_proxy.go 6.9 KB

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