annotate .svn/pristine/c8/c84d690d9bd0576dfc0e1af20e017bb13ff2e71d.svn-base @ 1628:9c5f8e24dadc live tip

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