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.

ldap.go 7.5KB

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