ldap.rb 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
  2. require 'net/ldap'
  3. require 'net/ldap/entry'
  4. # Class for establishing LDAP connections. A wrapper around Net::LDAP needed for Auth and Sync.
  5. # ATTENTION: Loads custom 'net/ldap/entry' from 'lib/core_ext' which extends the Net::LDAP::Entry class.
  6. #
  7. # @!attribute [r] connection
  8. # @return [Net::LDAP] the Net::LDAP instance with the established connection
  9. # @!attribute [r] base_dn
  10. # @return [String] the base dn used while initializing the connection
  11. class Ldap
  12. attr_reader :connection, :base_dn, :host, :port, :ssl
  13. # Initializes a LDAP connection.
  14. #
  15. # @param [Hash] config the configuration for establishing a LDAP connection. Default is Setting 'ldap_config'.
  16. # @option config [String] :host_url The LDAP host URL in the format '*protocol*://*host*:*port*'.
  17. # @option config [String] :host The LDAP explicit host. May contain the port. Gets overwritten by host_url if given.
  18. # @option config [Number] :port The LDAP port. Default is 389 LDAP or 636 for LDAPS. Gets overwritten by host_url if given.
  19. # @option config [Boolean] :ssl The LDAP SSL setting. Is set automatically for 'ldaps' protocol. Sets Port to 636 if non other is given.
  20. # @option config [String] :base_dn The base DN searches etc. are applied to.
  21. # @option config [String] :bind_user The username which should be used for bind.
  22. # @option config [String] :bind_pw The password which should be used for bind.
  23. #
  24. # @example
  25. # ldap = Ldap.new
  26. #
  27. # @return [nil]
  28. def initialize(config = nil)
  29. @config = config
  30. if @config.blank?
  31. @config = Setting.get('ldap_config')
  32. end
  33. connect
  34. end
  35. # Requests the rootDSE (the root of the directory data tree on a directory server).
  36. #
  37. # @example
  38. # ldap.preferences
  39. # #=> [:namingcontexts=>["DC=domain,DC=tld", "CN=Configuration,DC=domain,DC=tld"], :supportedldapversion=>["3", "2"], ...]
  40. #
  41. # @return [Hash{String => Array<String>}] The found RootDSEs.
  42. def preferences
  43. @connection.search_root_dse.to_h
  44. end
  45. # Performs a LDAP search and yields over the found LDAP entries.
  46. #
  47. # @param filter [String] The filter that should get applied to the search.
  48. # @param base [String] The base DN on which the search should get executed. Default is initialization parameter.
  49. # @param scope [Net::LDAP::SearchScope] The search scope as defined in Net::LDAP SearchScopes. Default is WholeSubtree.
  50. # @param attributes [Array<String>] Limits the requested entry attributes to the given list of attributes which increses the performance.
  51. #
  52. # @example
  53. # ldap.search('(objectClass=group)') do |entry|
  54. # p entry
  55. # end
  56. # #=> <Net::LDAP::Entry...>
  57. #
  58. # @return [true] Returns always true
  59. def search(filter, base: nil, scope: nil, attributes: nil)
  60. base ||= base_dn()
  61. scope ||= Net::LDAP::SearchScope_WholeSubtree
  62. @connection.search(
  63. base: base,
  64. filter: filter,
  65. scope: scope,
  66. attributes: attributes,
  67. return_result: false, # improves performance
  68. ) do |entry|
  69. yield entry
  70. end
  71. end
  72. # Checks if there are any entries for the given search criteria.
  73. #
  74. # @param (see Ldap#search)
  75. #
  76. # @example
  77. # ldap.entries?('(objectClass=group)')
  78. # #=> true
  79. #
  80. # @return [Boolean] Returns true if entries are present false if not.
  81. def entries?(*args)
  82. found = false
  83. search(*args) do |_entry|
  84. found = true
  85. break
  86. end
  87. found
  88. end
  89. # Counts the entries for the given search criteria.
  90. #
  91. # @param (see Ldap#search)
  92. #
  93. # @example
  94. # ldap.entries?('(objectClass=group)')
  95. # #=> 10
  96. #
  97. # @return [Number] The count of matching entries.
  98. def count(*args)
  99. counter = 0
  100. search(*args) do |_entry|
  101. counter += 1
  102. end
  103. counter
  104. end
  105. private
  106. def connect
  107. @connection ||= begin
  108. attributes_from_config
  109. binded_connection
  110. end
  111. end
  112. def binded_connection
  113. # ldap connect
  114. ldap = Net::LDAP.new(connection_params)
  115. # set auth data if needed
  116. if @bind_user && @bind_pw
  117. ldap.auth @bind_user, @bind_pw
  118. end
  119. return ldap if ldap.bind
  120. result = ldap.get_operation_result
  121. raise Exceptions::UnprocessableEntity, "Can't bind to '#{@host}', #{result.code}, #{result.message}"
  122. rescue => e
  123. Rails.logger.error e
  124. raise Exceptions::UnprocessableEntity, "Can't connect to '#{@host}' on port '#{@port}', #{e}"
  125. end
  126. def connection_params
  127. params = {
  128. host: @host,
  129. port: @port,
  130. }
  131. if @encryption
  132. params[:encryption] = @encryption
  133. end
  134. # special workaround for IBM bluepages
  135. # see issue #1422 for more details
  136. if @host == 'bluepages.ibm.com'
  137. params[:force_no_page] = true
  138. end
  139. params
  140. end
  141. def attributes_from_config
  142. # might change below
  143. @host = @config[:host]
  144. @port = @config[:port]
  145. @ssl = @config.fetch(:ssl, false)
  146. parse_host_url
  147. parse_host
  148. handle_ssl_config
  149. handle_bind_crendentials
  150. @base_dn = @config[:base_dn]
  151. # fallback to default
  152. # port if none given
  153. @port ||= 389
  154. end
  155. def parse_host_url
  156. @host_url = @config[:host_url]
  157. return if @host_url.blank?
  158. raise "Invalid host url '#{@host_url}'" if @host_url !~ %r{\A([^:]+)://(.+?)/?\z}
  159. @protocol = $1.to_sym
  160. @host = $2
  161. @ssl = @protocol == :ldaps
  162. end
  163. def parse_host
  164. return if @host !~ /\A([^:]+):(.+?)\z/
  165. @host = $1
  166. @port = $2.to_i
  167. end
  168. def handle_ssl_config
  169. return if !@ssl
  170. @port ||= @config.fetch(:port, 636)
  171. @encryption = {
  172. method: :simple_tls,
  173. }
  174. if !@config[:ssl_verify]
  175. @encryption[:tls_options] = {
  176. verify_mode: OpenSSL::SSL::VERIFY_NONE
  177. }
  178. end
  179. end
  180. def handle_bind_crendentials
  181. @bind_user = @config[:bind_user]
  182. @bind_pw = @config[:bind_pw]
  183. end
  184. end