ldap.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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. // remove or update org roles
  113. for _, org := range orgsQuery.Result {
  114. for _, group := range a.server.LdapGroups {
  115. if org.OrgId != group.OrgId {
  116. continue
  117. }
  118. if ldapUser.isMemberOf(group.GroupDN) {
  119. if org.Role != group.OrgRole {
  120. // update role
  121. cmd := m.UpdateOrgUserCommand{OrgId: org.OrgId, UserId: user.Id, Role: group.OrgRole}
  122. if err := bus.Dispatch(&cmd); err != nil {
  123. return err
  124. }
  125. }
  126. // ignore subsequent ldap group mapping matches
  127. break
  128. } else {
  129. // remove role
  130. cmd := m.RemoveOrgUserCommand{OrgId: org.OrgId, UserId: user.Id}
  131. if err := bus.Dispatch(&cmd); err != nil {
  132. return err
  133. }
  134. }
  135. }
  136. }
  137. // add missing org roles
  138. for _, group := range a.server.LdapGroups {
  139. if !ldapUser.isMemberOf(group.GroupDN) {
  140. continue
  141. }
  142. match := false
  143. for _, org := range orgsQuery.Result {
  144. if group.OrgId == org.OrgId {
  145. match = true
  146. }
  147. }
  148. if !match {
  149. // add role
  150. cmd := m.AddOrgUserCommand{UserId: user.Id, Role: group.OrgRole, OrgId: group.OrgId}
  151. if err := bus.Dispatch(&cmd); err != nil {
  152. return err
  153. }
  154. }
  155. }
  156. return nil
  157. }
  158. func (a *ldapAuther) secondBind(ldapUser *ldapUserInfo, userPassword string) error {
  159. if err := a.conn.Bind(ldapUser.DN, userPassword); err != nil {
  160. if ldapErr, ok := err.(*ldap.Error); ok {
  161. if ldapErr.ResultCode == 49 {
  162. return ErrInvalidCredentials
  163. }
  164. }
  165. return err
  166. }
  167. return nil
  168. }
  169. func (a *ldapAuther) initialBind(username, userPassword string) error {
  170. if a.server.BindPassword != "" {
  171. userPassword = a.server.BindPassword
  172. }
  173. bindPath := a.server.BindDN
  174. if strings.Contains(bindPath, "%s") {
  175. bindPath = fmt.Sprintf(a.server.BindDN, username)
  176. }
  177. if err := a.conn.Bind(bindPath, userPassword); err != nil {
  178. if ldapErr, ok := err.(*ldap.Error); ok {
  179. if ldapErr.ResultCode == 49 {
  180. return ErrInvalidCredentials
  181. }
  182. }
  183. return err
  184. }
  185. return nil
  186. }
  187. func (a *ldapAuther) searchForUser(username string) (*ldapUserInfo, error) {
  188. var searchResult *ldap.SearchResult
  189. var err error
  190. for _, searchBase := range a.server.SearchBaseDNs {
  191. searchReq := ldap.SearchRequest{
  192. BaseDN: searchBase,
  193. Scope: ldap.ScopeWholeSubtree,
  194. DerefAliases: ldap.NeverDerefAliases,
  195. Attributes: []string{
  196. a.server.Attr.Username,
  197. a.server.Attr.Surname,
  198. a.server.Attr.Email,
  199. a.server.Attr.Name,
  200. a.server.Attr.MemberOf,
  201. },
  202. Filter: fmt.Sprintf(a.server.SearchFilter, username),
  203. }
  204. searchResult, err = a.conn.Search(&searchReq)
  205. if err != nil {
  206. return nil, err
  207. }
  208. if len(searchResult.Entries) > 0 {
  209. break
  210. }
  211. }
  212. if len(searchResult.Entries) == 0 {
  213. return nil, ErrInvalidCredentials
  214. }
  215. if len(searchResult.Entries) > 1 {
  216. return nil, errors.New("Ldap search matched more than one entry, please review your filter setting")
  217. }
  218. return &ldapUserInfo{
  219. DN: searchResult.Entries[0].DN,
  220. LastName: getLdapAttr(a.server.Attr.Surname, searchResult),
  221. FirstName: getLdapAttr(a.server.Attr.Name, searchResult),
  222. Username: getLdapAttr(a.server.Attr.Username, searchResult),
  223. Email: getLdapAttr(a.server.Attr.Email, searchResult),
  224. MemberOf: getLdapAttrArray(a.server.Attr.MemberOf, searchResult),
  225. }, nil
  226. }
  227. func getLdapAttr(name string, result *ldap.SearchResult) string {
  228. for _, attr := range result.Entries[0].Attributes {
  229. if attr.Name == name {
  230. if len(attr.Values) > 0 {
  231. return attr.Values[0]
  232. }
  233. }
  234. }
  235. return ""
  236. }
  237. func getLdapAttrArray(name string, result *ldap.SearchResult) []string {
  238. for _, attr := range result.Entries[0].Attributes {
  239. if attr.Name == name {
  240. return attr.Values
  241. }
  242. }
  243. return []string{}
  244. }
  245. func createUserFromLdapInfo() error {
  246. return nil
  247. }