ldap.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. // Package ldap provide functions & structure to query a LDAP ldap directory
  5. // For now, it's mainly tested again an MS Active Directory service, see README.md for more information
  6. package ldap
  7. import (
  8. "crypto/tls"
  9. "fmt"
  10. "strings"
  11. "gopkg.in/ldap.v2"
  12. "github.com/gogits/gogs/modules/log"
  13. )
  14. // Basic LDAP authentication service
  15. type Source struct {
  16. Name string // canonical name (ie. corporate.ad)
  17. Host string // LDAP host
  18. Port int // port number
  19. UseSSL bool // Use SSL
  20. SkipVerify bool
  21. BindDN string // DN to bind with
  22. BindPassword string // Bind DN password
  23. UserBase string // Base search path for users
  24. UserDN string // Template for the DN of the user for simple auth
  25. AttributeUsername string // Username attribute
  26. AttributeName string // First name attribute
  27. AttributeSurname string // Surname attribute
  28. AttributeMail string // E-mail attribute
  29. Filter string // Query filter to validate entry
  30. AdminFilter string // Query filter to check if user is admin
  31. Enabled bool // if this source is disabled
  32. }
  33. func (ls *Source) sanitizedUserQuery(username string) (string, bool) {
  34. // See http://tools.ietf.org/search/rfc4515
  35. badCharacters := "\x00()*\\"
  36. if strings.ContainsAny(username, badCharacters) {
  37. log.Debug("'%s' contains invalid query characters. Aborting.", username)
  38. return "", false
  39. }
  40. return fmt.Sprintf(ls.Filter, username), true
  41. }
  42. func (ls *Source) sanitizedUserDN(username string) (string, bool) {
  43. // See http://tools.ietf.org/search/rfc4514: "special characters"
  44. badCharacters := "\x00()*\\,='\"#+;<> "
  45. if strings.ContainsAny(username, badCharacters) {
  46. log.Debug("'%s' contains invalid DN characters. Aborting.", username)
  47. return "", false
  48. }
  49. return fmt.Sprintf(ls.UserDN, username), true
  50. }
  51. func (ls *Source) findUserDN(l *ldap.Conn, name string) (string, bool) {
  52. log.Trace("Search for LDAP user: %s", name)
  53. if ls.BindDN != "" && ls.BindPassword != "" {
  54. err := l.Bind(ls.BindDN, ls.BindPassword)
  55. if err != nil {
  56. log.Debug("Failed to bind as BindDN[%s]: %v", ls.BindDN, err)
  57. return "", false
  58. }
  59. log.Trace("Bound as BindDN %s", ls.BindDN)
  60. } else {
  61. log.Trace("Proceeding with anonymous LDAP search.")
  62. }
  63. // A search for the user.
  64. userFilter, ok := ls.sanitizedUserQuery(name)
  65. if !ok {
  66. return "", false
  67. }
  68. log.Trace("Searching using filter %s", userFilter)
  69. search := ldap.NewSearchRequest(
  70. ls.UserBase, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0,
  71. false, userFilter, []string{}, nil)
  72. // Ensure we found a user
  73. sr, err := l.Search(search)
  74. if err != nil || len(sr.Entries) < 1 {
  75. log.Debug("Failed search using filter[%s]: %v", userFilter, err)
  76. return "", false
  77. } else if len(sr.Entries) > 1 {
  78. log.Debug("Filter '%s' returned more than one user.", userFilter)
  79. return "", false
  80. }
  81. userDN := sr.Entries[0].DN
  82. if userDN == "" {
  83. log.Error(4, "LDAP search was successful, but found no DN!")
  84. return "", false
  85. }
  86. return userDN, true
  87. }
  88. // searchEntry : search an LDAP source if an entry (name, passwd) is valid and in the specific filter
  89. func (ls *Source) SearchEntry(name, passwd string, directBind bool) (string, string, string, string, bool, bool) {
  90. l, err := ldapDial(ls)
  91. if err != nil {
  92. log.Error(4, "LDAP Connect error, %s:%v", ls.Host, err)
  93. ls.Enabled = false
  94. return "", "", "", "", false, false
  95. }
  96. defer l.Close()
  97. var userDN string
  98. if directBind {
  99. log.Trace("LDAP will bind directly via UserDN template: %s", ls.UserDN)
  100. var ok bool
  101. userDN, ok = ls.sanitizedUserDN(name)
  102. if !ok {
  103. return "", "", "", "", false, false
  104. }
  105. } else {
  106. log.Trace("LDAP will use BindDN.")
  107. var found bool
  108. userDN, found = ls.findUserDN(l, name)
  109. if !found {
  110. return "", "", "", "", false, false
  111. }
  112. }
  113. log.Trace("Binding with userDN: %s", userDN)
  114. err = l.Bind(userDN, passwd)
  115. if err != nil {
  116. log.Debug("LDAP auth. failed for %s, reason: %v", userDN, err)
  117. return "", "", "", "", false, false
  118. }
  119. log.Trace("Bound successfully with userDN: %s", userDN)
  120. userFilter, ok := ls.sanitizedUserQuery(name)
  121. if !ok {
  122. return "", "", "", "", false, false
  123. }
  124. search := ldap.NewSearchRequest(
  125. userDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, userFilter,
  126. []string{ls.AttributeUsername, ls.AttributeName, ls.AttributeSurname, ls.AttributeMail},
  127. nil)
  128. sr, err := l.Search(search)
  129. if err != nil {
  130. log.Error(4, "LDAP Search failed unexpectedly! (%v)", err)
  131. return "", "", "", "", false, false
  132. } else if len(sr.Entries) < 1 {
  133. if directBind {
  134. log.Error(4, "User filter inhibited user login.")
  135. } else {
  136. log.Error(4, "LDAP Search failed unexpectedly! (0 entries)")
  137. }
  138. return "", "", "", "", false, false
  139. }
  140. username_attr := sr.Entries[0].GetAttributeValue(ls.AttributeUsername)
  141. name_attr := sr.Entries[0].GetAttributeValue(ls.AttributeName)
  142. sn_attr := sr.Entries[0].GetAttributeValue(ls.AttributeSurname)
  143. mail_attr := sr.Entries[0].GetAttributeValue(ls.AttributeMail)
  144. admin_attr := false
  145. if len(ls.AdminFilter) > 0 {
  146. search = ldap.NewSearchRequest(
  147. userDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, ls.AdminFilter,
  148. []string{ls.AttributeName},
  149. nil)
  150. sr, err = l.Search(search)
  151. if err != nil {
  152. log.Error(4, "LDAP Admin Search failed unexpectedly! (%v)", err)
  153. } else if len(sr.Entries) < 1 {
  154. log.Error(4, "LDAP Admin Search failed")
  155. } else {
  156. admin_attr = true
  157. }
  158. }
  159. return username_attr, name_attr, sn_attr, mail_attr, admin_attr, true
  160. }
  161. func ldapDial(ls *Source) (*ldap.Conn, error) {
  162. if ls.UseSSL {
  163. log.Debug("Using TLS for LDAP without verifying: %v", ls.SkipVerify)
  164. return ldap.DialTLS("tcp", fmt.Sprintf("%s:%d", ls.Host, ls.Port), &tls.Config{
  165. InsecureSkipVerify: ls.SkipVerify,
  166. })
  167. } else {
  168. return ldap.Dial("tcp", fmt.Sprintf("%s:%d", ls.Host, ls.Port))
  169. }
  170. }