ldap.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  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. AttributesInBind bool // fetch attributes in bind context (not user)
  30. Filter string // Query filter to validate entry
  31. AdminFilter string // Query filter to check if user is admin
  32. Enabled bool // if this source is disabled
  33. }
  34. func (ls *Source) sanitizedUserQuery(username string) (string, bool) {
  35. // See http://tools.ietf.org/search/rfc4515
  36. badCharacters := "\x00()*\\"
  37. if strings.ContainsAny(username, badCharacters) {
  38. log.Debug("'%s' contains invalid query characters. Aborting.", username)
  39. return "", false
  40. }
  41. return fmt.Sprintf(ls.Filter, username), true
  42. }
  43. func (ls *Source) sanitizedUserDN(username string) (string, bool) {
  44. // See http://tools.ietf.org/search/rfc4514: "special characters"
  45. badCharacters := "\x00()*\\,='\"#+;<> "
  46. if strings.ContainsAny(username, badCharacters) {
  47. log.Debug("'%s' contains invalid DN characters. Aborting.", username)
  48. return "", false
  49. }
  50. return fmt.Sprintf(ls.UserDN, username), true
  51. }
  52. func (ls *Source) findUserDN(l *ldap.Conn, name string) (string, bool) {
  53. log.Trace("Search for LDAP user: %s", name)
  54. if ls.BindDN != "" && ls.BindPassword != "" {
  55. err := l.Bind(ls.BindDN, ls.BindPassword)
  56. if err != nil {
  57. log.Debug("Failed to bind as BindDN[%s]: %v", ls.BindDN, err)
  58. return "", false
  59. }
  60. log.Trace("Bound as BindDN %s", ls.BindDN)
  61. } else {
  62. log.Trace("Proceeding with anonymous LDAP search.")
  63. }
  64. // A search for the user.
  65. userFilter, ok := ls.sanitizedUserQuery(name)
  66. if !ok {
  67. return "", false
  68. }
  69. log.Trace("Searching for DN using filter %s and base %s", userFilter, ls.UserBase)
  70. search := ldap.NewSearchRequest(
  71. ls.UserBase, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0,
  72. false, userFilter, []string{}, nil)
  73. // Ensure we found a user
  74. sr, err := l.Search(search)
  75. if err != nil || len(sr.Entries) < 1 {
  76. log.Debug("Failed search using filter[%s]: %v", userFilter, err)
  77. return "", false
  78. } else if len(sr.Entries) > 1 {
  79. log.Debug("Filter '%s' returned more than one user.", userFilter)
  80. return "", false
  81. }
  82. userDN := sr.Entries[0].DN
  83. if userDN == "" {
  84. log.Error(4, "LDAP search was successful, but found no DN!")
  85. return "", false
  86. }
  87. return userDN, true
  88. }
  89. // searchEntry : search an LDAP source if an entry (name, passwd) is valid and in the specific filter
  90. func (ls *Source) SearchEntry(name, passwd string, directBind bool) (string, string, string, string, bool, bool) {
  91. l, err := ldapDial(ls)
  92. if err != nil {
  93. log.Error(4, "LDAP Connect error, %s:%v", ls.Host, err)
  94. ls.Enabled = false
  95. return "", "", "", "", false, false
  96. }
  97. defer l.Close()
  98. var userDN string
  99. if directBind {
  100. log.Trace("LDAP will bind directly via UserDN template: %s", ls.UserDN)
  101. var ok bool
  102. userDN, ok = ls.sanitizedUserDN(name)
  103. if !ok {
  104. return "", "", "", "", false, false
  105. }
  106. } else {
  107. log.Trace("LDAP will use BindDN.")
  108. var found bool
  109. userDN, found = ls.findUserDN(l, name)
  110. if !found {
  111. return "", "", "", "", false, false
  112. }
  113. }
  114. if directBind || !ls.AttributesInBind {
  115. // binds user (checking password) before looking-up attributes in user context
  116. err = bindUser(l, userDN, passwd)
  117. if err != nil {
  118. return "", "", "", "", false, false
  119. }
  120. }
  121. userFilter, ok := ls.sanitizedUserQuery(name)
  122. if !ok {
  123. return "", "", "", "", false, false
  124. }
  125. log.Trace("Fetching attributes '%v', '%v', '%v', '%v' with filter %s and base %s", ls.AttributeUsername, ls.AttributeName, ls.AttributeSurname, ls.AttributeMail, userFilter, userDN)
  126. search := ldap.NewSearchRequest(
  127. userDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, userFilter,
  128. []string{ls.AttributeUsername, ls.AttributeName, ls.AttributeSurname, ls.AttributeMail},
  129. nil)
  130. sr, err := l.Search(search)
  131. if err != nil {
  132. log.Error(4, "LDAP Search failed unexpectedly! (%v)", err)
  133. return "", "", "", "", false, false
  134. } else if len(sr.Entries) < 1 {
  135. if directBind {
  136. log.Error(4, "User filter inhibited user login.")
  137. } else {
  138. log.Error(4, "LDAP Search failed unexpectedly! (0 entries)")
  139. }
  140. return "", "", "", "", false, false
  141. }
  142. username_attr := sr.Entries[0].GetAttributeValue(ls.AttributeUsername)
  143. name_attr := sr.Entries[0].GetAttributeValue(ls.AttributeName)
  144. sn_attr := sr.Entries[0].GetAttributeValue(ls.AttributeSurname)
  145. mail_attr := sr.Entries[0].GetAttributeValue(ls.AttributeMail)
  146. admin_attr := false
  147. if len(ls.AdminFilter) > 0 {
  148. log.Trace("Checking admin with filter %s and base %s", ls.AdminFilter, userDN)
  149. search = ldap.NewSearchRequest(
  150. userDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, ls.AdminFilter,
  151. []string{ls.AttributeName},
  152. nil)
  153. sr, err = l.Search(search)
  154. if err != nil {
  155. log.Error(4, "LDAP Admin Search failed unexpectedly! (%v)", err)
  156. } else if len(sr.Entries) < 1 {
  157. log.Error(4, "LDAP Admin Search failed")
  158. } else {
  159. admin_attr = true
  160. }
  161. }
  162. if !directBind && ls.AttributesInBind {
  163. // binds user (checking password) after looking-up attributes in BindDN context
  164. err = bindUser(l, userDN, passwd)
  165. if err != nil {
  166. return "", "", "", "", false, false
  167. }
  168. }
  169. return username_attr, name_attr, sn_attr, mail_attr, admin_attr, true
  170. }
  171. func bindUser(l *ldap.Conn, userDN, passwd string) error {
  172. log.Trace("Binding with userDN: %s", userDN)
  173. err := l.Bind(userDN, passwd)
  174. if err != nil {
  175. log.Debug("LDAP auth. failed for %s, reason: %v", userDN, err)
  176. return err
  177. }
  178. log.Trace("Bound successfully with userDN: %s", userDN)
  179. return err
  180. }
  181. func ldapDial(ls *Source) (*ldap.Conn, error) {
  182. if ls.UseSSL {
  183. log.Debug("Using TLS for LDAP without verifying: %v", ls.SkipVerify)
  184. return ldap.DialTLS("tcp", fmt.Sprintf("%s:%d", ls.Host, ls.Port), &tls.Config{
  185. InsecureSkipVerify: ls.SkipVerify,
  186. })
  187. } else {
  188. return ldap.Dial("tcp", fmt.Sprintf("%s:%d", ls.Host, ls.Port))
  189. }
  190. }