ldap.go 12 KB

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