ldap.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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. break
  77. }
  78. }
  79. if !access {
  80. log.Info("Ldap Auth: user %s does not belong in any of the specified ldap groups, ldapUser groups: %v", ldapUser.Username, ldapUser.MemberOf)
  81. return nil, ErrInvalidCredentials
  82. }
  83. // get user from grafana db
  84. userQuery := m.GetUserByLoginQuery{LoginOrEmail: ldapUser.Username}
  85. if err := bus.Dispatch(&userQuery); err != nil {
  86. if err == m.ErrUserNotFound {
  87. return a.createGrafanaUser(ldapUser)
  88. } else {
  89. return nil, err
  90. }
  91. }
  92. return userQuery.Result, nil
  93. }
  94. func (a *ldapAuther) createGrafanaUser(ldapUser *ldapUserInfo) (*m.User, error) {
  95. cmd := m.CreateUserCommand{
  96. Login: ldapUser.Username,
  97. Email: ldapUser.Email,
  98. Name: fmt.Sprintf("%s %s", ldapUser.FirstName, ldapUser.LastName),
  99. }
  100. if err := bus.Dispatch(&cmd); err != nil {
  101. return nil, err
  102. }
  103. return &cmd.Result, nil
  104. }
  105. func (a *ldapAuther) syncOrgRoles(user *m.User, ldapUser *ldapUserInfo) error {
  106. if len(a.server.LdapGroups) == 0 {
  107. return nil
  108. }
  109. orgsQuery := m.GetUserOrgListQuery{UserId: user.Id}
  110. if err := bus.Dispatch(&orgsQuery); err != nil {
  111. return err
  112. }
  113. // update or remove org roles
  114. for _, org := range orgsQuery.Result {
  115. match := false
  116. for _, group := range a.server.LdapGroups {
  117. if org.OrgId != group.OrgId {
  118. continue
  119. }
  120. if ldapUser.isMemberOf(group.GroupDN) {
  121. match = true
  122. if org.Role != group.OrgRole {
  123. // update role
  124. cmd := m.UpdateOrgUserCommand{OrgId: org.OrgId, UserId: user.Id, Role: group.OrgRole}
  125. if err := bus.Dispatch(&cmd); err != nil {
  126. return err
  127. }
  128. }
  129. // ignore subsequent ldap group mapping matches
  130. break
  131. }
  132. }
  133. // remove role if no mappings match
  134. if !match {
  135. cmd := m.RemoveOrgUserCommand{OrgId: org.OrgId, UserId: user.Id}
  136. if err := bus.Dispatch(&cmd); err != nil {
  137. return err
  138. }
  139. }
  140. }
  141. // add missing org roles
  142. for _, group := range a.server.LdapGroups {
  143. if !ldapUser.isMemberOf(group.GroupDN) {
  144. continue
  145. }
  146. match := false
  147. for _, org := range orgsQuery.Result {
  148. if group.OrgId == org.OrgId {
  149. match = true
  150. break
  151. }
  152. }
  153. if !match {
  154. // add role
  155. cmd := m.AddOrgUserCommand{UserId: user.Id, Role: group.OrgRole, OrgId: group.OrgId}
  156. if err := bus.Dispatch(&cmd); err != nil {
  157. return err
  158. }
  159. break
  160. }
  161. }
  162. return nil
  163. }
  164. func (a *ldapAuther) secondBind(ldapUser *ldapUserInfo, userPassword string) error {
  165. if err := a.conn.Bind(ldapUser.DN, userPassword); err != nil {
  166. if ldapErr, ok := err.(*ldap.Error); ok {
  167. if ldapErr.ResultCode == 49 {
  168. return ErrInvalidCredentials
  169. }
  170. }
  171. return err
  172. }
  173. return nil
  174. }
  175. func (a *ldapAuther) initialBind(username, userPassword string) error {
  176. if a.server.BindPassword != "" {
  177. userPassword = a.server.BindPassword
  178. }
  179. bindPath := a.server.BindDN
  180. if strings.Contains(bindPath, "%s") {
  181. bindPath = fmt.Sprintf(a.server.BindDN, username)
  182. }
  183. if err := a.conn.Bind(bindPath, userPassword); err != nil {
  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) searchForUser(username string) (*ldapUserInfo, error) {
  194. var searchResult *ldap.SearchResult
  195. var err error
  196. for _, searchBase := range a.server.SearchBaseDNs {
  197. searchReq := ldap.SearchRequest{
  198. BaseDN: searchBase,
  199. Scope: ldap.ScopeWholeSubtree,
  200. DerefAliases: ldap.NeverDerefAliases,
  201. Attributes: []string{
  202. a.server.Attr.Username,
  203. a.server.Attr.Surname,
  204. a.server.Attr.Email,
  205. a.server.Attr.Name,
  206. a.server.Attr.MemberOf,
  207. },
  208. Filter: fmt.Sprintf(a.server.SearchFilter, username),
  209. }
  210. searchResult, err = a.conn.Search(&searchReq)
  211. if err != nil {
  212. return nil, err
  213. }
  214. if len(searchResult.Entries) > 0 {
  215. break
  216. }
  217. }
  218. if len(searchResult.Entries) == 0 {
  219. return nil, ErrInvalidCredentials
  220. }
  221. if len(searchResult.Entries) > 1 {
  222. return nil, errors.New("Ldap search matched more than one entry, please review your filter setting")
  223. }
  224. return &ldapUserInfo{
  225. DN: searchResult.Entries[0].DN,
  226. LastName: getLdapAttr(a.server.Attr.Surname, searchResult),
  227. FirstName: getLdapAttr(a.server.Attr.Name, searchResult),
  228. Username: getLdapAttr(a.server.Attr.Username, searchResult),
  229. Email: getLdapAttr(a.server.Attr.Email, searchResult),
  230. MemberOf: getLdapAttrArray(a.server.Attr.MemberOf, searchResult),
  231. }, nil
  232. }
  233. func getLdapAttr(name string, result *ldap.SearchResult) string {
  234. for _, attr := range result.Entries[0].Attributes {
  235. if attr.Name == name {
  236. if len(attr.Values) > 0 {
  237. return attr.Values[0]
  238. }
  239. }
  240. }
  241. return ""
  242. }
  243. func getLdapAttrArray(name string, result *ldap.SearchResult) []string {
  244. for _, attr := range result.Entries[0].Attributes {
  245. if attr.Name == name {
  246. return attr.Values
  247. }
  248. }
  249. return []string{}
  250. }
  251. func createUserFromLdapInfo() error {
  252. return nil
  253. }