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

ldap.go 11 kB

11 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
10 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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. "code.gitea.io/gitea/modules/log"
  12. ldap "gopkg.in/ldap.v3"
  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. AttributeSSHPublicKey string // LDAP SSH Public Key attribute
  39. SearchPageSize uint32 // Search with paging page size
  40. Filter string // Query filter to validate entry
  41. AdminFilter string // Query filter to check if user is admin
  42. Enabled bool // if this source is disabled
  43. AllowDeactivateAll bool // Allow an empty search response to deactivate all users from this source
  44. }
  45. // SearchResult : user data
  46. type SearchResult struct {
  47. Username string // Username
  48. Name string // Name
  49. Surname string // Surname
  50. Mail string // E-mail address
  51. SSHPublicKey []string // SSH Public Key
  52. IsAdmin bool // if user is administrator
  53. }
  54. func (ls *Source) sanitizedUserQuery(username string) (string, bool) {
  55. // See http://tools.ietf.org/search/rfc4515
  56. badCharacters := "\x00()*\\"
  57. if strings.ContainsAny(username, badCharacters) {
  58. log.Debug("'%s' contains invalid query characters. Aborting.", username)
  59. return "", false
  60. }
  61. return fmt.Sprintf(ls.Filter, username), true
  62. }
  63. func (ls *Source) sanitizedUserDN(username string) (string, bool) {
  64. // See http://tools.ietf.org/search/rfc4514: "special characters"
  65. badCharacters := "\x00()*\\,='\"#+;<>"
  66. if strings.ContainsAny(username, badCharacters) {
  67. log.Debug("'%s' contains invalid DN characters. Aborting.", username)
  68. return "", false
  69. }
  70. return fmt.Sprintf(ls.UserDN, username), true
  71. }
  72. func (ls *Source) findUserDN(l *ldap.Conn, name string) (string, bool) {
  73. log.Trace("Search for LDAP user: %s", name)
  74. // A search for the user.
  75. userFilter, ok := ls.sanitizedUserQuery(name)
  76. if !ok {
  77. return "", false
  78. }
  79. log.Trace("Searching for DN using filter %s and base %s", userFilter, ls.UserBase)
  80. search := ldap.NewSearchRequest(
  81. ls.UserBase, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0,
  82. false, userFilter, []string{}, nil)
  83. // Ensure we found a user
  84. sr, err := l.Search(search)
  85. if err != nil || len(sr.Entries) < 1 {
  86. log.Debug("Failed search using filter[%s]: %v", userFilter, err)
  87. return "", false
  88. } else if len(sr.Entries) > 1 {
  89. log.Debug("Filter '%s' returned more than one user.", userFilter)
  90. return "", false
  91. }
  92. userDN := sr.Entries[0].DN
  93. if userDN == "" {
  94. log.Error("LDAP search was successful, but found no DN!")
  95. return "", false
  96. }
  97. return userDN, true
  98. }
  99. func dial(ls *Source) (*ldap.Conn, error) {
  100. log.Trace("Dialing LDAP with security protocol (%v) without verifying: %v", ls.SecurityProtocol, ls.SkipVerify)
  101. tlsCfg := &tls.Config{
  102. ServerName: ls.Host,
  103. InsecureSkipVerify: ls.SkipVerify,
  104. }
  105. if ls.SecurityProtocol == SecurityProtocolLDAPS {
  106. return ldap.DialTLS("tcp", fmt.Sprintf("%s:%d", ls.Host, ls.Port), tlsCfg)
  107. }
  108. conn, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", ls.Host, ls.Port))
  109. if err != nil {
  110. return nil, fmt.Errorf("Dial: %v", err)
  111. }
  112. if ls.SecurityProtocol == SecurityProtocolStartTLS {
  113. if err = conn.StartTLS(tlsCfg); err != nil {
  114. conn.Close()
  115. return nil, fmt.Errorf("StartTLS: %v", err)
  116. }
  117. }
  118. return conn, nil
  119. }
  120. func bindUser(l *ldap.Conn, userDN, passwd string) error {
  121. log.Trace("Binding with userDN: %s", userDN)
  122. err := l.Bind(userDN, passwd)
  123. if err != nil {
  124. log.Debug("LDAP auth. failed for %s, reason: %v", userDN, err)
  125. return err
  126. }
  127. log.Trace("Bound successfully with userDN: %s", userDN)
  128. return err
  129. }
  130. func checkAdmin(l *ldap.Conn, ls *Source, userDN string) bool {
  131. if len(ls.AdminFilter) > 0 {
  132. log.Trace("Checking admin with filter %s and base %s", ls.AdminFilter, userDN)
  133. search := ldap.NewSearchRequest(
  134. userDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, ls.AdminFilter,
  135. []string{ls.AttributeName},
  136. nil)
  137. sr, err := l.Search(search)
  138. if err != nil {
  139. log.Error("LDAP Admin Search failed unexpectedly! (%v)", err)
  140. } else if len(sr.Entries) < 1 {
  141. log.Trace("LDAP Admin Search found no matching entries.")
  142. } else {
  143. return true
  144. }
  145. }
  146. return false
  147. }
  148. // SearchEntry : search an LDAP source if an entry (name, passwd) is valid and in the specific filter
  149. func (ls *Source) SearchEntry(name, passwd string, directBind bool) *SearchResult {
  150. // See https://tools.ietf.org/search/rfc4513#section-5.1.2
  151. if len(passwd) == 0 {
  152. log.Debug("Auth. failed for %s, password cannot be empty", name)
  153. return nil
  154. }
  155. l, err := dial(ls)
  156. if err != nil {
  157. log.Error("LDAP Connect error, %s:%v", ls.Host, err)
  158. ls.Enabled = false
  159. return nil
  160. }
  161. defer l.Close()
  162. var userDN string
  163. if directBind {
  164. log.Trace("LDAP will bind directly via UserDN template: %s", ls.UserDN)
  165. var ok bool
  166. userDN, ok = ls.sanitizedUserDN(name)
  167. if !ok {
  168. return nil
  169. }
  170. err = bindUser(l, userDN, passwd)
  171. if err != nil {
  172. return nil
  173. }
  174. if ls.UserBase != "" {
  175. // not everyone has a CN compatible with input name so we need to find
  176. // the real userDN in that case
  177. userDN, ok = ls.findUserDN(l, name)
  178. if !ok {
  179. return nil
  180. }
  181. }
  182. } else {
  183. log.Trace("LDAP will use BindDN.")
  184. var found bool
  185. if ls.BindDN != "" && ls.BindPassword != "" {
  186. err := l.Bind(ls.BindDN, ls.BindPassword)
  187. if err != nil {
  188. log.Debug("Failed to bind as BindDN[%s]: %v", ls.BindDN, err)
  189. return nil
  190. }
  191. log.Trace("Bound as BindDN %s", ls.BindDN)
  192. } else {
  193. log.Trace("Proceeding with anonymous LDAP search.")
  194. }
  195. userDN, found = ls.findUserDN(l, name)
  196. if !found {
  197. return nil
  198. }
  199. }
  200. if !ls.AttributesInBind {
  201. // binds user (checking password) before looking-up attributes in user context
  202. err = bindUser(l, userDN, passwd)
  203. if err != nil {
  204. return nil
  205. }
  206. }
  207. userFilter, ok := ls.sanitizedUserQuery(name)
  208. if !ok {
  209. return nil
  210. }
  211. var isAttributeSSHPublicKeySet = len(strings.TrimSpace(ls.AttributeSSHPublicKey)) > 0
  212. attribs := []string{ls.AttributeUsername, ls.AttributeName, ls.AttributeSurname, ls.AttributeMail}
  213. if isAttributeSSHPublicKeySet {
  214. attribs = append(attribs, ls.AttributeSSHPublicKey)
  215. }
  216. log.Trace("Fetching attributes '%v', '%v', '%v', '%v', '%v' with filter %s and base %s", ls.AttributeUsername, ls.AttributeName, ls.AttributeSurname, ls.AttributeMail, ls.AttributeSSHPublicKey, userFilter, userDN)
  217. search := ldap.NewSearchRequest(
  218. userDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, userFilter,
  219. attribs, nil)
  220. sr, err := l.Search(search)
  221. if err != nil {
  222. log.Error("LDAP Search failed unexpectedly! (%v)", err)
  223. return nil
  224. } else if len(sr.Entries) < 1 {
  225. if directBind {
  226. log.Trace("User filter inhibited user login.")
  227. } else {
  228. log.Trace("LDAP Search found no matching entries.")
  229. }
  230. return nil
  231. }
  232. var sshPublicKey []string
  233. username := sr.Entries[0].GetAttributeValue(ls.AttributeUsername)
  234. firstname := sr.Entries[0].GetAttributeValue(ls.AttributeName)
  235. surname := sr.Entries[0].GetAttributeValue(ls.AttributeSurname)
  236. mail := sr.Entries[0].GetAttributeValue(ls.AttributeMail)
  237. if isAttributeSSHPublicKeySet {
  238. sshPublicKey = sr.Entries[0].GetAttributeValues(ls.AttributeSSHPublicKey)
  239. }
  240. isAdmin := checkAdmin(l, ls, userDN)
  241. if !directBind && ls.AttributesInBind {
  242. // binds user (checking password) after looking-up attributes in BindDN context
  243. err = bindUser(l, userDN, passwd)
  244. if err != nil {
  245. return nil
  246. }
  247. }
  248. return &SearchResult{
  249. Username: username,
  250. Name: firstname,
  251. Surname: surname,
  252. Mail: mail,
  253. SSHPublicKey: sshPublicKey,
  254. IsAdmin: isAdmin,
  255. }
  256. }
  257. // UsePagedSearch returns if need to use paged search
  258. func (ls *Source) UsePagedSearch() bool {
  259. return ls.SearchPageSize > 0
  260. }
  261. // SearchEntries : search an LDAP source for all users matching userFilter
  262. func (ls *Source) SearchEntries() ([]*SearchResult, error) {
  263. l, err := dial(ls)
  264. if err != nil {
  265. log.Error("LDAP Connect error, %s:%v", ls.Host, err)
  266. ls.Enabled = false
  267. return nil, err
  268. }
  269. defer l.Close()
  270. if ls.BindDN != "" && ls.BindPassword != "" {
  271. err := l.Bind(ls.BindDN, ls.BindPassword)
  272. if err != nil {
  273. log.Debug("Failed to bind as BindDN[%s]: %v", ls.BindDN, err)
  274. return nil, err
  275. }
  276. log.Trace("Bound as BindDN %s", ls.BindDN)
  277. } else {
  278. log.Trace("Proceeding with anonymous LDAP search.")
  279. }
  280. userFilter := fmt.Sprintf(ls.Filter, "*")
  281. var isAttributeSSHPublicKeySet = len(strings.TrimSpace(ls.AttributeSSHPublicKey)) > 0
  282. attribs := []string{ls.AttributeUsername, ls.AttributeName, ls.AttributeSurname, ls.AttributeMail}
  283. if isAttributeSSHPublicKeySet {
  284. attribs = append(attribs, ls.AttributeSSHPublicKey)
  285. }
  286. log.Trace("Fetching attributes '%v', '%v', '%v', '%v', '%v' with filter %s and base %s", ls.AttributeUsername, ls.AttributeName, ls.AttributeSurname, ls.AttributeMail, ls.AttributeSSHPublicKey, userFilter, ls.UserBase)
  287. search := ldap.NewSearchRequest(
  288. ls.UserBase, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, userFilter,
  289. attribs, nil)
  290. var sr *ldap.SearchResult
  291. if ls.UsePagedSearch() {
  292. sr, err = l.SearchWithPaging(search, ls.SearchPageSize)
  293. } else {
  294. sr, err = l.Search(search)
  295. }
  296. if err != nil {
  297. log.Error("LDAP Search failed unexpectedly! (%v)", err)
  298. return nil, err
  299. }
  300. result := make([]*SearchResult, len(sr.Entries))
  301. for i, v := range sr.Entries {
  302. result[i] = &SearchResult{
  303. Username: v.GetAttributeValue(ls.AttributeUsername),
  304. Name: v.GetAttributeValue(ls.AttributeName),
  305. Surname: v.GetAttributeValue(ls.AttributeSurname),
  306. Mail: v.GetAttributeValue(ls.AttributeMail),
  307. IsAdmin: checkAdmin(l, ls, v.DN),
  308. }
  309. if isAttributeSSHPublicKeySet {
  310. result[i].SSHPublicKey = v.GetAttributeValues(ls.AttributeSSHPublicKey)
  311. }
  312. }
  313. return result, nil
  314. }