~ubuntu-branches/ubuntu/utopic/ruby-net-ldap/utopic-proposed

« back to all changes in this revision

Viewing changes to lib/net/ldap.rb

  • Committer: Package Import Robot
  • Author(s): Jérémy Lal
  • Date: 2012-05-14 17:25:45 UTC
  • mfrom: (1.1.1)
  • Revision ID: package-import@ubuntu.com-20120514172545-m08z3m92de2n2pfn
Tags: 0.3.1-1
* Upstream update.
* debian/watch: refer to latest net-ldap project.
* debian/copyright:
  + license changed to Expat, with permission from Ondřej Surý for the
    debian/* part.
  + format 1.0
  + add a lintian-override because Comment mentions old GPL license.
* debian/control:
  + Standards-Version 3.9.3 (no changes required)
  + Use anonscm.d.o in Vcs-* fields.
  + Update Homepage url.
  + XS-Ruby-Versions: all, this module is fine with ruby 1.8 and 1.9.
* debian/patches:
  + Unapply unneeded patches
  + 0003-fix_require_in_tests.patch: tests are called from CURDIR.
* Update debian/ruby-test-files.yaml

Show diffs side-by-side

added added

removed removed

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