dim-ruby-net-ldap 0.1.0

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