prathe-net-ldap 0.2.20110317223538

Sign up to get free protection for your applications and to get access to all the features.
Files changed (51) hide show
  1. data/.autotest +11 -0
  2. data/.gemtest +0 -0
  3. data/.rspec +2 -0
  4. data/Contributors.rdoc +21 -0
  5. data/Hacking.rdoc +68 -0
  6. data/History.rdoc +172 -0
  7. data/License.rdoc +29 -0
  8. data/Manifest.txt +49 -0
  9. data/README.rdoc +52 -0
  10. data/Rakefile +75 -0
  11. data/autotest/discover.rb +1 -0
  12. data/lib/net-ldap.rb +2 -0
  13. data/lib/net/ber.rb +318 -0
  14. data/lib/net/ber/ber_parser.rb +168 -0
  15. data/lib/net/ber/core_ext.rb +62 -0
  16. data/lib/net/ber/core_ext/array.rb +82 -0
  17. data/lib/net/ber/core_ext/bignum.rb +22 -0
  18. data/lib/net/ber/core_ext/false_class.rb +10 -0
  19. data/lib/net/ber/core_ext/fixnum.rb +66 -0
  20. data/lib/net/ber/core_ext/string.rb +60 -0
  21. data/lib/net/ber/core_ext/true_class.rb +12 -0
  22. data/lib/net/ldap.rb +1556 -0
  23. data/lib/net/ldap/dataset.rb +154 -0
  24. data/lib/net/ldap/dn.rb +225 -0
  25. data/lib/net/ldap/entry.rb +185 -0
  26. data/lib/net/ldap/filter.rb +759 -0
  27. data/lib/net/ldap/password.rb +31 -0
  28. data/lib/net/ldap/pdu.rb +256 -0
  29. data/lib/net/snmp.rb +268 -0
  30. data/net-ldap.gemspec +59 -0
  31. data/spec/integration/ssl_ber_spec.rb +36 -0
  32. data/spec/spec.opts +2 -0
  33. data/spec/spec_helper.rb +5 -0
  34. data/spec/unit/ber/ber_spec.rb +109 -0
  35. data/spec/unit/ber/core_ext/string_spec.rb +51 -0
  36. data/spec/unit/ldap/dn_spec.rb +80 -0
  37. data/spec/unit/ldap/entry_spec.rb +51 -0
  38. data/spec/unit/ldap/filter_spec.rb +84 -0
  39. data/spec/unit/ldap_spec.rb +48 -0
  40. data/test/common.rb +3 -0
  41. data/test/test_entry.rb +59 -0
  42. data/test/test_filter.rb +122 -0
  43. data/test/test_ldap_connection.rb +24 -0
  44. data/test/test_ldif.rb +79 -0
  45. data/test/test_password.rb +17 -0
  46. data/test/test_rename.rb +77 -0
  47. data/test/test_snmp.rb +114 -0
  48. data/test/testdata.ldif +101 -0
  49. data/testserver/ldapserver.rb +210 -0
  50. data/testserver/testdata.ldif +101 -0
  51. metadata +206 -0
@@ -0,0 +1,62 @@
1
+ # -*- ruby encoding: utf-8 -*-
2
+ require 'net/ber/ber_parser'
3
+ # :stopdoc:
4
+ class IO
5
+ include Net::BER::BERParser
6
+ end
7
+
8
+ class StringIO
9
+ include Net::BER::BERParser
10
+ end
11
+
12
+ if defined? ::OpenSSL
13
+ class OpenSSL::SSL::SSLSocket
14
+ include Net::BER::BERParser
15
+ end
16
+ end
17
+ # :startdoc:
18
+
19
+ module Net::BER::Extensions # :nodoc:
20
+ end
21
+
22
+ require 'net/ber/core_ext/string'
23
+ # :stopdoc:
24
+ class String
25
+ include Net::BER::BERParser
26
+ include Net::BER::Extensions::String
27
+ end
28
+
29
+ require 'net/ber/core_ext/array'
30
+ # :stopdoc:
31
+ class Array
32
+ include Net::BER::Extensions::Array
33
+ end
34
+ # :startdoc:
35
+
36
+ require 'net/ber/core_ext/bignum'
37
+ # :stopdoc:
38
+ class Bignum
39
+ include Net::BER::Extensions::Bignum
40
+ end
41
+ # :startdoc:
42
+
43
+ require 'net/ber/core_ext/fixnum'
44
+ # :stopdoc:
45
+ class Fixnum
46
+ include Net::BER::Extensions::Fixnum
47
+ end
48
+ # :startdoc:
49
+
50
+ require 'net/ber/core_ext/true_class'
51
+ # :stopdoc:
52
+ class TrueClass
53
+ include Net::BER::Extensions::TrueClass
54
+ end
55
+ # :startdoc:
56
+
57
+ require 'net/ber/core_ext/false_class'
58
+ # :stopdoc:
59
+ class FalseClass
60
+ include Net::BER::Extensions::FalseClass
61
+ end
62
+ # :startdoc:
@@ -0,0 +1,82 @@
1
+ # -*- ruby encoding: utf-8 -*-
2
+ ##
3
+ # BER extensions to the Array class.
4
+ module Net::BER::Extensions::Array
5
+ ##
6
+ # Converts an Array to a BER sequence. All values in the Array are
7
+ # expected to be in BER format prior to calling this method.
8
+ def to_ber(id = 0)
9
+ # The universal sequence tag 0x30 is composed of the base tag value
10
+ # (0x10) and the constructed flag (0x20).
11
+ to_ber_seq_internal(0x30 + id)
12
+ end
13
+ alias_method :to_ber_sequence, :to_ber
14
+
15
+ ##
16
+ # Converts an Array to a BER set. All values in the Array are expected to
17
+ # be in BER format prior to calling this method.
18
+ def to_ber_set(id = 0)
19
+ # The universal set tag 0x31 is composed of the base tag value (0x11)
20
+ # and the constructed flag (0x20).
21
+ to_ber_seq_internal(0x31 + id)
22
+ end
23
+
24
+ ##
25
+ # Converts an Array to an application-specific sequence, assigned a tag
26
+ # value that is meaningful to the particular protocol being used. All
27
+ # values in the Array are expected to be in BER format pr prior to calling
28
+ # this method.
29
+ #--
30
+ # Implementor's note 20100320(AZ): RFC 4511 (the LDAPv3 protocol) as well
31
+ # as earlier RFCs 1777 and 2559 seem to indicate that LDAP only has
32
+ # application constructed sequences (0x60). However, ldapsearch sends some
33
+ # context-specific constructed sequences (0xA0); other clients may do the
34
+ # same. This behaviour appears to violate the RFCs. In real-world
35
+ # practice, we may need to change calls of #to_ber_appsequence to
36
+ # #to_ber_contextspecific for full LDAP server compatibility.
37
+ #
38
+ # This note probably belongs elsewhere.
39
+ #++
40
+ def to_ber_appsequence(id = 0)
41
+ # The application sequence tag always starts from the application flag
42
+ # (0x40) and the constructed flag (0x20).
43
+ to_ber_seq_internal(0x60 + id)
44
+ end
45
+
46
+ ##
47
+ # Converts an Array to a context-specific sequence, assigned a tag value
48
+ # that is meaningful to the particular context of the particular protocol
49
+ # being used. All values in the Array are expected to be in BER format
50
+ # prior to calling this method.
51
+ def to_ber_contextspecific(id = 0)
52
+ # The application sequence tag always starts from the context flag
53
+ # (0x80) and the constructed flag (0x20).
54
+ to_ber_seq_internal(0xa0 + id)
55
+ end
56
+
57
+ ##
58
+ # The internal sequence packing routine. All values in the Array are
59
+ # expected to be in BER format prior to calling this method.
60
+ def to_ber_seq_internal(code)
61
+ s = self.join
62
+ [code].pack('C') + s.length.to_ber_length_encoding + s
63
+ end
64
+ private :to_ber_seq_internal
65
+
66
+ ##
67
+ # SNMP Object Identifiers (OID) are special arrays
68
+ #--
69
+ # 20100320 AZ: I do not think that this method should be in BER, since
70
+ # this appears to be SNMP-specific. This should probably be subsumed by a
71
+ # proper SNMP OID object.
72
+ #++
73
+ def to_ber_oid
74
+ ary = self.dup
75
+ first = ary.shift
76
+ raise Net::BER::BerError, "Invalid OID" unless [0, 1, 2].include?(first)
77
+ first = first * 40 + ary.shift
78
+ ary.unshift first
79
+ oid = ary.pack("w*")
80
+ [6, oid.length].pack("CC") + oid
81
+ end
82
+ end
@@ -0,0 +1,22 @@
1
+ # -*- ruby encoding: utf-8 -*-
2
+ ##
3
+ # BER extensions to the Bignum class.
4
+ module Net::BER::Extensions::Bignum
5
+ ##
6
+ # Converts a Bignum to an uncompressed BER integer.
7
+ def to_ber
8
+ result = []
9
+
10
+ # NOTE: Array#pack's 'w' is a BER _compressed_ integer. We need
11
+ # uncompressed BER integers, so we're not using that. See also:
12
+ # http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/228864
13
+ n = self
14
+ while n > 0
15
+ b = n & 0xff
16
+ result << b
17
+ n = n >> 8
18
+ end
19
+
20
+ "\002" + ([result.size] + result.reverse).pack('C*')
21
+ end
22
+ end
@@ -0,0 +1,10 @@
1
+ # -*- ruby encoding: utf-8 -*-
2
+ ##
3
+ # BER extensions to +false+.
4
+ module Net::BER::Extensions::FalseClass
5
+ ##
6
+ # Converts +false+ to the BER wireline representation of +false+.
7
+ def to_ber
8
+ "\001\001\000"
9
+ end
10
+ end
@@ -0,0 +1,66 @@
1
+ # -*- ruby encoding: utf-8 -*-
2
+ ##
3
+ # Ber extensions to the Fixnum class.
4
+ module Net::BER::Extensions::Fixnum
5
+ ##
6
+ # Converts the fixnum to BER format.
7
+ def to_ber
8
+ "\002#{to_ber_internal}"
9
+ end
10
+
11
+ ##
12
+ # Converts the fixnum to BER enumerated format.
13
+ def to_ber_enumerated
14
+ "\012#{to_ber_internal}"
15
+ end
16
+
17
+ ##
18
+ # Converts the fixnum to BER length encodining format.
19
+ def to_ber_length_encoding
20
+ if self <= 127
21
+ [self].pack('C')
22
+ else
23
+ i = [self].pack('N').sub(/^[\0]+/,"")
24
+ [0x80 + i.length].pack('C') + i
25
+ end
26
+ end
27
+
28
+ ##
29
+ # Generate a BER-encoding for an application-defined INTEGER. Examples of
30
+ # such integers are SNMP's Counter, Gauge, and TimeTick types.
31
+ def to_ber_application(tag)
32
+ [0x40 + tag].pack("C") + to_ber_internal
33
+ end
34
+
35
+ ##
36
+ # Used to BER-encode the length and content bytes of a Fixnum. Callers
37
+ # must prepend the tag byte for the contained value.
38
+ def to_ber_internal
39
+ # CAUTION: Bit twiddling ahead. You might want to shield your eyes or
40
+ # something.
41
+
42
+ # Looks for the first byte in the fixnum that is not all zeroes. It does
43
+ # this by masking one byte after another, checking the result for bits
44
+ # that are left on.
45
+ size = Net::BER::MAX_FIXNUM_SIZE
46
+ while size > 1
47
+ break if (self & (0xff << (size - 1) * 8)) > 0
48
+ size -= 1
49
+ end
50
+
51
+ # Store the size of the fixnum in the result
52
+ result = [size]
53
+
54
+ # Appends bytes to result, starting with higher orders first. Extraction
55
+ # of bytes is done by right shifting the original fixnum by an amount
56
+ # and then masking that with 0xff.
57
+ while size > 0
58
+ # right shift size - 1 bytes, mask with 0xff
59
+ result << ((self >> ((size - 1) * 8)) & 0xff)
60
+ size -= 1
61
+ end
62
+
63
+ result.pack('C*')
64
+ end
65
+ private :to_ber_internal
66
+ end
@@ -0,0 +1,60 @@
1
+ # -*- ruby encoding: utf-8 -*-
2
+ require 'stringio'
3
+
4
+ ##
5
+ # BER extensions to the String class.
6
+ module Net::BER::Extensions::String
7
+ ##
8
+ # Converts a string to a BER string. Universal octet-strings are tagged
9
+ # with 0x04, but other values are possible depending on the context, so we
10
+ # let the caller give us one.
11
+ #
12
+ # User code should call either #to_ber_application_string or
13
+ # #to_ber_contextspecific.
14
+ def to_ber(code = 0x04)
15
+ raw_string = raw_utf8_encoded
16
+ [code].pack('C') + raw_string.length.to_ber_length_encoding + raw_string
17
+ end
18
+
19
+ def raw_utf8_encoded
20
+ if self.respond_to?(:encode)
21
+ # Strings should be UTF-8 encoded according to LDAP.
22
+ # However, the BER code is not necessarily valid UTF-8
23
+ self.encode('UTF-8').force_encoding('ASCII-8BIT')
24
+ else
25
+ self
26
+ end
27
+ end
28
+ private :raw_utf8_encoded
29
+
30
+ ##
31
+ # Creates an application-specific BER string encoded value with the
32
+ # provided syntax code value.
33
+ def to_ber_application_string(code)
34
+ to_ber(0x40 + code)
35
+ end
36
+
37
+ ##
38
+ # Creates a context-specific BER string encoded value with the provided
39
+ # syntax code value.
40
+ def to_ber_contextspecific(code)
41
+ to_ber(0x80 + code)
42
+ end
43
+
44
+ ##
45
+ # Nondestructively reads a BER object from this string.
46
+ def read_ber(syntax = nil)
47
+ StringIO.new(self).read_ber(syntax)
48
+ end
49
+
50
+ ##
51
+ # Destructively reads a BER object from the string.
52
+ def read_ber!(syntax = nil)
53
+ io = StringIO.new(self)
54
+
55
+ result = io.read_ber(syntax)
56
+ self.slice!(0...io.pos)
57
+
58
+ return result
59
+ end
60
+ end
@@ -0,0 +1,12 @@
1
+ # -*- ruby encoding: utf-8 -*-
2
+ ##
3
+ # BER extensions to +true+.
4
+ module Net::BER::Extensions::TrueClass
5
+ ##
6
+ # Converts +true+ to the BER wireline representation of +true+.
7
+ def to_ber
8
+ # 20100319 AZ: Note that this may not be the completely correct value,
9
+ # per some test documentation. We need to determine the truth of this.
10
+ "\001\001\001"
11
+ end
12
+ end
@@ -0,0 +1,1556 @@
1
+ # -*- ruby encoding: utf-8 -*-
2
+ require 'ostruct'
3
+
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
17
+ end
18
+ require 'socket'
19
+
20
+ require 'net/ber'
21
+ require 'net/ldap/pdu'
22
+ require 'net/ldap/filter'
23
+ require 'net/ldap/dataset'
24
+ require 'net/ldap/password'
25
+ require 'net/ldap/entry'
26
+
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.2.2"
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
+ 12 => "Unavailable crtical extension",
321
+ 14 => "saslBindInProgress",
322
+ 16 => "No Such Attribute",
323
+ 17 => "Undefined Attribute Type",
324
+ 20 => "Attribute or Value Exists",
325
+ 32 => "No Such Object",
326
+ 34 => "Invalid DN Syntax",
327
+ 48 => "Inappropriate Authentication",
328
+ 49 => "Invalid Credentials",
329
+ 50 => "Insufficient Access Rights",
330
+ 51 => "Busy",
331
+ 52 => "Unavailable",
332
+ 53 => "Unwilling to perform",
333
+ 65 => "Object Class Violation",
334
+ 68 => "Entry Already Exists"
335
+ }
336
+
337
+ module LdapControls
338
+ PagedResults = "1.2.840.113556.1.4.319" # Microsoft evil from RFC 2696
339
+ end
340
+
341
+ def self.result2string(code) #:nodoc:
342
+ ResultStrings[code] || "unknown result (#{code})"
343
+ end
344
+
345
+ attr_accessor :host
346
+ attr_accessor :port
347
+ attr_accessor :base
348
+
349
+ # Instantiate an object of type Net::LDAP to perform directory operations.
350
+ # This constructor takes a Hash containing arguments, all of which are
351
+ # either optional or may be specified later with other methods as
352
+ # described below. The following arguments are supported:
353
+ # * :host => the LDAP server's IP-address (default 127.0.0.1)
354
+ # * :port => the LDAP server's TCP port (default 389)
355
+ # * :auth => a Hash containing authorization parameters. Currently
356
+ # supported values include: {:method => :anonymous} and {:method =>
357
+ # :simple, :username => your_user_name, :password => your_password }
358
+ # The password parameter may be a Proc that returns a String.
359
+ # * :base => a default treebase parameter for searches performed against
360
+ # the LDAP server. If you don't give this value, then each call to
361
+ # #search must specify a treebase parameter. If you do give this value,
362
+ # then it will be used in subsequent calls to #search that do not
363
+ # specify a treebase. If you give a treebase value in any particular
364
+ # call to #search, that value will override any treebase value you give
365
+ # here.
366
+ # * :encryption => specifies the encryption to be used in communicating
367
+ # with the LDAP server. The value is either a Hash containing additional
368
+ # parameters, or the Symbol :simple_tls, which is equivalent to
369
+ # specifying the Hash {:method => :simple_tls}. There is a fairly large
370
+ # range of potential values that may be given for this parameter. See
371
+ # #encryption for details.
372
+ #
373
+ # Instantiating a Net::LDAP object does <i>not</i> result in network
374
+ # traffic to the LDAP server. It simply stores the connection and binding
375
+ # parameters in the object.
376
+ def initialize(args = {})
377
+ @host = args[:host] || DefaultHost
378
+ @port = args[:port] || DefaultPort
379
+ @verbose = false # Make this configurable with a switch on the class.
380
+ @auth = args[:auth] || DefaultAuth
381
+ @base = args[:base] || DefaultTreebase
382
+ encryption args[:encryption] # may be nil
383
+
384
+ if pr = @auth[:password] and pr.respond_to?(:call)
385
+ @auth[:password] = pr.call
386
+ end
387
+
388
+ # This variable is only set when we are created with LDAP::open. All of
389
+ # our internal methods will connect using it, or else they will create
390
+ # their own.
391
+ @open_connection = nil
392
+ end
393
+
394
+ # Convenience method to specify authentication credentials to the LDAP
395
+ # server. Currently supports simple authentication requiring a username
396
+ # and password.
397
+ #
398
+ # Observe that on most LDAP servers, the username is a complete DN.
399
+ # However, with A/D, it's often possible to give only a user-name rather
400
+ # than a complete DN. In the latter case, beware that many A/D servers are
401
+ # configured to permit anonymous (uncredentialled) binding, and will
402
+ # silently accept your binding as anonymous if you give an unrecognized
403
+ # username. This is not usually what you want. (See
404
+ # #get_operation_result.)
405
+ #
406
+ # <b>Important:</b> The password argument may be a Proc that returns a
407
+ # string. This makes it possible for you to write client programs that
408
+ # solicit passwords from users or from other data sources without showing
409
+ # them in your code or on command lines.
410
+ #
411
+ # require 'net/ldap'
412
+ #
413
+ # ldap = Net::LDAP.new
414
+ # ldap.host = server_ip_address
415
+ # ldap.authenticate "cn=Your Username, cn=Users, dc=example, dc=com", "your_psw"
416
+ #
417
+ # Alternatively (with a password block):
418
+ #
419
+ # require 'net/ldap'
420
+ #
421
+ # ldap = Net::LDAP.new
422
+ # ldap.host = server_ip_address
423
+ # psw = proc { your_psw_function }
424
+ # ldap.authenticate "cn=Your Username, cn=Users, dc=example, dc=com", psw
425
+ #
426
+ def authenticate(username, password)
427
+ password = password.call if password.respond_to?(:call)
428
+ @auth = {
429
+ :method => :simple,
430
+ :username => username,
431
+ :password => password
432
+ }
433
+ end
434
+ alias_method :auth, :authenticate
435
+
436
+ # Convenience method to specify encryption characteristics for connections
437
+ # to LDAP servers. Called implicitly by #new and #open, but may also be
438
+ # called by user code if desired. The single argument is generally a Hash
439
+ # (but see below for convenience alternatives). This implementation is
440
+ # currently a stub, supporting only a few encryption alternatives. As
441
+ # additional capabilities are added, more configuration values will be
442
+ # added here.
443
+ #
444
+ # Currently, the only supported argument is { :method => :simple_tls }.
445
+ # (Equivalently, you may pass the symbol :simple_tls all by itself,
446
+ # without enclosing it in a Hash.)
447
+ #
448
+ # The :simple_tls encryption method encrypts <i>all</i> communications
449
+ # with the LDAP server. It completely establishes SSL/TLS encryption with
450
+ # the LDAP server before any LDAP-protocol data is exchanged. There is no
451
+ # plaintext negotiation and no special encryption-request controls are
452
+ # sent to the server. <i>The :simple_tls option is the simplest, easiest
453
+ # way to encrypt communications between Net::LDAP and LDAP servers.</i>
454
+ # It's intended for cases where you have an implicit level of trust in the
455
+ # authenticity of the LDAP server. No validation of the LDAP server's SSL
456
+ # certificate is performed. This means that :simple_tls will not produce
457
+ # errors if the LDAP server's encryption certificate is not signed by a
458
+ # well-known Certification Authority. If you get communications or
459
+ # protocol errors when using this option, check with your LDAP server
460
+ # administrator. Pay particular attention to the TCP port you are
461
+ # connecting to. It's impossible for an LDAP server to support plaintext
462
+ # LDAP communications and <i>simple TLS</i> connections on the same port.
463
+ # The standard TCP port for unencrypted LDAP connections is 389, but the
464
+ # standard port for simple-TLS encrypted connections is 636. Be sure you
465
+ # are using the correct port.
466
+ #
467
+ # <i>[Note: a future version of Net::LDAP will support the STARTTLS LDAP
468
+ # control, which will enable encrypted communications on the same TCP port
469
+ # used for unencrypted connections.]</i>
470
+ def encryption(args)
471
+ case args
472
+ when :simple_tls, :start_tls
473
+ args = { :method => args }
474
+ end
475
+ @encryption = args
476
+ end
477
+
478
+ # #open takes the same parameters as #new. #open makes a network
479
+ # connection to the LDAP server and then passes a newly-created Net::LDAP
480
+ # object to the caller-supplied block. Within the block, you can call any
481
+ # of the instance methods of Net::LDAP to perform operations against the
482
+ # LDAP directory. #open will perform all the operations in the
483
+ # user-supplied block on the same network connection, which will be closed
484
+ # automatically when the block finishes.
485
+ #
486
+ # # (PSEUDOCODE)
487
+ # auth = { :method => :simple, :username => username, :password => password }
488
+ # Net::LDAP.open(:host => ipaddress, :port => 389, :auth => auth) do |ldap|
489
+ # ldap.search(...)
490
+ # ldap.add(...)
491
+ # ldap.modify(...)
492
+ # end
493
+ def self.open(args)
494
+ ldap1 = new(args)
495
+ ldap1.open { |ldap| yield ldap }
496
+ end
497
+
498
+ # Returns a meaningful result any time after a protocol operation (#bind,
499
+ # #search, #add, #modify, #rename, #delete) has completed. It returns an
500
+ # #OpenStruct containing an LDAP result code (0 means success), and a
501
+ # human-readable string.
502
+ #
503
+ # unless ldap.bind
504
+ # puts "Result: #{ldap.get_operation_result.code}"
505
+ # puts "Message: #{ldap.get_operation_result.message}"
506
+ # end
507
+ #
508
+ # Certain operations return additional information, accessible through
509
+ # members of the object returned from #get_operation_result. Check
510
+ # #get_operation_result.error_message and
511
+ # #get_operation_result.matched_dn.
512
+ #
513
+ #--
514
+ # Modified the implementation, 20Mar07. We might get a hash of LDAP
515
+ # response codes instead of a simple numeric code.
516
+ #++
517
+ def get_operation_result
518
+ os = OpenStruct.new
519
+ if @result.is_a?(Hash)
520
+ # We might get a hash of LDAP response codes instead of a simple
521
+ # numeric code.
522
+ os.code = (@result[:resultCode] || "").to_i
523
+ os.error_message = @result[:errorMessage]
524
+ os.matched_dn = @result[:matchedDN]
525
+ elsif @result
526
+ os.code = @result
527
+ else
528
+ os.code = 0
529
+ end
530
+ os.message = Net::LDAP.result2string(os.code)
531
+ os
532
+ end
533
+
534
+ # Opens a network connection to the server and then passes <tt>self</tt>
535
+ # to the caller-supplied block. The connection is closed when the block
536
+ # completes. Used for executing multiple LDAP operations without requiring
537
+ # a separate network connection (and authentication) for each one.
538
+ # <i>Note:</i> You do not need to log-in or "bind" to the server. This
539
+ # will be done for you automatically. For an even simpler approach, see
540
+ # the class method Net::LDAP#open.
541
+ #
542
+ # # (PSEUDOCODE)
543
+ # auth = { :method => :simple, :username => username, :password => password }
544
+ # ldap = Net::LDAP.new(:host => ipaddress, :port => 389, :auth => auth)
545
+ # ldap.open do |ldap|
546
+ # ldap.search(...)
547
+ # ldap.add(...)
548
+ # ldap.modify(...)
549
+ # end
550
+ def open
551
+ # First we make a connection and then a binding, but we don't do
552
+ # anything with the bind results. We then pass self to the caller's
553
+ # block, where he will execute his LDAP operations. Of course they will
554
+ # all generate auth failures if the bind was unsuccessful.
555
+ raise Net::LDAP::LdapError, "Open already in progress" if @open_connection
556
+
557
+ begin
558
+ @open_connection = Net::LDAP::Connection.new(:host => @host,
559
+ :port => @port,
560
+ :encryption =>
561
+ @encryption)
562
+ @open_connection.bind(@auth)
563
+ yield self
564
+ ensure
565
+ @open_connection.close if @open_connection
566
+ @open_connection = nil
567
+ end
568
+ end
569
+
570
+ # Searches the LDAP directory for directory entries. Takes a hash argument
571
+ # with parameters. Supported parameters include:
572
+ # * :base (a string specifying the tree-base for the search);
573
+ # * :filter (an object of type Net::LDAP::Filter, defaults to
574
+ # objectclass=*);
575
+ # * :attributes (a string or array of strings specifying the LDAP
576
+ # attributes to return from the server);
577
+ # * :return_result (a boolean specifying whether to return a result set).
578
+ # * :attributes_only (a boolean flag, defaults false)
579
+ # * :scope (one of: Net::LDAP::SearchScope_BaseObject,
580
+ # Net::LDAP::SearchScope_SingleLevel,
581
+ # Net::LDAP::SearchScope_WholeSubtree. Default is WholeSubtree.)
582
+ # * :size (an integer indicating the maximum number of search entries to
583
+ # return. Default is zero, which signifies no limit.)
584
+ #
585
+ # #search queries the LDAP server and passes <i>each entry</i> to the
586
+ # caller-supplied block, as an object of type Net::LDAP::Entry. If the
587
+ # search returns 1000 entries, the block will be called 1000 times. If the
588
+ # search returns no entries, the block will not be called.
589
+ #
590
+ # #search returns either a result-set or a boolean, depending on the value
591
+ # of the <tt>:return_result</tt> argument. The default behavior is to
592
+ # return a result set, which is an Array of objects of class
593
+ # Net::LDAP::Entry. If you request a result set and #search fails with an
594
+ # error, it will return nil. Call #get_operation_result to get the error
595
+ # information returned by
596
+ # the LDAP server.
597
+ #
598
+ # When <tt>:return_result => false, </tt> #search will return only a
599
+ # Boolean, to indicate whether the operation succeeded. This can improve
600
+ # performance with very large result sets, because the library can discard
601
+ # each entry from memory after your block processes it.
602
+ #
603
+ # treebase = "dc=example, dc=com"
604
+ # filter = Net::LDAP::Filter.eq("mail", "a*.com")
605
+ # attrs = ["mail", "cn", "sn", "objectclass"]
606
+ # ldap.search(:base => treebase, :filter => filter, :attributes => attrs,
607
+ # :return_result => false) do |entry|
608
+ # puts "DN: #{entry.dn}"
609
+ # entry.each do |attr, values|
610
+ # puts ".......#{attr}:"
611
+ # values.each do |value|
612
+ # puts " #{value}"
613
+ # end
614
+ # end
615
+ # end
616
+ def search(args = {})
617
+ unless args[:ignore_server_caps]
618
+ args[:paged_searches_supported] = paged_searches_supported?
619
+ end
620
+
621
+ args[:base] ||= @base
622
+ return_result_set = args[:return_result] != false
623
+ result_set = return_result_set ? [] : nil
624
+
625
+ if @open_connection
626
+ @result = @open_connection.search(args) { |entry|
627
+ result_set << entry if result_set
628
+ yield entry if block_given?
629
+ }
630
+ else
631
+ @result = 0
632
+ begin
633
+ conn = Net::LDAP::Connection.new(:host => @host, :port => @port,
634
+ :encryption => @encryption)
635
+ if (@result = conn.bind(args[:auth] || @auth)) == 0
636
+ @result = conn.search(args) { |entry|
637
+ result_set << entry if result_set
638
+ yield entry if block_given?
639
+ }
640
+ end
641
+ ensure
642
+ conn.close if conn
643
+ end
644
+ end
645
+
646
+ if return_result_set
647
+ @result == 0 ? result_set : nil
648
+ else
649
+ @result == 0
650
+ end
651
+ end
652
+
653
+ # #bind connects to an LDAP server and requests authentication based on
654
+ # the <tt>:auth</tt> parameter passed to #open or #new. It takes no
655
+ # parameters.
656
+ #
657
+ # User code does not need to call #bind directly. It will be called
658
+ # implicitly by the library whenever you invoke an LDAP operation, such as
659
+ # #search or #add.
660
+ #
661
+ # It is useful, however, to call #bind in your own code when the only
662
+ # operation you intend to perform against the directory is to validate a
663
+ # login credential. #bind returns true or false to indicate whether the
664
+ # binding was successful. Reasons for failure include malformed or
665
+ # unrecognized usernames and incorrect passwords. Use
666
+ # #get_operation_result to find out what happened in case of failure.
667
+ #
668
+ # Here's a typical example using #bind to authenticate a credential which
669
+ # was (perhaps) solicited from the user of a 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
+ # Here's a more succinct example which does exactly the same thing, but
684
+ # collects all the required parameters into arguments:
685
+ #
686
+ # require 'net/ldap'
687
+ # ldap = Net::LDAP.new(:host => your_server_ip_address, :port => 389)
688
+ # if ldap.bind(:method => :simple, :username => your_user_name,
689
+ # :password => your_user_password)
690
+ # # authentication succeeded
691
+ # else
692
+ # # authentication failed
693
+ # p ldap.get_operation_result
694
+ # end
695
+ #
696
+ # You don't need to pass a user-password as a String object to bind. You
697
+ # can also pass a Ruby Proc object which returns a string. This will cause
698
+ # bind to execute the Proc (which might then solicit input from a user
699
+ # with console display suppressed). The String value returned from the
700
+ # Proc is used as the password.
701
+ #
702
+ # You don't have to create a new instance of Net::LDAP every time you
703
+ # perform a binding in this way. If you prefer, you can cache the
704
+ # Net::LDAP object and re-use it to perform subsequent bindings,
705
+ # <i>provided</i> you call #auth to specify a new credential before
706
+ # calling #bind. Otherwise, you'll just re-authenticate the previous user!
707
+ # (You don't need to re-set the values of #host and #port.) As noted in
708
+ # the documentation for #auth, the password parameter can be a Ruby Proc
709
+ # instead of a String.
710
+ def bind(auth = @auth)
711
+ if @open_connection
712
+ @result = @open_connection.bind(auth)
713
+ else
714
+ begin
715
+ conn = Connection.new(:host => @host, :port => @port,
716
+ :encryption => @encryption)
717
+ @result = conn.bind(auth)
718
+ ensure
719
+ conn.close if conn
720
+ end
721
+ end
722
+
723
+ @result == 0
724
+ end
725
+
726
+ # #bind_as is for testing authentication credentials.
727
+ #
728
+ # As described under #bind, most LDAP servers require that you supply a
729
+ # complete DN as a binding-credential, along with an authenticator such as
730
+ # a password. But for many applications (such as authenticating users to a
731
+ # Rails application), you often don't have a full DN to identify the user.
732
+ # You usually get a simple identifier like a username or an email address,
733
+ # along with a password. #bind_as allows you to authenticate these
734
+ # user-identifiers.
735
+ #
736
+ # #bind_as is a combination of a search and an LDAP binding. First, it
737
+ # connects and binds to the directory as normal. Then it searches the
738
+ # directory for an entry corresponding to the email address, username, or
739
+ # other string that you supply. If the entry exists, then #bind_as will
740
+ # <b>re-bind</b> as that user with the password (or other authenticator)
741
+ # that you supply.
742
+ #
743
+ # #bind_as takes the same parameters as #search, <i>with the addition of
744
+ # an authenticator.</i> Currently, this authenticator must be
745
+ # <tt>:password</tt>. Its value may be either a String, or a +proc+ that
746
+ # returns a String. #bind_as returns +false+ on failure. On success, it
747
+ # returns a result set, just as #search does. This result set is an Array
748
+ # of objects of type Net::LDAP::Entry. It contains the directory
749
+ # attributes corresponding to the user. (Just test whether the return
750
+ # value is logically true, if you don't need this additional information.)
751
+ #
752
+ # Here's how you would use #bind_as to authenticate an email address and
753
+ # password:
754
+ #
755
+ # require 'net/ldap'
756
+ #
757
+ # user, psw = "joe_user@yourcompany.com", "joes_psw"
758
+ #
759
+ # ldap = Net::LDAP.new
760
+ # ldap.host = "192.168.0.100"
761
+ # ldap.port = 389
762
+ # ldap.auth "cn=manager, dc=yourcompany, dc=com", "topsecret"
763
+ #
764
+ # result = ldap.bind_as(:base => "dc=yourcompany, dc=com",
765
+ # :filter => "(mail=#{user})",
766
+ # :password => psw)
767
+ # if result
768
+ # puts "Authenticated #{result.first.dn}"
769
+ # else
770
+ # puts "Authentication FAILED."
771
+ # end
772
+ def bind_as(args = {})
773
+ result = false
774
+ open { |me|
775
+ rs = search args
776
+ if rs and rs.first and dn = rs.first.dn
777
+ password = args[:password]
778
+ password = password.call if password.respond_to?(:call)
779
+ result = rs if bind(:method => :simple, :username => dn,
780
+ :password => password)
781
+ end
782
+ }
783
+ result
784
+ end
785
+
786
+ # Adds a new entry to the remote LDAP server.
787
+ # Supported arguments:
788
+ # :dn :: Full DN of the new entry
789
+ # :attributes :: Attributes of the new entry.
790
+ #
791
+ # The attributes argument is supplied as a Hash keyed by Strings or
792
+ # Symbols giving the attribute name, and mapping to Strings or Arrays of
793
+ # Strings giving the actual attribute values. Observe that most LDAP
794
+ # directories enforce schema constraints on the attributes contained in
795
+ # entries. #add will fail with a server-generated error if your attributes
796
+ # violate the server-specific constraints.
797
+ #
798
+ # Here's an example:
799
+ #
800
+ # dn = "cn=George Smith, ou=people, dc=example, dc=com"
801
+ # attr = {
802
+ # :cn => "George Smith",
803
+ # :objectclass => ["top", "inetorgperson"],
804
+ # :sn => "Smith",
805
+ # :mail => "gsmith@example.com"
806
+ # }
807
+ # Net::LDAP.open(:host => host) do |ldap|
808
+ # ldap.add(:dn => dn, :attributes => attr)
809
+ # end
810
+ def add(args)
811
+ if @open_connection
812
+ @result = @open_connection.add(args)
813
+ else
814
+ @result = 0
815
+ begin
816
+ conn = Connection.new(:host => @host, :port => @port,
817
+ :encryption => @encryption)
818
+ if (@result = conn.bind(args[:auth] || @auth)) == 0
819
+ @result = conn.add(args)
820
+ end
821
+ ensure
822
+ conn.close if conn
823
+ end
824
+ end
825
+ @result == 0
826
+ end
827
+
828
+ # Modifies the attribute values of a particular entry on the LDAP
829
+ # directory. Takes a hash with arguments. Supported arguments are:
830
+ # :dn :: (the full DN of the entry whose attributes are to be modified)
831
+ # :operations :: (the modifications to be performed, detailed next)
832
+ #
833
+ # This method returns True or False to indicate whether the operation
834
+ # succeeded or failed, with extended information available by calling
835
+ # #get_operation_result.
836
+ #
837
+ # Also see #add_attribute, #replace_attribute, or #delete_attribute, which
838
+ # provide simpler interfaces to this functionality.
839
+ #
840
+ # The LDAP protocol provides a full and well thought-out set of operations
841
+ # for changing the values of attributes, but they are necessarily somewhat
842
+ # complex and not always intuitive. If these instructions are confusing or
843
+ # incomplete, please send us email or create a bug report on rubyforge.
844
+ #
845
+ # The :operations parameter to #modify takes an array of
846
+ # operation-descriptors. Each individual operation is specified in one
847
+ # element of the array, and most LDAP servers will attempt to perform the
848
+ # operations in order.
849
+ #
850
+ # Each of the operations appearing in the Array must itself be an Array
851
+ # with exactly three elements: an operator:: must be :add, :replace, or
852
+ # :delete an attribute name:: the attribute name (string or symbol) to
853
+ # modify a value:: either a string or an array of strings.
854
+ #
855
+ # The :add operator will, unsurprisingly, add the specified values to the
856
+ # specified attribute. If the attribute does not already exist, :add will
857
+ # create it. Most LDAP servers will generate an error if you try to add a
858
+ # value that already exists.
859
+ #
860
+ # :replace will erase the current value(s) for the specified attribute, if
861
+ # there are any, and replace them with the specified value(s).
862
+ #
863
+ # :delete will remove the specified value(s) from the specified attribute.
864
+ # If you pass nil, an empty string, or an empty array as the value
865
+ # parameter to a :delete operation, the _entire_ _attribute_ will be
866
+ # deleted, along with all of its values.
867
+ #
868
+ # For example:
869
+ #
870
+ # dn = "mail=modifyme@example.com, ou=people, dc=example, dc=com"
871
+ # ops = [
872
+ # [:add, :mail, "aliasaddress@example.com"],
873
+ # [:replace, :mail, ["newaddress@example.com", "newalias@example.com"]],
874
+ # [:delete, :sn, nil]
875
+ # ]
876
+ # ldap.modify :dn => dn, :operations => ops
877
+ #
878
+ # <i>(This example is contrived since you probably wouldn't add a mail
879
+ # value right before replacing the whole attribute, but it shows that
880
+ # order of execution matters. Also, many LDAP servers won't let you delete
881
+ # SN because that would be a schema violation.)</i>
882
+ #
883
+ # It's essential to keep in mind that if you specify more than one
884
+ # operation in a call to #modify, most LDAP servers will attempt to
885
+ # perform all of the operations in the order you gave them. This matters
886
+ # because you may specify operations on the same attribute which must be
887
+ # performed in a certain order.
888
+ #
889
+ # Most LDAP servers will _stop_ processing your modifications if one of
890
+ # them causes an error on the server (such as a schema-constraint
891
+ # violation). If this happens, you will probably get a result code from
892
+ # the server that reflects only the operation that failed, and you may or
893
+ # may not get extended information that will tell you which one failed.
894
+ # #modify has no notion of an atomic transaction. If you specify a chain
895
+ # of modifications in one call to #modify, and one of them fails, the
896
+ # preceding ones will usually not be "rolled back, " resulting in a
897
+ # partial update. This is a limitation of the LDAP protocol, not of
898
+ # Net::LDAP.
899
+ #
900
+ # The lack of transactional atomicity in LDAP means that you're usually
901
+ # better off using the convenience methods #add_attribute,
902
+ # #replace_attribute, and #delete_attribute, which are are wrappers over
903
+ # #modify. However, certain LDAP servers may provide concurrency
904
+ # semantics, in which the several operations contained in a single #modify
905
+ # call are not interleaved with other modification-requests received
906
+ # simultaneously by the server. It bears repeating that this concurrency
907
+ # does _not_ imply transactional atomicity, which LDAP does not provide.
908
+ def modify(args)
909
+ if @open_connection
910
+ @result = @open_connection.modify(args)
911
+ else
912
+ @result = 0
913
+ begin
914
+ conn = Connection.new(:host => @host, :port => @port,
915
+ :encryption => @encryption)
916
+ if (@result = conn.bind(args[:auth] || @auth)) == 0
917
+ @result = conn.modify(args)
918
+ end
919
+ ensure
920
+ conn.close if conn
921
+ end
922
+ end
923
+ @result == 0
924
+ end
925
+
926
+ # Add a value to an attribute. Takes the full DN of the entry to modify,
927
+ # the name (Symbol or String) of the attribute, and the value (String or
928
+ # Array). If the attribute does not exist (and there are no schema
929
+ # violations), #add_attribute will create it with the caller-specified
930
+ # values. If the attribute already exists (and there are no schema
931
+ # violations), the caller-specified values will be _added_ to the values
932
+ # already present.
933
+ #
934
+ # Returns True or False to indicate whether the operation succeeded or
935
+ # failed, with extended information available by calling
936
+ # #get_operation_result. See also #replace_attribute and
937
+ # #delete_attribute.
938
+ #
939
+ # dn = "cn=modifyme, dc=example, dc=com"
940
+ # ldap.add_attribute dn, :mail, "newmailaddress@example.com"
941
+ def add_attribute(dn, attribute, value)
942
+ modify(:dn => dn, :operations => [[:add, attribute, value]])
943
+ end
944
+
945
+ # Replace the value of an attribute. #replace_attribute can be thought of
946
+ # as equivalent to calling #delete_attribute followed by #add_attribute.
947
+ # It takes the full DN of the entry to modify, the name (Symbol or String)
948
+ # of the attribute, and the value (String or Array). If the attribute does
949
+ # not exist, it will be created with the caller-specified value(s). If the
950
+ # attribute does exist, its values will be _discarded_ and replaced with
951
+ # the caller-specified values.
952
+ #
953
+ # Returns True or False to indicate whether the operation succeeded or
954
+ # failed, with extended information available by calling
955
+ # #get_operation_result. See also #add_attribute and #delete_attribute.
956
+ #
957
+ # dn = "cn=modifyme, dc=example, dc=com"
958
+ # ldap.replace_attribute dn, :mail, "newmailaddress@example.com"
959
+ def replace_attribute(dn, attribute, value)
960
+ modify(:dn => dn, :operations => [[:replace, attribute, value]])
961
+ end
962
+
963
+ # Delete an attribute and all its values. Takes the full DN of the entry
964
+ # to modify, and the name (Symbol or String) of the attribute to delete.
965
+ #
966
+ # Returns True or False to indicate whether the operation succeeded or
967
+ # failed, with extended information available by calling
968
+ # #get_operation_result. See also #add_attribute and #replace_attribute.
969
+ #
970
+ # dn = "cn=modifyme, dc=example, dc=com"
971
+ # ldap.delete_attribute dn, :mail
972
+ def delete_attribute(dn, attribute)
973
+ modify(:dn => dn, :operations => [[:delete, attribute, nil]])
974
+ end
975
+
976
+ # Rename an entry on the remote DIS by changing the last RDN of its DN.
977
+ #
978
+ # _Documentation_ _stub_
979
+ def rename(args)
980
+ if @open_connection
981
+ @result = @open_connection.rename(args)
982
+ else
983
+ @result = 0
984
+ begin
985
+ conn = Connection.new(:host => @host, :port => @port,
986
+ :encryption => @encryption)
987
+ if (@result = conn.bind(args[:auth] || @auth)) == 0
988
+ @result = conn.rename(args)
989
+ end
990
+ ensure
991
+ conn.close if conn
992
+ end
993
+ end
994
+ @result == 0
995
+ end
996
+ alias_method :modify_rdn, :rename
997
+
998
+ # Delete an entry from the LDAP directory. Takes a hash of arguments. The
999
+ # only supported argument is :dn, which must give the complete DN of the
1000
+ # entry to be deleted.
1001
+ #
1002
+ # Returns True or False to indicate whether the delete succeeded. Extended
1003
+ # status information is available by calling #get_operation_result.
1004
+ #
1005
+ # dn = "mail=deleteme@example.com, ou=people, dc=example, dc=com"
1006
+ # ldap.delete :dn => dn
1007
+ def delete(args)
1008
+ if @open_connection
1009
+ @result = @open_connection.delete(args)
1010
+ else
1011
+ @result = 0
1012
+ begin
1013
+ conn = Connection.new(:host => @host, :port => @port,
1014
+ :encryption => @encryption)
1015
+ if (@result = conn.bind(args[:auth] || @auth)) == 0
1016
+ @result = conn.delete(args)
1017
+ end
1018
+ ensure
1019
+ conn.close
1020
+ end
1021
+ end
1022
+ @result == 0
1023
+ end
1024
+
1025
+ # This method is experimental and subject to change. Return the rootDSE
1026
+ # record from the LDAP server as a Net::LDAP::Entry, or an empty Entry if
1027
+ # the server doesn't return the record.
1028
+ #--
1029
+ # cf. RFC4512 graf 5.1.
1030
+ # Note that the rootDSE record we return on success has an empty DN, which
1031
+ # is correct. On failure, the empty Entry will have a nil DN. There's no
1032
+ # real reason for that, so it can be changed if desired. The funky
1033
+ # number-disagreements in the set of attribute names is correct per the
1034
+ # RFC. We may be called by #search itself, which may need to determine
1035
+ # things like paged search capabilities. So to avoid an infinite regress,
1036
+ # set :ignore_server_caps, which prevents us getting called recursively.
1037
+ #++
1038
+ def search_root_dse
1039
+ rs = search(:ignore_server_caps => true, :base => "",
1040
+ :scope => SearchScope_BaseObject,
1041
+ :attributes => [ :namingContexts, :supportedLdapVersion,
1042
+ :altServer, :supportedControl, :supportedExtension,
1043
+ :supportedFeatures, :supportedSASLMechanisms])
1044
+ (rs and rs.first) or Net::LDAP::Entry.new
1045
+ end
1046
+
1047
+ # Return the root Subschema record from the LDAP server as a
1048
+ # Net::LDAP::Entry, or an empty Entry if the server doesn't return the
1049
+ # record. On success, the Net::LDAP::Entry returned from this call will
1050
+ # have the attributes :dn, :objectclasses, and :attributetypes. If there
1051
+ # is an error, call #get_operation_result for more information.
1052
+ #
1053
+ # ldap = Net::LDAP.new
1054
+ # ldap.host = "your.ldap.host"
1055
+ # ldap.auth "your-user-dn", "your-psw"
1056
+ # subschema_entry = ldap.search_subschema_entry
1057
+ #
1058
+ # subschema_entry.attributetypes.each do |attrtype|
1059
+ # # your code
1060
+ # end
1061
+ #
1062
+ # subschema_entry.objectclasses.each do |attrtype|
1063
+ # # your code
1064
+ # end
1065
+ #--
1066
+ # cf. RFC4512 section 4, particulary graff 4.4.
1067
+ # The :dn attribute in the returned Entry is the subschema name as
1068
+ # returned from the server. Set :ignore_server_caps, see the notes in
1069
+ # search_root_dse.
1070
+ #++
1071
+ def search_subschema_entry
1072
+ rs = search(:ignore_server_caps => true, :base => "",
1073
+ :scope => SearchScope_BaseObject,
1074
+ :attributes => [:subschemaSubentry])
1075
+ return Net::LDAP::Entry.new unless (rs and rs.first)
1076
+
1077
+ subschema_name = rs.first.subschemasubentry
1078
+ return Net::LDAP::Entry.new unless (subschema_name and subschema_name.first)
1079
+
1080
+ rs = search(:ignore_server_caps => true, :base => subschema_name.first,
1081
+ :scope => SearchScope_BaseObject,
1082
+ :filter => "objectclass=subschema",
1083
+ :attributes => [:objectclasses, :attributetypes])
1084
+ (rs and rs.first) or Net::LDAP::Entry.new
1085
+ end
1086
+
1087
+ #--
1088
+ # Convenience method to query server capabilities.
1089
+ # Only do this once per Net::LDAP object.
1090
+ # Note, we call a search, and we might be called from inside a search!
1091
+ # MUST refactor the root_dse call out.
1092
+ #++
1093
+ def paged_searches_supported?
1094
+ @server_caps ||= search_root_dse
1095
+ @server_caps[:supportedcontrol].include?(Net::LDAP::LdapControls::PagedResults)
1096
+ end
1097
+ end # class LDAP
1098
+
1099
+ # This is a private class used internally by the library. It should not
1100
+ # be called by user code.
1101
+ class Net::LDAP::Connection #:nodoc:
1102
+ LdapVersion = 3
1103
+ MaxSaslChallenges = 10
1104
+
1105
+ def initialize(server)
1106
+ begin
1107
+ @conn = TCPSocket.new(server[:host], server[:port])
1108
+ rescue SocketError
1109
+ raise Net::LDAP::LdapError, "No such address or other socket error."
1110
+ rescue Errno::ECONNREFUSED
1111
+ raise Net::LDAP::LdapError, "Server #{server[:host]} refused connection on port #{server[:port]}."
1112
+ end
1113
+
1114
+ if server[:encryption]
1115
+ setup_encryption server[:encryption]
1116
+ end
1117
+
1118
+ yield self if block_given?
1119
+ end
1120
+
1121
+ module GetbyteForSSLSocket
1122
+ def getbyte
1123
+ getc.ord
1124
+ end
1125
+ end
1126
+
1127
+ def self.wrap_with_ssl(io)
1128
+ raise Net::LDAP::LdapError, "OpenSSL is unavailable" unless Net::LDAP::HasOpenSSL
1129
+ ctx = OpenSSL::SSL::SSLContext.new
1130
+ conn = OpenSSL::SSL::SSLSocket.new(io, ctx)
1131
+ conn.connect
1132
+ conn.sync_close = true
1133
+
1134
+ conn.extend(GetbyteForSSLSocket) unless conn.respond_to?(:getbyte)
1135
+
1136
+ conn
1137
+ end
1138
+
1139
+ #--
1140
+ # Helper method called only from new, and only after we have a
1141
+ # successfully-opened @conn instance variable, which is a TCP connection.
1142
+ # Depending on the received arguments, we establish SSL, potentially
1143
+ # replacing the value of @conn accordingly. Don't generate any errors here
1144
+ # if no encryption is requested. DO raise Net::LDAP::LdapError objects if encryption
1145
+ # is requested and we have trouble setting it up. That includes if OpenSSL
1146
+ # is not set up on the machine. (Question: how does the Ruby OpenSSL
1147
+ # wrapper react in that case?) DO NOT filter exceptions raised by the
1148
+ # OpenSSL library. Let them pass back to the user. That should make it
1149
+ # easier for us to debug the problem reports. Presumably (hopefully?) that
1150
+ # will also produce recognizable errors if someone tries to use this on a
1151
+ # machine without OpenSSL.
1152
+ #
1153
+ # The simple_tls method is intended as the simplest, stupidest, easiest
1154
+ # solution for people who want nothing more than encrypted comms with the
1155
+ # LDAP server. It doesn't do any server-cert validation and requires
1156
+ # nothing in the way of key files and root-cert files, etc etc. OBSERVE:
1157
+ # WE REPLACE the value of @conn, which is presumed to be a connected
1158
+ # TCPSocket object.
1159
+ #
1160
+ # The start_tls method is supported by many servers over the standard LDAP
1161
+ # port. It does not require an alternative port for encrypted
1162
+ # communications, as with simple_tls. Thanks for Kouhei Sutou for
1163
+ # generously contributing the :start_tls path.
1164
+ #++
1165
+ def setup_encryption(args)
1166
+ case args[:method]
1167
+ when :simple_tls
1168
+ @conn = self.class.wrap_with_ssl(@conn)
1169
+ # additional branches requiring server validation and peer certs, etc.
1170
+ # go here.
1171
+ when :start_tls
1172
+ msgid = next_msgid.to_ber
1173
+ request = [Net::LDAP::StartTlsOid.to_ber].to_ber_appsequence(Net::LDAP::PDU::ExtendedRequest)
1174
+ request_pkt = [msgid, request].to_ber_sequence
1175
+ @conn.write request_pkt
1176
+ be = @conn.read_ber(Net::LDAP::AsnSyntax)
1177
+ raise Net::LDAP::LdapError, "no start_tls result" if be.nil?
1178
+ pdu = Net::LDAP::PDU.new(be)
1179
+ raise Net::LDAP::LdapError, "no start_tls result" if pdu.nil?
1180
+ if pdu.result_code.zero?
1181
+ @conn = self.class.wrap_with_ssl(@conn)
1182
+ else
1183
+ raise Net::LDAP::LdapError, "start_tls failed: #{pdu.result_code}"
1184
+ end
1185
+ else
1186
+ raise Net::LDAP::LdapError, "unsupported encryption method #{args[:method]}"
1187
+ end
1188
+ end
1189
+
1190
+ #--
1191
+ # This is provided as a convenience method to make sure a connection
1192
+ # object gets closed without waiting for a GC to happen. Clients shouldn't
1193
+ # have to call it, but perhaps it will come in handy someday.
1194
+ #++
1195
+ def close
1196
+ @conn.close
1197
+ @conn = nil
1198
+ end
1199
+
1200
+ def next_msgid
1201
+ @msgid ||= 0
1202
+ @msgid += 1
1203
+ end
1204
+
1205
+ def bind(auth)
1206
+ meth = auth[:method]
1207
+ if [:simple, :anonymous, :anon].include?(meth)
1208
+ bind_simple auth
1209
+ elsif meth == :sasl
1210
+ bind_sasl(auth)
1211
+ elsif meth == :gss_spnego
1212
+ bind_gss_spnego(auth)
1213
+ else
1214
+ raise Net::LDAP::LdapError, "Unsupported auth method (#{meth})"
1215
+ end
1216
+ end
1217
+
1218
+ #--
1219
+ # Implements a simple user/psw authentication. Accessed by calling #bind
1220
+ # with a method of :simple or :anonymous.
1221
+ #++
1222
+ def bind_simple(auth)
1223
+ user, psw = if auth[:method] == :simple
1224
+ [auth[:username] || auth[:dn], auth[:password]]
1225
+ else
1226
+ ["", ""]
1227
+ end
1228
+
1229
+ raise Net::LDAP::LdapError, "Invalid binding information" unless (user && psw)
1230
+
1231
+ msgid = next_msgid.to_ber
1232
+ request = [LdapVersion.to_ber, user.to_ber,
1233
+ psw.to_ber_contextspecific(0)].to_ber_appsequence(0)
1234
+ request_pkt = [msgid, request].to_ber_sequence
1235
+ @conn.write request_pkt
1236
+
1237
+ (be = @conn.read_ber(Net::LDAP::AsnSyntax) and pdu = Net::LDAP::PDU.new(be)) or raise Net::LDAP::LdapError, "no bind result"
1238
+
1239
+ pdu.result_code
1240
+ end
1241
+
1242
+ #--
1243
+ # Required parameters: :mechanism, :initial_credential and
1244
+ # :challenge_response
1245
+ #
1246
+ # Mechanism is a string value that will be passed in the SASL-packet's
1247
+ # "mechanism" field.
1248
+ #
1249
+ # Initial credential is most likely a string. It's passed in the initial
1250
+ # BindRequest that goes to the server. In some protocols, it may be empty.
1251
+ #
1252
+ # Challenge-response is a Ruby proc that takes a single parameter and
1253
+ # returns an object that will typically be a string. The
1254
+ # challenge-response block is called when the server returns a
1255
+ # BindResponse with a result code of 14 (saslBindInProgress). The
1256
+ # challenge-response block receives a parameter containing the data
1257
+ # returned by the server in the saslServerCreds field of the LDAP
1258
+ # BindResponse packet. The challenge-response block may be called multiple
1259
+ # times during the course of a SASL authentication, and each time it must
1260
+ # return a value that will be passed back to the server as the credential
1261
+ # data in the next BindRequest packet.
1262
+ #++
1263
+ def bind_sasl(auth)
1264
+ mech, cred, chall = auth[:mechanism], auth[:initial_credential],
1265
+ auth[:challenge_response]
1266
+ raise Net::LDAP::LdapError, "Invalid binding information" unless (mech && cred && chall)
1267
+
1268
+ n = 0
1269
+ loop {
1270
+ msgid = next_msgid.to_ber
1271
+ sasl = [mech.to_ber, cred.to_ber].to_ber_contextspecific(3)
1272
+ request = [LdapVersion.to_ber, "".to_ber, sasl].to_ber_appsequence(0)
1273
+ request_pkt = [msgid, request].to_ber_sequence
1274
+ @conn.write request_pkt
1275
+
1276
+ (be = @conn.read_ber(Net::LDAP::AsnSyntax) and pdu = Net::LDAP::PDU.new(be)) or raise Net::LDAP::LdapError, "no bind result"
1277
+ return pdu.result_code unless pdu.result_code == 14 # saslBindInProgress
1278
+ raise Net::LDAP::LdapError, "sasl-challenge overflow" if ((n += 1) > MaxSaslChallenges)
1279
+
1280
+ cred = chall.call(pdu.result_server_sasl_creds)
1281
+ }
1282
+
1283
+ raise Net::LDAP::LdapError, "why are we here?"
1284
+ end
1285
+ private :bind_sasl
1286
+
1287
+ #--
1288
+ # PROVISIONAL, only for testing SASL implementations. DON'T USE THIS YET.
1289
+ # Uses Kohei Kajimoto's Ruby/NTLM. We have to find a clean way to
1290
+ # integrate it without introducing an external dependency.
1291
+ #
1292
+ # This authentication method is accessed by calling #bind with a :method
1293
+ # parameter of :gss_spnego. It requires :username and :password
1294
+ # attributes, just like the :simple authentication method. It performs a
1295
+ # GSS-SPNEGO authentication with the server, which is presumed to be a
1296
+ # Microsoft Active Directory.
1297
+ #++
1298
+ def bind_gss_spnego(auth)
1299
+ require 'ntlm'
1300
+
1301
+ user, psw = [auth[:username] || auth[:dn], auth[:password]]
1302
+ raise Net::LDAP::LdapError, "Invalid binding information" unless (user && psw)
1303
+
1304
+ nego = proc { |challenge|
1305
+ t2_msg = NTLM::Message.parse(challenge)
1306
+ t3_msg = t2_msg.response({ :user => user, :password => psw },
1307
+ { :ntlmv2 => true })
1308
+ t3_msg.serialize
1309
+ }
1310
+
1311
+ bind_sasl(:method => :sasl, :mechanism => "GSS-SPNEGO",
1312
+ :initial_credential => NTLM::Message::Type1.new.serialize,
1313
+ :challenge_response => nego)
1314
+ end
1315
+ private :bind_gss_spnego
1316
+
1317
+ #--
1318
+ # Alternate implementation, this yields each search entry to the caller as
1319
+ # it are received.
1320
+ #
1321
+ # TODO: certain search parameters are hardcoded.
1322
+ # TODO: if we mis-parse the server results or the results are wrong, we
1323
+ # can block forever. That's because we keep reading results until we get a
1324
+ # type-5 packet, which might never come. We need to support the time-limit
1325
+ # in the protocol.
1326
+ #++
1327
+ def search(args = {})
1328
+ search_filter = (args && args[:filter]) ||
1329
+ Net::LDAP::Filter.eq("objectclass", "*")
1330
+ search_filter = Net::LDAP::Filter.construct(search_filter) if search_filter.is_a?(String)
1331
+ search_base = (args && args[:base]) || "dc=example, dc=com"
1332
+ search_attributes = ((args && args[:attributes]) || []).map { |attr| attr.to_s.to_ber}
1333
+ return_referrals = args && args[:return_referrals] == true
1334
+ sizelimit = (args && args[:size].to_i) || 0
1335
+ raise Net::LDAP::LdapError, "invalid search-size" unless sizelimit >= 0
1336
+ paged_searches_supported = (args && args[:paged_searches_supported])
1337
+
1338
+ attributes_only = (args and args[:attributes_only] == true)
1339
+ scope = args[:scope] || Net::LDAP::SearchScope_WholeSubtree
1340
+ raise Net::LDAP::LdapError, "invalid search scope" unless Net::LDAP::SearchScopes.include?(scope)
1341
+
1342
+ # An interesting value for the size limit would be close to A/D's
1343
+ # built-in page limit of 1000 records, but openLDAP newer than version
1344
+ # 2.2.0 chokes on anything bigger than 126. You get a silent error that
1345
+ # is easily visible by running slapd in debug mode. Go figure.
1346
+ #
1347
+ # Changed this around 06Sep06 to support a caller-specified search-size
1348
+ # limit. Because we ALWAYS do paged searches, we have to work around the
1349
+ # problem that it's not legal to specify a "normal" sizelimit (in the
1350
+ # body of the search request) that is larger than the page size we're
1351
+ # requesting. Unfortunately, I have the feeling that this will break
1352
+ # with LDAP servers that don't support paged searches!!!
1353
+ #
1354
+ # (Because we pass zero as the sizelimit on search rounds when the
1355
+ # remaining limit is larger than our max page size of 126. In these
1356
+ # cases, I think the caller's search limit will be ignored!)
1357
+ #
1358
+ # CONFIRMED: This code doesn't work on LDAPs that don't support paged
1359
+ # searches when the size limit is larger than 126. We're going to have
1360
+ # to do a root-DSE record search and not do a paged search if the LDAP
1361
+ # doesn't support it. Yuck.
1362
+ rfc2696_cookie = [126, ""]
1363
+ result_code = 0
1364
+ n_results = 0
1365
+
1366
+ loop {
1367
+ # should collect this into a private helper to clarify the structure
1368
+ query_limit = 0
1369
+ if sizelimit > 0
1370
+ if paged_searches_supported
1371
+ query_limit = (((sizelimit - n_results) < 126) ? (sizelimit -
1372
+ n_results) : 0)
1373
+ else
1374
+ query_limit = sizelimit
1375
+ end
1376
+ end
1377
+
1378
+ request = [
1379
+ search_base.to_ber,
1380
+ scope.to_ber_enumerated,
1381
+ 0.to_ber_enumerated,
1382
+ query_limit.to_ber, # size limit
1383
+ 0.to_ber,
1384
+ attributes_only.to_ber,
1385
+ search_filter.to_ber,
1386
+ search_attributes.to_ber_sequence
1387
+ ].to_ber_appsequence(3)
1388
+
1389
+ controls = []
1390
+ controls <<
1391
+ [
1392
+ Net::LDAP::LdapControls::PagedResults.to_ber,
1393
+ # Criticality MUST be false to interoperate with normal LDAPs.
1394
+ false.to_ber,
1395
+ rfc2696_cookie.map{ |v| v.to_ber}.to_ber_sequence.to_s.to_ber
1396
+ ].to_ber_sequence if paged_searches_supported
1397
+ controls = controls.empty? ? nil : controls.to_ber_contextspecific(0)
1398
+
1399
+ pkt = [next_msgid.to_ber, request, controls].compact.to_ber_sequence
1400
+ @conn.write pkt
1401
+
1402
+ result_code = 0
1403
+ controls = []
1404
+
1405
+ while (be = @conn.read_ber(Net::LDAP::AsnSyntax)) && (pdu = Net::LDAP::PDU.new(be))
1406
+ case pdu.app_tag
1407
+ when 4 # search-data
1408
+ n_results += 1
1409
+ yield pdu.search_entry if block_given?
1410
+ when 19 # search-referral
1411
+ if return_referrals
1412
+ if block_given?
1413
+ se = Net::LDAP::Entry.new
1414
+ se[:search_referrals] = (pdu.search_referrals || [])
1415
+ yield se
1416
+ end
1417
+ end
1418
+ when 5 # search-result
1419
+ result_code = pdu.result_code
1420
+ controls = pdu.result_controls
1421
+ break
1422
+ else
1423
+ raise Net::LDAP::LdapError, "invalid response-type in search: #{pdu.app_tag}"
1424
+ end
1425
+ end
1426
+
1427
+ # When we get here, we have seen a type-5 response. If there is no
1428
+ # error AND there is an RFC-2696 cookie, then query again for the next
1429
+ # page of results. If not, we're done. Don't screw this up or we'll
1430
+ # break every search we do.
1431
+ #
1432
+ # Noticed 02Sep06, look at the read_ber call in this loop, shouldn't
1433
+ # that have a parameter of AsnSyntax? Does this just accidentally
1434
+ # work? According to RFC-2696, the value expected in this position is
1435
+ # of type OCTET STRING, covered in the default syntax supported by
1436
+ # read_ber, so I guess we're ok.
1437
+ more_pages = false
1438
+ if result_code == 0 and controls
1439
+ controls.each do |c|
1440
+ if c.oid == Net::LDAP::LdapControls::PagedResults
1441
+ # just in case some bogus server sends us more than 1 of these.
1442
+ more_pages = false
1443
+ if c.value and c.value.length > 0
1444
+ cookie = c.value.read_ber[1]
1445
+ if cookie and cookie.length > 0
1446
+ rfc2696_cookie[1] = cookie
1447
+ more_pages = true
1448
+ end
1449
+ end
1450
+ end
1451
+ end
1452
+ end
1453
+
1454
+ break unless more_pages
1455
+ } # loop
1456
+
1457
+ result_code
1458
+ end
1459
+
1460
+ MODIFY_OPERATIONS = { #:nodoc:
1461
+ :add => 0,
1462
+ :delete => 1,
1463
+ :replace => 2
1464
+ }
1465
+
1466
+ def self.modify_ops(operations)
1467
+ ops = []
1468
+ if operations
1469
+ operations.each { |op, attrib, values|
1470
+ # TODO, fix the following line, which gives a bogus error if the
1471
+ # opcode is invalid.
1472
+ op_ber = MODIFY_OPERATIONS[op.to_sym].to_ber_enumerated
1473
+ values = [ values ].flatten.map { |v| v.to_ber if v }.to_ber_set
1474
+ values = [ attrib.to_s.to_ber, values ].to_ber_sequence
1475
+ ops << [ op_ber, values ].to_ber
1476
+ }
1477
+ end
1478
+ ops
1479
+ end
1480
+
1481
+ #--
1482
+ # TODO: need to support a time limit, in case the server fails to respond.
1483
+ # TODO: We're throwing an exception here on empty DN. Should return a
1484
+ # proper error instead, probaby from farther up the chain.
1485
+ # TODO: If the user specifies a bogus opcode, we'll throw a confusing
1486
+ # error here ("to_ber_enumerated is not defined on nil").
1487
+ #++
1488
+ def modify(args)
1489
+ modify_dn = args[:dn] or raise "Unable to modify empty DN"
1490
+ ops = self.class.modify_ops args[:operations]
1491
+ request = [ modify_dn.to_ber,
1492
+ ops.to_ber_sequence ].to_ber_appsequence(6)
1493
+ pkt = [ next_msgid.to_ber, request ].to_ber_sequence
1494
+ @conn.write pkt
1495
+
1496
+ (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"
1497
+ pdu.result_code
1498
+ end
1499
+
1500
+ #--
1501
+ # TODO: need to support a time limit, in case the server fails to respond.
1502
+ # Unlike other operation-methods in this class, we return a result hash
1503
+ # rather than a simple result number. This is experimental, and eventually
1504
+ # we'll want to do this with all the others. The point is to have access
1505
+ # to the error message and the matched-DN returned by the server.
1506
+ #++
1507
+ def add(args)
1508
+ add_dn = args[:dn] or raise Net::LDAP::LdapError, "Unable to add empty DN"
1509
+ add_attrs = []
1510
+ a = args[:attributes] and a.each { |k, v|
1511
+ add_attrs << [ k.to_s.to_ber, Array(v).map { |m| m.to_ber}.to_ber_set ].to_ber_sequence
1512
+ }
1513
+
1514
+ request = [add_dn.to_ber, add_attrs.to_ber_sequence].to_ber_appsequence(8)
1515
+ pkt = [next_msgid.to_ber, request].to_ber_sequence
1516
+ @conn.write pkt
1517
+
1518
+ (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"
1519
+ pdu.result_code
1520
+ end
1521
+
1522
+ #--
1523
+ # TODO: need to support a time limit, in case the server fails to respond.
1524
+ #++
1525
+ def rename args
1526
+ old_dn = args[:olddn] or raise "Unable to rename empty DN"
1527
+ new_rdn = args[:newrdn] or raise "Unable to rename to empty RDN"
1528
+ delete_attrs = args[:delete_attributes] ? true : false
1529
+ new_superior = args[:new_superior]
1530
+
1531
+ request = [old_dn.to_ber, new_rdn.to_ber, delete_attrs.to_ber]
1532
+ request << new_superior.to_ber unless new_superior == nil
1533
+
1534
+ pkt = [next_msgid.to_ber, request.to_ber_appsequence(12)].to_ber_sequence
1535
+ @conn.write pkt
1536
+
1537
+ (be = @conn.read_ber(Net::LDAP::AsnSyntax)) &&
1538
+ (pdu = Net::LDAP::PDU.new( be )) && (pdu.app_tag == 13) or
1539
+ raise Net::LDAP::LdapError.new( "response missing or invalid" )
1540
+ pdu.result_code
1541
+ end
1542
+
1543
+ #--
1544
+ # TODO, need to support a time limit, in case the server fails to respond.
1545
+ #++
1546
+ def delete(args)
1547
+ dn = args[:dn] or raise "Unable to delete empty DN"
1548
+
1549
+ request = dn.to_s.to_ber_application_string(10)
1550
+ pkt = [next_msgid.to_ber, request].to_ber_sequence
1551
+ @conn.write pkt
1552
+
1553
+ (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"
1554
+ pdu.result_code
1555
+ end
1556
+ end # class Connection