ldap.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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. log "gopkg.in/clog.v1"
  12. "gopkg.in/ldap.v2"
  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.Trace("Username contains invalid query characters: %s", 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) || strings.HasPrefix(username, " ") || strings.HasSuffix(username, " ") {
  54. log.Trace("Username contains invalid query characters: %s", 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.Trace("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.Trace("Failed search using filter '%s': %v", userFilter, err)
  84. return "", false
  85. } else if len(sr.Entries) > 1 {
  86. log.Trace("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.Trace("LDAP authentication failed for '%s': %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. // See https://tools.ietf.org/search/rfc4513#section-5.1.2
  130. if len(passwd) == 0 {
  131. log.Trace("authentication failed for '%s' with empty password")
  132. return "", "", "", "", false, false
  133. }
  134. l, err := dial(ls)
  135. if err != nil {
  136. log.Error(4, "LDAP connect failed for '%s': %v", ls.Host, err)
  137. ls.Enabled = false
  138. return "", "", "", "", false, false
  139. }
  140. defer l.Close()
  141. var userDN string
  142. if directBind {
  143. log.Trace("LDAP will bind directly via UserDN template: %s", ls.UserDN)
  144. var ok bool
  145. userDN, ok = ls.sanitizedUserDN(name)
  146. if !ok {
  147. return "", "", "", "", false, false
  148. }
  149. } else {
  150. log.Trace("LDAP will use BindDN")
  151. var found bool
  152. userDN, found = ls.findUserDN(l, name)
  153. if !found {
  154. return "", "", "", "", false, false
  155. }
  156. }
  157. if directBind || !ls.AttributesInBind {
  158. // binds user (checking password) before looking-up attributes in user context
  159. err = bindUser(l, userDN, passwd)
  160. if err != nil {
  161. return "", "", "", "", false, false
  162. }
  163. }
  164. userFilter, ok := ls.sanitizedUserQuery(name)
  165. if !ok {
  166. return "", "", "", "", false, false
  167. }
  168. log.Trace("Fetching attributes '%v', '%v', '%v', '%v' with filter '%s' and base '%s'", ls.AttributeUsername, ls.AttributeName, ls.AttributeSurname, ls.AttributeMail, userFilter, userDN)
  169. search := ldap.NewSearchRequest(
  170. userDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, userFilter,
  171. []string{ls.AttributeUsername, ls.AttributeName, ls.AttributeSurname, ls.AttributeMail},
  172. nil)
  173. sr, err := l.Search(search)
  174. if err != nil {
  175. log.Error(4, "LDAP search failed: %v", err)
  176. return "", "", "", "", false, false
  177. } else if len(sr.Entries) < 1 {
  178. if directBind {
  179. log.Error(4, "User filter inhibited user login")
  180. } else {
  181. log.Error(4, "LDAP search failed: 0 entries")
  182. }
  183. return "", "", "", "", false, false
  184. }
  185. username := sr.Entries[0].GetAttributeValue(ls.AttributeUsername)
  186. firstname := sr.Entries[0].GetAttributeValue(ls.AttributeName)
  187. surname := sr.Entries[0].GetAttributeValue(ls.AttributeSurname)
  188. mail := sr.Entries[0].GetAttributeValue(ls.AttributeMail)
  189. isAdmin := false
  190. if len(ls.AdminFilter) > 0 {
  191. log.Trace("Checking admin with filter '%s' and base '%s'", ls.AdminFilter, userDN)
  192. search = ldap.NewSearchRequest(
  193. userDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, ls.AdminFilter,
  194. []string{ls.AttributeName},
  195. nil)
  196. sr, err = l.Search(search)
  197. if err != nil {
  198. log.Error(4, "LDAP admin search failed: %v", err)
  199. } else if len(sr.Entries) < 1 {
  200. log.Error(4, "LDAP admin search failed: 0 entries")
  201. } else {
  202. isAdmin = true
  203. }
  204. }
  205. if !directBind && ls.AttributesInBind {
  206. // binds user (checking password) after looking-up attributes in BindDN context
  207. err = bindUser(l, userDN, passwd)
  208. if err != nil {
  209. return "", "", "", "", false, false
  210. }
  211. }
  212. return username, firstname, surname, mail, isAdmin, true
  213. }