You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

204 lines
5.9 KiB

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