Class: Net::LDAP::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/net/ldap.rb

Overview

This is a private class used internally by the library. It should not be called by user code.

Defined Under Namespace

Modules: GetbyteForSSLSocket

Constant Summary collapse

LdapVersion =

:nodoc:

3
MaxSaslChallenges =
10
MODIFY_OPERATIONS =

:nodoc:

{ #:nodoc:
  :add => 0,
  :delete => 1,
  :replace => 2
}

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(server) {|_self| ... } ⇒ Connection

Returns a new instance of Connection.

Yields:

  • (_self)

Yield Parameters:



1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
# File 'lib/net/ldap.rb', line 1133

def initialize(server)
  begin
    @conn = TCPSocket.new(server[:host], server[:port])
  rescue SocketError
    raise Net::LDAP::LdapError, "No such address or other socket error."
  rescue Errno::ECONNREFUSED
    raise Net::LDAP::LdapError, "Server #{server[:host]} refused connection on port #{server[:port]}."
  end

  if server[:encryption]
    setup_encryption server[:encryption]
  end

  yield self if block_given?
end

Class Method Details

.modify_ops(operations) ⇒ Object



1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
# File 'lib/net/ldap.rb', line 1536

def self.modify_ops(operations)
  ops = []
  if operations
    operations.each { |op, attrib, values|
      # TODO, fix the following line, which gives a bogus error if the
      # opcode is invalid.
      op_ber = MODIFY_OPERATIONS[op.to_sym].to_ber_enumerated
      values = [ values ].flatten.map { |v| v.to_ber if v }.to_ber_set
      values = [ attrib.to_s.to_ber, values ].to_ber_sequence
      ops << [ op_ber, values ].to_ber
    }
  end
  ops
end

.wrap_with_ssl(io) ⇒ Object



1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
# File 'lib/net/ldap.rb', line 1155

def self.wrap_with_ssl(io)
  raise Net::LDAP::LdapError, "OpenSSL is unavailable" unless Net::LDAP::HasOpenSSL
  ctx = OpenSSL::SSL::SSLContext.new
  conn = OpenSSL::SSL::SSLSocket.new(io, ctx)
  conn.connect
  conn.sync_close = true

  conn.extend(GetbyteForSSLSocket) unless conn.respond_to?(:getbyte)

  conn
end

Instance Method Details

#add(args) ⇒ Object

– TODO: need to support a time limit, in case the server fails to respond. Unlike other operation-methods in this class, we return a result hash rather than a simple result number. This is experimental, and eventually we’ll want to do this with all the others. The point is to have access to the error message and the matched-DN returned by the server. ++



1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
# File 'lib/net/ldap.rb', line 1578

def add(args)
  add_dn = args[:dn] or raise Net::LDAP::LdapError, "Unable to add empty DN"
  add_attrs = []
  a = args[:attributes] and a.each { |k, v|
    add_attrs << [ k.to_s.to_ber, Array(v).map { |m| m.to_ber}.to_ber_set ].to_ber_sequence
  }

  request = [add_dn.to_ber, add_attrs.to_ber_sequence].to_ber_appsequence(8)
  pkt = [next_msgid.to_ber, request].to_ber_sequence
  @conn.write pkt

  (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"

  pdu
end

#bind(auth) ⇒ Object



1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
# File 'lib/net/ldap.rb', line 1233

def bind(auth)
  meth = auth[:method]
  if [:simple, :anonymous, :anon].include?(meth)
    bind_simple auth
  elsif meth == :sasl
    bind_sasl(auth)
  elsif meth == :gss_spnego
    bind_gss_spnego(auth)
  else
    raise Net::LDAP::LdapError, "Unsupported auth method (#{meth})"
  end
end

#bind_simple(auth) ⇒ Object

– Implements a simple user/psw authentication. Accessed by calling #bind with a method of :simple or :anonymous. ++



1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
# File 'lib/net/ldap.rb', line 1250

def bind_simple(auth)
  user, psw = if auth[:method] == :simple
                [auth[:username] || auth[:dn], auth[:password]]
              else
                ["", ""]
              end

  raise Net::LDAP::LdapError, "Invalid binding information" unless (user && psw)

  msgid = next_msgid.to_ber
  request = [LdapVersion.to_ber, user.to_ber,
    psw.to_ber_contextspecific(0)].to_ber_appsequence(0)
  request_pkt = [msgid, request].to_ber_sequence
  @conn.write request_pkt

  (be = @conn.read_ber(Net::LDAP::AsnSyntax) and pdu = Net::LDAP::PDU.new(be)) or raise Net::LDAP::LdapError, "no bind result"

  pdu
end

#closeObject

– This is provided as a convenience method to make sure a connection object gets closed without waiting for a GC to happen. Clients shouldn’t have to call it, but perhaps it will come in handy someday. ++



1223
1224
1225
1226
# File 'lib/net/ldap.rb', line 1223

def close
  @conn.close
  @conn = nil
end

#delete(args) ⇒ Object

– TODO, need to support a time limit, in case the server fails to respond. ++



1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
# File 'lib/net/ldap.rb', line 1622

def delete(args)
  dn = args[:dn] or raise "Unable to delete empty DN"
  controls = args.include?(:control_codes) ? args[:control_codes].to_ber_control : nil #use nil so we can compact later
  request = dn.to_s.to_ber_application_string(10)
  pkt = [next_msgid.to_ber, request, controls].compact.to_ber_sequence
  @conn.write pkt

  (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"

  pdu
end

#encode_sort_controls(sort_definitions) ⇒ Object

– Allow the caller to specify a sort control

The format of the sort control needs to be:

:sort_control => [“cn”] # just a string or :sort_control => [[“cn”, “matchingRule”, true]] #attribute, matchingRule, direction (true / false) or :sort_control => [“givenname”,“sn”] #multiple strings or arrays



1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
# File 'lib/net/ldap.rb', line 1357

def encode_sort_controls(sort_definitions)
  return sort_definitions unless sort_definitions

  sort_control_values = sort_definitions.map do |control|
    control = Array(control) # if there is only an attribute name as a string then infer the orderinrule and reverseorder
    control[0] = String(control[0]).to_ber,
    control[1] = String(control[1]).to_ber,
    control[2] = (control[2] == true).to_ber
    control.to_ber_sequence
  end
  sort_control = [
    Net::LDAP::LDAPControls::SORT_REQUEST.to_ber,
    false.to_ber,
    sort_control_values.to_ber_sequence.to_s.to_ber
  ].to_ber_sequence
end

#modify(args) ⇒ Object

– TODO: need to support a time limit, in case the server fails to respond. TODO: We’re throwing an exception here on empty DN. Should return a proper error instead, probaby from farther up the chain. TODO: If the user specifies a bogus opcode, we’ll throw a confusing error here (“to_ber_enumerated is not defined on nil”). ++



1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
# File 'lib/net/ldap.rb', line 1558

def modify(args)
  modify_dn = args[:dn] or raise "Unable to modify empty DN"
  ops = self.class.modify_ops args[:operations]
  request = [ modify_dn.to_ber,
    ops.to_ber_sequence ].to_ber_appsequence(6)
  pkt = [ next_msgid.to_ber, request ].to_ber_sequence
  @conn.write pkt

  (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"

  pdu
end

#next_msgidObject



1228
1229
1230
1231
# File 'lib/net/ldap.rb', line 1228

def next_msgid
  @msgid ||= 0
  @msgid += 1
end

#rename(args) ⇒ Object

– TODO: need to support a time limit, in case the server fails to respond. ++



1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
# File 'lib/net/ldap.rb', line 1600

def rename(args)
  old_dn = args[:olddn] or raise "Unable to rename empty DN"
  new_rdn = args[:newrdn] or raise "Unable to rename to empty RDN"
  delete_attrs = args[:delete_attributes] ? true : false
  new_superior = args[:new_superior]

  request = [old_dn.to_ber, new_rdn.to_ber, delete_attrs.to_ber]
  request << new_superior.to_ber_contextspecific(0) unless new_superior == nil

  pkt = [next_msgid.to_ber, request.to_ber_appsequence(12)].to_ber_sequence
  @conn.write pkt

  (be = @conn.read_ber(Net::LDAP::AsnSyntax)) &&
  (pdu = Net::LDAP::PDU.new( be )) && (pdu.app_tag == 13) or
  raise Net::LDAP::LdapError.new( "response missing or invalid" )

  pdu
end

#search(args = {}) ⇒ Object

– Alternate implementation, this yields each search entry to the caller as it are received.

TODO: certain search parameters are hardcoded. TODO: if we mis-parse the server results or the results are wrong, we can block forever. That’s because we keep reading results until we get a type-5 packet, which might never come. We need to support the time-limit in the protocol. ++



1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
# File 'lib/net/ldap.rb', line 1384

def search(args = {})
  search_filter = (args && args[:filter]) ||
    Net::LDAP::Filter.eq("objectclass", "*")
  search_filter = Net::LDAP::Filter.construct(search_filter) if search_filter.is_a?(String)
  search_base = (args && args[:base]) || "dc=example, dc=com"
  search_attributes = ((args && args[:attributes]) || []).map { |attr| attr.to_s.to_ber}
  return_referrals = args && args[:return_referrals] == true
  sizelimit = (args && args[:size].to_i) || 0
  raise Net::LDAP::LdapError, "invalid search-size" unless sizelimit >= 0
  paged_searches_supported = (args && args[:paged_searches_supported])

  attributes_only = (args and args[:attributes_only] == true)
  scope = args[:scope] || Net::LDAP::SearchScope_WholeSubtree
  raise Net::LDAP::LdapError, "invalid search scope" unless Net::LDAP::SearchScopes.include?(scope)

  sort_control = encode_sort_controls(args.fetch(:sort_controls){ false })
  # An interesting value for the size limit would be close to A/D's
  # built-in page limit of 1000 records, but openLDAP newer than version
  # 2.2.0 chokes on anything bigger than 126. You get a silent error that
  # is easily visible by running slapd in debug mode. Go figure.
  #
  # Changed this around 06Sep06 to support a caller-specified search-size
  # limit. Because we ALWAYS do paged searches, we have to work around the
  # problem that it's not legal to specify a "normal" sizelimit (in the
  # body of the search request) that is larger than the page size we're
  # requesting. Unfortunately, I have the feeling that this will break
  # with LDAP servers that don't support paged searches!!!
  #
  # (Because we pass zero as the sizelimit on search rounds when the
  # remaining limit is larger than our max page size of 126. In these
  # cases, I think the caller's search limit will be ignored!)
  #
  # CONFIRMED: This code doesn't work on LDAPs that don't support paged
  # searches when the size limit is larger than 126. We're going to have
  # to do a root-DSE record search and not do a paged search if the LDAP
  # doesn't support it. Yuck.
  rfc2696_cookie = [126, ""]
  result_pdu = nil
  n_results = 0

  loop {
    # should collect this into a private helper to clarify the structure
    query_limit = 0
    if sizelimit > 0
      if paged_searches_supported
        query_limit = (((sizelimit - n_results) < 126) ? (sizelimit -
                                                          n_results) : 0)
      else
        query_limit = sizelimit
      end
    end

    request = [
      search_base.to_ber,
      scope.to_ber_enumerated,
      0.to_ber_enumerated,
      query_limit.to_ber, # size limit
      0.to_ber,
      attributes_only.to_ber,
      search_filter.to_ber,
      search_attributes.to_ber_sequence
    ].to_ber_appsequence(3)

	# rfc2696_cookie sometimes contains binary data from Microsoft Active Directory
	# this breaks when calling to_ber. (Can't force binary data to UTF-8)
	# we have to disable paging (even though server supports it) to get around this...

    controls = []
    controls <<
      [
        Net::LDAP::LDAPControls::PAGED_RESULTS.to_ber,
        # Criticality MUST be false to interoperate with normal LDAPs.
        false.to_ber,
        rfc2696_cookie.map{ |v| v.to_ber}.to_ber_sequence.to_s.to_ber
      ].to_ber_sequence if paged_searches_supported
    controls << sort_control if sort_control
    controls = controls.empty? ? nil : controls.to_ber_contextspecific(0)

    pkt = [next_msgid.to_ber, request, controls].compact.to_ber_sequence
    @conn.write pkt

    result_pdu = nil
    controls = []

    while (be = @conn.read_ber(Net::LDAP::AsnSyntax)) && (pdu = Net::LDAP::PDU.new(be))
      case pdu.app_tag
      when 4 # search-data
        n_results += 1
        yield pdu.search_entry if block_given?
      when 19 # search-referral
        if return_referrals
          if block_given?
            se = Net::LDAP::Entry.new
            se[:search_referrals] = (pdu.search_referrals || [])
            yield se
          end
        end
      when 5 # search-result
        result_pdu = pdu
        controls = pdu.result_controls
        if return_referrals && result_code == 10
          if block_given?
            se = Net::LDAP::Entry.new
            se[:search_referrals] = (pdu.search_referrals || [])
            yield se
          end
        end
        break
      else
        raise Net::LDAP::LdapError, "invalid response-type in search: #{pdu.app_tag}"
      end
    end

    # When we get here, we have seen a type-5 response. If there is no
    # error AND there is an RFC-2696 cookie, then query again for the next
    # page of results. If not, we're done. Don't screw this up or we'll
    # break every search we do.
    #
    # Noticed 02Sep06, look at the read_ber call in this loop, shouldn't
    # that have a parameter of AsnSyntax? Does this just accidentally
    # work? According to RFC-2696, the value expected in this position is
    # of type OCTET STRING, covered in the default syntax supported by
    # read_ber, so I guess we're ok.
    more_pages = false
    if result_pdu.result_code == 0 and controls
      controls.each do |c|
        if c.oid == Net::LDAP::LDAPControls::PAGED_RESULTS
          # just in case some bogus server sends us more than 1 of these.
          more_pages = false
          if c.value and c.value.length > 0
            cookie = c.value.read_ber[1]
            if cookie and cookie.length > 0
              rfc2696_cookie[1] = cookie
              more_pages = true
            end
          end
        end
      end
    end

    break unless more_pages
  } # loop

  result_pdu || OpenStruct.new(:status => :failure, :result_code => 1, :message => "Invalid search")
end

#setup_encryption(args) ⇒ Object

– Helper method called only from new, and only after we have a successfully-opened @conn instance variable, which is a TCP connection. Depending on the received arguments, we establish SSL, potentially replacing the value of @conn accordingly. Don’t generate any errors here if no encryption is requested. DO raise Net::LDAP::LdapError objects if encryption is requested and we have trouble setting it up. That includes if OpenSSL is not set up on the machine. (Question: how does the Ruby OpenSSL wrapper react in that case?) DO NOT filter exceptions raised by the OpenSSL library. Let them pass back to the user. That should make it easier for us to debug the problem reports. Presumably (hopefully?) that will also produce recognizable errors if someone tries to use this on a machine without OpenSSL.

The simple_tls method is intended as the simplest, stupidest, easiest solution for people who want nothing more than encrypted comms with the LDAP server. It doesn’t do any server-cert validation and requires nothing in the way of key files and root-cert files, etc etc. OBSERVE: WE REPLACE the value of @conn, which is presumed to be a connected TCPSocket object.

The start_tls method is supported by many servers over the standard LDAP port. It does not require an alternative port for encrypted communications, as with simple_tls. Thanks for Kouhei Sutou for generously contributing the :start_tls path. ++



1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
# File 'lib/net/ldap.rb', line 1193

def setup_encryption(args)
  case args[:method]
  when :simple_tls
    @conn = self.class.wrap_with_ssl(@conn)
    # additional branches requiring server validation and peer certs, etc.
    # go here.
  when :start_tls
    msgid = next_msgid.to_ber
    request = [Net::LDAP::StartTlsOid.to_ber].to_ber_appsequence(Net::LDAP::PDU::ExtendedRequest)
    request_pkt = [msgid, request].to_ber_sequence
    @conn.write request_pkt
    be = @conn.read_ber(Net::LDAP::AsnSyntax)
    raise Net::LDAP::LdapError, "no start_tls result" if be.nil?
    pdu = Net::LDAP::PDU.new(be)
    raise Net::LDAP::LdapError, "no start_tls result" if pdu.nil?
    if pdu.result_code.zero?
      @conn = self.class.wrap_with_ssl(@conn)
    else
      raise Net::LDAP::LdapError, "start_tls failed: #{pdu.result_code}"
    end
  else
    raise Net::LDAP::LdapError, "unsupported encryption method #{args[:method]}"
  end
end