annotate vendor/plugins/ruby-net-ldap-0.0.4/lib/net/ldap.rb @ 904:0a8317a50fa0 redmine-1.1

Close obsolete branch redmine-1.1
author Chris Cannam
date Fri, 14 Jan 2011 12:53:21 +0000
parents 513646585e45
children
rev   line source
Chris@0 1 # $Id: ldap.rb 154 2006-08-15 09:35:43Z blackhedd $
Chris@0 2 #
Chris@0 3 # Net::LDAP for Ruby
Chris@0 4 #
Chris@0 5 #
Chris@0 6 # Copyright (C) 2006 by Francis Cianfrocca. All Rights Reserved.
Chris@0 7 #
Chris@0 8 # Written and maintained by Francis Cianfrocca, gmail: garbagecat10.
Chris@0 9 #
Chris@0 10 # This program is free software.
Chris@0 11 # You may re-distribute and/or modify this program under the same terms
Chris@0 12 # as Ruby itself: Ruby Distribution License or GNU General Public License.
Chris@0 13 #
Chris@0 14 #
Chris@0 15 # See Net::LDAP for documentation and usage samples.
Chris@0 16 #
Chris@0 17
Chris@0 18
Chris@0 19 require 'socket'
Chris@0 20 require 'ostruct'
Chris@0 21
Chris@0 22 begin
Chris@0 23 require 'openssl'
Chris@0 24 $net_ldap_openssl_available = true
Chris@0 25 rescue LoadError
Chris@0 26 end
Chris@0 27
Chris@0 28 require 'net/ber'
Chris@0 29 require 'net/ldap/pdu'
Chris@0 30 require 'net/ldap/filter'
Chris@0 31 require 'net/ldap/dataset'
Chris@0 32 require 'net/ldap/psw'
Chris@0 33 require 'net/ldap/entry'
Chris@0 34
Chris@0 35
Chris@0 36 module Net
Chris@0 37
Chris@0 38
Chris@0 39 # == Net::LDAP
Chris@0 40 #
Chris@0 41 # This library provides a pure-Ruby implementation of the
Chris@0 42 # LDAP client protocol, per RFC-2251.
Chris@0 43 # It can be used to access any server which implements the
Chris@0 44 # LDAP protocol.
Chris@0 45 #
Chris@0 46 # Net::LDAP is intended to provide full LDAP functionality
Chris@0 47 # while hiding the more arcane aspects
Chris@0 48 # the LDAP protocol itself, and thus presenting as Ruby-like
Chris@0 49 # a programming interface as possible.
Chris@0 50 #
Chris@0 51 # == Quick-start for the Impatient
Chris@0 52 # === Quick Example of a user-authentication against an LDAP directory:
Chris@0 53 #
Chris@0 54 # require 'rubygems'
Chris@0 55 # require 'net/ldap'
Chris@0 56 #
Chris@0 57 # ldap = Net::LDAP.new
Chris@0 58 # ldap.host = your_server_ip_address
Chris@0 59 # ldap.port = 389
Chris@0 60 # ldap.auth "joe_user", "opensesame"
Chris@0 61 # if ldap.bind
Chris@0 62 # # authentication succeeded
Chris@0 63 # else
Chris@0 64 # # authentication failed
Chris@0 65 # end
Chris@0 66 #
Chris@0 67 #
Chris@0 68 # === Quick Example of a search against an LDAP directory:
Chris@0 69 #
Chris@0 70 # require 'rubygems'
Chris@0 71 # require 'net/ldap'
Chris@0 72 #
Chris@0 73 # ldap = Net::LDAP.new :host => server_ip_address,
Chris@0 74 # :port => 389,
Chris@0 75 # :auth => {
Chris@0 76 # :method => :simple,
Chris@0 77 # :username => "cn=manager,dc=example,dc=com",
Chris@0 78 # :password => "opensesame"
Chris@0 79 # }
Chris@0 80 #
Chris@0 81 # filter = Net::LDAP::Filter.eq( "cn", "George*" )
Chris@0 82 # treebase = "dc=example,dc=com"
Chris@0 83 #
Chris@0 84 # ldap.search( :base => treebase, :filter => filter ) do |entry|
Chris@0 85 # puts "DN: #{entry.dn}"
Chris@0 86 # entry.each do |attribute, values|
Chris@0 87 # puts " #{attribute}:"
Chris@0 88 # values.each do |value|
Chris@0 89 # puts " --->#{value}"
Chris@0 90 # end
Chris@0 91 # end
Chris@0 92 # end
Chris@0 93 #
Chris@0 94 # p ldap.get_operation_result
Chris@0 95 #
Chris@0 96 #
Chris@0 97 # == A Brief Introduction to LDAP
Chris@0 98 #
Chris@0 99 # We're going to provide a quick, informal introduction to LDAP
Chris@0 100 # terminology and
Chris@0 101 # typical operations. If you're comfortable with this material, skip
Chris@0 102 # ahead to "How to use Net::LDAP." If you want a more rigorous treatment
Chris@0 103 # of this material, we recommend you start with the various IETF and ITU
Chris@0 104 # standards that relate to LDAP.
Chris@0 105 #
Chris@0 106 # === Entities
Chris@0 107 # LDAP is an Internet-standard protocol used to access directory servers.
Chris@0 108 # The basic search unit is the <i>entity,</i> which corresponds to
Chris@0 109 # a person or other domain-specific object.
Chris@0 110 # A directory service which supports the LDAP protocol typically
Chris@0 111 # stores information about a number of entities.
Chris@0 112 #
Chris@0 113 # === Principals
Chris@0 114 # LDAP servers are typically used to access information about people,
Chris@0 115 # but also very often about such items as printers, computers, and other
Chris@0 116 # resources. To reflect this, LDAP uses the term <i>entity,</i> or less
Chris@0 117 # commonly, <i>principal,</i> to denote its basic data-storage unit.
Chris@0 118 #
Chris@0 119 #
Chris@0 120 # === Distinguished Names
Chris@0 121 # In LDAP's view of the world,
Chris@0 122 # an entity is uniquely identified by a globally-unique text string
Chris@0 123 # called a <i>Distinguished Name,</i> originally defined in the X.400
Chris@0 124 # standards from which LDAP is ultimately derived.
Chris@0 125 # Much like a DNS hostname, a DN is a "flattened" text representation
Chris@0 126 # of a string of tree nodes. Also like DNS (and unlike Java package
Chris@0 127 # names), a DN expresses a chain of tree-nodes written from left to right
Chris@0 128 # in order from the most-resolved node to the most-general one.
Chris@0 129 #
Chris@0 130 # If you know the DN of a person or other entity, then you can query
Chris@0 131 # an LDAP-enabled directory for information (attributes) about the entity.
Chris@0 132 # Alternatively, you can query the directory for a list of DNs matching
Chris@0 133 # a set of criteria that you supply.
Chris@0 134 #
Chris@0 135 # === Attributes
Chris@0 136 #
Chris@0 137 # In the LDAP view of the world, a DN uniquely identifies an entity.
Chris@0 138 # Information about the entity is stored as a set of <i>Attributes.</i>
Chris@0 139 # An attribute is a text string which is associated with zero or more
Chris@0 140 # values. Most LDAP-enabled directories store a well-standardized
Chris@0 141 # range of attributes, and constrain their values according to standard
Chris@0 142 # rules.
Chris@0 143 #
Chris@0 144 # A good example of an attribute is <tt>sn,</tt> which stands for "Surname."
Chris@0 145 # This attribute is generally used to store a person's surname, or last name.
Chris@0 146 # Most directories enforce the standard convention that
Chris@0 147 # an entity's <tt>sn</tt> attribute have <i>exactly one</i> value. In LDAP
Chris@0 148 # jargon, that means that <tt>sn</tt> must be <i>present</i> and
Chris@0 149 # <i>single-valued.</i>
Chris@0 150 #
Chris@0 151 # Another attribute is <tt>mail,</tt> which is used to store email addresses.
Chris@0 152 # (No, there is no attribute called "email," perhaps because X.400 terminology
Chris@0 153 # predates the invention of the term <i>email.</i>) <tt>mail</tt> differs
Chris@0 154 # from <tt>sn</tt> in that most directories permit any number of values for the
Chris@0 155 # <tt>mail</tt> attribute, including zero.
Chris@0 156 #
Chris@0 157 #
Chris@0 158 # === Tree-Base
Chris@0 159 # We said above that X.400 Distinguished Names are <i>globally unique.</i>
Chris@0 160 # In a manner reminiscent of DNS, LDAP supposes that each directory server
Chris@0 161 # contains authoritative attribute data for a set of DNs corresponding
Chris@0 162 # to a specific sub-tree of the (notional) global directory tree.
Chris@0 163 # This subtree is generally configured into a directory server when it is
Chris@0 164 # created. It matters for this discussion because most servers will not
Chris@0 165 # allow you to query them unless you specify a correct tree-base.
Chris@0 166 #
Chris@0 167 # Let's say you work for the engineering department of Big Company, Inc.,
Chris@0 168 # whose internet domain is bigcompany.com. You may find that your departmental
Chris@0 169 # directory is stored in a server with a defined tree-base of
Chris@0 170 # ou=engineering,dc=bigcompany,dc=com
Chris@0 171 # You will need to supply this string as the <i>tree-base</i> when querying this
Chris@0 172 # directory. (Ou is a very old X.400 term meaning "organizational unit."
Chris@0 173 # Dc is a more recent term meaning "domain component.")
Chris@0 174 #
Chris@0 175 # === LDAP Versions
Chris@0 176 # (stub, discuss v2 and v3)
Chris@0 177 #
Chris@0 178 # === LDAP Operations
Chris@0 179 # The essential operations are: #bind, #search, #add, #modify, #delete, and #rename.
Chris@0 180 # ==== Bind
Chris@0 181 # #bind supplies a user's authentication credentials to a server, which in turn verifies
Chris@0 182 # or rejects them. There is a range of possibilities for credentials, but most directories
Chris@0 183 # support a simple username and password authentication.
Chris@0 184 #
Chris@0 185 # Taken by itself, #bind can be used to authenticate a user against information
Chris@0 186 # stored in a directory, for example to permit or deny access to some other resource.
Chris@0 187 # In terms of the other LDAP operations, most directories require a successful #bind to
Chris@0 188 # be performed before the other operations will be permitted. Some servers permit certain
Chris@0 189 # operations to be performed with an "anonymous" binding, meaning that no credentials are
Chris@0 190 # presented by the user. (We're glossing over a lot of platform-specific detail here.)
Chris@0 191 #
Chris@0 192 # ==== Search
Chris@0 193 # Calling #search against the directory involves specifying a treebase, a set of <i>search filters,</i>
Chris@0 194 # and a list of attribute values.
Chris@0 195 # The filters specify ranges of possible values for particular attributes. Multiple
Chris@0 196 # filters can be joined together with AND, OR, and NOT operators.
Chris@0 197 # A server will respond to a #search by returning a list of matching DNs together with a
Chris@0 198 # set of attribute values for each entity, depending on what attributes the search requested.
Chris@0 199 #
Chris@0 200 # ==== Add
Chris@0 201 # #add specifies a new DN and an initial set of attribute values. If the operation
Chris@0 202 # succeeds, a new entity with the corresponding DN and attributes is added to the directory.
Chris@0 203 #
Chris@0 204 # ==== Modify
Chris@0 205 # #modify specifies an entity DN, and a list of attribute operations. #modify is used to change
Chris@0 206 # the attribute values stored in the directory for a particular entity.
Chris@0 207 # #modify may add or delete attributes (which are lists of values) or it change attributes by
Chris@0 208 # adding to or deleting from their values.
Chris@0 209 # Net::LDAP provides three easier methods to modify an entry's attribute values:
Chris@0 210 # #add_attribute, #replace_attribute, and #delete_attribute.
Chris@0 211 #
Chris@0 212 # ==== Delete
Chris@0 213 # #delete specifies an entity DN. If it succeeds, the entity and all its attributes
Chris@0 214 # is removed from the directory.
Chris@0 215 #
Chris@0 216 # ==== Rename (or Modify RDN)
Chris@0 217 # #rename (or #modify_rdn) is an operation added to version 3 of the LDAP protocol. It responds to
Chris@0 218 # the often-arising need to change the DN of an entity without discarding its attribute values.
Chris@0 219 # In earlier LDAP versions, the only way to do this was to delete the whole entity and add it
Chris@0 220 # again with a different DN.
Chris@0 221 #
Chris@0 222 # #rename works by taking an "old" DN (the one to change) and a "new RDN," which is the left-most
Chris@0 223 # part of the DN string. If successful, #rename changes the entity DN so that its left-most
Chris@0 224 # node corresponds to the new RDN given in the request. (RDN, or "relative distinguished name,"
Chris@0 225 # denotes a single tree-node as expressed in a DN, which is a chain of tree nodes.)
Chris@0 226 #
Chris@0 227 # == How to use Net::LDAP
Chris@0 228 #
Chris@0 229 # To access Net::LDAP functionality in your Ruby programs, start by requiring
Chris@0 230 # the library:
Chris@0 231 #
Chris@0 232 # require 'net/ldap'
Chris@0 233 #
Chris@0 234 # If you installed the Gem version of Net::LDAP, and depending on your version of
Chris@0 235 # Ruby and rubygems, you _may_ also need to require rubygems explicitly:
Chris@0 236 #
Chris@0 237 # require 'rubygems'
Chris@0 238 # require 'net/ldap'
Chris@0 239 #
Chris@0 240 # Most operations with Net::LDAP start by instantiating a Net::LDAP object.
Chris@0 241 # The constructor for this object takes arguments specifying the network location
Chris@0 242 # (address and port) of the LDAP server, and also the binding (authentication)
Chris@0 243 # credentials, typically a username and password.
Chris@0 244 # Given an object of class Net:LDAP, you can then perform LDAP operations by calling
Chris@0 245 # instance methods on the object. These are documented with usage examples below.
Chris@0 246 #
Chris@0 247 # The Net::LDAP library is designed to be very disciplined about how it makes network
Chris@0 248 # connections to servers. This is different from many of the standard native-code
Chris@0 249 # libraries that are provided on most platforms, which share bloodlines with the
Chris@0 250 # original Netscape/Michigan LDAP client implementations. These libraries sought to
Chris@0 251 # insulate user code from the workings of the network. This is a good idea of course,
Chris@0 252 # but the practical effect has been confusing and many difficult bugs have been caused
Chris@0 253 # by the opacity of the native libraries, and their variable behavior across platforms.
Chris@0 254 #
Chris@0 255 # In general, Net::LDAP instance methods which invoke server operations make a connection
Chris@0 256 # to the server when the method is called. They execute the operation (typically binding first)
Chris@0 257 # and then disconnect from the server. The exception is Net::LDAP#open, which makes a connection
Chris@0 258 # to the server and then keeps it open while it executes a user-supplied block. Net::LDAP#open
Chris@0 259 # closes the connection on completion of the block.
Chris@0 260 #
Chris@0 261
Chris@0 262 class LDAP
Chris@0 263
Chris@0 264 class LdapError < Exception; end
Chris@0 265
Chris@0 266 VERSION = "0.0.4"
Chris@0 267
Chris@0 268
Chris@0 269 SearchScope_BaseObject = 0
Chris@0 270 SearchScope_SingleLevel = 1
Chris@0 271 SearchScope_WholeSubtree = 2
Chris@0 272 SearchScopes = [SearchScope_BaseObject, SearchScope_SingleLevel, SearchScope_WholeSubtree]
Chris@0 273
Chris@0 274 AsnSyntax = {
Chris@0 275 :application => {
Chris@0 276 :constructed => {
Chris@0 277 0 => :array, # BindRequest
Chris@0 278 1 => :array, # BindResponse
Chris@0 279 2 => :array, # UnbindRequest
Chris@0 280 3 => :array, # SearchRequest
Chris@0 281 4 => :array, # SearchData
Chris@0 282 5 => :array, # SearchResult
Chris@0 283 6 => :array, # ModifyRequest
Chris@0 284 7 => :array, # ModifyResponse
Chris@0 285 8 => :array, # AddRequest
Chris@0 286 9 => :array, # AddResponse
Chris@0 287 10 => :array, # DelRequest
Chris@0 288 11 => :array, # DelResponse
Chris@0 289 12 => :array, # ModifyRdnRequest
Chris@0 290 13 => :array, # ModifyRdnResponse
Chris@0 291 14 => :array, # CompareRequest
Chris@0 292 15 => :array, # CompareResponse
Chris@0 293 16 => :array, # AbandonRequest
Chris@0 294 19 => :array, # SearchResultReferral
Chris@0 295 24 => :array, # Unsolicited Notification
Chris@0 296 }
Chris@0 297 },
Chris@0 298 :context_specific => {
Chris@0 299 :primitive => {
Chris@0 300 0 => :string, # password
Chris@0 301 1 => :string, # Kerberos v4
Chris@0 302 2 => :string, # Kerberos v5
Chris@0 303 },
Chris@0 304 :constructed => {
Chris@0 305 0 => :array, # RFC-2251 Control
Chris@0 306 3 => :array, # Seach referral
Chris@0 307 }
Chris@0 308 }
Chris@0 309 }
Chris@0 310
Chris@0 311 DefaultHost = "127.0.0.1"
Chris@0 312 DefaultPort = 389
Chris@0 313 DefaultAuth = {:method => :anonymous}
Chris@0 314 DefaultTreebase = "dc=com"
Chris@0 315
Chris@0 316
Chris@0 317 ResultStrings = {
Chris@0 318 0 => "Success",
Chris@0 319 1 => "Operations Error",
Chris@0 320 2 => "Protocol Error",
Chris@0 321 3 => "Time Limit Exceeded",
Chris@0 322 4 => "Size Limit Exceeded",
Chris@0 323 12 => "Unavailable crtical extension",
Chris@0 324 16 => "No Such Attribute",
Chris@0 325 17 => "Undefined Attribute Type",
Chris@0 326 20 => "Attribute or Value Exists",
Chris@0 327 32 => "No Such Object",
Chris@0 328 34 => "Invalid DN Syntax",
Chris@0 329 48 => "Invalid DN Syntax",
Chris@0 330 48 => "Inappropriate Authentication",
Chris@0 331 49 => "Invalid Credentials",
Chris@0 332 50 => "Insufficient Access Rights",
Chris@0 333 51 => "Busy",
Chris@0 334 52 => "Unavailable",
Chris@0 335 53 => "Unwilling to perform",
Chris@0 336 65 => "Object Class Violation",
Chris@0 337 68 => "Entry Already Exists"
Chris@0 338 }
Chris@0 339
Chris@0 340
Chris@0 341 module LdapControls
Chris@0 342 PagedResults = "1.2.840.113556.1.4.319" # Microsoft evil from RFC 2696
Chris@0 343 end
Chris@0 344
Chris@0 345
Chris@0 346 #
Chris@0 347 # LDAP::result2string
Chris@0 348 #
Chris@0 349 def LDAP::result2string code # :nodoc:
Chris@0 350 ResultStrings[code] || "unknown result (#{code})"
Chris@0 351 end
Chris@0 352
Chris@0 353
Chris@0 354 attr_accessor :host, :port, :base
Chris@0 355
Chris@0 356
Chris@0 357 # Instantiate an object of type Net::LDAP to perform directory operations.
Chris@0 358 # 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 359 # are supported:
Chris@0 360 # * :host => the LDAP server's IP-address (default 127.0.0.1)
Chris@0 361 # * :port => the LDAP server's TCP port (default 389)
Chris@0 362 # * :auth => a Hash containing authorization parameters. Currently supported values include:
Chris@0 363 # {:method => :anonymous} and
Chris@0 364 # {:method => :simple, :username => your_user_name, :password => your_password }
Chris@0 365 # The password parameter may be a Proc that returns a String.
Chris@0 366 # * :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 367 # * :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 368 #
Chris@0 369 # Instantiating a Net::LDAP object does <i>not</i> result in network traffic to
Chris@0 370 # the LDAP server. It simply stores the connection and binding parameters in the
Chris@0 371 # object.
Chris@0 372 #
Chris@0 373 def initialize args = {}
Chris@0 374 @host = args[:host] || DefaultHost
Chris@0 375 @port = args[:port] || DefaultPort
Chris@0 376 @verbose = false # Make this configurable with a switch on the class.
Chris@0 377 @auth = args[:auth] || DefaultAuth
Chris@0 378 @base = args[:base] || DefaultTreebase
Chris@0 379 encryption args[:encryption] # may be nil
Chris@0 380
Chris@0 381 if pr = @auth[:password] and pr.respond_to?(:call)
Chris@0 382 @auth[:password] = pr.call
Chris@0 383 end
Chris@0 384
Chris@0 385 # This variable is only set when we are created with LDAP::open.
Chris@0 386 # All of our internal methods will connect using it, or else
Chris@0 387 # they will create their own.
Chris@0 388 @open_connection = nil
Chris@0 389 end
Chris@0 390
Chris@0 391 # Convenience method to specify authentication credentials to the LDAP
Chris@0 392 # server. Currently supports simple authentication requiring
Chris@0 393 # a username and password.
Chris@0 394 #
Chris@0 395 # Observe that on most LDAP servers,
Chris@0 396 # the username is a complete DN. However, with A/D, it's often possible
Chris@0 397 # to give only a user-name rather than a complete DN. In the latter
Chris@0 398 # case, beware that many A/D servers are configured to permit anonymous
Chris@0 399 # (uncredentialled) binding, and will silently accept your binding
Chris@0 400 # as anonymous if you give an unrecognized username. This is not usually
Chris@0 401 # what you want. (See #get_operation_result.)
Chris@0 402 #
Chris@0 403 # <b>Important:</b> The password argument may be a Proc that returns a string.
Chris@0 404 # This makes it possible for you to write client programs that solicit
Chris@0 405 # passwords from users or from other data sources without showing them
Chris@0 406 # in your code or on command lines.
Chris@0 407 #
Chris@0 408 # require 'net/ldap'
Chris@0 409 #
Chris@0 410 # ldap = Net::LDAP.new
Chris@0 411 # ldap.host = server_ip_address
Chris@0 412 # ldap.authenticate "cn=Your Username,cn=Users,dc=example,dc=com", "your_psw"
Chris@0 413 #
Chris@0 414 # Alternatively (with a password block):
Chris@0 415 #
Chris@0 416 # require 'net/ldap'
Chris@0 417 #
Chris@0 418 # ldap = Net::LDAP.new
Chris@0 419 # ldap.host = server_ip_address
Chris@0 420 # psw = proc { your_psw_function }
Chris@0 421 # ldap.authenticate "cn=Your Username,cn=Users,dc=example,dc=com", psw
Chris@0 422 #
Chris@0 423 def authenticate username, password
Chris@0 424 password = password.call if password.respond_to?(:call)
Chris@0 425 @auth = {:method => :simple, :username => username, :password => password}
Chris@0 426 end
Chris@0 427
Chris@0 428 alias_method :auth, :authenticate
Chris@0 429
Chris@0 430 # Convenience method to specify encryption characteristics for connections
Chris@0 431 # to LDAP servers. Called implicitly by #new and #open, but may also be called
Chris@0 432 # by user code if desired.
Chris@0 433 # The single argument is generally a Hash (but see below for convenience alternatives).
Chris@0 434 # This implementation is currently a stub, supporting only a few encryption
Chris@0 435 # alternatives. As additional capabilities are added, more configuration values
Chris@0 436 # will be added here.
Chris@0 437 #
Chris@0 438 # Currently, the only supported argument is {:method => :simple_tls}.
Chris@0 439 # (Equivalently, you may pass the symbol :simple_tls all by itself, without
Chris@0 440 # enclosing it in a Hash.)
Chris@0 441 #
Chris@0 442 # The :simple_tls encryption method encrypts <i>all</i> communications with the LDAP
Chris@0 443 # server.
Chris@0 444 # It completely establishes SSL/TLS encryption with the LDAP server
Chris@0 445 # before any LDAP-protocol data is exchanged.
Chris@0 446 # There is no plaintext negotiation and no special encryption-request controls
Chris@0 447 # are sent to the server.
Chris@0 448 # <i>The :simple_tls option is the simplest, easiest way to encrypt communications
Chris@0 449 # between Net::LDAP and LDAP servers.</i>
Chris@0 450 # It's intended for cases where you have an implicit level of trust in the authenticity
Chris@0 451 # of the LDAP server. No validation of the LDAP server's SSL certificate is
Chris@0 452 # performed. This means that :simple_tls will not produce errors if the LDAP
Chris@0 453 # server's encryption certificate is not signed by a well-known Certification
Chris@0 454 # Authority.
Chris@0 455 # If you get communications or protocol errors when using this option, check
Chris@0 456 # with your LDAP server administrator. Pay particular attention to the TCP port
Chris@0 457 # you are connecting to. It's impossible for an LDAP server to support plaintext
Chris@0 458 # LDAP communications and <i>simple TLS</i> connections on the same port.
Chris@0 459 # The standard TCP port for unencrypted LDAP connections is 389, but the standard
Chris@0 460 # port for simple-TLS encrypted connections is 636. Be sure you are using the
Chris@0 461 # correct port.
Chris@0 462 #
Chris@0 463 # <i>[Note: a future version of Net::LDAP will support the STARTTLS LDAP control,
Chris@0 464 # which will enable encrypted communications on the same TCP port used for
Chris@0 465 # unencrypted connections.]</i>
Chris@0 466 #
Chris@0 467 def encryption args
Chris@0 468 if args == :simple_tls
Chris@0 469 args = {:method => :simple_tls}
Chris@0 470 end
Chris@0 471 @encryption = args
Chris@0 472 end
Chris@0 473
Chris@0 474
Chris@0 475 # #open takes the same parameters as #new. #open makes a network connection to the
Chris@0 476 # LDAP server and then passes a newly-created Net::LDAP object to the caller-supplied block.
Chris@0 477 # Within the block, you can call any of the instance methods of Net::LDAP to
Chris@0 478 # perform operations against the LDAP directory. #open will perform all the
Chris@0 479 # operations in the user-supplied block on the same network connection, which
Chris@0 480 # will be closed automatically when the block finishes.
Chris@0 481 #
Chris@0 482 # # (PSEUDOCODE)
Chris@0 483 # auth = {:method => :simple, :username => username, :password => password}
Chris@0 484 # Net::LDAP.open( :host => ipaddress, :port => 389, :auth => auth ) do |ldap|
Chris@0 485 # ldap.search( ... )
Chris@0 486 # ldap.add( ... )
Chris@0 487 # ldap.modify( ... )
Chris@0 488 # end
Chris@0 489 #
Chris@0 490 def LDAP::open args
Chris@0 491 ldap1 = LDAP.new args
Chris@0 492 ldap1.open {|ldap| yield ldap }
Chris@0 493 end
Chris@0 494
Chris@0 495 # Returns a meaningful result any time after
Chris@0 496 # a protocol operation (#bind, #search, #add, #modify, #rename, #delete)
Chris@0 497 # has completed.
Chris@0 498 # It returns an #OpenStruct containing an LDAP result code (0 means success),
Chris@0 499 # and a human-readable string.
Chris@0 500 # unless ldap.bind
Chris@0 501 # puts "Result: #{ldap.get_operation_result.code}"
Chris@0 502 # puts "Message: #{ldap.get_operation_result.message}"
Chris@0 503 # end
Chris@0 504 #
Chris@0 505 def get_operation_result
Chris@0 506 os = OpenStruct.new
Chris@0 507 if @result
Chris@0 508 os.code = @result
Chris@0 509 else
Chris@0 510 os.code = 0
Chris@0 511 end
Chris@0 512 os.message = LDAP.result2string( os.code )
Chris@0 513 os
Chris@0 514 end
Chris@0 515
Chris@0 516
Chris@0 517 # Opens a network connection to the server and then
Chris@0 518 # passes <tt>self</tt> to the caller-supplied block. The connection is
Chris@0 519 # closed when the block completes. Used for executing multiple
Chris@0 520 # LDAP operations without requiring a separate network connection
Chris@0 521 # (and authentication) for each one.
Chris@0 522 # <i>Note:</i> You do not need to log-in or "bind" to the server. This will
Chris@0 523 # be done for you automatically.
Chris@0 524 # For an even simpler approach, see the class method Net::LDAP#open.
Chris@0 525 #
Chris@0 526 # # (PSEUDOCODE)
Chris@0 527 # auth = {:method => :simple, :username => username, :password => password}
Chris@0 528 # ldap = Net::LDAP.new( :host => ipaddress, :port => 389, :auth => auth )
Chris@0 529 # ldap.open do |ldap|
Chris@0 530 # ldap.search( ... )
Chris@0 531 # ldap.add( ... )
Chris@0 532 # ldap.modify( ... )
Chris@0 533 # end
Chris@0 534 #--
Chris@0 535 # First we make a connection and then a binding, but we don't
Chris@0 536 # do anything with the bind results.
Chris@0 537 # We then pass self to the caller's block, where he will execute
Chris@0 538 # his LDAP operations. Of course they will all generate auth failures
Chris@0 539 # if the bind was unsuccessful.
Chris@0 540 def open
Chris@0 541 raise LdapError.new( "open already in progress" ) if @open_connection
Chris@0 542 @open_connection = Connection.new( :host => @host, :port => @port, :encryption => @encryption )
Chris@0 543 @open_connection.bind @auth
Chris@0 544 yield self
Chris@0 545 @open_connection.close
Chris@0 546 @open_connection = nil
Chris@0 547 end
Chris@0 548
Chris@0 549
Chris@0 550 # Searches the LDAP directory for directory entries.
Chris@0 551 # Takes a hash argument with parameters. Supported parameters include:
Chris@0 552 # * :base (a string specifying the tree-base for the search);
Chris@0 553 # * :filter (an object of type Net::LDAP::Filter, defaults to objectclass=*);
Chris@0 554 # * :attributes (a string or array of strings specifying the LDAP attributes to return from the server);
Chris@0 555 # * :return_result (a boolean specifying whether to return a result set).
Chris@0 556 # * :attributes_only (a boolean flag, defaults false)
Chris@0 557 # * :scope (one of: Net::LDAP::SearchScope_BaseObject, Net::LDAP::SearchScope_SingleLevel, Net::LDAP::SearchScope_WholeSubtree. Default is WholeSubtree.)
Chris@0 558 #
Chris@0 559 # #search queries the LDAP server and passes <i>each entry</i> to the
Chris@0 560 # caller-supplied block, as an object of type Net::LDAP::Entry.
Chris@0 561 # If the search returns 1000 entries, the block will
Chris@0 562 # be called 1000 times. If the search returns no entries, the block will
Chris@0 563 # not be called.
Chris@0 564 #
Chris@0 565 #--
Chris@0 566 # ORIGINAL TEXT, replaced 04May06.
Chris@0 567 # #search returns either a result-set or a boolean, depending on the
Chris@0 568 # value of the <tt>:return_result</tt> argument. The default behavior is to return
Chris@0 569 # a result set, which is a hash. Each key in the hash is a string specifying
Chris@0 570 # the DN of an entry. The corresponding value for each key is a Net::LDAP::Entry object.
Chris@0 571 # If you request a result set and #search fails with an error, it will return nil.
Chris@0 572 # Call #get_operation_result to get the error information returned by
Chris@0 573 # the LDAP server.
Chris@0 574 #++
Chris@0 575 # #search returns either a result-set or a boolean, depending on the
Chris@0 576 # value of the <tt>:return_result</tt> argument. The default behavior is to return
Chris@0 577 # a result set, which is an Array of objects of class Net::LDAP::Entry.
Chris@0 578 # If you request a result set and #search fails with an error, it will return nil.
Chris@0 579 # Call #get_operation_result to get the error information returned by
Chris@0 580 # the LDAP server.
Chris@0 581 #
Chris@0 582 # When <tt>:return_result => false,</tt> #search will
Chris@0 583 # return only a Boolean, to indicate whether the operation succeeded. This can improve performance
Chris@0 584 # with very large result sets, because the library can discard each entry from memory after
Chris@0 585 # your block processes it.
Chris@0 586 #
Chris@0 587 #
Chris@0 588 # treebase = "dc=example,dc=com"
Chris@0 589 # filter = Net::LDAP::Filter.eq( "mail", "a*.com" )
Chris@0 590 # attrs = ["mail", "cn", "sn", "objectclass"]
Chris@0 591 # ldap.search( :base => treebase, :filter => filter, :attributes => attrs, :return_result => false ) do |entry|
Chris@0 592 # puts "DN: #{entry.dn}"
Chris@0 593 # entry.each do |attr, values|
Chris@0 594 # puts ".......#{attr}:"
Chris@0 595 # values.each do |value|
Chris@0 596 # puts " #{value}"
Chris@0 597 # end
Chris@0 598 # end
Chris@0 599 # end
Chris@0 600 #
Chris@0 601 #--
Chris@0 602 # This is a re-implementation of search that replaces the
Chris@0 603 # original one (now renamed searchx and possibly destined to go away).
Chris@0 604 # The difference is that we return a dataset (or nil) from the
Chris@0 605 # call, and pass _each entry_ as it is received from the server
Chris@0 606 # to the caller-supplied block. This will probably make things
Chris@0 607 # far faster as we can do useful work during the network latency
Chris@0 608 # of the search. The downside is that we have no access to the
Chris@0 609 # whole set while processing the blocks, so we can't do stuff
Chris@0 610 # like sort the DNs until after the call completes.
Chris@0 611 # It's also possible that this interacts badly with server timeouts.
Chris@0 612 # We'll have to ensure that something reasonable happens if
Chris@0 613 # the caller has processed half a result set when we throw a timeout
Chris@0 614 # error.
Chris@0 615 # Another important difference is that we return a result set from
Chris@0 616 # this method rather than a T/F indication.
Chris@0 617 # Since this can be very heavy-weight, we define an argument flag
Chris@0 618 # that the caller can set to suppress the return of a result set,
Chris@0 619 # if he's planning to process every entry as it comes from the server.
Chris@0 620 #
Chris@0 621 # REINTERPRETED the result set, 04May06. Originally this was a hash
Chris@0 622 # of entries keyed by DNs. But let's get away from making users
Chris@0 623 # handle DNs. Change it to a plain array. Eventually we may
Chris@0 624 # want to return a Dataset object that delegates to an internal
Chris@0 625 # array, so we can provide sort methods and what-not.
Chris@0 626 #
Chris@0 627 def search args = {}
Chris@0 628 args[:base] ||= @base
Chris@0 629 result_set = (args and args[:return_result] == false) ? nil : []
Chris@0 630
Chris@0 631 if @open_connection
Chris@0 632 @result = @open_connection.search( args ) {|entry|
Chris@0 633 result_set << entry if result_set
Chris@0 634 yield( entry ) if block_given?
Chris@0 635 }
Chris@0 636 else
Chris@0 637 @result = 0
Chris@0 638 conn = Connection.new( :host => @host, :port => @port, :encryption => @encryption )
Chris@0 639 if (@result = conn.bind( args[:auth] || @auth )) == 0
Chris@0 640 @result = conn.search( args ) {|entry|
Chris@0 641 result_set << entry if result_set
Chris@0 642 yield( entry ) if block_given?
Chris@0 643 }
Chris@0 644 end
Chris@0 645 conn.close
Chris@0 646 end
Chris@0 647
Chris@0 648 @result == 0 and result_set
Chris@0 649 end
Chris@0 650
Chris@0 651 # #bind connects to an LDAP server and requests authentication
Chris@0 652 # based on the <tt>:auth</tt> parameter passed to #open or #new.
Chris@0 653 # It takes no parameters.
Chris@0 654 #
Chris@0 655 # User code does not need to call #bind directly. It will be called
Chris@0 656 # implicitly by the library whenever you invoke an LDAP operation,
Chris@0 657 # such as #search or #add.
Chris@0 658 #
Chris@0 659 # It is useful, however, to call #bind in your own code when the
Chris@0 660 # only operation you intend to perform against the directory is
Chris@0 661 # to validate a login credential. #bind returns true or false
Chris@0 662 # to indicate whether the binding was successful. Reasons for
Chris@0 663 # failure include malformed or unrecognized usernames and
Chris@0 664 # incorrect passwords. Use #get_operation_result to find out
Chris@0 665 # what happened in case of failure.
Chris@0 666 #
Chris@0 667 # Here's a typical example using #bind to authenticate a
Chris@0 668 # credential which was (perhaps) solicited from the user of a
Chris@0 669 # web site:
Chris@0 670 #
Chris@0 671 # require 'net/ldap'
Chris@0 672 # ldap = Net::LDAP.new
Chris@0 673 # ldap.host = your_server_ip_address
Chris@0 674 # ldap.port = 389
Chris@0 675 # ldap.auth your_user_name, your_user_password
Chris@0 676 # if ldap.bind
Chris@0 677 # # authentication succeeded
Chris@0 678 # else
Chris@0 679 # # authentication failed
Chris@0 680 # p ldap.get_operation_result
Chris@0 681 # end
Chris@0 682 #
Chris@0 683 # You don't have to create a new instance of Net::LDAP every time
Chris@0 684 # you perform a binding in this way. If you prefer, you can cache the Net::LDAP object
Chris@0 685 # and re-use it to perform subsequent bindings, <i>provided</i> you call
Chris@0 686 # #auth to specify a new credential before calling #bind. Otherwise, you'll
Chris@0 687 # just re-authenticate the previous user! (You don't need to re-set
Chris@0 688 # the values of #host and #port.) As noted in the documentation for #auth,
Chris@0 689 # the password parameter can be a Ruby Proc instead of a String.
Chris@0 690 #
Chris@0 691 #--
Chris@0 692 # If there is an @open_connection, then perform the bind
Chris@0 693 # on it. Otherwise, connect, bind, and disconnect.
Chris@0 694 # The latter operation is obviously useful only as an auth check.
Chris@0 695 #
Chris@0 696 def bind auth=@auth
Chris@0 697 if @open_connection
Chris@0 698 @result = @open_connection.bind auth
Chris@0 699 else
Chris@0 700 conn = Connection.new( :host => @host, :port => @port , :encryption => @encryption)
Chris@0 701 @result = conn.bind @auth
Chris@0 702 conn.close
Chris@0 703 end
Chris@0 704
Chris@0 705 @result == 0
Chris@0 706 end
Chris@0 707
Chris@0 708 #
Chris@0 709 # #bind_as is for testing authentication credentials.
Chris@0 710 #
Chris@0 711 # As described under #bind, most LDAP servers require that you supply a complete DN
Chris@0 712 # as a binding-credential, along with an authenticator such as a password.
Chris@0 713 # But for many applications (such as authenticating users to a Rails application),
Chris@0 714 # you often don't have a full DN to identify the user. You usually get a simple
Chris@0 715 # identifier like a username or an email address, along with a password.
Chris@0 716 # #bind_as allows you to authenticate these user-identifiers.
Chris@0 717 #
Chris@0 718 # #bind_as is a combination of a search and an LDAP binding. First, it connects and
Chris@0 719 # binds to the directory as normal. Then it searches the directory for an entry
Chris@0 720 # corresponding to the email address, username, or other string that you supply.
Chris@0 721 # If the entry exists, then #bind_as will <b>re-bind</b> as that user with the
Chris@0 722 # password (or other authenticator) that you supply.
Chris@0 723 #
Chris@0 724 # #bind_as takes the same parameters as #search, <i>with the addition of an
Chris@0 725 # authenticator.</i> Currently, this authenticator must be <tt>:password</tt>.
Chris@0 726 # Its value may be either a String, or a +proc+ that returns a String.
Chris@0 727 # #bind_as returns +false+ on failure. On success, it returns a result set,
Chris@0 728 # just as #search does. This result set is an Array of objects of
Chris@0 729 # type Net::LDAP::Entry. It contains the directory attributes corresponding to
Chris@0 730 # the user. (Just test whether the return value is logically true, if you don't
Chris@0 731 # need this additional information.)
Chris@0 732 #
Chris@0 733 # Here's how you would use #bind_as to authenticate an email address and password:
Chris@0 734 #
Chris@0 735 # require 'net/ldap'
Chris@0 736 #
Chris@0 737 # user,psw = "joe_user@yourcompany.com", "joes_psw"
Chris@0 738 #
Chris@0 739 # ldap = Net::LDAP.new
Chris@0 740 # ldap.host = "192.168.0.100"
Chris@0 741 # ldap.port = 389
Chris@0 742 # ldap.auth "cn=manager,dc=yourcompany,dc=com", "topsecret"
Chris@0 743 #
Chris@0 744 # result = ldap.bind_as(
Chris@0 745 # :base => "dc=yourcompany,dc=com",
Chris@0 746 # :filter => "(mail=#{user})",
Chris@0 747 # :password => psw
Chris@0 748 # )
Chris@0 749 # if result
Chris@0 750 # puts "Authenticated #{result.first.dn}"
Chris@0 751 # else
Chris@0 752 # puts "Authentication FAILED."
Chris@0 753 # end
Chris@0 754 def bind_as args={}
Chris@0 755 result = false
Chris@0 756 open {|me|
Chris@0 757 rs = search args
Chris@0 758 if rs and rs.first and dn = rs.first.dn
Chris@0 759 password = args[:password]
Chris@0 760 password = password.call if password.respond_to?(:call)
Chris@0 761 result = rs if bind :method => :simple, :username => dn, :password => password
Chris@0 762 end
Chris@0 763 }
Chris@0 764 result
Chris@0 765 end
Chris@0 766
Chris@0 767
Chris@0 768 # Adds a new entry to the remote LDAP server.
Chris@0 769 # Supported arguments:
Chris@0 770 # :dn :: Full DN of the new entry
Chris@0 771 # :attributes :: Attributes of the new entry.
Chris@0 772 #
Chris@0 773 # The attributes argument is supplied as a Hash keyed by Strings or Symbols
Chris@0 774 # giving the attribute name, and mapping to Strings or Arrays of Strings
Chris@0 775 # giving the actual attribute values. Observe that most LDAP directories
Chris@0 776 # enforce schema constraints on the attributes contained in entries.
Chris@0 777 # #add will fail with a server-generated error if your attributes violate
Chris@0 778 # the server-specific constraints.
Chris@0 779 # Here's an example:
Chris@0 780 #
Chris@0 781 # dn = "cn=George Smith,ou=people,dc=example,dc=com"
Chris@0 782 # attr = {
Chris@0 783 # :cn => "George Smith",
Chris@0 784 # :objectclass => ["top", "inetorgperson"],
Chris@0 785 # :sn => "Smith",
Chris@0 786 # :mail => "gsmith@example.com"
Chris@0 787 # }
Chris@0 788 # Net::LDAP.open (:host => host) do |ldap|
Chris@0 789 # ldap.add( :dn => dn, :attributes => attr )
Chris@0 790 # end
Chris@0 791 #
Chris@0 792 def add args
Chris@0 793 if @open_connection
Chris@0 794 @result = @open_connection.add( args )
Chris@0 795 else
Chris@0 796 @result = 0
Chris@0 797 conn = Connection.new( :host => @host, :port => @port, :encryption => @encryption)
Chris@0 798 if (@result = conn.bind( args[:auth] || @auth )) == 0
Chris@0 799 @result = conn.add( args )
Chris@0 800 end
Chris@0 801 conn.close
Chris@0 802 end
Chris@0 803 @result == 0
Chris@0 804 end
Chris@0 805
Chris@0 806
Chris@0 807 # Modifies the attribute values of a particular entry on the LDAP directory.
Chris@0 808 # Takes a hash with arguments. Supported arguments are:
Chris@0 809 # :dn :: (the full DN of the entry whose attributes are to be modified)
Chris@0 810 # :operations :: (the modifications to be performed, detailed next)
Chris@0 811 #
Chris@0 812 # This method returns True or False to indicate whether the operation
Chris@0 813 # succeeded or failed, with extended information available by calling
Chris@0 814 # #get_operation_result.
Chris@0 815 #
Chris@0 816 # Also see #add_attribute, #replace_attribute, or #delete_attribute, which
Chris@0 817 # provide simpler interfaces to this functionality.
Chris@0 818 #
Chris@0 819 # The LDAP protocol provides a full and well thought-out set of operations
Chris@0 820 # for changing the values of attributes, but they are necessarily somewhat complex
Chris@0 821 # and not always intuitive. If these instructions are confusing or incomplete,
Chris@0 822 # please send us email or create a bug report on rubyforge.
Chris@0 823 #
Chris@0 824 # The :operations parameter to #modify takes an array of operation-descriptors.
Chris@0 825 # Each individual operation is specified in one element of the array, and
Chris@0 826 # most LDAP servers will attempt to perform the operations in order.
Chris@0 827 #
Chris@0 828 # Each of the operations appearing in the Array must itself be an Array
Chris@0 829 # with exactly three elements:
Chris@0 830 # an operator:: must be :add, :replace, or :delete
Chris@0 831 # an attribute name:: the attribute name (string or symbol) to modify
Chris@0 832 # a value:: either a string or an array of strings.
Chris@0 833 #
Chris@0 834 # The :add operator will, unsurprisingly, add the specified values to
Chris@0 835 # the specified attribute. If the attribute does not already exist,
Chris@0 836 # :add will create it. Most LDAP servers will generate an error if you
Chris@0 837 # try to add a value that already exists.
Chris@0 838 #
Chris@0 839 # :replace will erase the current value(s) for the specified attribute,
Chris@0 840 # if there are any, and replace them with the specified value(s).
Chris@0 841 #
Chris@0 842 # :delete will remove the specified value(s) from the specified attribute.
Chris@0 843 # If you pass nil, an empty string, or an empty array as the value parameter
Chris@0 844 # to a :delete operation, the _entire_ _attribute_ will be deleted, along
Chris@0 845 # with all of its values.
Chris@0 846 #
Chris@0 847 # For example:
Chris@0 848 #
Chris@0 849 # dn = "mail=modifyme@example.com,ou=people,dc=example,dc=com"
Chris@0 850 # ops = [
Chris@0 851 # [:add, :mail, "aliasaddress@example.com"],
Chris@0 852 # [:replace, :mail, ["newaddress@example.com", "newalias@example.com"]],
Chris@0 853 # [:delete, :sn, nil]
Chris@0 854 # ]
Chris@0 855 # ldap.modify :dn => dn, :operations => ops
Chris@0 856 #
Chris@0 857 # <i>(This example is contrived since you probably wouldn't add a mail
Chris@0 858 # value right before replacing the whole attribute, but it shows that order
Chris@0 859 # of execution matters. Also, many LDAP servers won't let you delete SN
Chris@0 860 # because that would be a schema violation.)</i>
Chris@0 861 #
Chris@0 862 # It's essential to keep in mind that if you specify more than one operation in
Chris@0 863 # a call to #modify, most LDAP servers will attempt to perform all of the operations
Chris@0 864 # in the order you gave them.
Chris@0 865 # This matters because you may specify operations on the
Chris@0 866 # same attribute which must be performed in a certain order.
Chris@0 867 #
Chris@0 868 # Most LDAP servers will _stop_ processing your modifications if one of them
Chris@0 869 # causes an error on the server (such as a schema-constraint violation).
Chris@0 870 # If this happens, you will probably get a result code from the server that
Chris@0 871 # reflects only the operation that failed, and you may or may not get extended
Chris@0 872 # information that will tell you which one failed. #modify has no notion
Chris@0 873 # of an atomic transaction. If you specify a chain of modifications in one
Chris@0 874 # call to #modify, and one of them fails, the preceding ones will usually
Chris@0 875 # not be "rolled back," resulting in a partial update. This is a limitation
Chris@0 876 # of the LDAP protocol, not of Net::LDAP.
Chris@0 877 #
Chris@0 878 # The lack of transactional atomicity in LDAP means that you're usually
Chris@0 879 # better off using the convenience methods #add_attribute, #replace_attribute,
Chris@0 880 # and #delete_attribute, which are are wrappers over #modify. However, certain
Chris@0 881 # LDAP servers may provide concurrency semantics, in which the several operations
Chris@0 882 # contained in a single #modify call are not interleaved with other
Chris@0 883 # modification-requests received simultaneously by the server.
Chris@0 884 # It bears repeating that this concurrency does _not_ imply transactional
Chris@0 885 # atomicity, which LDAP does not provide.
Chris@0 886 #
Chris@0 887 def modify args
Chris@0 888 if @open_connection
Chris@0 889 @result = @open_connection.modify( args )
Chris@0 890 else
Chris@0 891 @result = 0
Chris@0 892 conn = Connection.new( :host => @host, :port => @port, :encryption => @encryption )
Chris@0 893 if (@result = conn.bind( args[:auth] || @auth )) == 0
Chris@0 894 @result = conn.modify( args )
Chris@0 895 end
Chris@0 896 conn.close
Chris@0 897 end
Chris@0 898 @result == 0
Chris@0 899 end
Chris@0 900
Chris@0 901
Chris@0 902 # Add a value to an attribute.
Chris@0 903 # Takes the full DN of the entry to modify,
Chris@0 904 # the name (Symbol or String) of the attribute, and the value (String or
Chris@0 905 # Array). If the attribute does not exist (and there are no schema violations),
Chris@0 906 # #add_attribute will create it with the caller-specified values.
Chris@0 907 # If the attribute already exists (and there are no schema violations), the
Chris@0 908 # caller-specified values will be _added_ to the values already present.
Chris@0 909 #
Chris@0 910 # Returns True or False to indicate whether the operation
Chris@0 911 # succeeded or failed, with extended information available by calling
Chris@0 912 # #get_operation_result. See also #replace_attribute and #delete_attribute.
Chris@0 913 #
Chris@0 914 # dn = "cn=modifyme,dc=example,dc=com"
Chris@0 915 # ldap.add_attribute dn, :mail, "newmailaddress@example.com"
Chris@0 916 #
Chris@0 917 def add_attribute dn, attribute, value
Chris@0 918 modify :dn => dn, :operations => [[:add, attribute, value]]
Chris@0 919 end
Chris@0 920
Chris@0 921 # Replace the value of an attribute.
Chris@0 922 # #replace_attribute can be thought of as equivalent to calling #delete_attribute
Chris@0 923 # followed by #add_attribute. It takes the full DN of the entry to modify,
Chris@0 924 # the name (Symbol or String) of the attribute, and the value (String or
Chris@0 925 # Array). If the attribute does not exist, it will be created with the
Chris@0 926 # caller-specified value(s). If the attribute does exist, its values will be
Chris@0 927 # _discarded_ and replaced with the caller-specified values.
Chris@0 928 #
Chris@0 929 # Returns True or False to indicate whether the operation
Chris@0 930 # succeeded or failed, with extended information available by calling
Chris@0 931 # #get_operation_result. See also #add_attribute and #delete_attribute.
Chris@0 932 #
Chris@0 933 # dn = "cn=modifyme,dc=example,dc=com"
Chris@0 934 # ldap.replace_attribute dn, :mail, "newmailaddress@example.com"
Chris@0 935 #
Chris@0 936 def replace_attribute dn, attribute, value
Chris@0 937 modify :dn => dn, :operations => [[:replace, attribute, value]]
Chris@0 938 end
Chris@0 939
Chris@0 940 # Delete an attribute and all its values.
Chris@0 941 # Takes the full DN of the entry to modify, and the
Chris@0 942 # name (Symbol or String) of the attribute to delete.
Chris@0 943 #
Chris@0 944 # Returns True or False to indicate whether the operation
Chris@0 945 # succeeded or failed, with extended information available by calling
Chris@0 946 # #get_operation_result. See also #add_attribute and #replace_attribute.
Chris@0 947 #
Chris@0 948 # dn = "cn=modifyme,dc=example,dc=com"
Chris@0 949 # ldap.delete_attribute dn, :mail
Chris@0 950 #
Chris@0 951 def delete_attribute dn, attribute
Chris@0 952 modify :dn => dn, :operations => [[:delete, attribute, nil]]
Chris@0 953 end
Chris@0 954
Chris@0 955
Chris@0 956 # Rename an entry on the remote DIS by changing the last RDN of its DN.
Chris@0 957 # _Documentation_ _stub_
Chris@0 958 #
Chris@0 959 def rename args
Chris@0 960 if @open_connection
Chris@0 961 @result = @open_connection.rename( args )
Chris@0 962 else
Chris@0 963 @result = 0
Chris@0 964 conn = Connection.new( :host => @host, :port => @port, :encryption => @encryption )
Chris@0 965 if (@result = conn.bind( args[:auth] || @auth )) == 0
Chris@0 966 @result = conn.rename( args )
Chris@0 967 end
Chris@0 968 conn.close
Chris@0 969 end
Chris@0 970 @result == 0
Chris@0 971 end
Chris@0 972
Chris@0 973 # modify_rdn is an alias for #rename.
Chris@0 974 def modify_rdn args
Chris@0 975 rename args
Chris@0 976 end
Chris@0 977
Chris@0 978 # Delete an entry from the LDAP directory.
Chris@0 979 # Takes a hash of arguments.
Chris@0 980 # The only supported argument is :dn, which must
Chris@0 981 # give the complete DN of the entry to be deleted.
Chris@0 982 # Returns True or False to indicate whether the delete
Chris@0 983 # succeeded. Extended status information is available by
Chris@0 984 # calling #get_operation_result.
Chris@0 985 #
Chris@0 986 # dn = "mail=deleteme@example.com,ou=people,dc=example,dc=com"
Chris@0 987 # ldap.delete :dn => dn
Chris@0 988 #
Chris@0 989 def delete args
Chris@0 990 if @open_connection
Chris@0 991 @result = @open_connection.delete( args )
Chris@0 992 else
Chris@0 993 @result = 0
Chris@0 994 conn = Connection.new( :host => @host, :port => @port, :encryption => @encryption )
Chris@0 995 if (@result = conn.bind( args[:auth] || @auth )) == 0
Chris@0 996 @result = conn.delete( args )
Chris@0 997 end
Chris@0 998 conn.close
Chris@0 999 end
Chris@0 1000 @result == 0
Chris@0 1001 end
Chris@0 1002
Chris@0 1003 end # class LDAP
Chris@0 1004
Chris@0 1005
Chris@0 1006
Chris@0 1007 class LDAP
Chris@0 1008 # This is a private class used internally by the library. It should not be called by user code.
Chris@0 1009 class Connection # :nodoc:
Chris@0 1010
Chris@0 1011 LdapVersion = 3
Chris@0 1012
Chris@0 1013
Chris@0 1014 #--
Chris@0 1015 # initialize
Chris@0 1016 #
Chris@0 1017 def initialize server
Chris@0 1018 begin
Chris@0 1019 @conn = TCPsocket.new( server[:host], server[:port] )
Chris@0 1020 rescue
Chris@0 1021 raise LdapError.new( "no connection to server" )
Chris@0 1022 end
Chris@0 1023
Chris@0 1024 if server[:encryption]
Chris@0 1025 setup_encryption server[:encryption]
Chris@0 1026 end
Chris@0 1027
Chris@0 1028 yield self if block_given?
Chris@0 1029 end
Chris@0 1030
Chris@0 1031
Chris@0 1032 #--
Chris@0 1033 # Helper method called only from new, and only after we have a successfully-opened
Chris@0 1034 # @conn instance variable, which is a TCP connection.
Chris@0 1035 # Depending on the received arguments, we establish SSL, potentially replacing
Chris@0 1036 # the value of @conn accordingly.
Chris@0 1037 # Don't generate any errors here if no encryption is requested.
Chris@0 1038 # DO raise LdapError objects if encryption is requested and we have trouble setting
Chris@0 1039 # it up. That includes if OpenSSL is not set up on the machine. (Question:
Chris@0 1040 # how does the Ruby OpenSSL wrapper react in that case?)
Chris@0 1041 # DO NOT filter exceptions raised by the OpenSSL library. Let them pass back
Chris@0 1042 # to the user. That should make it easier for us to debug the problem reports.
Chris@0 1043 # Presumably (hopefully?) that will also produce recognizable errors if someone
Chris@0 1044 # tries to use this on a machine without OpenSSL.
Chris@0 1045 #
Chris@0 1046 # The simple_tls method is intended as the simplest, stupidest, easiest solution
Chris@0 1047 # for people who want nothing more than encrypted comms with the LDAP server.
Chris@0 1048 # It doesn't do any server-cert validation and requires nothing in the way
Chris@0 1049 # of key files and root-cert files, etc etc.
Chris@0 1050 # OBSERVE: WE REPLACE the value of @conn, which is presumed to be a connected
Chris@0 1051 # TCPsocket object.
Chris@0 1052 #
Chris@0 1053 def setup_encryption args
Chris@0 1054 case args[:method]
Chris@0 1055 when :simple_tls
Chris@0 1056 raise LdapError.new("openssl unavailable") unless $net_ldap_openssl_available
Chris@0 1057 ctx = OpenSSL::SSL::SSLContext.new
Chris@0 1058 @conn = OpenSSL::SSL::SSLSocket.new(@conn, ctx)
Chris@0 1059 @conn.connect
Chris@0 1060 @conn.sync_close = true
Chris@0 1061 # additional branches requiring server validation and peer certs, etc. go here.
Chris@0 1062 else
Chris@0 1063 raise LdapError.new( "unsupported encryption method #{args[:method]}" )
Chris@0 1064 end
Chris@0 1065 end
Chris@0 1066
Chris@0 1067 #--
Chris@0 1068 # close
Chris@0 1069 # This is provided as a convenience method to make
Chris@0 1070 # sure a connection object gets closed without waiting
Chris@0 1071 # for a GC to happen. Clients shouldn't have to call it,
Chris@0 1072 # but perhaps it will come in handy someday.
Chris@0 1073 def close
Chris@0 1074 @conn.close
Chris@0 1075 @conn = nil
Chris@0 1076 end
Chris@0 1077
Chris@0 1078 #--
Chris@0 1079 # next_msgid
Chris@0 1080 #
Chris@0 1081 def next_msgid
Chris@0 1082 @msgid ||= 0
Chris@0 1083 @msgid += 1
Chris@0 1084 end
Chris@0 1085
Chris@0 1086
Chris@0 1087 #--
Chris@0 1088 # bind
Chris@0 1089 #
Chris@0 1090 def bind auth
Chris@0 1091 user,psw = case auth[:method]
Chris@0 1092 when :anonymous
Chris@0 1093 ["",""]
Chris@0 1094 when :simple
Chris@0 1095 [auth[:username] || auth[:dn], auth[:password]]
Chris@0 1096 end
Chris@0 1097 raise LdapError.new( "invalid binding information" ) unless (user && psw)
Chris@0 1098
Chris@0 1099 msgid = next_msgid.to_ber
Chris@0 1100 request = [LdapVersion.to_ber, user.to_ber, psw.to_ber_contextspecific(0)].to_ber_appsequence(0)
Chris@0 1101 request_pkt = [msgid, request].to_ber_sequence
Chris@0 1102 @conn.write request_pkt
Chris@0 1103
Chris@0 1104 (be = @conn.read_ber(AsnSyntax) and pdu = Net::LdapPdu.new( be )) or raise LdapError.new( "no bind result" )
Chris@0 1105 pdu.result_code
Chris@0 1106 end
Chris@0 1107
Chris@0 1108 #--
Chris@0 1109 # search
Chris@0 1110 # Alternate implementation, this yields each search entry to the caller
Chris@0 1111 # as it are received.
Chris@0 1112 # TODO, certain search parameters are hardcoded.
Chris@0 1113 # TODO, if we mis-parse the server results or the results are wrong, we can block
Chris@0 1114 # forever. That's because we keep reading results until we get a type-5 packet,
Chris@0 1115 # which might never come. We need to support the time-limit in the protocol.
Chris@0 1116 #--
Chris@0 1117 # WARNING: this code substantially recapitulates the searchx method.
Chris@0 1118 #
Chris@0 1119 # 02May06: Well, I added support for RFC-2696-style paged searches.
Chris@0 1120 # This is used on all queries because the extension is marked non-critical.
Chris@0 1121 # As far as I know, only A/D uses this, but it's required for A/D. Otherwise
Chris@0 1122 # you won't get more than 1000 results back from a query.
Chris@0 1123 # This implementation is kindof clunky and should probably be refactored.
Chris@0 1124 # Also, is it my imagination, or are A/Ds the slowest directory servers ever???
Chris@0 1125 #
Chris@0 1126 def search args = {}
Chris@0 1127 search_filter = (args && args[:filter]) || Filter.eq( "objectclass", "*" )
Chris@0 1128 search_filter = Filter.construct(search_filter) if search_filter.is_a?(String)
Chris@0 1129 search_base = (args && args[:base]) || "dc=example,dc=com"
Chris@0 1130 search_attributes = ((args && args[:attributes]) || []).map {|attr| attr.to_s.to_ber}
Chris@0 1131 return_referrals = args && args[:return_referrals] == true
Chris@0 1132
Chris@0 1133 attributes_only = (args and args[:attributes_only] == true)
Chris@0 1134 scope = args[:scope] || Net::LDAP::SearchScope_WholeSubtree
Chris@0 1135 raise LdapError.new( "invalid search scope" ) unless SearchScopes.include?(scope)
Chris@0 1136
Chris@0 1137 # An interesting value for the size limit would be close to A/D's built-in
Chris@0 1138 # page limit of 1000 records, but openLDAP newer than version 2.2.0 chokes
Chris@0 1139 # on anything bigger than 126. You get a silent error that is easily visible
Chris@0 1140 # by running slapd in debug mode. Go figure.
Chris@0 1141 rfc2696_cookie = [126, ""]
Chris@0 1142 result_code = 0
Chris@0 1143
Chris@0 1144 loop {
Chris@0 1145 # should collect this into a private helper to clarify the structure
Chris@0 1146
Chris@0 1147 request = [
Chris@0 1148 search_base.to_ber,
Chris@0 1149 scope.to_ber_enumerated,
Chris@0 1150 0.to_ber_enumerated,
Chris@0 1151 0.to_ber,
Chris@0 1152 0.to_ber,
Chris@0 1153 attributes_only.to_ber,
Chris@0 1154 search_filter.to_ber,
Chris@0 1155 search_attributes.to_ber_sequence
Chris@0 1156 ].to_ber_appsequence(3)
Chris@0 1157
Chris@0 1158 controls = [
Chris@0 1159 [
Chris@0 1160 LdapControls::PagedResults.to_ber,
Chris@0 1161 false.to_ber, # criticality MUST be false to interoperate with normal LDAPs.
Chris@0 1162 rfc2696_cookie.map{|v| v.to_ber}.to_ber_sequence.to_s.to_ber
Chris@0 1163 ].to_ber_sequence
Chris@0 1164 ].to_ber_contextspecific(0)
Chris@0 1165
Chris@0 1166 pkt = [next_msgid.to_ber, request, controls].to_ber_sequence
Chris@0 1167 @conn.write pkt
Chris@0 1168
Chris@0 1169 result_code = 0
Chris@0 1170 controls = []
Chris@0 1171
Chris@0 1172 while (be = @conn.read_ber(AsnSyntax)) && (pdu = LdapPdu.new( be ))
Chris@0 1173 case pdu.app_tag
Chris@0 1174 when 4 # search-data
Chris@0 1175 yield( pdu.search_entry ) if block_given?
Chris@0 1176 when 19 # search-referral
Chris@0 1177 if return_referrals
Chris@0 1178 if block_given?
Chris@0 1179 se = Net::LDAP::Entry.new
Chris@0 1180 se[:search_referrals] = (pdu.search_referrals || [])
Chris@0 1181 yield se
Chris@0 1182 end
Chris@0 1183 end
Chris@0 1184 #p pdu.referrals
Chris@0 1185 when 5 # search-result
Chris@0 1186 result_code = pdu.result_code
Chris@0 1187 controls = pdu.result_controls
Chris@0 1188 break
Chris@0 1189 else
Chris@0 1190 raise LdapError.new( "invalid response-type in search: #{pdu.app_tag}" )
Chris@0 1191 end
Chris@0 1192 end
Chris@0 1193
Chris@0 1194 # When we get here, we have seen a type-5 response.
Chris@0 1195 # If there is no error AND there is an RFC-2696 cookie,
Chris@0 1196 # then query again for the next page of results.
Chris@0 1197 # If not, we're done.
Chris@0 1198 # Don't screw this up or we'll break every search we do.
Chris@0 1199 more_pages = false
Chris@0 1200 if result_code == 0 and controls
Chris@0 1201 controls.each do |c|
Chris@0 1202 if c.oid == LdapControls::PagedResults
Chris@0 1203 more_pages = false # just in case some bogus server sends us >1 of these.
Chris@0 1204 if c.value and c.value.length > 0
Chris@0 1205 cookie = c.value.read_ber[1]
Chris@0 1206 if cookie and cookie.length > 0
Chris@0 1207 rfc2696_cookie[1] = cookie
Chris@0 1208 more_pages = true
Chris@0 1209 end
Chris@0 1210 end
Chris@0 1211 end
Chris@0 1212 end
Chris@0 1213 end
Chris@0 1214
Chris@0 1215 break unless more_pages
Chris@0 1216 } # loop
Chris@0 1217
Chris@0 1218 result_code
Chris@0 1219 end
Chris@0 1220
Chris@0 1221
Chris@0 1222
Chris@0 1223
Chris@0 1224 #--
Chris@0 1225 # modify
Chris@0 1226 # TODO, need to support a time limit, in case the server fails to respond.
Chris@0 1227 # TODO!!! We're throwing an exception here on empty DN.
Chris@0 1228 # Should return a proper error instead, probaby from farther up the chain.
Chris@0 1229 # TODO!!! If the user specifies a bogus opcode, we'll throw a
Chris@0 1230 # confusing error here ("to_ber_enumerated is not defined on nil").
Chris@0 1231 #
Chris@0 1232 def modify args
Chris@0 1233 modify_dn = args[:dn] or raise "Unable to modify empty DN"
Chris@0 1234 modify_ops = []
Chris@0 1235 a = args[:operations] and a.each {|op, attr, values|
Chris@0 1236 # TODO, fix the following line, which gives a bogus error
Chris@0 1237 # if the opcode is invalid.
Chris@0 1238 op_1 = {:add => 0, :delete => 1, :replace => 2} [op.to_sym].to_ber_enumerated
Chris@0 1239 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 1240 }
Chris@0 1241
Chris@0 1242 request = [modify_dn.to_ber, modify_ops.to_ber_sequence].to_ber_appsequence(6)
Chris@0 1243 pkt = [next_msgid.to_ber, request].to_ber_sequence
Chris@0 1244 @conn.write pkt
Chris@0 1245
Chris@0 1246 (be = @conn.read_ber(AsnSyntax)) && (pdu = LdapPdu.new( be )) && (pdu.app_tag == 7) or raise LdapError.new( "response missing or invalid" )
Chris@0 1247 pdu.result_code
Chris@0 1248 end
Chris@0 1249
Chris@0 1250
Chris@0 1251 #--
Chris@0 1252 # add
Chris@0 1253 # TODO, need to support a time limit, in case the server fails to respond.
Chris@0 1254 #
Chris@0 1255 def add args
Chris@0 1256 add_dn = args[:dn] or raise LdapError.new("Unable to add empty DN")
Chris@0 1257 add_attrs = []
Chris@0 1258 a = args[:attributes] and a.each {|k,v|
Chris@0 1259 add_attrs << [ k.to_s.to_ber, v.to_a.map {|m| m.to_ber}.to_ber_set ].to_ber_sequence
Chris@0 1260 }
Chris@0 1261
Chris@0 1262 request = [add_dn.to_ber, add_attrs.to_ber_sequence].to_ber_appsequence(8)
Chris@0 1263 pkt = [next_msgid.to_ber, request].to_ber_sequence
Chris@0 1264 @conn.write pkt
Chris@0 1265
Chris@0 1266 (be = @conn.read_ber(AsnSyntax)) && (pdu = LdapPdu.new( be )) && (pdu.app_tag == 9) or raise LdapError.new( "response missing or invalid" )
Chris@0 1267 pdu.result_code
Chris@0 1268 end
Chris@0 1269
Chris@0 1270
Chris@0 1271 #--
Chris@0 1272 # rename
Chris@0 1273 # TODO, need to support a time limit, in case the server fails to respond.
Chris@0 1274 #
Chris@0 1275 def rename args
Chris@0 1276 old_dn = args[:olddn] or raise "Unable to rename empty DN"
Chris@0 1277 new_rdn = args[:newrdn] or raise "Unable to rename to empty RDN"
Chris@0 1278 delete_attrs = args[:delete_attributes] ? true : false
Chris@0 1279
Chris@0 1280 request = [old_dn.to_ber, new_rdn.to_ber, delete_attrs.to_ber].to_ber_appsequence(12)
Chris@0 1281 pkt = [next_msgid.to_ber, request].to_ber_sequence
Chris@0 1282 @conn.write pkt
Chris@0 1283
Chris@0 1284 (be = @conn.read_ber(AsnSyntax)) && (pdu = LdapPdu.new( be )) && (pdu.app_tag == 13) or raise LdapError.new( "response missing or invalid" )
Chris@0 1285 pdu.result_code
Chris@0 1286 end
Chris@0 1287
Chris@0 1288
Chris@0 1289 #--
Chris@0 1290 # delete
Chris@0 1291 # TODO, need to support a time limit, in case the server fails to respond.
Chris@0 1292 #
Chris@0 1293 def delete args
Chris@0 1294 dn = args[:dn] or raise "Unable to delete empty DN"
Chris@0 1295
Chris@0 1296 request = dn.to_s.to_ber_application_string(10)
Chris@0 1297 pkt = [next_msgid.to_ber, request].to_ber_sequence
Chris@0 1298 @conn.write pkt
Chris@0 1299
Chris@0 1300 (be = @conn.read_ber(AsnSyntax)) && (pdu = LdapPdu.new( be )) && (pdu.app_tag == 11) or raise LdapError.new( "response missing or invalid" )
Chris@0 1301 pdu.result_code
Chris@0 1302 end
Chris@0 1303
Chris@0 1304
Chris@0 1305 end # class Connection
Chris@0 1306 end # class LDAP
Chris@0 1307
Chris@0 1308
Chris@0 1309 end # module Net
Chris@0 1310
Chris@0 1311