auth_proxy.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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. readLDAPConfig = ldap.ReadConfig
  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 := readLDAPConfig()
  176. if len(config.Servers) == 0 {
  177. return 0, newError("No LDAP servers available", nil)
  178. }
  179. for _, server := range config.Servers {
  180. author := auth.LDAP(server)
  181. if err := author.SyncUser(query); err != nil {
  182. return 0, newError(err.Error(), nil)
  183. }
  184. }
  185. return query.User.Id, nil
  186. }
  187. // GetUserIDViaHeader gets user from the header only
  188. func (auth *AuthProxy) GetUserIDViaHeader() (int64, error) {
  189. extUser := &models.ExternalUserInfo{
  190. AuthModule: "authproxy",
  191. AuthId: auth.header,
  192. }
  193. if auth.headerType == "username" {
  194. extUser.Login = auth.header
  195. // only set Email if it can be parsed as an email address
  196. emailAddr, emailErr := mail.ParseAddress(auth.header)
  197. if emailErr == nil {
  198. extUser.Email = emailAddr.Address
  199. }
  200. } else if auth.headerType == "email" {
  201. extUser.Email = auth.header
  202. extUser.Login = auth.header
  203. } else {
  204. return 0, newError("Auth proxy header property invalid", nil)
  205. }
  206. for _, field := range []string{"Name", "Email", "Login"} {
  207. if auth.headers[field] == "" {
  208. continue
  209. }
  210. if val := auth.ctx.Req.Header.Get(auth.headers[field]); val != "" {
  211. reflect.ValueOf(extUser).Elem().FieldByName(field).SetString(val)
  212. }
  213. }
  214. // add/update user in grafana
  215. cmd := &models.UpsertUserCommand{
  216. ReqContext: auth.ctx,
  217. ExternalUser: extUser,
  218. SignupAllowed: setting.AuthProxyAutoSignUp,
  219. }
  220. err := bus.Dispatch(cmd)
  221. if err != nil {
  222. return 0, err
  223. }
  224. return cmd.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() *Error {
  239. // Make sure we do not rewrite the expiration time
  240. if auth.InCache() {
  241. return nil
  242. }
  243. var (
  244. key = auth.getKey()
  245. value, _ = auth.GetUserIDViaCache()
  246. expiration = time.Duration(-auth.cacheTTL) * time.Minute
  247. err = auth.store.Set(key, value, expiration)
  248. )
  249. if err != nil {
  250. return newError(err.Error(), nil)
  251. }
  252. return nil
  253. }
  254. // coerceProxyAddress gets network of the presented CIDR notation
  255. func coerceProxyAddress(proxyAddr string) (*net.IPNet, error) {
  256. proxyAddr = strings.TrimSpace(proxyAddr)
  257. if !strings.Contains(proxyAddr, "/") {
  258. proxyAddr = strings.Join([]string{proxyAddr, "32"}, "/")
  259. }
  260. _, network, err := net.ParseCIDR(proxyAddr)
  261. return network, err
  262. }