ldap.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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(name string) (string, bool) {
  52. l, err := ldapDial(ls)
  53. if err != nil {
  54. log.Error(4, "LDAP Connect error, %s:%v", ls.Host, err)
  55. ls.Enabled = false
  56. return "", false
  57. }
  58. defer l.Close()
  59. log.Trace("Search for LDAP user: %s", name)
  60. if ls.BindDN != "" && ls.BindPassword != "" {
  61. err = l.Bind(ls.BindDN, ls.BindPassword)
  62. if err != nil {
  63. log.Debug("Failed to bind as BindDN[%s]: %v", ls.BindDN, err)
  64. return "", false
  65. }
  66. log.Trace("Bound as BindDN %s", ls.BindDN)
  67. } else {
  68. log.Trace("Proceeding with anonymous LDAP search.")
  69. }
  70. // A search for the user.
  71. userFilter, ok := ls.sanitizedUserQuery(name)
  72. if !ok {
  73. return "", false
  74. }
  75. log.Trace("Searching using filter %s", userFilter)
  76. search := ldap.NewSearchRequest(
  77. ls.UserBase, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0,
  78. false, userFilter, []string{}, nil)
  79. // Ensure we found a user
  80. sr, err := l.Search(search)
  81. if err != nil || len(sr.Entries) < 1 {
  82. log.Debug("Failed search using filter[%s]: %v", userFilter, err)
  83. return "", false
  84. } else if len(sr.Entries) > 1 {
  85. log.Debug("Filter '%s' returned more than one user.", userFilter)
  86. return "", false
  87. }
  88. userDN := sr.Entries[0].DN
  89. if userDN == "" {
  90. log.Error(4, "LDAP search was successful, but found no DN!")
  91. return "", false
  92. }
  93. return userDN, true
  94. }
  95. // searchEntry : search an LDAP source if an entry (name, passwd) is valid and in the specific filter
  96. func (ls *Source) SearchEntry(name, passwd string, directBind bool) (string, string, string, string, bool, bool) {
  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(name)
  109. if !found {
  110. return "", "", "", "", false, false
  111. }
  112. }
  113. l, err := ldapDial(ls)
  114. if err != nil {
  115. log.Error(4, "LDAP Connect error (%s): %v", ls.Host, err)
  116. ls.Enabled = false
  117. return "", "", "", "", false, false
  118. }
  119. defer l.Close()
  120. log.Trace("Binding with userDN: %s", userDN)
  121. err = l.Bind(userDN, passwd)
  122. if err != nil {
  123. log.Debug("LDAP auth. failed for %s, reason: %v", userDN, err)
  124. return "", "", "", "", false, false
  125. }
  126. log.Trace("Bound successfully with userDN: %s", userDN)
  127. userFilter, ok := ls.sanitizedUserQuery(name)
  128. if !ok {
  129. return "", "", "", "", false, false
  130. }
  131. search := ldap.NewSearchRequest(
  132. userDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, userFilter,
  133. []string{ls.AttributeName, ls.AttributeSurname, ls.AttributeMail},
  134. nil)
  135. sr, err := l.Search(search)
  136. if err != nil {
  137. log.Error(4, "LDAP Search failed unexpectedly! (%v)", err)
  138. return "", "", "", "", false, false
  139. } else if len(sr.Entries) < 1 {
  140. if directBind {
  141. log.Error(4, "User filter inhibited user login.")
  142. } else {
  143. log.Error(4, "LDAP Search failed unexpectedly! (0 entries)")
  144. }
  145. return "", "", "", "", false, false
  146. }
  147. username_attr := sr.Entries[0].GetAttributeValue(ls.AttributeUsername)
  148. name_attr := sr.Entries[0].GetAttributeValue(ls.AttributeName)
  149. sn_attr := sr.Entries[0].GetAttributeValue(ls.AttributeSurname)
  150. mail_attr := sr.Entries[0].GetAttributeValue(ls.AttributeMail)
  151. admin_attr := false
  152. if len(ls.AdminFilter) > 0 {
  153. search = ldap.NewSearchRequest(
  154. userDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, ls.AdminFilter,
  155. []string{ls.AttributeName},
  156. nil)
  157. sr, err = l.Search(search)
  158. if err != nil {
  159. log.Error(4, "LDAP Admin Search failed unexpectedly! (%v)", err)
  160. } else if len(sr.Entries) < 1 {
  161. log.Error(4, "LDAP Admin Search failed")
  162. } else {
  163. admin_attr = true
  164. }
  165. }
  166. return username_attr, name_attr, sn_attr, mail_attr, admin_attr, true
  167. }
  168. func ldapDial(ls *Source) (*ldap.Conn, error) {
  169. if ls.UseSSL {
  170. log.Debug("Using TLS for LDAP without verifying: %v", ls.SkipVerify)
  171. return ldap.DialTLS("tcp", fmt.Sprintf("%s:%d", ls.Host, ls.Port), &tls.Config{
  172. InsecureSkipVerify: ls.SkipVerify,
  173. })
  174. } else {
  175. return ldap.Dial("tcp", fmt.Sprintf("%s:%d", ls.Host, ls.Port))
  176. }
  177. }