ldap.rb 5.8 KB

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