ldap.go 6.7 KB

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