ldap.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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. type SecurityProtocol int
  15. // Note: new type must be added at the end of list to maintain compatibility.
  16. const (
  17. SECURITY_PROTOCOL_UNENCRYPTED SecurityProtocol = iota
  18. SECURITY_PROTOCOL_LDAPS
  19. SECURITY_PROTOCOL_START_TLS
  20. )
  21. // Basic LDAP authentication service
  22. type Source struct {
  23. Name string // canonical name (ie. corporate.ad)
  24. Host string // LDAP host
  25. Port int // port number
  26. SecurityProtocol SecurityProtocol
  27. SkipVerify bool
  28. BindDN string // DN to bind with
  29. BindPassword string // Bind DN password
  30. UserBase string // Base search path for users
  31. UserDN string // Template for the DN of the user for simple auth
  32. AttributeUsername string // Username attribute
  33. AttributeName string // First name attribute
  34. AttributeSurname string // Surname attribute
  35. AttributeMail string // E-mail attribute
  36. AttributesInBind bool // fetch attributes in bind context (not user)
  37. Filter string // Query filter to validate entry
  38. AdminFilter string // Query filter to check if user is admin
  39. Enabled bool // if this source is disabled
  40. }
  41. func (ls *Source) sanitizedUserQuery(username string) (string, bool) {
  42. // See http://tools.ietf.org/search/rfc4515
  43. badCharacters := "\x00()*\\"
  44. if strings.ContainsAny(username, badCharacters) {
  45. log.Debug("'%s' contains invalid query characters. Aborting.", username)
  46. return "", false
  47. }
  48. return fmt.Sprintf(ls.Filter, username), true
  49. }
  50. func (ls *Source) sanitizedUserDN(username string) (string, bool) {
  51. // See http://tools.ietf.org/search/rfc4514: "special characters"
  52. badCharacters := "\x00()*\\,='\"#+;<> "
  53. if strings.ContainsAny(username, badCharacters) {
  54. log.Debug("'%s' contains invalid DN characters. Aborting.", username)
  55. return "", false
  56. }
  57. return fmt.Sprintf(ls.UserDN, username), true
  58. }
  59. func (ls *Source) findUserDN(l *ldap.Conn, name string) (string, bool) {
  60. log.Trace("Search for LDAP user: %s", name)
  61. if ls.BindDN != "" && ls.BindPassword != "" {
  62. err := l.Bind(ls.BindDN, ls.BindPassword)
  63. if err != nil {
  64. log.Debug("Failed to bind as BindDN[%s]: %v", ls.BindDN, err)
  65. return "", false
  66. }
  67. log.Trace("Bound as BindDN %s", ls.BindDN)
  68. } else {
  69. log.Trace("Proceeding with anonymous LDAP search.")
  70. }
  71. // A search for the user.
  72. userFilter, ok := ls.sanitizedUserQuery(name)
  73. if !ok {
  74. return "", false
  75. }
  76. log.Trace("Searching for DN using filter %s and base %s", userFilter, ls.UserBase)
  77. search := ldap.NewSearchRequest(
  78. ls.UserBase, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0,
  79. false, userFilter, []string{}, nil)
  80. // Ensure we found a user
  81. sr, err := l.Search(search)
  82. if err != nil || len(sr.Entries) < 1 {
  83. log.Debug("Failed search using filter[%s]: %v", userFilter, err)
  84. return "", false
  85. } else if len(sr.Entries) > 1 {
  86. log.Debug("Filter '%s' returned more than one user.", userFilter)
  87. return "", false
  88. }
  89. userDN := sr.Entries[0].DN
  90. if userDN == "" {
  91. log.Error(4, "LDAP search was successful, but found no DN!")
  92. return "", false
  93. }
  94. return userDN, true
  95. }
  96. func dial(ls *Source) (*ldap.Conn, error) {
  97. log.Trace("Dialing LDAP with security protocol (%v) without verifying: %v", ls.SecurityProtocol, ls.SkipVerify)
  98. tlsCfg := &tls.Config{
  99. ServerName: ls.Host,
  100. InsecureSkipVerify: ls.SkipVerify,
  101. }
  102. if ls.SecurityProtocol == SECURITY_PROTOCOL_LDAPS {
  103. return ldap.DialTLS("tcp", fmt.Sprintf("%s:%d", ls.Host, ls.Port), tlsCfg)
  104. }
  105. conn, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", ls.Host, ls.Port))
  106. if err != nil {
  107. return nil, fmt.Errorf("Dial: %v", err)
  108. }
  109. if ls.SecurityProtocol == SECURITY_PROTOCOL_START_TLS {
  110. if err = conn.StartTLS(tlsCfg); err != nil {
  111. conn.Close()
  112. return nil, fmt.Errorf("StartTLS: %v", err)
  113. }
  114. }
  115. return conn, nil
  116. }
  117. func bindUser(l *ldap.Conn, userDN, passwd string) error {
  118. log.Trace("Binding with userDN: %s", userDN)
  119. err := l.Bind(userDN, passwd)
  120. if err != nil {
  121. log.Debug("LDAP auth. failed for %s, reason: %v", userDN, err)
  122. return err
  123. }
  124. log.Trace("Bound successfully with userDN: %s", userDN)
  125. return err
  126. }
  127. // searchEntry : search an LDAP source if an entry (name, passwd) is valid and in the specific filter
  128. func (ls *Source) SearchEntry(name, passwd string, directBind bool) (string, string, string, string, bool, bool) {
  129. l, err := dial(ls)
  130. if err != nil {
  131. log.Error(4, "LDAP Connect error, %s:%v", ls.Host, err)
  132. ls.Enabled = false
  133. return "", "", "", "", false, false
  134. }
  135. defer l.Close()
  136. var userDN string
  137. if directBind {
  138. log.Trace("LDAP will bind directly via UserDN template: %s", ls.UserDN)
  139. var ok bool
  140. userDN, ok = ls.sanitizedUserDN(name)
  141. if !ok {
  142. return "", "", "", "", false, false
  143. }
  144. } else {
  145. log.Trace("LDAP will use BindDN.")
  146. var found bool
  147. userDN, found = ls.findUserDN(l, name)
  148. if !found {
  149. return "", "", "", "", false, false
  150. }
  151. }
  152. if directBind || !ls.AttributesInBind {
  153. // binds user (checking password) before looking-up attributes in user context
  154. err = bindUser(l, userDN, passwd)
  155. if err != nil {
  156. return "", "", "", "", false, false
  157. }
  158. }
  159. userFilter, ok := ls.sanitizedUserQuery(name)
  160. if !ok {
  161. return "", "", "", "", false, false
  162. }
  163. log.Trace("Fetching attributes '%v', '%v', '%v', '%v' with filter %s and base %s", ls.AttributeUsername, ls.AttributeName, ls.AttributeSurname, ls.AttributeMail, userFilter, userDN)
  164. search := ldap.NewSearchRequest(
  165. userDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, userFilter,
  166. []string{ls.AttributeUsername, ls.AttributeName, ls.AttributeSurname, ls.AttributeMail},
  167. nil)
  168. sr, err := l.Search(search)
  169. if err != nil {
  170. log.Error(4, "LDAP Search failed unexpectedly! (%v)", err)
  171. return "", "", "", "", false, false
  172. } else if len(sr.Entries) < 1 {
  173. if directBind {
  174. log.Error(4, "User filter inhibited user login.")
  175. } else {
  176. log.Error(4, "LDAP Search failed unexpectedly! (0 entries)")
  177. }
  178. return "", "", "", "", false, false
  179. }
  180. username := sr.Entries[0].GetAttributeValue(ls.AttributeUsername)
  181. firstname := sr.Entries[0].GetAttributeValue(ls.AttributeName)
  182. surname := sr.Entries[0].GetAttributeValue(ls.AttributeSurname)
  183. mail := sr.Entries[0].GetAttributeValue(ls.AttributeMail)
  184. isAdmin := false
  185. if len(ls.AdminFilter) > 0 {
  186. log.Trace("Checking admin with filter %s and base %s", ls.AdminFilter, userDN)
  187. search = ldap.NewSearchRequest(
  188. userDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, ls.AdminFilter,
  189. []string{ls.AttributeName},
  190. nil)
  191. sr, err = l.Search(search)
  192. if err != nil {
  193. log.Error(4, "LDAP Admin Search failed unexpectedly! (%v)", err)
  194. } else if len(sr.Entries) < 1 {
  195. log.Error(4, "LDAP Admin Search failed")
  196. } else {
  197. isAdmin = true
  198. }
  199. }
  200. if !directBind && ls.AttributesInBind {
  201. // binds user (checking password) after looking-up attributes in BindDN context
  202. err = bindUser(l, userDN, passwd)
  203. if err != nil {
  204. return "", "", "", "", false, false
  205. }
  206. }
  207. return username, firstname, surname, mail, isAdmin, true
  208. }