ldap.go 6.5 KB

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