ldap.go 7.0 KB

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