ldap.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. package login
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "errors"
  6. "fmt"
  7. "io/ioutil"
  8. "strings"
  9. "github.com/davecgh/go-spew/spew"
  10. "github.com/go-ldap/ldap"
  11. "github.com/grafana/grafana/pkg/bus"
  12. "github.com/grafana/grafana/pkg/log"
  13. m "github.com/grafana/grafana/pkg/models"
  14. )
  15. type ldapAuther struct {
  16. server *LdapServerConf
  17. conn *ldap.Conn
  18. requireSecondBind bool
  19. }
  20. func NewLdapAuthenticator(server *LdapServerConf) *ldapAuther {
  21. return &ldapAuther{server: server}
  22. }
  23. func (a *ldapAuther) Dial() error {
  24. var err error
  25. var certPool *x509.CertPool
  26. if a.server.RootCACert != "" {
  27. certPool := x509.NewCertPool()
  28. for _, caCertFile := range strings.Split(a.server.RootCACert, " ") {
  29. if pem, err := ioutil.ReadFile(caCertFile); err != nil {
  30. return err
  31. } else {
  32. if !certPool.AppendCertsFromPEM(pem) {
  33. return errors.New("Failed to append CA certficate " + caCertFile)
  34. }
  35. }
  36. }
  37. }
  38. for _, host := range strings.Split(a.server.Host, " ") {
  39. address := fmt.Sprintf("%s:%d", host, a.server.Port)
  40. if a.server.UseSSL {
  41. tlsCfg := &tls.Config{
  42. InsecureSkipVerify: a.server.SkipVerifySSL,
  43. ServerName: host,
  44. RootCAs: certPool,
  45. }
  46. a.conn, err = ldap.DialTLS("tcp", address, tlsCfg)
  47. } else {
  48. a.conn, err = ldap.Dial("tcp", address)
  49. }
  50. if err == nil {
  51. return nil
  52. }
  53. }
  54. return err
  55. }
  56. func (a *ldapAuther) login(query *LoginUserQuery) error {
  57. if err := a.Dial(); err != nil {
  58. return err
  59. }
  60. defer a.conn.Close()
  61. // perform initial authentication
  62. if err := a.initialBind(query.Username, query.Password); err != nil {
  63. return err
  64. }
  65. // find user entry & attributes
  66. if ldapUser, err := a.searchForUser(query.Username); err != nil {
  67. return err
  68. } else {
  69. if ldapCfg.VerboseLogging {
  70. log.Info("Ldap User Info: %s", spew.Sdump(ldapUser))
  71. }
  72. // check if a second user bind is needed
  73. if a.requireSecondBind {
  74. if err := a.secondBind(ldapUser, query.Password); err != nil {
  75. return err
  76. }
  77. }
  78. if grafanaUser, err := a.getGrafanaUserFor(ldapUser); err != nil {
  79. return err
  80. } else {
  81. // sync user details
  82. if err := a.syncUserInfo(grafanaUser, ldapUser); err != nil {
  83. return err
  84. }
  85. // sync org roles
  86. if err := a.syncOrgRoles(grafanaUser, ldapUser); err != nil {
  87. return err
  88. }
  89. query.User = grafanaUser
  90. return nil
  91. }
  92. }
  93. }
  94. func (a *ldapAuther) getGrafanaUserFor(ldapUser *ldapUserInfo) (*m.User, error) {
  95. // validate that the user has access
  96. // if there are no ldap group mappings access is true
  97. // otherwise a single group must match
  98. access := len(a.server.LdapGroups) == 0
  99. for _, ldapGroup := range a.server.LdapGroups {
  100. if ldapUser.isMemberOf(ldapGroup.GroupDN) {
  101. access = true
  102. break
  103. }
  104. }
  105. if !access {
  106. log.Info("Ldap Auth: user %s does not belong in any of the specified ldap groups, ldapUser groups: %v", ldapUser.Username, ldapUser.MemberOf)
  107. return nil, ErrInvalidCredentials
  108. }
  109. // get user from grafana db
  110. userQuery := m.GetUserByLoginQuery{LoginOrEmail: ldapUser.Username}
  111. if err := bus.Dispatch(&userQuery); err != nil {
  112. if err == m.ErrUserNotFound {
  113. return a.createGrafanaUser(ldapUser)
  114. } else {
  115. return nil, err
  116. }
  117. }
  118. return userQuery.Result, nil
  119. }
  120. func (a *ldapAuther) createGrafanaUser(ldapUser *ldapUserInfo) (*m.User, error) {
  121. cmd := m.CreateUserCommand{
  122. Login: ldapUser.Username,
  123. Email: ldapUser.Email,
  124. Name: fmt.Sprintf("%s %s", ldapUser.FirstName, ldapUser.LastName),
  125. }
  126. if err := bus.Dispatch(&cmd); err != nil {
  127. return nil, err
  128. }
  129. return &cmd.Result, nil
  130. }
  131. func (a *ldapAuther) syncUserInfo(user *m.User, ldapUser *ldapUserInfo) error {
  132. var name = fmt.Sprintf("%s %s", ldapUser.FirstName, ldapUser.LastName)
  133. if user.Email == ldapUser.Email && user.Name == name {
  134. return nil
  135. }
  136. log.Info("Ldap: Syncing user info %s", ldapUser.Username)
  137. updateCmd := m.UpdateUserCommand{}
  138. updateCmd.UserId = user.Id
  139. updateCmd.Login = user.Login
  140. updateCmd.Email = ldapUser.Email
  141. updateCmd.Name = fmt.Sprintf("%s %s", ldapUser.FirstName, ldapUser.LastName)
  142. return bus.Dispatch(&updateCmd)
  143. }
  144. func (a *ldapAuther) syncOrgRoles(user *m.User, ldapUser *ldapUserInfo) error {
  145. if len(a.server.LdapGroups) == 0 {
  146. return nil
  147. }
  148. orgsQuery := m.GetUserOrgListQuery{UserId: user.Id}
  149. if err := bus.Dispatch(&orgsQuery); err != nil {
  150. return err
  151. }
  152. handledOrgIds := map[int64]bool{}
  153. // update or remove org roles
  154. for _, org := range orgsQuery.Result {
  155. match := false
  156. handledOrgIds[org.OrgId] = true
  157. for _, group := range a.server.LdapGroups {
  158. if org.OrgId != group.OrgId {
  159. continue
  160. }
  161. if ldapUser.isMemberOf(group.GroupDN) {
  162. match = true
  163. if org.Role != group.OrgRole {
  164. // update role
  165. cmd := m.UpdateOrgUserCommand{OrgId: org.OrgId, UserId: user.Id, Role: group.OrgRole}
  166. if err := bus.Dispatch(&cmd); err != nil {
  167. return err
  168. }
  169. }
  170. // ignore subsequent ldap group mapping matches
  171. break
  172. }
  173. }
  174. // remove role if no mappings match
  175. if !match {
  176. cmd := m.RemoveOrgUserCommand{OrgId: org.OrgId, UserId: user.Id}
  177. if err := bus.Dispatch(&cmd); err != nil {
  178. return err
  179. }
  180. }
  181. }
  182. // add missing org roles
  183. for _, group := range a.server.LdapGroups {
  184. if !ldapUser.isMemberOf(group.GroupDN) {
  185. continue
  186. }
  187. if _, exists := handledOrgIds[group.OrgId]; exists {
  188. continue
  189. }
  190. // add role
  191. cmd := m.AddOrgUserCommand{UserId: user.Id, Role: group.OrgRole, OrgId: group.OrgId}
  192. if err := bus.Dispatch(&cmd); err != nil {
  193. return err
  194. }
  195. // mark this group has handled so we do not process it again
  196. handledOrgIds[group.OrgId] = true
  197. }
  198. return nil
  199. }
  200. func (a *ldapAuther) secondBind(ldapUser *ldapUserInfo, userPassword string) error {
  201. if err := a.conn.Bind(ldapUser.DN, userPassword); err != nil {
  202. if ldapCfg.VerboseLogging {
  203. log.Info("LDAP second bind failed, %v", err)
  204. }
  205. if ldapErr, ok := err.(*ldap.Error); ok {
  206. if ldapErr.ResultCode == 49 {
  207. return ErrInvalidCredentials
  208. }
  209. }
  210. return err
  211. }
  212. return nil
  213. }
  214. func (a *ldapAuther) initialBind(username, userPassword string) error {
  215. if a.server.BindPassword != "" || a.server.BindDN == "" {
  216. userPassword = a.server.BindPassword
  217. a.requireSecondBind = true
  218. }
  219. bindPath := a.server.BindDN
  220. if strings.Contains(bindPath, "%s") {
  221. bindPath = fmt.Sprintf(a.server.BindDN, username)
  222. }
  223. if err := a.conn.Bind(bindPath, userPassword); err != nil {
  224. if ldapCfg.VerboseLogging {
  225. log.Info("LDAP initial bind failed, %v", err)
  226. }
  227. if ldapErr, ok := err.(*ldap.Error); ok {
  228. if ldapErr.ResultCode == 49 {
  229. return ErrInvalidCredentials
  230. }
  231. }
  232. return err
  233. }
  234. return nil
  235. }
  236. func (a *ldapAuther) searchForUser(username string) (*ldapUserInfo, error) {
  237. var searchResult *ldap.SearchResult
  238. var err error
  239. for _, searchBase := range a.server.SearchBaseDNs {
  240. searchReq := ldap.SearchRequest{
  241. BaseDN: searchBase,
  242. Scope: ldap.ScopeWholeSubtree,
  243. DerefAliases: ldap.NeverDerefAliases,
  244. Attributes: []string{
  245. a.server.Attr.Username,
  246. a.server.Attr.Surname,
  247. a.server.Attr.Email,
  248. a.server.Attr.Name,
  249. a.server.Attr.MemberOf,
  250. },
  251. Filter: strings.Replace(a.server.SearchFilter, "%s", username, -1),
  252. }
  253. searchResult, err = a.conn.Search(&searchReq)
  254. if err != nil {
  255. return nil, err
  256. }
  257. if len(searchResult.Entries) > 0 {
  258. break
  259. }
  260. }
  261. if len(searchResult.Entries) == 0 {
  262. return nil, ErrInvalidCredentials
  263. }
  264. if len(searchResult.Entries) > 1 {
  265. return nil, errors.New("Ldap search matched more than one entry, please review your filter setting")
  266. }
  267. var memberOf []string
  268. if a.server.GroupSearchFilter == "" {
  269. memberOf = getLdapAttrArray(a.server.Attr.MemberOf, searchResult)
  270. } else {
  271. // If we are using a POSIX LDAP schema it won't support memberOf, so we manually search the groups
  272. var groupSearchResult *ldap.SearchResult
  273. for _, groupSearchBase := range a.server.GroupSearchBaseDNs {
  274. filter := strings.Replace(a.server.GroupSearchFilter, "%s", username, -1)
  275. if ldapCfg.VerboseLogging {
  276. log.Info("LDAP: Searching for user's groups: %s", filter)
  277. }
  278. groupSearchReq := ldap.SearchRequest{
  279. BaseDN: groupSearchBase,
  280. Scope: ldap.ScopeWholeSubtree,
  281. DerefAliases: ldap.NeverDerefAliases,
  282. Attributes: []string{
  283. // Here MemberOf would be the thing that identifies the group, which is normally 'cn'
  284. a.server.Attr.MemberOf,
  285. },
  286. Filter: filter,
  287. }
  288. groupSearchResult, err = a.conn.Search(&groupSearchReq)
  289. if err != nil {
  290. return nil, err
  291. }
  292. if len(groupSearchResult.Entries) > 0 {
  293. for i := range groupSearchResult.Entries {
  294. memberOf = append(memberOf, getLdapAttrN(a.server.Attr.MemberOf, groupSearchResult, i))
  295. }
  296. break
  297. }
  298. }
  299. }
  300. return &ldapUserInfo{
  301. DN: searchResult.Entries[0].DN,
  302. LastName: getLdapAttr(a.server.Attr.Surname, searchResult),
  303. FirstName: getLdapAttr(a.server.Attr.Name, searchResult),
  304. Username: getLdapAttr(a.server.Attr.Username, searchResult),
  305. Email: getLdapAttr(a.server.Attr.Email, searchResult),
  306. MemberOf: memberOf,
  307. }, nil
  308. }
  309. func getLdapAttrN(name string, result *ldap.SearchResult, n int) string {
  310. for _, attr := range result.Entries[n].Attributes {
  311. if attr.Name == name {
  312. if len(attr.Values) > 0 {
  313. return attr.Values[0]
  314. }
  315. }
  316. }
  317. return ""
  318. }
  319. func getLdapAttr(name string, result *ldap.SearchResult) string {
  320. return getLdapAttrN(name, result, 0)
  321. }
  322. func getLdapAttrArray(name string, result *ldap.SearchResult) []string {
  323. for _, attr := range result.Entries[0].Attributes {
  324. if attr.Name == name {
  325. return attr.Values
  326. }
  327. }
  328. return []string{}
  329. }
  330. func createUserFromLdapInfo() error {
  331. return nil
  332. }