net-ldap-1 0.4.0

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