ldap.go 7.7 KB

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