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