Chris@0: # $Id: ldap.rb 154 2006-08-15 09:35:43Z blackhedd $ Chris@0: # Chris@0: # Net::LDAP for Ruby Chris@0: # Chris@0: # Chris@0: # Copyright (C) 2006 by Francis Cianfrocca. All Rights Reserved. Chris@0: # Chris@0: # Written and maintained by Francis Cianfrocca, gmail: garbagecat10. Chris@0: # Chris@0: # This program is free software. Chris@0: # You may re-distribute and/or modify this program under the same terms Chris@0: # as Ruby itself: Ruby Distribution License or GNU General Public License. Chris@0: # Chris@0: # Chris@0: # See Net::LDAP for documentation and usage samples. Chris@0: # Chris@0: Chris@0: Chris@0: require 'socket' Chris@0: require 'ostruct' Chris@0: Chris@0: begin Chris@0: require 'openssl' Chris@0: $net_ldap_openssl_available = true Chris@0: rescue LoadError Chris@0: end Chris@0: Chris@0: require 'net/ber' Chris@0: require 'net/ldap/pdu' Chris@0: require 'net/ldap/filter' Chris@0: require 'net/ldap/dataset' Chris@0: require 'net/ldap/psw' Chris@0: require 'net/ldap/entry' Chris@0: Chris@0: Chris@0: module Net Chris@0: Chris@0: Chris@0: # == Net::LDAP Chris@0: # Chris@0: # This library provides a pure-Ruby implementation of the Chris@0: # LDAP client protocol, per RFC-2251. Chris@0: # It can be used to access any server which implements the Chris@0: # LDAP protocol. Chris@0: # Chris@0: # Net::LDAP is intended to provide full LDAP functionality Chris@0: # while hiding the more arcane aspects Chris@0: # the LDAP protocol itself, and thus presenting as Ruby-like Chris@0: # a programming interface as possible. Chris@0: # Chris@0: # == Quick-start for the Impatient Chris@0: # === Quick Example of a user-authentication against an LDAP directory: Chris@0: # Chris@0: # require 'rubygems' Chris@0: # require 'net/ldap' Chris@0: # Chris@0: # ldap = Net::LDAP.new Chris@0: # ldap.host = your_server_ip_address Chris@0: # ldap.port = 389 Chris@0: # ldap.auth "joe_user", "opensesame" Chris@0: # if ldap.bind Chris@0: # # authentication succeeded Chris@0: # else Chris@0: # # authentication failed Chris@0: # end Chris@0: # Chris@0: # Chris@0: # === Quick Example of a search against an LDAP directory: Chris@0: # Chris@0: # require 'rubygems' Chris@0: # require 'net/ldap' Chris@0: # Chris@0: # ldap = Net::LDAP.new :host => server_ip_address, Chris@0: # :port => 389, Chris@0: # :auth => { Chris@0: # :method => :simple, Chris@0: # :username => "cn=manager,dc=example,dc=com", Chris@0: # :password => "opensesame" Chris@0: # } Chris@0: # Chris@0: # filter = Net::LDAP::Filter.eq( "cn", "George*" ) Chris@0: # treebase = "dc=example,dc=com" Chris@0: # Chris@0: # ldap.search( :base => treebase, :filter => filter ) do |entry| Chris@0: # puts "DN: #{entry.dn}" Chris@0: # entry.each do |attribute, values| Chris@0: # puts " #{attribute}:" Chris@0: # values.each do |value| Chris@0: # puts " --->#{value}" Chris@0: # end Chris@0: # end Chris@0: # end Chris@0: # Chris@0: # p ldap.get_operation_result Chris@0: # Chris@0: # Chris@0: # == A Brief Introduction to LDAP Chris@0: # Chris@0: # We're going to provide a quick, informal introduction to LDAP Chris@0: # terminology and Chris@0: # typical operations. If you're comfortable with this material, skip Chris@0: # ahead to "How to use Net::LDAP." If you want a more rigorous treatment Chris@0: # of this material, we recommend you start with the various IETF and ITU Chris@0: # standards that relate to LDAP. Chris@0: # Chris@0: # === Entities Chris@0: # LDAP is an Internet-standard protocol used to access directory servers. Chris@0: # The basic search unit is the entity, which corresponds to Chris@0: # a person or other domain-specific object. Chris@0: # A directory service which supports the LDAP protocol typically Chris@0: # stores information about a number of entities. Chris@0: # Chris@0: # === Principals Chris@0: # LDAP servers are typically used to access information about people, Chris@0: # but also very often about such items as printers, computers, and other Chris@0: # resources. To reflect this, LDAP uses the term entity, or less Chris@0: # commonly, principal, to denote its basic data-storage unit. Chris@0: # Chris@0: # Chris@0: # === Distinguished Names Chris@0: # In LDAP's view of the world, Chris@0: # an entity is uniquely identified by a globally-unique text string Chris@0: # called a Distinguished Name, originally defined in the X.400 Chris@0: # standards from which LDAP is ultimately derived. Chris@0: # Much like a DNS hostname, a DN is a "flattened" text representation Chris@0: # of a string of tree nodes. Also like DNS (and unlike Java package Chris@0: # names), a DN expresses a chain of tree-nodes written from left to right Chris@0: # in order from the most-resolved node to the most-general one. Chris@0: # Chris@0: # If you know the DN of a person or other entity, then you can query Chris@0: # an LDAP-enabled directory for information (attributes) about the entity. Chris@0: # Alternatively, you can query the directory for a list of DNs matching Chris@0: # a set of criteria that you supply. Chris@0: # Chris@0: # === Attributes Chris@0: # Chris@0: # In the LDAP view of the world, a DN uniquely identifies an entity. Chris@0: # Information about the entity is stored as a set of Attributes. Chris@0: # An attribute is a text string which is associated with zero or more Chris@0: # values. Most LDAP-enabled directories store a well-standardized Chris@0: # range of attributes, and constrain their values according to standard Chris@0: # rules. Chris@0: # Chris@0: # A good example of an attribute is sn, which stands for "Surname." Chris@0: # This attribute is generally used to store a person's surname, or last name. Chris@0: # Most directories enforce the standard convention that Chris@0: # an entity's sn attribute have exactly one value. In LDAP Chris@0: # jargon, that means that sn must be present and Chris@0: # single-valued. Chris@0: # Chris@0: # Another attribute is mail, which is used to store email addresses. Chris@0: # (No, there is no attribute called "email," perhaps because X.400 terminology Chris@0: # predates the invention of the term email.) mail differs Chris@0: # from sn in that most directories permit any number of values for the Chris@0: # mail attribute, including zero. Chris@0: # Chris@0: # Chris@0: # === Tree-Base Chris@0: # We said above that X.400 Distinguished Names are globally unique. Chris@0: # In a manner reminiscent of DNS, LDAP supposes that each directory server Chris@0: # contains authoritative attribute data for a set of DNs corresponding Chris@0: # to a specific sub-tree of the (notional) global directory tree. Chris@0: # This subtree is generally configured into a directory server when it is Chris@0: # created. It matters for this discussion because most servers will not Chris@0: # allow you to query them unless you specify a correct tree-base. Chris@0: # Chris@0: # Let's say you work for the engineering department of Big Company, Inc., Chris@0: # whose internet domain is bigcompany.com. You may find that your departmental Chris@0: # directory is stored in a server with a defined tree-base of Chris@0: # ou=engineering,dc=bigcompany,dc=com Chris@0: # You will need to supply this string as the tree-base when querying this Chris@0: # directory. (Ou is a very old X.400 term meaning "organizational unit." Chris@0: # Dc is a more recent term meaning "domain component.") Chris@0: # Chris@0: # === LDAP Versions Chris@0: # (stub, discuss v2 and v3) Chris@0: # Chris@0: # === LDAP Operations Chris@0: # The essential operations are: #bind, #search, #add, #modify, #delete, and #rename. Chris@0: # ==== Bind Chris@0: # #bind supplies a user's authentication credentials to a server, which in turn verifies Chris@0: # or rejects them. There is a range of possibilities for credentials, but most directories Chris@0: # support a simple username and password authentication. Chris@0: # Chris@0: # Taken by itself, #bind can be used to authenticate a user against information Chris@0: # stored in a directory, for example to permit or deny access to some other resource. Chris@0: # In terms of the other LDAP operations, most directories require a successful #bind to Chris@0: # be performed before the other operations will be permitted. Some servers permit certain Chris@0: # operations to be performed with an "anonymous" binding, meaning that no credentials are Chris@0: # presented by the user. (We're glossing over a lot of platform-specific detail here.) Chris@0: # Chris@0: # ==== Search Chris@0: # Calling #search against the directory involves specifying a treebase, a set of search filters, Chris@0: # and a list of attribute values. Chris@0: # The filters specify ranges of possible values for particular attributes. Multiple Chris@0: # filters can be joined together with AND, OR, and NOT operators. Chris@0: # A server will respond to a #search by returning a list of matching DNs together with a Chris@0: # set of attribute values for each entity, depending on what attributes the search requested. Chris@0: # Chris@0: # ==== Add Chris@0: # #add specifies a new DN and an initial set of attribute values. If the operation Chris@0: # succeeds, a new entity with the corresponding DN and attributes is added to the directory. Chris@0: # Chris@0: # ==== Modify Chris@0: # #modify specifies an entity DN, and a list of attribute operations. #modify is used to change Chris@0: # the attribute values stored in the directory for a particular entity. Chris@0: # #modify may add or delete attributes (which are lists of values) or it change attributes by Chris@0: # adding to or deleting from their values. Chris@0: # Net::LDAP provides three easier methods to modify an entry's attribute values: Chris@0: # #add_attribute, #replace_attribute, and #delete_attribute. Chris@0: # Chris@0: # ==== Delete Chris@0: # #delete specifies an entity DN. If it succeeds, the entity and all its attributes Chris@0: # is removed from the directory. Chris@0: # Chris@0: # ==== Rename (or Modify RDN) Chris@0: # #rename (or #modify_rdn) is an operation added to version 3 of the LDAP protocol. It responds to Chris@0: # the often-arising need to change the DN of an entity without discarding its attribute values. Chris@0: # In earlier LDAP versions, the only way to do this was to delete the whole entity and add it Chris@0: # again with a different DN. Chris@0: # Chris@0: # #rename works by taking an "old" DN (the one to change) and a "new RDN," which is the left-most Chris@0: # part of the DN string. If successful, #rename changes the entity DN so that its left-most Chris@0: # node corresponds to the new RDN given in the request. (RDN, or "relative distinguished name," Chris@0: # denotes a single tree-node as expressed in a DN, which is a chain of tree nodes.) Chris@0: # Chris@0: # == How to use Net::LDAP Chris@0: # Chris@0: # To access Net::LDAP functionality in your Ruby programs, start by requiring Chris@0: # the library: Chris@0: # Chris@0: # require 'net/ldap' Chris@0: # Chris@0: # If you installed the Gem version of Net::LDAP, and depending on your version of Chris@0: # Ruby and rubygems, you _may_ also need to require rubygems explicitly: Chris@0: # Chris@0: # require 'rubygems' Chris@0: # require 'net/ldap' Chris@0: # Chris@0: # Most operations with Net::LDAP start by instantiating a Net::LDAP object. Chris@0: # The constructor for this object takes arguments specifying the network location Chris@0: # (address and port) of the LDAP server, and also the binding (authentication) Chris@0: # credentials, typically a username and password. Chris@0: # Given an object of class Net:LDAP, you can then perform LDAP operations by calling Chris@0: # instance methods on the object. These are documented with usage examples below. Chris@0: # Chris@0: # The Net::LDAP library is designed to be very disciplined about how it makes network Chris@0: # connections to servers. This is different from many of the standard native-code Chris@0: # libraries that are provided on most platforms, which share bloodlines with the Chris@0: # original Netscape/Michigan LDAP client implementations. These libraries sought to Chris@0: # insulate user code from the workings of the network. This is a good idea of course, Chris@0: # but the practical effect has been confusing and many difficult bugs have been caused Chris@0: # by the opacity of the native libraries, and their variable behavior across platforms. Chris@0: # Chris@0: # In general, Net::LDAP instance methods which invoke server operations make a connection Chris@0: # to the server when the method is called. They execute the operation (typically binding first) Chris@0: # and then disconnect from the server. The exception is Net::LDAP#open, which makes a connection Chris@0: # to the server and then keeps it open while it executes a user-supplied block. Net::LDAP#open Chris@0: # closes the connection on completion of the block. Chris@0: # Chris@0: Chris@0: class LDAP Chris@0: Chris@0: class LdapError < Exception; end Chris@0: Chris@0: VERSION = "0.0.4" Chris@0: Chris@0: Chris@0: SearchScope_BaseObject = 0 Chris@0: SearchScope_SingleLevel = 1 Chris@0: SearchScope_WholeSubtree = 2 Chris@0: SearchScopes = [SearchScope_BaseObject, SearchScope_SingleLevel, SearchScope_WholeSubtree] Chris@0: Chris@0: AsnSyntax = { Chris@0: :application => { Chris@0: :constructed => { Chris@0: 0 => :array, # BindRequest Chris@0: 1 => :array, # BindResponse Chris@0: 2 => :array, # UnbindRequest Chris@0: 3 => :array, # SearchRequest Chris@0: 4 => :array, # SearchData Chris@0: 5 => :array, # SearchResult Chris@0: 6 => :array, # ModifyRequest Chris@0: 7 => :array, # ModifyResponse Chris@0: 8 => :array, # AddRequest Chris@0: 9 => :array, # AddResponse Chris@0: 10 => :array, # DelRequest Chris@0: 11 => :array, # DelResponse Chris@0: 12 => :array, # ModifyRdnRequest Chris@0: 13 => :array, # ModifyRdnResponse Chris@0: 14 => :array, # CompareRequest Chris@0: 15 => :array, # CompareResponse Chris@0: 16 => :array, # AbandonRequest Chris@0: 19 => :array, # SearchResultReferral Chris@0: 24 => :array, # Unsolicited Notification Chris@0: } Chris@0: }, Chris@0: :context_specific => { Chris@0: :primitive => { Chris@0: 0 => :string, # password Chris@0: 1 => :string, # Kerberos v4 Chris@0: 2 => :string, # Kerberos v5 Chris@0: }, Chris@0: :constructed => { Chris@0: 0 => :array, # RFC-2251 Control Chris@0: 3 => :array, # Seach referral Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: DefaultHost = "127.0.0.1" Chris@0: DefaultPort = 389 Chris@0: DefaultAuth = {:method => :anonymous} Chris@0: DefaultTreebase = "dc=com" Chris@0: Chris@0: Chris@0: ResultStrings = { Chris@0: 0 => "Success", Chris@0: 1 => "Operations Error", Chris@0: 2 => "Protocol Error", Chris@0: 3 => "Time Limit Exceeded", Chris@0: 4 => "Size Limit Exceeded", Chris@0: 12 => "Unavailable crtical extension", Chris@0: 16 => "No Such Attribute", Chris@0: 17 => "Undefined Attribute Type", Chris@0: 20 => "Attribute or Value Exists", Chris@0: 32 => "No Such Object", Chris@0: 34 => "Invalid DN Syntax", Chris@0: 48 => "Invalid DN Syntax", Chris@0: 48 => "Inappropriate Authentication", Chris@0: 49 => "Invalid Credentials", Chris@0: 50 => "Insufficient Access Rights", Chris@0: 51 => "Busy", Chris@0: 52 => "Unavailable", Chris@0: 53 => "Unwilling to perform", Chris@0: 65 => "Object Class Violation", Chris@0: 68 => "Entry Already Exists" Chris@0: } Chris@0: Chris@0: Chris@0: module LdapControls Chris@0: PagedResults = "1.2.840.113556.1.4.319" # Microsoft evil from RFC 2696 Chris@0: end Chris@0: Chris@0: Chris@0: # Chris@0: # LDAP::result2string Chris@0: # Chris@0: def LDAP::result2string code # :nodoc: Chris@0: ResultStrings[code] || "unknown result (#{code})" Chris@0: end Chris@0: Chris@0: Chris@0: attr_accessor :host, :port, :base Chris@0: Chris@0: Chris@0: # Instantiate an object of type Net::LDAP to perform directory operations. Chris@0: # This constructor takes a Hash containing arguments, all of which are either optional or may be specified later with other methods as described below. The following arguments Chris@0: # are supported: Chris@0: # * :host => the LDAP server's IP-address (default 127.0.0.1) Chris@0: # * :port => the LDAP server's TCP port (default 389) Chris@0: # * :auth => a Hash containing authorization parameters. Currently supported values include: Chris@0: # {:method => :anonymous} and Chris@0: # {:method => :simple, :username => your_user_name, :password => your_password } Chris@0: # The password parameter may be a Proc that returns a String. Chris@0: # * :base => a default treebase parameter for searches performed against the LDAP server. If you don't give this value, then each call to #search must specify a treebase parameter. If you do give this value, then it will be used in subsequent calls to #search that do not specify a treebase. If you give a treebase value in any particular call to #search, that value will override any treebase value you give here. Chris@0: # * :encryption => specifies the encryption to be used in communicating with the LDAP server. The value is either a Hash containing additional parameters, or the Symbol :simple_tls, which is equivalent to specifying the Hash {:method => :simple_tls}. There is a fairly large range of potential values that may be given for this parameter. See #encryption for details. Chris@0: # Chris@0: # Instantiating a Net::LDAP object does not result in network traffic to Chris@0: # the LDAP server. It simply stores the connection and binding parameters in the Chris@0: # object. Chris@0: # Chris@0: def initialize args = {} Chris@0: @host = args[:host] || DefaultHost Chris@0: @port = args[:port] || DefaultPort Chris@0: @verbose = false # Make this configurable with a switch on the class. Chris@0: @auth = args[:auth] || DefaultAuth Chris@0: @base = args[:base] || DefaultTreebase Chris@0: encryption args[:encryption] # may be nil Chris@0: Chris@0: if pr = @auth[:password] and pr.respond_to?(:call) Chris@0: @auth[:password] = pr.call Chris@0: end Chris@0: Chris@0: # This variable is only set when we are created with LDAP::open. Chris@0: # All of our internal methods will connect using it, or else Chris@0: # they will create their own. Chris@0: @open_connection = nil Chris@0: end Chris@0: Chris@0: # Convenience method to specify authentication credentials to the LDAP Chris@0: # server. Currently supports simple authentication requiring Chris@0: # a username and password. Chris@0: # Chris@0: # Observe that on most LDAP servers, Chris@0: # the username is a complete DN. However, with A/D, it's often possible Chris@0: # to give only a user-name rather than a complete DN. In the latter Chris@0: # case, beware that many A/D servers are configured to permit anonymous Chris@0: # (uncredentialled) binding, and will silently accept your binding Chris@0: # as anonymous if you give an unrecognized username. This is not usually Chris@0: # what you want. (See #get_operation_result.) Chris@0: # Chris@0: # Important: The password argument may be a Proc that returns a string. Chris@0: # This makes it possible for you to write client programs that solicit Chris@0: # passwords from users or from other data sources without showing them Chris@0: # in your code or on command lines. Chris@0: # Chris@0: # require 'net/ldap' Chris@0: # Chris@0: # ldap = Net::LDAP.new Chris@0: # ldap.host = server_ip_address Chris@0: # ldap.authenticate "cn=Your Username,cn=Users,dc=example,dc=com", "your_psw" Chris@0: # Chris@0: # Alternatively (with a password block): Chris@0: # Chris@0: # require 'net/ldap' Chris@0: # Chris@0: # ldap = Net::LDAP.new Chris@0: # ldap.host = server_ip_address Chris@0: # psw = proc { your_psw_function } Chris@0: # ldap.authenticate "cn=Your Username,cn=Users,dc=example,dc=com", psw Chris@0: # Chris@0: def authenticate username, password Chris@0: password = password.call if password.respond_to?(:call) Chris@0: @auth = {:method => :simple, :username => username, :password => password} Chris@0: end Chris@0: Chris@0: alias_method :auth, :authenticate Chris@0: Chris@0: # Convenience method to specify encryption characteristics for connections Chris@0: # to LDAP servers. Called implicitly by #new and #open, but may also be called Chris@0: # by user code if desired. Chris@0: # The single argument is generally a Hash (but see below for convenience alternatives). Chris@0: # This implementation is currently a stub, supporting only a few encryption Chris@0: # alternatives. As additional capabilities are added, more configuration values Chris@0: # will be added here. Chris@0: # Chris@0: # Currently, the only supported argument is {:method => :simple_tls}. Chris@0: # (Equivalently, you may pass the symbol :simple_tls all by itself, without Chris@0: # enclosing it in a Hash.) Chris@0: # Chris@0: # The :simple_tls encryption method encrypts all communications with the LDAP Chris@0: # server. Chris@0: # It completely establishes SSL/TLS encryption with the LDAP server Chris@0: # before any LDAP-protocol data is exchanged. Chris@0: # There is no plaintext negotiation and no special encryption-request controls Chris@0: # are sent to the server. Chris@0: # The :simple_tls option is the simplest, easiest way to encrypt communications Chris@0: # between Net::LDAP and LDAP servers. Chris@0: # It's intended for cases where you have an implicit level of trust in the authenticity Chris@0: # of the LDAP server. No validation of the LDAP server's SSL certificate is Chris@0: # performed. This means that :simple_tls will not produce errors if the LDAP Chris@0: # server's encryption certificate is not signed by a well-known Certification Chris@0: # Authority. Chris@0: # If you get communications or protocol errors when using this option, check Chris@0: # with your LDAP server administrator. Pay particular attention to the TCP port Chris@0: # you are connecting to. It's impossible for an LDAP server to support plaintext Chris@0: # LDAP communications and simple TLS connections on the same port. Chris@0: # The standard TCP port for unencrypted LDAP connections is 389, but the standard Chris@0: # port for simple-TLS encrypted connections is 636. Be sure you are using the Chris@0: # correct port. Chris@0: # Chris@0: # [Note: a future version of Net::LDAP will support the STARTTLS LDAP control, Chris@0: # which will enable encrypted communications on the same TCP port used for Chris@0: # unencrypted connections.] Chris@0: # Chris@0: def encryption args Chris@0: if args == :simple_tls Chris@0: args = {:method => :simple_tls} Chris@0: end Chris@0: @encryption = args Chris@0: end Chris@0: Chris@0: Chris@0: # #open takes the same parameters as #new. #open makes a network connection to the Chris@0: # LDAP server and then passes a newly-created Net::LDAP object to the caller-supplied block. Chris@0: # Within the block, you can call any of the instance methods of Net::LDAP to Chris@0: # perform operations against the LDAP directory. #open will perform all the Chris@0: # operations in the user-supplied block on the same network connection, which Chris@0: # will be closed automatically when the block finishes. Chris@0: # Chris@0: # # (PSEUDOCODE) Chris@0: # auth = {:method => :simple, :username => username, :password => password} Chris@0: # Net::LDAP.open( :host => ipaddress, :port => 389, :auth => auth ) do |ldap| Chris@0: # ldap.search( ... ) Chris@0: # ldap.add( ... ) Chris@0: # ldap.modify( ... ) Chris@0: # end Chris@0: # Chris@0: def LDAP::open args Chris@0: ldap1 = LDAP.new args Chris@0: ldap1.open {|ldap| yield ldap } Chris@0: end Chris@0: Chris@0: # Returns a meaningful result any time after Chris@0: # a protocol operation (#bind, #search, #add, #modify, #rename, #delete) Chris@0: # has completed. Chris@0: # It returns an #OpenStruct containing an LDAP result code (0 means success), Chris@0: # and a human-readable string. Chris@0: # unless ldap.bind Chris@0: # puts "Result: #{ldap.get_operation_result.code}" Chris@0: # puts "Message: #{ldap.get_operation_result.message}" Chris@0: # end Chris@0: # Chris@0: def get_operation_result Chris@0: os = OpenStruct.new Chris@0: if @result Chris@0: os.code = @result Chris@0: else Chris@0: os.code = 0 Chris@0: end Chris@0: os.message = LDAP.result2string( os.code ) Chris@0: os Chris@0: end Chris@0: Chris@0: Chris@0: # Opens a network connection to the server and then Chris@0: # passes self to the caller-supplied block. The connection is Chris@0: # closed when the block completes. Used for executing multiple Chris@0: # LDAP operations without requiring a separate network connection Chris@0: # (and authentication) for each one. Chris@0: # Note: You do not need to log-in or "bind" to the server. This will Chris@0: # be done for you automatically. Chris@0: # For an even simpler approach, see the class method Net::LDAP#open. Chris@0: # Chris@0: # # (PSEUDOCODE) Chris@0: # auth = {:method => :simple, :username => username, :password => password} Chris@0: # ldap = Net::LDAP.new( :host => ipaddress, :port => 389, :auth => auth ) Chris@0: # ldap.open do |ldap| Chris@0: # ldap.search( ... ) Chris@0: # ldap.add( ... ) Chris@0: # ldap.modify( ... ) Chris@0: # end Chris@0: #-- Chris@0: # First we make a connection and then a binding, but we don't Chris@0: # do anything with the bind results. Chris@0: # We then pass self to the caller's block, where he will execute Chris@0: # his LDAP operations. Of course they will all generate auth failures Chris@0: # if the bind was unsuccessful. Chris@0: def open Chris@0: raise LdapError.new( "open already in progress" ) if @open_connection Chris@0: @open_connection = Connection.new( :host => @host, :port => @port, :encryption => @encryption ) Chris@0: @open_connection.bind @auth Chris@0: yield self Chris@0: @open_connection.close Chris@0: @open_connection = nil Chris@0: end Chris@0: Chris@0: Chris@0: # Searches the LDAP directory for directory entries. Chris@0: # Takes a hash argument with parameters. Supported parameters include: Chris@0: # * :base (a string specifying the tree-base for the search); Chris@0: # * :filter (an object of type Net::LDAP::Filter, defaults to objectclass=*); Chris@0: # * :attributes (a string or array of strings specifying the LDAP attributes to return from the server); Chris@0: # * :return_result (a boolean specifying whether to return a result set). Chris@0: # * :attributes_only (a boolean flag, defaults false) Chris@0: # * :scope (one of: Net::LDAP::SearchScope_BaseObject, Net::LDAP::SearchScope_SingleLevel, Net::LDAP::SearchScope_WholeSubtree. Default is WholeSubtree.) Chris@0: # Chris@0: # #search queries the LDAP server and passes each entry to the Chris@0: # caller-supplied block, as an object of type Net::LDAP::Entry. Chris@0: # If the search returns 1000 entries, the block will Chris@0: # be called 1000 times. If the search returns no entries, the block will Chris@0: # not be called. Chris@0: # Chris@0: #-- Chris@0: # ORIGINAL TEXT, replaced 04May06. Chris@0: # #search returns either a result-set or a boolean, depending on the Chris@0: # value of the :return_result argument. The default behavior is to return Chris@0: # a result set, which is a hash. Each key in the hash is a string specifying Chris@0: # the DN of an entry. The corresponding value for each key is a Net::LDAP::Entry object. Chris@0: # If you request a result set and #search fails with an error, it will return nil. Chris@0: # Call #get_operation_result to get the error information returned by Chris@0: # the LDAP server. Chris@0: #++ Chris@0: # #search returns either a result-set or a boolean, depending on the Chris@0: # value of the :return_result argument. The default behavior is to return Chris@0: # a result set, which is an Array of objects of class Net::LDAP::Entry. Chris@0: # If you request a result set and #search fails with an error, it will return nil. Chris@0: # Call #get_operation_result to get the error information returned by Chris@0: # the LDAP server. Chris@0: # Chris@0: # When :return_result => false, #search will Chris@0: # return only a Boolean, to indicate whether the operation succeeded. This can improve performance Chris@0: # with very large result sets, because the library can discard each entry from memory after Chris@0: # your block processes it. Chris@0: # Chris@0: # Chris@0: # treebase = "dc=example,dc=com" Chris@0: # filter = Net::LDAP::Filter.eq( "mail", "a*.com" ) Chris@0: # attrs = ["mail", "cn", "sn", "objectclass"] Chris@0: # ldap.search( :base => treebase, :filter => filter, :attributes => attrs, :return_result => false ) do |entry| Chris@0: # puts "DN: #{entry.dn}" Chris@0: # entry.each do |attr, values| Chris@0: # puts ".......#{attr}:" Chris@0: # values.each do |value| Chris@0: # puts " #{value}" Chris@0: # end Chris@0: # end Chris@0: # end Chris@0: # Chris@0: #-- Chris@0: # This is a re-implementation of search that replaces the Chris@0: # original one (now renamed searchx and possibly destined to go away). Chris@0: # The difference is that we return a dataset (or nil) from the Chris@0: # call, and pass _each entry_ as it is received from the server Chris@0: # to the caller-supplied block. This will probably make things Chris@0: # far faster as we can do useful work during the network latency Chris@0: # of the search. The downside is that we have no access to the Chris@0: # whole set while processing the blocks, so we can't do stuff Chris@0: # like sort the DNs until after the call completes. Chris@0: # It's also possible that this interacts badly with server timeouts. Chris@0: # We'll have to ensure that something reasonable happens if Chris@0: # the caller has processed half a result set when we throw a timeout Chris@0: # error. Chris@0: # Another important difference is that we return a result set from Chris@0: # this method rather than a T/F indication. Chris@0: # Since this can be very heavy-weight, we define an argument flag Chris@0: # that the caller can set to suppress the return of a result set, Chris@0: # if he's planning to process every entry as it comes from the server. Chris@0: # Chris@0: # REINTERPRETED the result set, 04May06. Originally this was a hash Chris@0: # of entries keyed by DNs. But let's get away from making users Chris@0: # handle DNs. Change it to a plain array. Eventually we may Chris@0: # want to return a Dataset object that delegates to an internal Chris@0: # array, so we can provide sort methods and what-not. Chris@0: # Chris@0: def search args = {} Chris@0: args[:base] ||= @base Chris@0: result_set = (args and args[:return_result] == false) ? nil : [] Chris@0: Chris@0: if @open_connection Chris@0: @result = @open_connection.search( args ) {|entry| Chris@0: result_set << entry if result_set Chris@0: yield( entry ) if block_given? Chris@0: } Chris@0: else Chris@0: @result = 0 Chris@0: conn = Connection.new( :host => @host, :port => @port, :encryption => @encryption ) Chris@0: if (@result = conn.bind( args[:auth] || @auth )) == 0 Chris@0: @result = conn.search( args ) {|entry| Chris@0: result_set << entry if result_set Chris@0: yield( entry ) if block_given? Chris@0: } Chris@0: end Chris@0: conn.close Chris@0: end Chris@0: Chris@0: @result == 0 and result_set Chris@0: end Chris@0: Chris@0: # #bind connects to an LDAP server and requests authentication Chris@0: # based on the :auth parameter passed to #open or #new. Chris@0: # It takes no parameters. Chris@0: # Chris@0: # User code does not need to call #bind directly. It will be called Chris@0: # implicitly by the library whenever you invoke an LDAP operation, Chris@0: # such as #search or #add. Chris@0: # Chris@0: # It is useful, however, to call #bind in your own code when the Chris@0: # only operation you intend to perform against the directory is Chris@0: # to validate a login credential. #bind returns true or false Chris@0: # to indicate whether the binding was successful. Reasons for Chris@0: # failure include malformed or unrecognized usernames and Chris@0: # incorrect passwords. Use #get_operation_result to find out Chris@0: # what happened in case of failure. Chris@0: # Chris@0: # Here's a typical example using #bind to authenticate a Chris@0: # credential which was (perhaps) solicited from the user of a Chris@0: # web site: Chris@0: # Chris@0: # require 'net/ldap' Chris@0: # ldap = Net::LDAP.new Chris@0: # ldap.host = your_server_ip_address Chris@0: # ldap.port = 389 Chris@0: # ldap.auth your_user_name, your_user_password Chris@0: # if ldap.bind Chris@0: # # authentication succeeded Chris@0: # else Chris@0: # # authentication failed Chris@0: # p ldap.get_operation_result Chris@0: # end Chris@0: # Chris@0: # You don't have to create a new instance of Net::LDAP every time Chris@0: # you perform a binding in this way. If you prefer, you can cache the Net::LDAP object Chris@0: # and re-use it to perform subsequent bindings, provided you call Chris@0: # #auth to specify a new credential before calling #bind. Otherwise, you'll Chris@0: # just re-authenticate the previous user! (You don't need to re-set Chris@0: # the values of #host and #port.) As noted in the documentation for #auth, Chris@0: # the password parameter can be a Ruby Proc instead of a String. Chris@0: # Chris@0: #-- Chris@0: # If there is an @open_connection, then perform the bind Chris@0: # on it. Otherwise, connect, bind, and disconnect. Chris@0: # The latter operation is obviously useful only as an auth check. Chris@0: # Chris@0: def bind auth=@auth Chris@0: if @open_connection Chris@0: @result = @open_connection.bind auth Chris@0: else Chris@0: conn = Connection.new( :host => @host, :port => @port , :encryption => @encryption) Chris@0: @result = conn.bind @auth Chris@0: conn.close Chris@0: end Chris@0: Chris@0: @result == 0 Chris@0: end Chris@0: Chris@0: # Chris@0: # #bind_as is for testing authentication credentials. Chris@0: # Chris@0: # As described under #bind, most LDAP servers require that you supply a complete DN Chris@0: # as a binding-credential, along with an authenticator such as a password. Chris@0: # But for many applications (such as authenticating users to a Rails application), Chris@0: # you often don't have a full DN to identify the user. You usually get a simple Chris@0: # identifier like a username or an email address, along with a password. Chris@0: # #bind_as allows you to authenticate these user-identifiers. Chris@0: # Chris@0: # #bind_as is a combination of a search and an LDAP binding. First, it connects and Chris@0: # binds to the directory as normal. Then it searches the directory for an entry Chris@0: # corresponding to the email address, username, or other string that you supply. Chris@0: # If the entry exists, then #bind_as will re-bind as that user with the Chris@0: # password (or other authenticator) that you supply. Chris@0: # Chris@0: # #bind_as takes the same parameters as #search, with the addition of an Chris@0: # authenticator. Currently, this authenticator must be :password. Chris@0: # Its value may be either a String, or a +proc+ that returns a String. Chris@0: # #bind_as returns +false+ on failure. On success, it returns a result set, Chris@0: # just as #search does. This result set is an Array of objects of Chris@0: # type Net::LDAP::Entry. It contains the directory attributes corresponding to Chris@0: # the user. (Just test whether the return value is logically true, if you don't Chris@0: # need this additional information.) Chris@0: # Chris@0: # Here's how you would use #bind_as to authenticate an email address and password: Chris@0: # Chris@0: # require 'net/ldap' Chris@0: # Chris@0: # user,psw = "joe_user@yourcompany.com", "joes_psw" Chris@0: # Chris@0: # ldap = Net::LDAP.new Chris@0: # ldap.host = "192.168.0.100" Chris@0: # ldap.port = 389 Chris@0: # ldap.auth "cn=manager,dc=yourcompany,dc=com", "topsecret" Chris@0: # Chris@0: # result = ldap.bind_as( Chris@0: # :base => "dc=yourcompany,dc=com", Chris@0: # :filter => "(mail=#{user})", Chris@0: # :password => psw Chris@0: # ) Chris@0: # if result Chris@0: # puts "Authenticated #{result.first.dn}" Chris@0: # else Chris@0: # puts "Authentication FAILED." Chris@0: # end Chris@0: def bind_as args={} Chris@0: result = false Chris@0: open {|me| Chris@0: rs = search args Chris@0: if rs and rs.first and dn = rs.first.dn Chris@0: password = args[:password] Chris@0: password = password.call if password.respond_to?(:call) Chris@0: result = rs if bind :method => :simple, :username => dn, :password => password Chris@0: end Chris@0: } Chris@0: result Chris@0: end Chris@0: Chris@0: Chris@0: # Adds a new entry to the remote LDAP server. Chris@0: # Supported arguments: Chris@0: # :dn :: Full DN of the new entry Chris@0: # :attributes :: Attributes of the new entry. Chris@0: # Chris@0: # The attributes argument is supplied as a Hash keyed by Strings or Symbols Chris@0: # giving the attribute name, and mapping to Strings or Arrays of Strings Chris@0: # giving the actual attribute values. Observe that most LDAP directories Chris@0: # enforce schema constraints on the attributes contained in entries. Chris@0: # #add will fail with a server-generated error if your attributes violate Chris@0: # the server-specific constraints. Chris@0: # Here's an example: Chris@0: # Chris@0: # dn = "cn=George Smith,ou=people,dc=example,dc=com" Chris@0: # attr = { Chris@0: # :cn => "George Smith", Chris@0: # :objectclass => ["top", "inetorgperson"], Chris@0: # :sn => "Smith", Chris@0: # :mail => "gsmith@example.com" Chris@0: # } Chris@0: # Net::LDAP.open (:host => host) do |ldap| Chris@0: # ldap.add( :dn => dn, :attributes => attr ) Chris@0: # end Chris@0: # Chris@0: def add args Chris@0: if @open_connection Chris@0: @result = @open_connection.add( args ) Chris@0: else Chris@0: @result = 0 Chris@0: conn = Connection.new( :host => @host, :port => @port, :encryption => @encryption) Chris@0: if (@result = conn.bind( args[:auth] || @auth )) == 0 Chris@0: @result = conn.add( args ) Chris@0: end Chris@0: conn.close Chris@0: end Chris@0: @result == 0 Chris@0: end Chris@0: Chris@0: Chris@0: # Modifies the attribute values of a particular entry on the LDAP directory. Chris@0: # Takes a hash with arguments. Supported arguments are: Chris@0: # :dn :: (the full DN of the entry whose attributes are to be modified) Chris@0: # :operations :: (the modifications to be performed, detailed next) Chris@0: # Chris@0: # This method returns True or False to indicate whether the operation Chris@0: # succeeded or failed, with extended information available by calling Chris@0: # #get_operation_result. Chris@0: # Chris@0: # Also see #add_attribute, #replace_attribute, or #delete_attribute, which Chris@0: # provide simpler interfaces to this functionality. Chris@0: # Chris@0: # The LDAP protocol provides a full and well thought-out set of operations Chris@0: # for changing the values of attributes, but they are necessarily somewhat complex Chris@0: # and not always intuitive. If these instructions are confusing or incomplete, Chris@0: # please send us email or create a bug report on rubyforge. Chris@0: # Chris@0: # The :operations parameter to #modify takes an array of operation-descriptors. Chris@0: # Each individual operation is specified in one element of the array, and Chris@0: # most LDAP servers will attempt to perform the operations in order. Chris@0: # Chris@0: # Each of the operations appearing in the Array must itself be an Array Chris@0: # with exactly three elements: Chris@0: # an operator:: must be :add, :replace, or :delete Chris@0: # an attribute name:: the attribute name (string or symbol) to modify Chris@0: # a value:: either a string or an array of strings. Chris@0: # Chris@0: # The :add operator will, unsurprisingly, add the specified values to Chris@0: # the specified attribute. If the attribute does not already exist, Chris@0: # :add will create it. Most LDAP servers will generate an error if you Chris@0: # try to add a value that already exists. Chris@0: # Chris@0: # :replace will erase the current value(s) for the specified attribute, Chris@0: # if there are any, and replace them with the specified value(s). Chris@0: # Chris@0: # :delete will remove the specified value(s) from the specified attribute. Chris@0: # If you pass nil, an empty string, or an empty array as the value parameter Chris@0: # to a :delete operation, the _entire_ _attribute_ will be deleted, along Chris@0: # with all of its values. Chris@0: # Chris@0: # For example: Chris@0: # Chris@0: # dn = "mail=modifyme@example.com,ou=people,dc=example,dc=com" Chris@0: # ops = [ Chris@0: # [:add, :mail, "aliasaddress@example.com"], Chris@0: # [:replace, :mail, ["newaddress@example.com", "newalias@example.com"]], Chris@0: # [:delete, :sn, nil] Chris@0: # ] Chris@0: # ldap.modify :dn => dn, :operations => ops Chris@0: # Chris@0: # (This example is contrived since you probably wouldn't add a mail Chris@0: # value right before replacing the whole attribute, but it shows that order Chris@0: # of execution matters. Also, many LDAP servers won't let you delete SN Chris@0: # because that would be a schema violation.) Chris@0: # Chris@0: # It's essential to keep in mind that if you specify more than one operation in Chris@0: # a call to #modify, most LDAP servers will attempt to perform all of the operations Chris@0: # in the order you gave them. Chris@0: # This matters because you may specify operations on the Chris@0: # same attribute which must be performed in a certain order. Chris@0: # Chris@0: # Most LDAP servers will _stop_ processing your modifications if one of them Chris@0: # causes an error on the server (such as a schema-constraint violation). Chris@0: # If this happens, you will probably get a result code from the server that Chris@0: # reflects only the operation that failed, and you may or may not get extended Chris@0: # information that will tell you which one failed. #modify has no notion Chris@0: # of an atomic transaction. If you specify a chain of modifications in one Chris@0: # call to #modify, and one of them fails, the preceding ones will usually Chris@0: # not be "rolled back," resulting in a partial update. This is a limitation Chris@0: # of the LDAP protocol, not of Net::LDAP. Chris@0: # Chris@0: # The lack of transactional atomicity in LDAP means that you're usually Chris@0: # better off using the convenience methods #add_attribute, #replace_attribute, Chris@0: # and #delete_attribute, which are are wrappers over #modify. However, certain Chris@0: # LDAP servers may provide concurrency semantics, in which the several operations Chris@0: # contained in a single #modify call are not interleaved with other Chris@0: # modification-requests received simultaneously by the server. Chris@0: # It bears repeating that this concurrency does _not_ imply transactional Chris@0: # atomicity, which LDAP does not provide. Chris@0: # Chris@0: def modify args Chris@0: if @open_connection Chris@0: @result = @open_connection.modify( args ) Chris@0: else Chris@0: @result = 0 Chris@0: conn = Connection.new( :host => @host, :port => @port, :encryption => @encryption ) Chris@0: if (@result = conn.bind( args[:auth] || @auth )) == 0 Chris@0: @result = conn.modify( args ) Chris@0: end Chris@0: conn.close Chris@0: end Chris@0: @result == 0 Chris@0: end Chris@0: Chris@0: Chris@0: # Add a value to an attribute. Chris@0: # Takes the full DN of the entry to modify, Chris@0: # the name (Symbol or String) of the attribute, and the value (String or Chris@0: # Array). If the attribute does not exist (and there are no schema violations), Chris@0: # #add_attribute will create it with the caller-specified values. Chris@0: # If the attribute already exists (and there are no schema violations), the Chris@0: # caller-specified values will be _added_ to the values already present. Chris@0: # Chris@0: # Returns True or False to indicate whether the operation Chris@0: # succeeded or failed, with extended information available by calling Chris@0: # #get_operation_result. See also #replace_attribute and #delete_attribute. Chris@0: # Chris@0: # dn = "cn=modifyme,dc=example,dc=com" Chris@0: # ldap.add_attribute dn, :mail, "newmailaddress@example.com" Chris@0: # Chris@0: def add_attribute dn, attribute, value Chris@0: modify :dn => dn, :operations => [[:add, attribute, value]] Chris@0: end Chris@0: Chris@0: # Replace the value of an attribute. Chris@0: # #replace_attribute can be thought of as equivalent to calling #delete_attribute Chris@0: # followed by #add_attribute. It takes the full DN of the entry to modify, Chris@0: # the name (Symbol or String) of the attribute, and the value (String or Chris@0: # Array). If the attribute does not exist, it will be created with the Chris@0: # caller-specified value(s). If the attribute does exist, its values will be Chris@0: # _discarded_ and replaced with the caller-specified values. Chris@0: # Chris@0: # Returns True or False to indicate whether the operation Chris@0: # succeeded or failed, with extended information available by calling Chris@0: # #get_operation_result. See also #add_attribute and #delete_attribute. Chris@0: # Chris@0: # dn = "cn=modifyme,dc=example,dc=com" Chris@0: # ldap.replace_attribute dn, :mail, "newmailaddress@example.com" Chris@0: # Chris@0: def replace_attribute dn, attribute, value Chris@0: modify :dn => dn, :operations => [[:replace, attribute, value]] Chris@0: end Chris@0: Chris@0: # Delete an attribute and all its values. Chris@0: # Takes the full DN of the entry to modify, and the Chris@0: # name (Symbol or String) of the attribute to delete. Chris@0: # Chris@0: # Returns True or False to indicate whether the operation Chris@0: # succeeded or failed, with extended information available by calling Chris@0: # #get_operation_result. See also #add_attribute and #replace_attribute. Chris@0: # Chris@0: # dn = "cn=modifyme,dc=example,dc=com" Chris@0: # ldap.delete_attribute dn, :mail Chris@0: # Chris@0: def delete_attribute dn, attribute Chris@0: modify :dn => dn, :operations => [[:delete, attribute, nil]] Chris@0: end Chris@0: Chris@0: Chris@0: # Rename an entry on the remote DIS by changing the last RDN of its DN. Chris@0: # _Documentation_ _stub_ Chris@0: # Chris@0: def rename args Chris@0: if @open_connection Chris@0: @result = @open_connection.rename( args ) Chris@0: else Chris@0: @result = 0 Chris@0: conn = Connection.new( :host => @host, :port => @port, :encryption => @encryption ) Chris@0: if (@result = conn.bind( args[:auth] || @auth )) == 0 Chris@0: @result = conn.rename( args ) Chris@0: end Chris@0: conn.close Chris@0: end Chris@0: @result == 0 Chris@0: end Chris@0: Chris@0: # modify_rdn is an alias for #rename. Chris@0: def modify_rdn args Chris@0: rename args Chris@0: end Chris@0: Chris@0: # Delete an entry from the LDAP directory. Chris@0: # Takes a hash of arguments. Chris@0: # The only supported argument is :dn, which must Chris@0: # give the complete DN of the entry to be deleted. Chris@0: # Returns True or False to indicate whether the delete Chris@0: # succeeded. Extended status information is available by Chris@0: # calling #get_operation_result. Chris@0: # Chris@0: # dn = "mail=deleteme@example.com,ou=people,dc=example,dc=com" Chris@0: # ldap.delete :dn => dn Chris@0: # Chris@0: def delete args Chris@0: if @open_connection Chris@0: @result = @open_connection.delete( args ) Chris@0: else Chris@0: @result = 0 Chris@0: conn = Connection.new( :host => @host, :port => @port, :encryption => @encryption ) Chris@0: if (@result = conn.bind( args[:auth] || @auth )) == 0 Chris@0: @result = conn.delete( args ) Chris@0: end Chris@0: conn.close Chris@0: end Chris@0: @result == 0 Chris@0: end Chris@0: Chris@0: end # class LDAP Chris@0: Chris@0: Chris@0: Chris@0: class LDAP Chris@0: # This is a private class used internally by the library. It should not be called by user code. Chris@0: class Connection # :nodoc: Chris@0: Chris@0: LdapVersion = 3 Chris@0: Chris@0: Chris@0: #-- Chris@0: # initialize Chris@0: # Chris@0: def initialize server Chris@0: begin Chris@0: @conn = TCPsocket.new( server[:host], server[:port] ) Chris@0: rescue Chris@0: raise LdapError.new( "no connection to server" ) Chris@0: end Chris@0: Chris@0: if server[:encryption] Chris@0: setup_encryption server[:encryption] Chris@0: end Chris@0: Chris@0: yield self if block_given? Chris@0: end Chris@0: Chris@0: Chris@0: #-- Chris@0: # Helper method called only from new, and only after we have a successfully-opened Chris@0: # @conn instance variable, which is a TCP connection. Chris@0: # Depending on the received arguments, we establish SSL, potentially replacing Chris@0: # the value of @conn accordingly. Chris@0: # Don't generate any errors here if no encryption is requested. Chris@0: # DO raise LdapError objects if encryption is requested and we have trouble setting Chris@0: # it up. That includes if OpenSSL is not set up on the machine. (Question: Chris@0: # how does the Ruby OpenSSL wrapper react in that case?) Chris@0: # DO NOT filter exceptions raised by the OpenSSL library. Let them pass back Chris@0: # to the user. That should make it easier for us to debug the problem reports. Chris@0: # Presumably (hopefully?) that will also produce recognizable errors if someone Chris@0: # tries to use this on a machine without OpenSSL. Chris@0: # Chris@0: # The simple_tls method is intended as the simplest, stupidest, easiest solution Chris@0: # for people who want nothing more than encrypted comms with the LDAP server. Chris@0: # It doesn't do any server-cert validation and requires nothing in the way Chris@0: # of key files and root-cert files, etc etc. Chris@0: # OBSERVE: WE REPLACE the value of @conn, which is presumed to be a connected Chris@0: # TCPsocket object. Chris@0: # Chris@0: def setup_encryption args Chris@0: case args[:method] Chris@0: when :simple_tls Chris@0: raise LdapError.new("openssl unavailable") unless $net_ldap_openssl_available Chris@0: ctx = OpenSSL::SSL::SSLContext.new Chris@0: @conn = OpenSSL::SSL::SSLSocket.new(@conn, ctx) Chris@0: @conn.connect Chris@0: @conn.sync_close = true Chris@0: # additional branches requiring server validation and peer certs, etc. go here. Chris@0: else Chris@0: raise LdapError.new( "unsupported encryption method #{args[:method]}" ) Chris@0: end Chris@0: end Chris@0: Chris@0: #-- Chris@0: # close Chris@0: # This is provided as a convenience method to make Chris@0: # sure a connection object gets closed without waiting Chris@0: # for a GC to happen. Clients shouldn't have to call it, Chris@0: # but perhaps it will come in handy someday. Chris@0: def close Chris@0: @conn.close Chris@0: @conn = nil Chris@0: end Chris@0: Chris@0: #-- Chris@0: # next_msgid Chris@0: # Chris@0: def next_msgid Chris@0: @msgid ||= 0 Chris@0: @msgid += 1 Chris@0: end Chris@0: Chris@0: Chris@0: #-- Chris@0: # bind Chris@0: # Chris@0: def bind auth Chris@0: user,psw = case auth[:method] Chris@0: when :anonymous Chris@0: ["",""] Chris@0: when :simple Chris@0: [auth[:username] || auth[:dn], auth[:password]] Chris@0: end Chris@0: raise LdapError.new( "invalid binding information" ) unless (user && psw) Chris@0: Chris@0: msgid = next_msgid.to_ber Chris@0: request = [LdapVersion.to_ber, user.to_ber, psw.to_ber_contextspecific(0)].to_ber_appsequence(0) Chris@0: request_pkt = [msgid, request].to_ber_sequence Chris@0: @conn.write request_pkt Chris@0: Chris@0: (be = @conn.read_ber(AsnSyntax) and pdu = Net::LdapPdu.new( be )) or raise LdapError.new( "no bind result" ) Chris@0: pdu.result_code Chris@0: end Chris@0: Chris@0: #-- Chris@0: # search Chris@0: # Alternate implementation, this yields each search entry to the caller Chris@0: # as it are received. Chris@0: # TODO, certain search parameters are hardcoded. Chris@0: # TODO, if we mis-parse the server results or the results are wrong, we can block Chris@0: # forever. That's because we keep reading results until we get a type-5 packet, Chris@0: # which might never come. We need to support the time-limit in the protocol. Chris@0: #-- Chris@0: # WARNING: this code substantially recapitulates the searchx method. Chris@0: # Chris@0: # 02May06: Well, I added support for RFC-2696-style paged searches. Chris@0: # This is used on all queries because the extension is marked non-critical. Chris@0: # As far as I know, only A/D uses this, but it's required for A/D. Otherwise Chris@0: # you won't get more than 1000 results back from a query. Chris@0: # This implementation is kindof clunky and should probably be refactored. Chris@0: # Also, is it my imagination, or are A/Ds the slowest directory servers ever??? Chris@0: # Chris@0: def search args = {} Chris@0: search_filter = (args && args[:filter]) || Filter.eq( "objectclass", "*" ) Chris@0: search_filter = Filter.construct(search_filter) if search_filter.is_a?(String) Chris@0: search_base = (args && args[:base]) || "dc=example,dc=com" Chris@0: search_attributes = ((args && args[:attributes]) || []).map {|attr| attr.to_s.to_ber} Chris@0: return_referrals = args && args[:return_referrals] == true Chris@0: Chris@0: attributes_only = (args and args[:attributes_only] == true) Chris@0: scope = args[:scope] || Net::LDAP::SearchScope_WholeSubtree Chris@0: raise LdapError.new( "invalid search scope" ) unless SearchScopes.include?(scope) Chris@0: Chris@0: # An interesting value for the size limit would be close to A/D's built-in Chris@0: # page limit of 1000 records, but openLDAP newer than version 2.2.0 chokes Chris@0: # on anything bigger than 126. You get a silent error that is easily visible Chris@0: # by running slapd in debug mode. Go figure. Chris@0: rfc2696_cookie = [126, ""] Chris@0: result_code = 0 Chris@0: Chris@0: loop { Chris@0: # should collect this into a private helper to clarify the structure Chris@0: Chris@0: request = [ Chris@0: search_base.to_ber, Chris@0: scope.to_ber_enumerated, Chris@0: 0.to_ber_enumerated, Chris@0: 0.to_ber, Chris@0: 0.to_ber, Chris@0: attributes_only.to_ber, Chris@0: search_filter.to_ber, Chris@0: search_attributes.to_ber_sequence Chris@0: ].to_ber_appsequence(3) Chris@0: Chris@0: controls = [ Chris@0: [ Chris@0: LdapControls::PagedResults.to_ber, Chris@0: false.to_ber, # criticality MUST be false to interoperate with normal LDAPs. Chris@0: rfc2696_cookie.map{|v| v.to_ber}.to_ber_sequence.to_s.to_ber Chris@0: ].to_ber_sequence Chris@0: ].to_ber_contextspecific(0) Chris@0: Chris@0: pkt = [next_msgid.to_ber, request, controls].to_ber_sequence Chris@0: @conn.write pkt Chris@0: Chris@0: result_code = 0 Chris@0: controls = [] Chris@0: Chris@0: while (be = @conn.read_ber(AsnSyntax)) && (pdu = LdapPdu.new( be )) Chris@0: case pdu.app_tag Chris@0: when 4 # search-data Chris@0: yield( pdu.search_entry ) if block_given? Chris@0: when 19 # search-referral Chris@0: if return_referrals Chris@0: if block_given? Chris@0: se = Net::LDAP::Entry.new Chris@0: se[:search_referrals] = (pdu.search_referrals || []) Chris@0: yield se Chris@0: end Chris@0: end Chris@0: #p pdu.referrals Chris@0: when 5 # search-result Chris@0: result_code = pdu.result_code Chris@0: controls = pdu.result_controls Chris@0: break Chris@0: else Chris@0: raise LdapError.new( "invalid response-type in search: #{pdu.app_tag}" ) Chris@0: end Chris@0: end Chris@0: Chris@0: # When we get here, we have seen a type-5 response. Chris@0: # If there is no error AND there is an RFC-2696 cookie, Chris@0: # then query again for the next page of results. Chris@0: # If not, we're done. Chris@0: # Don't screw this up or we'll break every search we do. Chris@0: more_pages = false Chris@0: if result_code == 0 and controls Chris@0: controls.each do |c| Chris@0: if c.oid == LdapControls::PagedResults Chris@0: more_pages = false # just in case some bogus server sends us >1 of these. Chris@0: if c.value and c.value.length > 0 Chris@0: cookie = c.value.read_ber[1] Chris@0: if cookie and cookie.length > 0 Chris@0: rfc2696_cookie[1] = cookie Chris@0: more_pages = true Chris@0: end Chris@0: end Chris@0: end Chris@0: end Chris@0: end Chris@0: Chris@0: break unless more_pages Chris@0: } # loop Chris@0: Chris@0: result_code Chris@0: end Chris@0: Chris@0: Chris@0: Chris@0: Chris@0: #-- Chris@0: # modify Chris@0: # TODO, need to support a time limit, in case the server fails to respond. Chris@0: # TODO!!! We're throwing an exception here on empty DN. Chris@0: # Should return a proper error instead, probaby from farther up the chain. Chris@0: # TODO!!! If the user specifies a bogus opcode, we'll throw a Chris@0: # confusing error here ("to_ber_enumerated is not defined on nil"). Chris@0: # Chris@0: def modify args Chris@0: modify_dn = args[:dn] or raise "Unable to modify empty DN" Chris@0: modify_ops = [] Chris@0: a = args[:operations] and a.each {|op, attr, values| Chris@0: # TODO, fix the following line, which gives a bogus error Chris@0: # if the opcode is invalid. Chris@0: op_1 = {:add => 0, :delete => 1, :replace => 2} [op.to_sym].to_ber_enumerated Chris@0: modify_ops << [op_1, [attr.to_s.to_ber, values.to_a.map {|v| v.to_ber}.to_ber_set].to_ber_sequence].to_ber_sequence Chris@0: } Chris@0: Chris@0: request = [modify_dn.to_ber, modify_ops.to_ber_sequence].to_ber_appsequence(6) Chris@0: pkt = [next_msgid.to_ber, request].to_ber_sequence Chris@0: @conn.write pkt Chris@0: Chris@0: (be = @conn.read_ber(AsnSyntax)) && (pdu = LdapPdu.new( be )) && (pdu.app_tag == 7) or raise LdapError.new( "response missing or invalid" ) Chris@0: pdu.result_code Chris@0: end Chris@0: Chris@0: Chris@0: #-- Chris@0: # add Chris@0: # TODO, need to support a time limit, in case the server fails to respond. Chris@0: # Chris@0: def add args Chris@0: add_dn = args[:dn] or raise LdapError.new("Unable to add empty DN") Chris@0: add_attrs = [] Chris@0: a = args[:attributes] and a.each {|k,v| Chris@0: add_attrs << [ k.to_s.to_ber, v.to_a.map {|m| m.to_ber}.to_ber_set ].to_ber_sequence Chris@0: } Chris@0: Chris@0: request = [add_dn.to_ber, add_attrs.to_ber_sequence].to_ber_appsequence(8) Chris@0: pkt = [next_msgid.to_ber, request].to_ber_sequence Chris@0: @conn.write pkt Chris@0: Chris@0: (be = @conn.read_ber(AsnSyntax)) && (pdu = LdapPdu.new( be )) && (pdu.app_tag == 9) or raise LdapError.new( "response missing or invalid" ) Chris@0: pdu.result_code Chris@0: end Chris@0: Chris@0: Chris@0: #-- Chris@0: # rename Chris@0: # TODO, need to support a time limit, in case the server fails to respond. Chris@0: # Chris@0: def rename args Chris@0: old_dn = args[:olddn] or raise "Unable to rename empty DN" Chris@0: new_rdn = args[:newrdn] or raise "Unable to rename to empty RDN" Chris@0: delete_attrs = args[:delete_attributes] ? true : false Chris@0: Chris@0: request = [old_dn.to_ber, new_rdn.to_ber, delete_attrs.to_ber].to_ber_appsequence(12) Chris@0: pkt = [next_msgid.to_ber, request].to_ber_sequence Chris@0: @conn.write pkt Chris@0: Chris@0: (be = @conn.read_ber(AsnSyntax)) && (pdu = LdapPdu.new( be )) && (pdu.app_tag == 13) or raise LdapError.new( "response missing or invalid" ) Chris@0: pdu.result_code Chris@0: end Chris@0: Chris@0: Chris@0: #-- Chris@0: # delete Chris@0: # TODO, need to support a time limit, in case the server fails to respond. Chris@0: # Chris@0: def delete args Chris@0: dn = args[:dn] or raise "Unable to delete empty DN" Chris@0: Chris@0: request = dn.to_s.to_ber_application_string(10) Chris@0: pkt = [next_msgid.to_ber, request].to_ber_sequence Chris@0: @conn.write pkt Chris@0: Chris@0: (be = @conn.read_ber(AsnSyntax)) && (pdu = LdapPdu.new( be )) && (pdu.app_tag == 11) or raise LdapError.new( "response missing or invalid" ) Chris@0: pdu.result_code Chris@0: end Chris@0: Chris@0: Chris@0: end # class Connection Chris@0: end # class LDAP Chris@0: Chris@0: Chris@0: end # module Net Chris@0: Chris@0: